Welcome to the Data Engineering category of DZone, where you will find all the information you need for AI/ML, big data, data, databases, and IoT. As you determine the first steps for new systems or reevaluate existing ones, you're going to require tools and resources to gather, store, and analyze data. The Zones within our Data Engineering category contain resources that will help you expertly navigate through the SDLC Analysis stage.
Artificial intelligence (AI) and machine learning (ML) are two fields that work together to create computer systems capable of perception, recognition, decision-making, and translation. Separately, AI is the ability for a computer system to mimic human intelligence through math and logic, and ML builds off AI by developing methods that "learn" through experience and do not require instruction. In the AI/ML Zone, you'll find resources ranging from tutorials to use cases that will help you navigate this rapidly growing field.
Big data comprises datasets that are massive, varied, complex, and can't be handled traditionally. Big data can include both structured and unstructured data, and it is often stored in data lakes or data warehouses. As organizations grow, big data becomes increasingly more crucial for gathering business insights and analytics. The Big Data Zone contains the resources you need for understanding data storage, data modeling, ELT, ETL, and more.
Data is at the core of software development. Think of it as information stored in anything from text documents and images to entire software programs, and these bits of information need to be processed, read, analyzed, stored, and transported throughout systems. In this Zone, you'll find resources covering the tools and strategies you need to handle data properly.
A database is a collection of structured data that is stored in a computer system, and it can be hosted on-premises or in the cloud. As databases are designed to enable easy access to data, our resources are compiled here for smooth browsing of everything you need to know from database management systems to database languages.
IoT, or the Internet of Things, is a technological field that makes it possible for users to connect devices and systems and exchange data over the internet. Through DZone's IoT resources, you'll learn about smart devices, sensors, networks, edge computing, and many other technologies — including those that are now part of the average person's daily life.
The Query Takes 20 ms. Why Does the API Take Two Seconds?
Spring AI Migration: From the Vertex AI Gemini Module to the Google GenAI SDK
A cyber-security engineer reviews a log file and notices a strange behavior. When PHP’s memory ceiling is reached, the engine fires a hard request to kill the process. That violent stop, he found, had an unfortunate consequence; it left the PHP server open to remote commands. The engineer paused. In theory, if a hacker could control what was written into that memory space right before the crash, they might force the engine to execute their own commands during the cleanup loop. To turn that dangling pointer into a real system breach over a live web connection, an attacker would have to perform digital acrobatics. They would need to send precise, multi-part payloads — crafted down to the exact byte — to groom server memory, predict chunk allocations across network latency, and time the exact microsecond the engine ran out of memory. A human hacker trying to build a working exploit faced hundreds of hours of manual trial and error. The sheer complexity of the exploit was the gate to its execution. The engineering team concluded that fixing the flaw risked breaking runtime performance or shattering backward compatibility for thousands of third-party C-extensions. Their finding: Low severity. Highly complex. Practically unexploitable. People evaluated the risk, weighed the cognitive friction required to weaponize it, and concluded that PHP was safe behind the wall of Complexity Defense — the assumption that a vulnerability is functionally harmless because exploiting it is too hard, too tedious, or too time-consuming. For two years they were right. There were no recorded incidents of attempting a breach using this specific exploit. The Alarm Goes Off In August 2026, researchers fed the Zend Engine's source code into frontier AI reasoning models. These AI engines didn't care about human fatigue, backward-compatibility debates, or the difficulty of the math. They ingested the constraints, mapped thousands of execution branches in parallel, and solved the multi-variable memory layout puzzle in seconds. By afternoon, the "unexploitable" low-severity ticket from 2024 was solved, registering a vulnerability that exposed about 70% of global websites to remote control. The PHP Foundation published PHP2Shell (CVE-2026-109618 and CVE-2026-109619), triggering a global wave of emergency site shutdowns and patching. The Dual Engine: A Mirror of Human Intent Commentary on the discovery of this vulnerability ran the spectrum. Half the headlines warned that AI was being weaponized to break the internet; the other half praised AI researchers for saving us from a silent zero-day. Both narratives miss the fundamental reality. What happened with PHP2Shell has nothing to do with sci-fi narratives of apocalyptic AI or automated digital utopias. AI is neither the hero nor the villain here — it is an intent-agnostic cognitive force multiplier. Our cybersecurity engineer applied AI to find and fix vulnerabilities. The potential hacker could use AI to deliver exact exploit instructions. The Benefit: Rapid Diagnostic Exposure For defensive teams, AI is the ultimate diagnostic lens. AI democratizes high-tier code analysis, allowing defenders to parse millions of line interactions, surface hidden architectural defects, and fix them before they are weaponized in the wild. The Risk: The Democratization of Exploits The exact capability that lets an AI model find a flaw also allows it to synthesize the exploit. Historically, even if a bad actor discovered a subtle memory bug, actually building a working exploit required world-class reverse-engineering talent. AI erases that barrier to entry. It takes high-complexity edge cases and translates them into turn-key attack vectors for anyone with access to sufficient compute. Two caveats keep this honest. First, the defender's window was short. Reporting indicates details leaked, a proof-of-concept tool surfaced, and exploitation attempts followed the disclosure. A head start measured in days is not a comfortable margin. Second, the contest is asymmetric. Defenders have to patch millions of instances. Attackers only need one unpatched entry. Engineering Takeaways: The End of "Security Through Obscurity” The PHP2Shell event isn't proof of autonomous AI systems running amok; it is proof that cognitive friction is no longer a valid security control. Whether you are managing an engineering team or advising executive leadership, the collapse of Complexity Defense forces three immediate operational shifts: Kill the "Low Severity/Hard to Exploit" Triage Category: "Too hard to weaponize" is obsolete. If your security backlog contains technical debt for flaws that were marked "low priority" because building an exploit seemed too complicated — revisit them now.“Time-to-Patch” is the Modern Security Metric: The gap between "bug known" and "working exploit" has collapsed. What matters now is how quickly your environment can absorb an upstream fix without breaking production. Companies that can't answer "which of our systems run PHP" in an hour have already lost time. Passive security methods will be quickly overwhelmed by autonomous agents.Proactive AI Auditing is Mandatory: Waiting for third-party disclosures or CVE reports is a risky strategy. Point AI-assisted analysis at your proprietary code and your critical dependencies. Scanning once is not enough. This has to run continuously, not on an annual audit cadence. Death of the Complexity Defense The organizations that thrive in this new landscape will acknowledge the new requirement for speed-to-discover and speed-to-patch metrics. Security control can no longer be practiced on a periodic cadence. Using AI to discover and secure vulnerabilities will become essential to security practice. The doom vs. utopia conversation, beloved by the media, is irrelevant to this discussion. AI has no intent; it’s an intent multiplier and facilitator. It’s open to the benevolent work of the researcher and the malevolent intent of the hacker. PHP2Shell was a disruptive, painful event for engineering teams worldwide, but it stripped away a comforting illusion: that software can be protected by how hard it is to attack. Friction that once protected us is gone, and the old categories of "low priority" and "practically unexploitable" need rewriting. The Complexity Defense is dead in the face of AI.
AI coding capacity rarely lands evenly across a team. Copilot usually arrives through a company contract where each developer works against a personal limit per billing period: a per-user credit allowance, or a per-user budget that admins set on top of the organization's pool. Some developers burn through theirs in the first week. Others end the period with credits left over, and some have no license at all. Each limit belongs to one person, so the leftover credits do nothing for the colleague who ran out. That is capacity the company has already paid for, sitting idle next to people who could use it. The usual workaround is a favor in a chat window: "Can you run this through Copilot for me?" It works once. As a habit, it breaks down quickly. The request carries half the context, the colleague spends their own allowance asking clarifying questions, nobody reviews what was asked for, and whatever was decided lives in a Copilot conversation that nobody else will ever read. I wanted something sturdier, so I wrote it down as a process and put it in a companion repository: a PRD for the process itself, a task template, an example task (TASK-042), and the architecture, coding, and testing guides the task points to. This article is about the governance side of that proposal: who is responsible for what, where the quality gates sit, how accountability is kept, and how you would tell whether it is working. It describes a proposed process. I don't have adoption numbers from a live rollout, and I won't invent any. The Model in One Paragraph A developer who owns a piece of work but lacks AI capacity (the owner) writes a task specification as a Markdown file in the repository. A reviewer checks it against a definition of ready. A colleague with spare Copilot capacity (the delegate) implements it with Copilot, runs the tests, and writes implementation notes back into the same file. The owner validates the result, makes the final commit, and opens the pull request, which goes through the same CI/CD pipeline as everything else. One rule underpins all of it: nobody transfers tokens, credits, licenses, or accounts. The delegate uses their own seat for work assigned to them through the normal tracker, and the only thing that moves between people is a specification. Where Spec-Driven Development and Spec Kit Fit The process is spec-driven development applied to a staffing problem. In spec-driven development, a written specification comes first, and the code is generated from it, so the spec stays the reference when the code is reviewed or changed. GitHub Spec Kit packages that approach as a set of agent commands. You run /speckit-constitution once per project, then /speckit-specify, /speckit-plan, /speckit-tasks and /speckit-implement for each feature, followed by /speckit-converge. Implement and converge repeat until converge reports "Converged". Spec Kit supports Copilot directly: install the CLI with uv tool install specify-cli and run specify init <project> --integration copilot. In Spec Kit, one person drives every step. This process splits the same steps across roles, and the spec becomes the handoff between two people as well as the input to the agent: Spec Kit stepIn this processWhoConstitutionTeam standards in /docs and .github/copilot-instructions.mdTeam, maintained by tech leadsSpecifyBusiness requirements written up as a taskOwner, from the business inputPlan and tasksThe approved TASK-NNN.md fileOwner writes it, reviewer approves itImplementThe Copilot session that spends creditsDelegateConvergeThe validation loop until the result matches the specOwner, with the delegate for more iterations Teams already using Spec Kit can keep its commands and add the role split. Teams that aren't can use the plain Markdown template from the companion repo and get the same structure. Roles and Responsibilities A process that spans two people and an AI needs explicit ownership, or every failure turns into "I thought you checked that". The PRD defines four roles. The table below turns them into a RACI matrix (Responsible, Accountable, Consulted, Informed) across the steps of one task. ActivityBusinessOwnerReviewerDelegateCI/CDRequirements and acceptance criteriaR/ACIWrite TASK-NNN.md and open the issueCR/ACheck the definition of readyCR/AChoose a delegateR/ACImplement with Copilot (code, tests, docs)ARRun the full test suite before handbackARFill in implementation notesARValidate the resultCR/ACFinal commit and pull requestR/ABuild, tests, scans, quality gatesIRPromote reusable notes into /docsR/ACC Look at the Owner column. Apart from the requirements, the readiness check, and the pipeline itself, every row has an "A" there. The owner is accountable for the task from the moment it is written until it merges, including the steps the delegate performs. If accountability followed whoever held a Copilot license, it would move from person to person with each task. The owner knows the domain, wrote the spec, and will maintain the code afterward, so the owner signs off. The reviewer's role is narrow on purpose. They don't review code at this stage. They review the specification before anybody spends credits on it. Code review still happens later on the pull request, through whatever review rules the repository already enforces. Figure 1: One delegated task end to end. The readiness review happens before any AI credits are spent. Legend ColorParticipantBlueOwner, accountable for the taskPurpleReviewer, gatekeeper for the specificationGreenDelegate, the only role that spends creditsYellowCopilot in agent modeOrangeGit repository (/docs/backlog)RedCI/CD pipeline The Specification Is the Interface Treat the task file the way you would treat an API contract between two services. Each side can work without knowing the other's internals, as long as both honor the contract. Here the two sides happen to be a person and a person-plus-AI, and the contract is a Markdown file under version control. This is the core of TASK-042 from the companion repo: Markdown # TASK-042: Generate order summary report Status: Approved Owner: <name> Reviewer: <name> Delegate: <name> Issue: <link> ## Objective Generate the order summary report from normalized order records. ## Expected behavior 1. Load the report configuration. 2. Retrieve the eligible orders. 3. Generate the report. 4. Store the delivery metadata. ## Architecture constraints - Follow [ARCHITECTURE.md](../ARCHITECTURE.md). - Follow [CODING_GUIDE.md](../CODING_GUIDE.md). - Do not bypass the defined service boundaries. ## Acceptance criteria - [ ] The report is generated for all eligible orders. - [ ] The job can be restarted after a failure. - [ ] A failed run is recorded. - [ ] Unit tests cover the new code. - [ ] Integration tests cover the end-to-end flow. ## Out of scope - File transport - Customer notification ## References - [TESTING_GUIDE.md](../TESTING_GUIDE.md) - [Report generation design](../specs/report-generation/design.md) ## Implementation notes Filled in by the delegate at handback. - Changed: - Decisions: - Open questions: Each section maps to a familiar contract term: Objective and expected behavior are the operation's signature. They say what the work does, in steps that can be checked.Architecture constraints are invariants. In the example repo, ARCHITECTURE.md says a layer never calls the layer above it and services never read each other's tables. A constraint stated once in a guide and referenced from every task survives far better than one repeated in a chat prompt.Acceptance criteria are postconditions. The testing guide requires each criterion to map to at least one test, which turns the contract into something a machine can partly verify.Out of scope prevents scope creep. An AI agent with file-system access will happily "improve" adjacent code. Telling it in writing what not to touch is cheaper than reverting it later.References are the context window, made explicit. The delegate points Copilot at these files instead of pasting their content.Implementation notes are the response payload: what changed, what was decided, and what is still open. The status field (Draft, Approved, In progress, In validation, Done) gives the file a small lifecycle. Each task also gets a GitHub issue with an ai-delegation label that links the file, so the issue board shows which tasks are waiting for a delegate and who has taken which. The file holds the content and the issue handles the workflow, so the two don't compete. Definition of Ready as a Quality Gate In this model, the scarce resource is the delegate's AI allowance, plus their time. Both get wasted the same way: the agent has to guess, guesses wrong, and the delegate burns credits steering it back. An agent guesses when the spec leaves a gap, and gaps are cheapest to close before anyone starts a session. So the process puts a gate in front of the expensive step, the same way a pipeline runs cheap checks before expensive ones. The reviewer approves a task only when all of these hold: The objective fits in one or two sentences.Each expected behavior is a concrete step, not a wish.Each acceptance criterion can be checked by a test or a visible result.Out of scope is listed.Every referenced document exists and is current.Input and output examples are included where the format matters.The task contains no secrets, credentials, or production data.The task fits one session. As a rule of thumb, it should produce a PR one person can review in under an hour. Bigger work is split. None of these items requires AI capacity. The owner, who by definition is short on credits, does the parts of the job that don't consume them: thinking, specifying, and later validating. The credits go to the implementation, where an agent saves the most typing. Figure 2: Two loops. The review loop is cheap and can run as often as needed. The implementation loop consumes credits, so the first loop exists to keep the second one short. Legend ElementMeaningSwimlane colorRole performing the stepOrange diamondDecision pointUpward return arrowLoop back to an earlier step The second loop has a rule of its own. When the owner finds a gap during validation, small fixes are done directly. Anything bigger goes back into the task file first and only then to the delegate. That keeps the spec in sync with what was built, and it stops the iteration from sliding back into an untracked chat thread. Ownership and the Same Gates for Everyone Two design choices keep delegated work from becoming a second-class citizen. First, the owner validates, and the owner opens the pull request. The delegate hands back a branch with passing tests and filled-in notes and never merges it. The owner runs the unit and integration tests, any functional or simulation tests, and checks the affected screens. Then the owner makes the final commit. When a production issue shows up six months later, the PR history points to someone who understood the change well enough to sign for it. Second, there is no AI lane in the pipeline. Delegated work passes the same build, tests, security scans, and quality gates as anything else, and merges only if all of them pass. It can be tempting to relax review for "simple generated code." The PRD rules that out as a non-goal: the process must not change existing CI/CD, review, or quality-gate rules. Gates that are adequate for human-written code should hold for agent-written code too. If they don't, they had gaps before any agent showed up. A variant works with the same governance. Copilot cloud agent (which GitHub's documentation earlier called the coding agent) can start work from a GitHub issue, work in the background in its own environment, and open a pull request. A delegate can start that session from the task's issue. The owner then validates the agent's PR exactly as they would validate a branch from a colleague. GitHub's own docs say the session logs "do not replace your own review and testing", which matches the model. Knowledge Retention: /docs versus Chat History The informal favor also loses knowledge. Every clarifying exchange, every rejected approach, and every assumption the agent made lives in a session that ends. The model counters this with a simple rule from the PRD: the repository is the source of truth, and nothing needed to understand a task exists only in a Copilot conversation. In practice, that rule rests on three layers of version-controlled artifacts. Figure 3: Repository artifacts that carry the process. Standing docs change slowly, task files change per unit of work, and the .github configuration shapes how the AI behaves for every delegate. Legend ColorArtifact typeLight blueStanding documentation (/docs, /docs/specs)AmberTask specification (/docs/backlog)GreenCopilot configuration (.github)RedQuality gate (CI workflow)PurpleTracking (GitHub issue) The .github layer keeps delegates consistent. Without it, every delegate brings their own habits and prompts, and the output varies with whoever picks up the task. GitHub documents a repository-wide instructions file at .github/copilot-instructions.md, path-specific instructions in .github/instructions/NAME.instructions.md (each with an applyTo glob), and AGENTS.md files that agents read. Reusable prompt files live in .github/prompts with a .prompt.md extension and are available in VS Code, Visual Studio and JetBrains IDEs. The companion repo ships both files. The repository instructions tell Copilot that the task file is the only source of requirements: Markdown ## When implementing a task - The task file in `docs/backlog/TASK-NNN-*.md` is the only source of requirements. Do not add behavior it does not ask for, and respect its "Out of scope" list. - Follow `docs/ARCHITECTURE.md`, `docs/CODING_GUIDE.md` and `docs/TESTING_GUIDE.md`. - Every acceptance criterion maps to at least one test. Run the full test suite before handing back. - Fill in the task's "Implementation notes" section: what changed, decisions made, open questions. - If the task is ambiguous, stop and list the questions instead of guessing. The shared implement-task prompt gives every delegate the same procedure, so nobody re-explains the conventions, and every handback looks the same: YAML --- description: Implement an approved TASK-NNN.md spec as a delegate, then hand it back to the owner agent: agent --- You are the delegate for the task file given in the input (for example `#file:docs/backlog/TASK-042-order-summary-report.md`). 1. Read the task file and every document in its "References" and "Architecture constraints" sections. 2. Check the task against the definition of ready in `docs/spec/PRD-copilot-capacity-sharing.md`. If anything is missing or ambiguous, stop and list the questions for the owner. Do not implement. 3. Propose a short plan: files to create or change, and which test covers each acceptance criterion. Wait for confirmation. 4. Implement the plan: code, unit tests, integration tests and documentation updates. Stay inside the task's scope. 5. Run the full test suite. Fix failures, including existing tests you broke. 6. Fill in the task's "Implementation notes" (Changed, Decisions, Open questions) and set its status to "In validation". 7. Summarize the result for the owner in five lines or fewer. In step 2, the prompt re-checks the definition of ready before writing any code, so a spec that slipped past the reviewer gets stopped at the cost of one short exchange instead of a full implementation. Step 3 makes "plan first" part of the procedure instead of leaving it to each delegate's discipline. The last step of the process closes the loop on knowledge: after merge, the team moves anything worth reusing from the implementation notes into /docs. A decision about restart semantics, for example, belongs in specs/report-generation/design.md, where the next task can reference it. Spending Credits Deliberately GitHub changed how Copilot usage is metered during 2026. Since June 1, 2026, plans are billed by usage: GitHub AI Credits, consumed according to token usage, replaced premium requests as the billing unit (premium requests survive only on some legacy plans), and code completions are not billed in credits. Plan details and allowances keep moving, so I won't quote them here. Check the Copilot billing docs for your plan. From the organization's point of view, the credits form one budget, but per-user allowances or per-user budgets split it into personal limits. The process doesn't change whose limit is whose. It changes where the work goes, so a developer with room left can serve a colleague who has hit their limit, without buying extra seats. Where an organization pools credits with no per-user caps, that argument is weaker, but developers without a license still need this route. Whatever the unit, the process treats credits as a budget and shapes sessions to match: Run one task per session, started fresh. Long sessions drag old context along, and token-based billing charges for it.Reference files instead of pasting them. Point Copilot at the task file and its references (#file, #codebase in VS Code chat) rather than copying content into the prompt.Plan before editing. The shared prompt stops after the plan. A wrong plan caught early costs one exchange. A wrong implementation costs many.Match the model to the step. Routine steps (boilerplate, renames, simple tests) rarely need the most expensive model. Check current model rates before choosing, since they change.Stop loops early. If the agent keeps circling, the spec is the problem. Fix the task file instead of retrying. The same habits help owners stretch their own small allowance. Security and Policy Delegation doesn't widen anyone's access. The delegate already has repository access through the normal permissions, and the process grants nothing new. Three rules keep it that way: Task files never contain secrets, credentials, or production data. Use synthetic examples. Task files are committed and readable by everyone with repo access, and they are fed to an AI tool.Copilot is used only within the organization's approved AI policy and settings, such as content exclusions and public code filtering.Work the delegate's role could not normally touch stays with the owner. "Needs access the delegate lacks" is one of the explicit reasons not to delegate. There is one question I would put to the organization's licensing or legal contact before rollout, not answer myself: does having one seat holder implement work owned by a colleague fit your agreement and internal policy? Structurally, the delegate is just working an assigned ticket with their own tool, which is ordinary teamwork. Still, a short written confirmation is cheaper than an awkward conversation later. Measuring Whether It Pays Off A process without signals turns into ritual. The PRD proposes a small set of per-sprint measures. None of them needs new tooling, and each one answers a specific question. SignalQuestion it answersWarning signTasks delegated and mergedIs the process being used at all?Many delegated, few mergedIterations per taskWas the spec actually ready?More than two iterations on a regular basisTime from approval to merge vs. similar hand-built tasksDoes delegation save time end to end?Delegated tasks consistently slowerTasks waiting for a delegateIs capacity matched to demand?Queue growing sprint over sprintCredits left unused at period endIs paid capacity reaching real work?Delegates finish periods with large balances while tasks waitCredits consumed per delegated taskAre sessions efficient?High spend on tasks that needed many iterations Most of this comes straight from GitHub. For example, approval-to-merge time can be approximated from the ai-delegation issues: Shell # Closed delegation issues with lead time in days (issue creation as a proxy for approval) gh issue list --label ai-delegation --state closed --limit 200 \ --json number,title,createdAt,closedAt | jq -r '.[] | [.number, (((.closedAt|fromdateiso8601) - (.createdAt|fromdateiso8601)) / 86400 | floor), .title] | @tsv' For the credit signal, GitHub added a per-user ai_credits_used field to the Copilot usage metrics API in June 2026. GitHub describes it as a metrics signal rather than a billed total, which is precise enough for spotting trends. Comparing a delegate's consumption in sprints with and without delegated tasks gives a rough cost per task. Watch the iteration count most closely. It measures spec quality, which is the one variable the owner fully controls. If it creeps up, tighten the definition of ready before anything else. Trade-Offs and When Not to Delegate Delegation has a fixed overhead: a spec, a review, a handoff, and a validation. That overhead is worth paying only when the implementation is larger than the ceremony around it. Figure 4: A quick screen before writing a task file. Legend ColorMeaningOrange diamondScreening questionBlue boxKeep the work with the ownerGrey boxNeutral stepGreen boxDelegate through a task file Good candidates are new endpoints, services, or jobs with a clear spec, test suites for existing code, mechanical refactors across many files, boilerplate (DTOs, mappers, repositories, migrations), and documentation generated from code. Poor candidates are one-line fixes, exploratory work where the design is still open, live incidents, and anything that needs access the delegate doesn't have. The process also has costs: Latency: a task waits for review and then for a delegate. For urgent work, this is a real cost, which is why incidents are excluded.Reviewer bottleneck: if one tech lead reviews every spec, they become the constraint. Rotate the reviewer role or let senior developers review each other's specs.Uneven load on delegates: the people with spare capacity can end up as an internal service desk. The capacity notes on the issue board ("can take two tasks this sprint") exist, so delegates control their own intake.Skill drift: an owner who never drives an AI agent doesn't learn to. If the gap in capacity is temporary, plan to close it rather than institutionalize it.Specs that rot: a task file is only as good as the documents it references. If ARCHITECTURE.md is stale, every task that points to it inherits the error. The readiness check on referenced docs is there for that reason. A side effect may outlast the whole arrangement: teams that adopt it end up with better specs and better standing documentation, whether or not anyone is short on credits. If capacity evens out next year, the team keeps the specs and the /docs folder. Summary Uneven AI capacity is a resource-allocation problem: credits the company already paid for sit unused next to developers who have none. Informal favors handle it poorly. A version-controlled task spec handles it as a contract.Nobody transfers credits or accounts. The owner specifies and validates, and the delegate spends credits only on implementation.The definition of ready is a quality gate placed before the expensive step, so gaps in the spec are closed before anyone spends credits on them.The owner stays accountable end to end and opens the PR. Delegated work passes exactly the same CI/CD gates as any other change.Knowledge lives in /docs and .github, not in chat sessions, and a small set of signals tells you whether the process earns its overhead. The full PRD, the task template, TASK-042 and the supporting guides are in the companion repo. Fork it and adapt the roles and the definition of "ready" to your own team. How does your team handle uneven access to AI coding tools? I'm curious whether others formalized it or still run on favors. Please let me know in the comments. Examples repository: every example in this article (the PRD, the TASK-042 task spec, the team guides, the Copilot instructions, the prompt file, and the diagrams) is in https://github.com/wallaceespindola/share-tokens-using-spec-driven-dev. Need more tech insights? Check out my GitHub, LinkedIn, and Speaker Deck. Happy coding! Wallace Espindola, Solution Architect GitHub: https://github.com/wallaceespindola/LinkedIn: https://www.linkedin.com/in/wallaceespindola/Speaker Deck: https://speakerdeck.com/wallacese
Artificial intelligence is transforming software engineering by accelerating code generation, testing, documentation, and architectural exploration. However, faster code delivery does not guarantee better software. As AI becomes integral to development, technical leaders must ensure that productivity gains do not compromise quality, critical thinking, or engineering ownership. Ultimately, when an AI-generated solution fails in production, responsibility remains with the engineers and the organization. For Staff Engineers, this shift extends beyond adopting new tools. They must not only use AI effectively but also guide teams to question its outputs, understand trade-offs, recognize limitations, and make informed decisions. How can leaders scale teams without introducing new dependencies? How can they promote AI adoption while maintaining engineering judgment? This article examines the challenges, opportunities, and common pitfalls of technical leadership in the age of AI, focusing on how Staff Engineers can turn individual productivity gains into lasting team capabilities. The Emerging Role of Staff Engineers in the Age of AI As software organizations grow, technical decisions become more complex, and coordinating multiple teams becomes challenging. Architectural inconsistencies, knowledge silos, conflicting priorities, and team dependencies can slow delivery, even when individual engineers are productive. Organizations need technical leaders who deal with these issues without adding management layers or becoming decision bottlenecks. Staff Engineers serve an important role by aligning technical decisions with enterprise objectives, guiding architecture, mentoring engineers, and helping teams work autonomously. Unlike Engineering Managers, Staff Engineers lead through technical expertise, collaboration, and influence rather than formal authority. AI does not change the fundamentals of good software engineering. Core practices such as understanding requirements, evaluating trade-offs, code review, testing, and maintaining architectural consistency are necessary. AI makes these practices even more important by highlighting organizational strengths and weaknesses. While tasks like code generation, exploring codebases, creating tests, and drafting documentation can be accelerated, faster implementation does not guarantee better software. Rapid development can quickly spread poor decisions or inadequate validation and affect more components. Conversely, strong engineering decisions and effective practices can have an even greater positive impact when AI amplifies them. Staff Engineers should not act as the final reviewer for every AI-generated contribution, as this would create a new bottleneck. Instead, they must strengthen engineering practices that enable teams to question AI-generated solutions, evaluate trade-offs, verify assumptions, and maintain ownership of technical decisions. AI speeds up development, but it can amplify both strengths and weaknesses. Technical leaders must ensure that increased speed leads to sustainable organizational capabilities as AI becomes integral to software development. Challenges Every Technical Leader Must Face AI delivers new challenges to software engineering organizations, though many are familiar. Issues like technical debt, knowledge gaps, inconsistent quality, and poor architectural decisions persist, but now emerge faster and at greater scale. For Staff Engineers, the challenge is not just integrating AI into workflows, but ensuring teams can understand, evaluate, and take responsibility for their deliverables. Balancing Development Speed With Engineering Quality One of the most visible benefits of AI is the ability to accelerate software development. Engineers can generate implementations, tests, and documentation in minutes rather than hours. However, faster development does not necessarily mean higher productivity or business value. The 2025 DORA Report describes AI as an amplifier of existing organizational strengths and weaknesses. Similarly, a 2025 METR study found that experienced developers took longer on specific open-source tasks when using AI tools, challenging the assumption that AI adoption automatically improves productivity. Staff Engineers must ensure engineering quality matches implementation speed. For example, a team using AI to generate multiple services may produce code that works independently but introduces inconsistent error handling, duplicated logic, or unnecessary complexity upon integration. Technical leaders should look beyond code output and encourage teams to evaluate maintainability, security, integration, and business outcomes. Producing more code is easy; ensuring the organization can operate and evolve it remains a core engineering responsibility. Preserving Critical Thinking and Engineering Knowledge AI can explain unfamiliar code, propose algorithms, recommend dependencies, and generate documentation. However, its responses may include incorrect assumptions, fabricated references, or convincing but inaccurate explanations. Research on automation bias and cognitive offloading shows that while lowering cognitive effort is not inherently negative, accepting automated suggestions without independent verification can undermine engineering judgment. Consider an engineer who uses AI to generate code but cannot explain the design choices or potential production failures. The team gains code without gaining the knowledge needed to maintain it. AI-generated documentation poses a similar risk: more documents do not guarantee accuracy or understanding. Staff Engineers should foster a culture where questioning AI-generated solutions is expected, engineers can justify their decisions, and people remain responsible for understanding the software. Avoiding New Organizational Bottlenecks AI can speed up individual work, but architectural decisions, integration, and cross-team dependencies still require coordination. Research on Collaborative Overload shows that collaboration can become concentrated among a few employees. In software engineering, this relates to the Bus Factor, where too few people hold critical knowledge. AI can worsen these issues if teams generate solutions faster than leaders can review or coordinate them. Consider a Staff Engineer reviewing architectural changes across multiple teams. As AI accelerates implementation, more decisions require validation, but the organization’s decision-making capacity does not increase. The solution is not to speed up reviews, but to establish architectural guidelines, share knowledge, and develop engineers who can make informed decisions independently. Otherwise, AI may boost individual productivity while reducing organizational scalability. These challenges emphasize a key point: adopting AI does not automatically improve engineering effectiveness. However, the same technology that exposes weaknesses in quality, knowledge sharing, and joint effort can also help address them. With effective technical leadership, AI can enhance how teams learn, experiment, and deliver software. Opportunities AI Creates for Technical Leadership While AI creates challenges, it also lets Staff Engineers rethink team workflows, distribute responsibilities more effectively, and deliver more value. The main opportunity isn't just increased code output, but empowering more engineers to participate in architectural decisions, strategic projects, and innovation. Democratizing Software Architecture and Planning Engineering As AI reduces the effort needed for routine implementation, code generation becomes a commodity. This shift allows more engineers to move beyond implementation and engage in software architecture, technical strategy, and business discussions. Instead of limiting these responsibilities to a few senior professionals, Staff Engineers can promote greater participation in evaluating trade-offs, understanding business needs, and making technical decisions. However, access to AI does not automatically develop architectural expertise. Staff Engineers should guide this transition through mentoring, shared principles, and opportunities for engineers to exercise judgment. The goal is not to make everyone a software architect, but to build teams that think beyond code and understand the impact of their decisions. Turning Information Noise Into Engineering Knowledge AI makes information easier to generate, but not always easier to trust or understand. Teams can quickly produce documentation, explanations, recommendations, and technical alternatives, which may lead to information overload. Staff Engineers should establish practices that value relevant, verified knowledge over volume, ensuring documentation backs engineering decisions rather than creating noise. This entails encouraging concise documentation, validating AI-generated explanations against actual system operation, and keeping clear records of key architectural decisions. Rather than measuring knowledge sharing by document count, technical leaders should focus on whether engineers understand systems, take informed decisions, and work independently. Allowing Faster Experimentation and Innovation AI can lower the cost of exploring technical alternatives, building prototypes, and evaluating architectural hypotheses. Engineers can test different approaches before committing significant resources, letting teams explore options that once demanded considerable effort. For Staff Engineers, this is an opportunity to encourage ingenuity while ensuring experimentation matches business priorities. However, generating more alternatives does not guarantee better decisions. Technical leaders should help teams distinguish promising experiments from unnecessary complexity, specify clear evaluation criteria, and validate results before adopting solutions. The real advantage is not more frequent experimentation, but faster learning and better-informed decisions. These opportunities suggest that AI’s greatest contribution to technical leadership may be expanding what teams can achieve together. The next challenge is to turn this potential into lasting organizational scalability without creating new dependencies or compromising engineering ownership. Conclusion: AI Amplifies Capabilities, Leadership Amplifies Teams AI is transforming software development, but software engineers' core responsibilities remain unchanged. Understanding problems, evaluating trade-offs, maintaining quality, and owning technical decisions are still essential. The primary shift is the increased speed at which decisions, both positive and negative, can impact an organization. For Staff Engineers, the challenge is not just adopting AI, but also fostering technical maturity, autonomy, and critical thinking within their teams. Ultimately, successful technical leadership is measured not by code volume or AI adoption, but by the team's ability to deliver reliable software, make informed decisions, and drive continuous improvement. AI can enhance engineering capabilities, but it cannot replace human judgment. Engineers remain responsible for thinking, questioning, and leading, while technical leaders must develop these capabilities across their teams.
Many quality engineering teams have started using agentic AI testing. They connect an agent to their app and give it a human-readable task like “Test the checkout flow and tell me if anything is broken.” And it often works great! A few minutes later, they have their answer. However, if they send that same request tomorrow, even with the same exact code set, that “great” answer might just change. This happens because the agent takes an alternate route through checkout. Or tests different details. Or uses different test data. Regardless of the why, the test just isn’t consistent. In fact, in a recent experiment, Slack’s engineering team showed that only about 20% of runs follow the exact same sequence of actions … even with the same detailed prompts! This is a problem for regression tests and audits, or anything else that needs to be consistent. If a regression test fails, you need to know it’s the application that changed, not your test. In this article, I’ll show you how to use AI agent workspaces to make agentic quality engineering more repeatable. What Is an AI Agent Workspace? An AI agent workspace is a single controlled place for building and running your test agents. It’s a platform where you design your AI test agents, build the workflows they follow, then run and monitor those workflows. Workspaces help control agent sprawl (prompts and agents scattered across tools and teams) and give you a single location for governance and maintenance. Workspaces are typically built from three components: A workflow that defines the steps.An AI agent that executes each step.Tools that connect agents to services like Jira, GitHub, or your test management system. Two key features of workspaces include: Approval gates that pause the workflow, allowing a human to review output before continuing on.Saved workflows that run the same defined steps every time, using the same instructions and same toolset. Setting Up an AI Agent Workspace for Regression Testing Let’s look at how you can do this in the real world. First, as with many solutions, you can build your own AI agent workspace or buy one off the shelf. Building Your Own Workspace If you want to build it yourself, take a look at LangGraph. LangGraph is an open-source framework that gives you the needed workflow structure and human-in-the-loop checks. With LangGraph, you’ll need to custom-build some of the functionality yourself, especially around the testing itself. At a high level, you'll need to: Write the workflow in code (including handling failures)Generate the testsWrite the logic for checking for duplicate testsAnd wire in your test tools. Once it’s running, you’ll need to maintain it, including keeping a run history for audits and updating things when your tools or models change. Building makes the most sense if you need full control over your models and where your data lives, or if for some reason you can’t use the test tools a commercial workspace is built around. Using an Off-the-Shelf Workspace Let’s look in detail at an example of perhaps the more common choice, integrating off-the-shelf software. For our example, we’ll use Tricentis AI Workspace. It fits well into our definition as it uses the three key components: workflows, agents, and toolsets. In this case, a toolset can connect to other products such as Tosca Cloud, qTest, and NeoLoad, or popular outside services like Jira and GitHub. To start, we’ll use the workflow assistant. We’ll tell it about our goals, inputs, and branching. Let’s use a common real-world case: a checkout regression suite. In our example, Story PROMO-214 just came in and adds promo codes to the checkout. We want to create new tests for whatever isn’t yet covered, plus make any updates to existing tests. We definitely don’t want duplicates. And we don’t want anything saved until a human validates everything. First, let’s describe the workflow to the AI assistant. We might start with something like this: Shell Create a workflow with three inputs: a Jira ticket ID, a qTest project name, and a qTest module name. Read the requirements and acceptance criteria from the ticket. Generate test cases with the Tricentis Quality Agent. Wait for the generation job to finish, and end the workflow if it fails. Compare the generated test cases with the existing test cases in the qTest module, and propose which ones to create, update, or delete. Don’t change anything in qTest until a person approves it. From here, the assistant may ask a few follow-up questions. It then creates any agents the workflow needs, connects the steps, and activates the workflow. Once it’s built, we can go back into the agents it created or reused and refine them. Making the Workflow Repeatable Here’s where it can get a little tricky. The workflow above defines the steps, but each step still runs using an LLM, so the same step can produce different output on different runs. The prompt we just wrote is only used to build the workflow. On each run, every step follows its own agent’s settings and instructions, so that’s where we tighten things up. Tools. Give each agent just the tools it needs. Our Jira reader, for example, just gets read access to Jira. The step that compares test cases doesn’t need any tools at all. And only the last step is allowed write access to qTest. When you set up each agent, you pick its tools from a list.Temperature. This controls how random, or creative, the model is allowed to be. In AI Workspace, temperature runs from 0.0 to 2.0. Some newer models don’t accept a temperature setting at all, so check yours. But keep in mind that even a temperature of 0 doesn’t guarantee identical output! You’ll find Temperature under each agent’s Advanced settings.More specific instructions. Clearly spell out the rules and output format in each agent’s instructions. This way the model has less room for interpretation. For example, here’s what I’d give the comparison agent: Shell Compare the generated test cases with the existing qTest test cases from the earlier steps. Score each match on keyword overlap, test functionality, and test step content. Exclude matches below 70%. Return JSON with one entry per test case: the action (create, update, or delete), the matching qTest case ID (if any), and a one-line reason. Never propose a new test case without a requirement behind it. Fail if a test requirement is missing. To add approval gates, open the relevant workflow step, select Enable approval gate, and turn on Require approval. When we run the new workflow, we enter a ticket ID, a qTest project, and a module. The workflow reads the ticket, generates the tests, compares them with what’s already in qTest, and waits for a person to approve the proposed changes. This is where repeatability comes from. The workflow creates tests the same way each time, and once they’re saved in qTest, they follow the same exact steps on every run, whether a tester runs them or you automate them in Tosca. A workflow can kick off manually, on a schedule, or with an event. For PROMO-214, we want the workflow to start when the story moves to Ready for QA. Jira Automation can watch for that status change and send a POST request to the workflow’s webhook URL. And what about audits for when things go wrong? Workflow runs are tracked, so each one appears in the run history, and you can export it. Using Templates AI Workspace comes with templates that can help you get started: “Find and update relevant test cases.” Starts by reading a Jira ticket. Then it generates tests, checks them against your existing qTest cases, and updates qTest. There are three approval gates along the way, including a final one before it changes your qTest project.“Test coverage analyzer.” Compares requirements with qTest cases and reports an estimated coverage percentage.“Get your test requirements ready.” Runs before testing starts. It flags vague or missing acceptance criteria in your requirements and drafts questions for whoever wrote them. Here’s how “Find and update relevant test cases” looks. It’s very close to what we just asked the assistant to build. If we started from this template for PROMO-214, I’d keep all three of its approval gates: On the generated tests. Does a 10% code really take $10 off a $100 cart?On the change proposal. A test lead checks proposed updates/deletes, watching for a test, for example, that’s marked for deletion but is still needed.Before the write to qTest. A final review before anything changes. What Still Needs a Human in Agentic Quality Engineering You could save your workflow here and start testing. But I wouldn’t. A bad decision saved into a workflow … is a bad decision that repeats on every single run. So I like to keep a few steps with the humans. First, human approval gates are always a good idea just as a sanity check before an agent’s output reaches your test repository, or anywhere else that’s hard to clean up. Humans also should decide if a test is checking the right thing. Distinguishing correct behavior from incorrect behavior is what researchers call the oracle problem, and it’s been a bottleneck in test automation for a long time. One recent study of LLM-generated unit test assertions across 24 Java projects, with the code in the prompt, found that LLM-based test generation approaches “mainly capture the actual program behavior.” In other words, an LLM that reads your code tends to treat whatever the code actually does as correct. Finally, someone should check the actual coverage. A number in a coverage template is just an estimate of how well your tests match requirements. I’d have a person spot-check the matches before anyone reports an official coverage number. Conclusion My readers may recall my personal mission statement, which I feel can apply to any IT professional: “Focus your time on delivering features/functionality that extends the value of your intellectual property. Leverage frameworks, products, and services for everything else.” - J. Vester I don’t know anyone whose intellectual property became more valuable from retyping a test prompt and hoping for the same result. With an AI agent workspace, that job goes to a saved workflow, and your team gets to decide what to test and what the right result is. Have a really great day!
Most of our tickets end the same way now. Someone copies the issue text into Claude Code or Codex, adds “look at the memory notes first,” waits, pushes a branch, opens a PR, and pastes the link back into the ticket. The work is done by the agent. The glue around it is done by hand, and nothing records which run produced which PR, what it cost, or why the first try failed. So we moved the glue into Origin. An issue now has a Start with button. It hands the issue to an agent that runs on your own machine, in its own worktree, and the run is recorded on the issue: who ran it, which agent and model, how long, what it cost, how many lines, and whether its PR was merged. This post shows how it looks and what it does. A separate write-up covers how we built it. One List, Every Source Issues come from five places and land in one list: GitHub and GitLab issues (two-way sync), Jira, issues created in Origin, security alerts from Dependabot and code scanning, and TODOs that agents left in the repo’s memory notes. The list sorts by priority and filters by repo, source, and assignee. Each row shows the source, labels, priority, and, once an agent has worked on it, the number of sessions and the AI cost. The host stays the owner of what it owns. Title, body, labels, assignees, and open/closed come from GitHub or GitLab, and Origin writes assignees back. Origin owns the states the host does not have: in progress, in review, and blocked. Start With an Agent The menu lists the agents Origin can launch headless: Claude Code, Codex, Gemini CLI, Cursor, Copilot CLI, and Antigravity. Pick one, and you get the Start dialog. The prompt is built from the issue and the repo’s memory (here, 4,418 characters and 10 lines of memory), and you can edit it before you start. Below is the exact command the button runs, so you can run the same thing from a terminal: Shell origin issue start OR-44 --agent claude --background Without Run in the background, Origin opens a terminal in your checkout with the agent and the prompt in it, and you work as usual. With it, there is no terminal. The agent runs headless in a new worktree on branch issue/OR-44-…, so your own checkout can stay dirty. When the agent exits cleanly, Origin pushes the branch and opens a PR. It never merges and never force-pushes. The run happens on your machine, with your agent CLI and your agent’s account. Origin’s server never runs code. The button opens a getorigin:// link that carries only the repo and issue IDs; the Origin CLI on your machine reads the issue with your own key and starts the agent. The full log stays in ~/.origin/agent-runs/. The server gets the status, the exit code, and the last few log lines. Before It Starts: Is the Agent Signed In, and Is the Task Clear? A signed-out Claude Code exits in a second with “Not logged in,” and for a while that run still looked completed. Now a background run first checks that the agent is signed in. If it is not, nothing starts, no worktree is made, and the issue shows a failed run with the reason. The Agents page shows the same check per machine; above, the last background Claude run on this MacBook could not sign in. The second check is about the task. A one-line issue leaves the agent guessing, and a background agent has nobody to ask. So before a background run, Claude or Codex reads the repo in a read-only mode, without hooks and without saving a session, and answers one question: is this clear enough to do? If yes, it writes a short brief (files and approach) into the prompt. If not, it asks up to three questions. They appear on the issue; nothing starts, and you answer on the page or with: Shell origin issue answer OR-44 "Keep v1 readable; consumers must handle both" A run can also stop and ask halfway. When you answer, the next start resumes the same agent session (claude --resume, codex exec resume) if that session is on this computer, so the agent keeps what it already read. Otherwise it starts fresh with every answer in the prompt. Every Attempt Stays on the Issue This issue was not written by a person. Claude Code left it as a TODO in the repo’s memory during an earlier session (“the header’s tokens, cost and tools chips still come from the old session totals”), and Origin turned it into an issue. Antigravity took it twice. The first run failed, and the table says so; before we recorded runs, a run that died before the agent’s first hook fired left no trace at all. The second run worked for 30 minutes and opened PR #2487 with +846 −70 lines in 9 files. The issue moved to In review on its own. Each row links to the captured session, so you can read every prompt, tool call, and diff of that run. Status follows the work: start or claim → in progress, PR open → in review, PR merged → closed, PR closed unmerged → back to in progress. An agent can also end with a line like [Origin: Outcome] blocked — which schema version?, and the issue goes to blocked with that question on it. Race Two Agents on the Same Issue If you are not sure which agent is best for a task, give it to two to four of them. Each runs in the background on its own branch from the same base, and each one that finishes cleanly opens its own PR. Merge the best one, and the issue closes. This one was a Dependabot alert for source-map-js. Origin turned it into an issue with acceptance criteria (the lockfile no longer resolves a vulnerable version, tests pass). Claude’s PR was merged at $0.50. Codex’s PR was closed; it cost $0.96 and used about ten times the tokens. Over a few dozen issues, that table tells you which agent to give which kind of work. For closed issues, the page also gives a origin benchmark replay-tasks command, so you can replay the issue on other agents later and grade them against the tests the merged PR added. Agents That Pick Up Work Themselves The Start button is one way in. The other is the queue. Origin’s MCP server gives agents list_tasks, take_task, finish_task and release_task. An agent in a session can take the next ready issue, and two agents can never take the same one: a claim is a single conditional database write, so exactly one of them wins, and the others get “claimed”. A claim is a lease (30 minutes by default) renewed by the session’s heartbeat. If the agent dies, the lease runs out, and the task is free again, without a cleanup job. Issues with open dependencies are not served. What It Will Not Do Run anything on Origin’s servers. The agent runs on your machine, with your installed CLI and your account.Use a blanket permission bypass. Each agent gets the narrowest unattended mode it has: Claude’s --permission-mode auto, Codex’s workspace-write sandbox, a per-run Antigravity project allowed only git and read-only commands with no network, a scoped .cursor/cli.json.Merge, or force-push. It opens a PR and stops.Run forever. Background runs stop after 120 minutes by default, together with every process the agent started.Send the whole log to the server. Only the status and the last lines. Try It You need the Origin CLI, and at least one agent CLI signed in. Run origin url-handler install once so the Start button can reach your machine, then open Issues and press Start with. From a terminal, it is origin issue start <id> --agent codex --background, origin issue race <id> --agents claude,codex and origin issue runs to see what is running.
The Number That Didn't Make Sense A few months ago, I was looking at our delivery numbers, and something felt off. Pull requests merged were up. Commits were up. By every activity metric we tracked, the team was producing more than it had before we rolled out AI coding tools in earnest. And yet features were not landing faster. If anything, the time from "code complete" to "in production" had gotten worse. I sat in on a few review queues to understand why. What I found was not lazy reviewers or careless authors. It was six senior engineers staring at pull requests that were three, four, five times the size they used to be — trying to hold an entire AI-generated change in their heads and decide whether they trusted it. We had automated writing code. We had not changed anything about how we verified it. So the bottleneck didn't disappear. It moved. This Is Not Just My Team The data coming out this fall says the same thing at scale. Qodo's 2026 State of AI Code Quality Report, published in September, found that developers and engineering leaders independently ranked the same problem first: reviewing and validating AI-generated code is now the top bottleneck preventing AI from actually accelerating delivery. It was also the most-cited quality and governance gap among leaders, at 48%. Other analyses put numbers on the queue itself. AI-generated pull requests wait far longer for review than human-written ones. Review time has climbed sharply even as merge counts climb. One widely cited analysis of millions of pull requests described the gap plainly: developers feel about 20% faster with AI, and measure about 19% slower. That gap — feels faster, ships slower — is the tell. If your team feels busy and productive and your releases are still slipping, look at the review queue before you look anywhere else. There is a debate on Hacker News right now about whether AI is lowering code quality. I think that debate is asking the wrong question. The sharper version I saw in that thread was this: if AI-generated code is lowering your quality, that is a management failure, not a tool failure. I agree with that more than I'm comfortable with. Because it puts the problem on my desk, not the vendor's. Why Review Breaks First Review was designed for a world where writing code was the expensive part. A human author wrote a change slowly, understood most of it, and a reviewer checked the parts the author might have missed. The sizes were manageable because human typing speed was a natural limiter. Nobody opened a 900-line pull request on a Tuesday afternoon by accident. Agents removed that limiter, and nobody redesigned what came next. Now the author often didn't write the code in the traditional sense at all. They prompted it, skimmed the output, and opened the PR. Which means the first person to truly read the code is the reviewer. Review stopped being a check. It became the reading. Add one more thing: reviewers don't trust this code the way they trust a colleague's. Qodo calls the extra effort a "trust tax" — reviewing AI code takes about the same clock time as before for many developers, but with noticeably more cognitive effort. I recognize that tax. You read an AI change differently. You are not just asking, "Is this right?" You are asking, "Does the author actually know why this is here?" Multiply that by twenty or thirty PRs a day across a team and the math stops working, no matter how good your engineers are. What I Changed — and What I Didn't My first instinct was wrong. I considered adding review capacity: rotate more seniors into review, set response-time targets, nag the queue down. That treats review like ticket triage. I have lived that life before in operations, where the answer to a growing queue was always more hands on the queue — right up until we automated the queue itself. Queues that grow because of a system design problem don't get fixed by staffing them harder. So we changed the system instead. We tiered review by risk, not by habit. A config change, a test addition, and a change to a production data path used to get the same review ritual. They don't anymore. Low-risk, reversible changes get a lighter path — automated checks, an agent pre-review, and one human who is accountable for the merge. High-risk changes get the opposite: smaller scope, mandatory second reviewer, and no merge until someone can explain the change without the AI summary open in front of them. We made PR size a team problem again. Agents will happily generate a sweeping change because sweeping changes are easy to generate. We set an expectation that large changes get split before review, by the author, not discovered by the reviewer. If a change is too big to review well, it is too big to merge. That one rule did more for our queue than any tool we bought. We put the agent to work on review — inside an authority boundary. An agent pre-reviews for the mechanical things humans are bad at catching when they're tired: missing tests, inconsistent patterns, risky calls, changes that don't match the description. It posts that as a first pass. It does not approve. It does not merge. Approval is a judgment call, and in my world judgment calls stay with humans. This is the same authority envelope I apply to agents in operations: automate the execution, keep the irreversible decisions with people. We started measuring verification, not just production. For years my dashboards celebrated output: PRs merged, story points, commits. Now I want to see review wait time, PR size distribution, rework after merge, and how often a change that passed review still caused an incident. If AI is going to be judged, judge the whole workflow, not the typing. The Part Leaders Keep Missing Here is the uncomfortable part for people in roles like mine. Ninety percent of engineering leaders in that Qodo study said they were confident reporting AI's impact to executives or the board. Only 45% said they had evidence tracing AI activity to the code changes it produced. Read that again. Most of us are reporting confidence we cannot actually trace. I don't think that's dishonesty. I think it's that our metrics were built for the old workflow, where output was a decent proxy for progress. It isn't anymore. When an agent can produce output on demand, output stops meaning anything. Verification is where the value — and the risk — actually sits now. So if you are a director or a head of engineering being asked "what are we getting for our AI spend?", the honest place to start is not a productivity chart. It's three questions: Can you trace which changes in production were agent-generated? Can you show what your review system caught before merge, and what it missed? And is your time-to-production getting better, or just your time-to-first-draft? If you can't answer those, you don't have an AI strategy yet. You have an AI purchase. Where This Goes Next I don't believe the answer is less AI code. The genie is not going back in the bottle, and honestly, I wouldn't put it back if I could. The agents are good at the execution work. That's the same lesson I learned moving operations from manual runbooks to agentic systems: let the machines do the work that doesn't require judgment, and protect human time for the work that does. Review is judgment work. It just got buried under a pile of execution volume. The teams that win this next phase won't be the ones that generate the most code. They'll be the ones that rebuilt verification — review, testing, evals, observability — to run at the same speed as generation. That's an engineering leadership job. It's not a tooling purchase, and it's not a hiring plan. It's the job. At least, these days, it's mine.
If you deploy an open-weights model like Llama 3 on your own infrastructure, one of your first surprises will likely be the output of nvidia-smi: GPUNameMemory-UsageGPU-UtilOperational State0NVIDIA H100 80GB76,420 MiB / 81,559 MiB (93.7%)38%Memory-Bound Table 1: Initial GPU telemetry during generative inference (Llama 3 70B). Memory-Usage and GPU-Util are as reported by nvidia-smi; the operational state is inferred. Memory is nearly fully committed while compute cores remain largely underutilized. What you may find is that VRAM is almost full, but GPU utilization hovers between 35% and 45%. Even that 40% figure is deceptive. That column only reports the fraction of time that any GPU kernel was active, not whether compute cores were saturated — a memory-bound loop copying bytes back and forth can register high utilization while doing negligible mathematical work. The hardware isn't waiting on math; it's waiting on memory, spending most of its clock cycles moving weights and cached tokens across the bus while compute cores sit idle. To see why this happens, and how engines like vLLM, SGLang, and TensorRT-LLM fix it, we have to look at what is actually happening during generation. 1. Prefill, Decode, and the Batching Economy Every generative LLM request runs in two distinct phases: Prefill (Prompt Processing): The model ingests the entire prompt in a single forward pass. Because all input tokens are known upfront, this phase executes as large matrix multiplications. The GPU's Tensor Cores are fully saturated, arithmetic intensity is high, and processing is compute-bound.Decode (Token Generation): The model generates one token at a time. For each new token, the GPU must read every parameter in the model and all historical context from VRAM into its local on-chip SRAM cache. Because this step produces only a single token per stream, arithmetic intensity is low. The hardware is bottlenecked entirely by memory bandwidth. Because output generation requires hundreds of sequential steps while prompt ingestion takes only one, the vast majority of execution time is spent in the memory-bound decode phase. This brings us to the core reason batching matters: amortizing weight transfers. When serving a single request, the GPU must transfer roughly 140 GB of weights (for a 70-billion-parameter model in 16-bit precision, distributed across multiple GPUs) across its memory bus, just to generate one token. If you batch 32 concurrent requests together, the GPU reads the 140 GB of weights across the bus once, and reuses them to calculate output tokens for all 32 users in the same forward pass. Scaling from a batch size of 1 to 32 is sub-linear, because attention operations and KV cache access scale with batch size. But amortizing the static weight read typically yields roughly an order of magnitude increase in aggregate throughput over single-stream generation on modern hardware (which follows from the roofline scaling analysis in Pope et al., 2023). The bottleneck to higher throughput is keeping that batch size as large as possible. Traditional serving architectures, however, make this almost impossible. 2. The Limits of Static Batching and Contiguous Memory In computer vision or embedding models, static batching works reliably. You collect N inputs, group them into a single tensor, run the forward pass, and every sample finishes simultaneously. Generative text does not behave this way. Request lengths are fundamentally unpredictable. Consider four requests submitted in the same batch: Request 1 (classification): generates 2 tokensRequest 2 (short summary): generates 45 tokensRequest 3 (code explanation): generates 210 tokensRequest 4 (essay): generates 850 tokens Under static batching, Request 1 finishes after step 2. But because the batch tensor has fixed dimensions, Request 1 cannot leave GPU memory. Its slot remains locked. For the remaining 848 iterations, the GPU performs matrix operations on padded zeros for Request 1, 2, and 3 while waiting for Request 4 to conclude. Figure 1: The straggler problem in static batching. When requests vary in completion length, early-terminating requests lock GPU memory and waste compute on padding tokens until the slowest sequence completes. Why couldn't traditional systems release finished sequences and admit new ones? Because of how they allocated the Key-Value (KV) cache. The KV Cache Footprint To avoid recalculating attention for previous tokens at every step, transformers store intermediate Key and Value tensors in GPU memory. The formula for the KV cache size per token is: Plain Text bytes_per_token = 2 (K and V) × layers × kv_heads × head_dim × bytes_per_value For a model like Llama 3 70B running in 16-bit precision (80 layers, 8 Key-Value heads using Grouped-Query Attention, head dimension 128, 2 bytes per float): Plain Text 2 × 80 × 8 × 128 × 2 = 327,680 bytes ≈ 320 KB per token A single conversation reaching an 8,192-token context consumes 2.56 GB of VRAM for its KV cache alone. Serving 40 concurrent requests at that length demands over 100 GB of memory just for context, on top of the model weights. The Contiguous Allocation Problem Standard CUDA memory allocators require a tensor's underlying storage buffer to be contiguous in physical memory. Because an engine cannot predict whether an incoming request will generate 10 tokens or 4,000 tokens, naive frameworks allocated space for the sequence's maximum possible length upfront. Figure 2: Traditional contiguous pre-allocation waste. Because the runtime cannot predict completion length, it allocates contiguous VRAM for the maximum possible context, stranding the majority of memory in unused reservations. A 2023 paper (Efficient Memory Management for Large Language Model Serving with PagedAttention, SOSP 2023) by Kwon et al. showed that in production systems, 60% to 80% of the memory set aside for the KV cache was wasted. This waste resulted from three sources: Over-reservation: Space held for future tokens that the user never generated.Internal fragmentation: Fixed-size pre-allocated slots exceeding actual sequence lengths.External fragmentation: Free memory scattered in disjointed blocks too small to fit a new maximum-length request. Because memory was exhausted by empty reservations, engines were forced to severely restrict concurrent batch sizes. The GPU cores sat starved for work. 3. PagedAttention and Continuous Batching Modern serving systems solve these constraints by borrowing virtual memory concepts that operating systems developed decades ago. Figure 3: PagedAttention memory architecture. The logical KV cache is partitioned into fixed 16-token pages. A centralized block table maps logical indices to non-contiguous physical memory in VRAM, eliminating internal fragmentation and memory reservations. PagedAttention Instead of forcing a sequence's KV cache into a single continuous buffer, PagedAttention breaks it into fixed-size physical blocks (pages), typically sized to hold 16 or 32 tokens. A central Block Table tracks which physical blocks belong to which sequence. Physical blocks do not need to be adjacent in VRAM. When a request begins, the engine allocates only the blocks needed for the prompt. As the model generates new tokens, it assigns an additional block only when the active one fills up. This achieves what Kwon et al. describe as "near-zero waste in KV cache memory." With a 16-token block size, the only memory a sequence can waste is the unfilled slots in its final block — at most 15 tokens. Whether a generation finishes after 50 tokens or 5,000 tokens, the maximum possible waste per sequence is bounded by those few unused slots, driving memory waste toward zero as context grows. By eliminating fragmentation, the available VRAM can suddenly accommodate significantly more concurrent sequences. Prefix Sharing and Copy-on-Write Paged memory management unlocks a second major advantage: zero-overhead prompt sharing. In applications like multi-turn chatbots, few-shot evaluations, or multi-agent frameworks, dozens of requests often share an identical system prompt. In older systems, that shared prompt had to be evaluated and stored in memory for every single user. Under PagedAttention, multiple logical block tables can point to the same physical memory blocks. The engine evaluates the system prompt once. All subsequent requests reference those read-only physical blocks. If a request branches or appends unique tokens, the engine allocates a new private block on write (Copy-on-Write). In production setups with heavy system prompts, this substantially reduces memory usage across concurrent sessions. Continuous Batching With dynamic block allocation in place, the need for static batching disappears. Modern engines implement Continuous Batching (iteration-level scheduling, originally proposed in the Orca paper by Yu et al., OSDI 2022). In their original evaluation, the Orca authors demonstrated up to a 36.9x throughput improvement over FasterTransformer on a 175-billion-parameter model at matched latency by replacing request-level batching with iteration-level scheduling. Instead of scheduling at the request level, the engine makes scheduling decisions after every single token iteration: At each step, all active sequences execute one forward pass.If Request 1 emits an end-of-sequence token, it is evicted immediately.Its physical blocks are freed back to the memory pool.An incoming request waiting in the queue is pulled into the batch for the next step. Figure 4: Continuous batching (iteration-level scheduling). Sequences are evaluated and scheduled at every token step. As soon as a request emits an end-of-sequence token, its VRAM blocks are reclaimed, and a waiting query is immediately admitted into the forward pass. The batch stays saturated. Fast requests exit without delay; long requests continue without holding other users hostage. 4. What the Empirical Data Shows: The SOSP Evaluation To see how these architectural changes translate into real-world performance, we can look at the empirical evaluation published by Kwon et al. in the original vLLM paper (SOSP '23). The researchers evaluated inference performance on NVIDIA A100-80GB GPUs across 1, 4, and 8 GPU configurations using OPT (13B, 66B, and 175B) and LLaMA-13B. They tested against two real-world trace datasets: ShareGPT (transcripts of actual ChatGPT interactions with wide variations in prompt and completion lengths) and Alpaca. Their evaluation compared vLLM against NVIDIA's FasterTransformer and three reimplemented variants of Orca (Yu et al., 2022). The Memory Findings The paper's central discovery was the scale of KV cache memory waste in existing systems. As the authors noted: "only 20.4% – 38.2% of the KV cache memory is used to store the actual token states in the existing systems." The remaining 61.8% to 79.6% was lost to internal fragmentation, over-reservation, and external memory gaps between sequences. By contrast, PagedAttention eliminates internal and external fragmentation by allocating blocks dynamically, bringing KV cache waste down to near-zero. Throughput and Request Rates By eliminating memory waste and packing significantly more sequences into available VRAM, vLLM achieved substantial throughput gains: 2–4× higher throughput: The paper's headline finding shows vLLM improves throughput across popular models by 2–4× at the same level of latency compared to state-of-the-art baselines like FasterTransformer and Orca.Up to 22× higher request capacity: In heavy-load scenarios (§6.2), vLLM sustained up to 22× higher request arrival rates than FasterTransformer before violating target latency thresholds. Note on project launch claims: The often-cited "up to 24x" throughput number originates from the vLLM project's initial release blog, which benchmarked against unoptimized Hugging Face Transformers pipelines on A10G and 40GB A100 GPUs, rather than the peer-reviewed FasterTransformer and Orca baselines evaluated at SOSP. Why Orca Wasn't Enough: The "Oracle" Comparison The most revealing comparison in the paper is not against FasterTransformer, but against Orca. Orca was never open-sourced. To establish a rigorous comparison, the vLLM authors reimplemented Orca in three variants, differing strictly in how memory was allocated: Orca-Max: Pre-allocates memory for the model's maximum sequence length upfront (2,048 tokens in the evaluation)Orca-Pow2: A bounded reservation policy that over-reserves space for outputs by up to 2×, rounding the required reservation up to the nearest power of two (for example, reserving 32 positions for a 25-token response).Orca-Oracle: An idealized, theoretical upper bound that magically knows the exact output length of every request in advance and reserves only that amount. The critical takeaway: vLLM sustained 1.7× – 2.7× higher request rates compared to Orca (Oracle). Even when Orca was given an impossible advantage — a magic crystal ball that predicted the exact output length of every request — vLLM still outperformed it by roughly 2x. Because Orca still required each sequence's KV cache to reside in contiguous physical memory. Contiguous allocation inevitably leaves small, unusable gaps between sequences as requests start and finish. Orca proved that iteration-level scheduling fixes the compute scheduling bottleneck. But PagedAttention proved that non-contiguous paging is necessary to fix the physical memory bottleneck. Without both, an engine runs out of physical memory long before it can saturate the GPU cores. Testing on Your Own Hardware If you have access to an NVIDIA GPU and want to evaluate these dynamics on your own traffic distribution, vLLM includes built-in benchmarking utilities: Shell # 1. Start the vLLM server vllm serve meta-llama/Meta-Llama-3-8B-Instruct \ --gpu-memory-utilization 0.90 \ --port 8000 & # 2. Wait until the server is live until curl -s http://localhost:8000/health > /dev/null; do sleep 2 done # 3. Run a saturating benchmark using the ShareGPT dataset python3 benchmarks/benchmark_serving.py \ --backend vllm \ --model meta-llama/Meta-Llama-3-8B-Instruct \ --dataset-name sharegpt \ --dataset-path ./ShareGPT_V3_unfiltered_cleaned_split.json \ --num-prompts 200 \ --request-rate inf 5. Sizing the KV Cache: How Production Memory Actually Works A common source of confusion when configuring engines like vLLM is the relationship between max context length, concurrency ceilings, and physical memory. Consider this production command: Shell vllm serve meta-llama/Meta-Llama-3-70B-Instruct \ --tensor-parallel-size 4 \ --gpu-memory-utilization 0.90 \ --max-model-len 8192 \ --max-num-seqs 128 At first glance, the numbers might appear contradictory. Earlier calculations showed that for Llama 3 70B, an 8,192-token sequence requires roughly 2.56 GB of KV cache. If --max-num-seqs is set to 128, wouldn't that require 128 × 2.56 GB = 327.68 GB of KV cache? Across 4x H100 GPUs (320 GB total), after loading ~140 GB of model weights, there would not be enough memory left. The explanation is that in modern engines, --max-num-seqs is an admission ceiling, not a memory reservation. Here is how the memory is actually budgeted: Total Hardware Memory: 4 × 80 GB = 320 GB.Allocation Cap: With --gpu-memory-utilization 0.90, vLLM reserves 320 × 0.90 = 288 GB. (The remaining 32 GB is left for transient CUDA activation memory and PyTorch runtime overhead).Weight Footprint: A 70B model in 16-bit precision occupies approximately 140 GB.Usable KV Cache Pool: 288 GB minus 140 GB leaves 148 GB for the KV cache pool. At 320 KB per token, 148 GB (roughly 148 billion bytes divided by 327,680 bytes per token) accommodates approximately 452,000 active tokens. If every single user generated text out to the absolute limit of 8,192 tokens simultaneously, the pool would saturate at: Plain Text 452,000 tokens ÷ 8,192 tokens/request ≈ 55 concurrent requests In reality, most production traffic skews short. Most queries generate between 150 and 600 tokens. If the average active sequence length is 600 tokens, that same 148 GB pool can comfortably sustain over 700 concurrent requests before running out of blocks. The --max-num-seqs 128 parameter merely tells the scheduler: "Never pack more than 128 active requests into a single forward pass, even if there is free memory available." This prevents individual iteration passes from becoming excessively compute-heavy. 6. The Trade-offs and the Operational Reality Continuous batching optimizes aggregate system throughput (tokens/sec across all users). It does not improve single-request latency. If your system receives exactly one request at 2:00 AM, continuous batching provides zero speedup compared to standard Hugging Face code. Under heavy concurrent load, Inter-Token Latency will even degrade slightly because the GPU's memory bus is saturated across dozens of requests. The Prefill Bubble and Chunked Prefill When a user submits a large prompt (e.g., a 6,000-token PDF in a RAG pipeline), processing that prompt requires a compute-heavy prefill. In early continuous batching setups, a massive incoming prefill would monopolize the GPU for 200MS or more. Every active decode stream paused while the prefill finished, causing visible stutter in users' streaming text. Modern engines resolve this using Chunked Prefill (introduced by Agrawal et al. in Sarathi-Serve, 2024). The engine divides large prompts into smaller chunks (typically 512 tokens) and co-schedules them alongside active decode iterations. Chunked prefill is enabled by default in recent versions of vLLM (v0.6+). You can verify this in your server startup logs (look for the engine initialization line confirming chunked prefill is enabled). Memory Exhaustion and Preemption When traffic spikes and the KV block pool runs out of memory, the engine must resolve the shortage. Because vLLM does not pre-allocate per-request memory, it can overcommit. If the block pool is 100% full and an active request demands another block to generate its next token, the engine triggers preemption: The engine pauses an active sequence.It either swaps the sequence's KV blocks to host CPU memory, or frees them entirely.When GPU memory clears, the preempted sequence is recomputed from its prompt. Preemptions show up in monitoring as sudden, severe tail-latency spikes. 7. A Production Diagnostic Checklist When debugging inference performance on your own clusters, avoid relying on surface-level GPU utilization metrics. Instead, monitor vLLM's exposed Prometheus metrics (/metrics). Metric ObservationRoot CauseActionable Remedyvllm:num_requests_waiting > 0 and vllm:gpu_cache_usage_perc < 0.60Requests are queueing even though memory is free.Your --max-num-seqs ceiling is set too low. Increase it to allow higher batch concurrency.vllm:gpu_cache_usage_perc ≈ 1.0 and vllm:num_preemptions_total > 0The KV pool is completely exhausted. Incoming requests cause active queries to abort and recompute.Lower your concurrency ceiling, reduce --max-model-len, or add tensor-parallel GPU capacity.Mean ITL is steady, but p99 ITL shows periodic spikesLong incoming prompts are stalling active decodes.Confirm that chunked prefill is active in your startup logs. The Broader Ecosystem While vLLM popularized PagedAttention, these techniques are standard across modern inference systems: SGLang: Integrates RadixAttention, which maintains an explicit radix tree for automatic KV cache reuse across complex multi-turn and structured decoding workflows.TensorRT-LLM: NVIDIA's optimized serving framework, offering native in-flight batching and paged memory integrated directly with custom Tensor Core kernels.Hugging Face TGI: Uses continuous batching (via FlashAttention and Paged Attention kernels) tailored for Kubernetes deployments. If your generative AI workloads run on unbatched pipelines or static batching servers, moving to an engine with paged memory and iteration-level scheduling is the most reliable way to lower your cost per token and get your GPUs doing useful work. References Kwon, W., Li, Z., Zhuang, S., Sheng, Y., Zheng, L., Yu, C. H., ... & Stoica, I. (2023). Efficient memory management for large language model serving with PagedAttention. Proceedings of the 29th ACM Symposium on Operating Systems Principles (SOSP '23), 611-626.Yu, G. I., Jeong, J. S., Kim, G. W., Kim, S., & Chun, B. G. (2022). Orca: A distributed serving system for Transformer-Based generative models. 16th USENIX Symposium on Operating Systems Design and Implementation (OSDI '22), 521-538.Agrawal, A., Kedia, N., Panwar, A., Mohan, J., Kwatra, N., Gulavani, B. S., ... & Ramjee, R. (2024). Taming throughput-latency tradeoff in LLM inference with Sarathi-Serve. arXiv preprint arXiv:2403.02310.Pope, R., Douglas, S., Chowdhery, A., Devlin, J., Bradbury, J., Heek, J., ... & Dean, J. (2023). Efficiently scaling transformer inference. Proceedings of Machine Learning and Systems (MLSys '23), 5.
TL;DR: A Successful AI Pilot Proves Nothing Thesis: This article explains seven AI adoption failures that follow a successful AI pilot, from unready data to overloaded reviewers and premature cuts, and how practitioners set the standard, collect the evidence, and inspect the results before scaling anything. Your AI pilot worked: the demo impressed the steering committee, the time savings on the slide looked fantastic, and the sponsor is already drafting the rollout budget. However, the AI pilot answered a narrower question than the budget. It showed that the technology can do the task under test conditions, with clean data, a hand-picked team, and a process that mainly exists in the standard operating procedures. Two questions remain open, and nobody has collected evidence for them: whether ordinary teams can run the workflow reliably, and whether expanding beyond the pilot pays off. Here are seven AI adoption failures that keep recurring in legacy organizations in 2026, each with a warning sign you can check this week, a countermeasure, plus five questions for the scaling decision itself. You do not need to own the budget to use them, because the evidence a scaling decision needs comes from the people closest to the work: they agree on the quality standard, for example, using the AI Definition of Done before the trial, collect the evidence while the workflow runs, and inspect the delegation over time in an AI Delegation Audit. Spoiler alert for the seasoned agile practitioner: If you lived through an Agile transformation, most of the failures will look familiar. History rhymes, and AI, as Agile, is no exception. Disclaimer: I read Charniak/McDermott’s book on "Artificial Intelligence" decades ago; of course, I use AI for research, translations, proofreading, challenging story arcs and article structures, creating artifacts such as graphics, and summarization. It is a production tool, not a substitute for thinking. The AI Pilot Succeeded, and That Is the Problem A small, well-designed AI experiment that fails is cheap: it costs a few weeks, a small budget, and some pride, and it usually teaches the organization something about its data and its processes. A successful pilot, however, can become expensive because it gives the sponsor what looks like evidence for a rollout the pilot never tested. Then, once the rollout begins, the AI meets the organization as it actually runs, and the expected outcome turns into escalations, workarounds, and change requests that nobody put on the original slide. None of this makes the AI pilot worthless. Testing a narrow technical hypothesis under controlled conditions is legitimate, and curated data and motivated volunteers may be exactly the right setup. The failure happens one step later, when the organization uses the result to answer a question the pilot never asked. There are three questions hidden behind "the AI pilot worked," and each of them needs different evidence: Can the technology do this task? Evidence: performance under specified test conditions, which is what a pilot usually delivers.Can ordinary teams run this workflow reliably? Evidence: results on representative cases, the exceptions, the support requests, and the time people spend preparing the input and reviewing the output.Should we scale the AI pilot? Evidence: value that holds over months, quality the recipients accept, the full operating cost including review, and an accountable owner who can stop the workflow when it fails. Too many rollout budgets get approved on the answer to the first question alone, resulting in preventable AI Adoption failures. To keep this concrete, I will follow one hypothetical AI pilot through the article (the organization and its numbers are invented): an AI drafts the weekly stakeholder status report from Jira for one product team, the team's product manager reviews each draft, the report goes out in 20 minutes instead of 3 hours, and the sponsor now wants the same for all 40 product teams by next quarter. In an earlier article on why AI transformations rhyme with Agile transformations, I described the greenfield showcase as one of five patterns the two share. The seven failures below follow once the applause fades, grouped by when they occur. Your Part When You Do Not Own the Budget If you are a Scrum Master, Project Manager, Product Owner, Product Manager, or Agile Coach, you probably do not decide about reskilling budgets or the rollout plan. Nevertheless, you sit closer to the evidence than anyone on the steering committee, and you can do five things for one expansion decision: Observe how the workflow actually runs, workarounds included.Name the assumptions the business case takes for granted.Agree with the recipients of the output on what "good enough" means.Count the preparation, review, correction, and exception handling the output requires.Recommend continuing, changing, or stopping, with the evidence behind it. None of this gives you authority over employment policy. However, it puts something better than the pilot slide in front of the people who have that authority and will help to avoid AI Adoption failures. Before You Start: Two AI Adoption Failures Decided in the Boardroom 1. You Never Created the Conditions Classic change management applies to AI adoption as much as it applied to every reorganization before it: people need to understand what is in it for them personally, and they need to believe the answer. Too often, the official message about AI is a license announcement on the intranet, while the unofficial message, the one people hear at the coffee machine, is that AI exists to reduce headcount. People act on the second message, and it is hard to blame them for it. If you want subject matter experts to share how the work really gets done (see failure 4), they need to hear, explicitly and from someone with authority, that the organization values their knowledge and expects AI to multiply what they can do with it. Nobody becomes AI-native by licensing Copilot, and creating the environment for lasting change is, as so often, primarily a people and culture effort. The counter-example everyone seems to cite these days comes from Ingka Group, the franchisee that runs most IKEA stores. According to Fortune's July 2026 report, Ingka introduced its customer service bot Billie in 2021 and retrained the roughly 8,500 call center employees whose routine work the bot took over, instead of laying them off. Their remote sales channel generated €1.25 billion in the last fiscal year. Investing in the people did not rule out early savings, either: Ingka's own 2023 account puts Billie's savings at nearly €13 million. (The hundreds of corporate roles Ingka and Inter IKEA cut in spring 2026 were, according to Fortune, neither in the remote sales centers nor attributed to AI.) My reading of the case is that the visible decision to keep the call center employees is what made the rest work. The warning sign: Ask five people outside the AI steering committee what the AI initiative means for their job. If the answers range from "nobody told us" to "they will cut us," the trust problem is unresolved, whatever the license report says. What to do instead: This countermeasure has two parts with different owners. Leadership must commit, in writing, to what happens to the time AI frees up, who decides about it, and how much reskilling the organization will fund before the first workflow changes. From inside the team, you can ask those five people yourself, take their answers to the sponsor unedited, and give your subject matter experts a role worth wanting: they decide whether the AI's output is good enough, which is exactly what an AI Definition of Done writes down. 2. You Gave It the Wrong Job The second failure begins with a list of use cases compiled by asking "Where can we use AI?" instead of "Where does our work wait, break, or get redone?" The answers then point AI at the wrong job in two ways. The first kind of wrong job needs no model at all: a weekly report that a spreadsheet formula could assemble, or a routing decision that a simple rule could make. A language model does such tasks less reliably and at a recurring cost. The question I now ask before the A3 Framework's three categories, Assist, Automate, and Avoid, is: "Does this task need a model at all?" If a rule, a script, or a feature of a deterministic system you already use can do it reliably, it is not an AI task. In the status report example, counting tickets per status and listing what moved since last week are jobs for a Jira filter or dashboard; the model earns its place only in the part that needs interpretation, such as explaining what the numbers mean for the stakeholder's next decision. The second kind of wrong job is a step that is not the bottleneck. If drafting a proposal takes 2 hours and its approval takes 3 weeks, an AI that drafts in 10 minutes saves time you can measure, yet it barely changes the lead time the customer experiences. Agile practitioners know this from flow metrics: accelerating a step that is not the constraint does little for the whole system. The warning sign: Your list of AI use cases has no column for where work waits, and nobody asked whether a simpler, deterministic solution exists. What to do instead: Map one value stream from request to delivery, find where the work waits longest, and ask of each candidate step whether it needs an AI model at all, before anyone discusses which model. From Pilot to Production: Three AI Adoption Failures in the Trenches 3. It Only Works in the AI Pilot The pilot's data was usually prepared for the AI pilot: someone picked a clean extract, removed duplicates, filled in missing fields, and decided which of three customer records was the real one. Production data comes without that service, often from several "sources of truth" that may contradict each other. The hypothetical pilot team closed its stale tickets and added the missing estimates before the first run, while the boards of the other 39 teams still carry tickets nobody has touched for a year and statuses that contradict the comments. In February 2025, Gartner put the condition plainly: according to analyst Roxane Edjlali, AI-ready data must be "representative of the use case," including its errors and outliers. A carefully built evaluation set can be representative by design, so curation, as such, is not the problem. The problem is a data set someone cleaned so that the pilot would succeed, combined with a business case that assumes nobody will ever have to do that cleaning again. The warning sign: Ask who prepared the pilot's data and how long it took. If the answer involves a person cleaning records by hand, find out which part was a one-time cleanup and which part recurs every week. The recurring part needs a person in production, too, and the business case probably does not include them. What to do instead: Test the workflow on a representative sample from the production system, messy cases and important exceptions included, in an environment your data protection and security people have approved. (Pushing a raw production extract full of customer records into an AI pilot tool can create a compliance problem of its own.) Then count how many cases need a human to repair the input first, because that number belongs in the business case. 4. You Can't Automate a Tangle Behind the process documentation of every legacy organization sits a second organization that actually keeps the work alive. Its members know whom to call when a shipment is stuck, how to work around a standard operating procedure that no longer describes reality and stands between the customer and the value, and when to simply ignore a rule to get things done. None of this is written down, which is one reason why it works, and also why nobody outside the team sees it. When you automate the documented process, you automate the fiction. The AI works from the standard operating procedure, and it may misread that procedure or depart from it in ways nobody anticipated. Meanwhile, the human workarounds drop out of the loop, and exceptions that used to be resolved with a phone call turn into escalations. Back in the status report pilot, the team's experienced product person knew that "In Review" on her board means "waiting for the vendor," and she corrected every draft accordingly before sending it. Nobody counted those corrections, and none of the other 39 teams has her. To make matters worse, the people who know the workarounds are often the same people who fear for their jobs (see failure 1), so they have little reason to volunteer what they know. The warning sign: Nobody on the AI project has spent a day with the people who do the work, and the process map came from the quality management handbook. What to do instead: Sit with the people who do the work and ask, "What do you do when this step fails?" For the workflow you want to delegate, and only for that one, write down the workarounds and handoffs, then decide which exceptions to keep, which to remove, and which to leave with people. That takes a few hours with the team instead of a process redesign program, and the result is the task split between human and AI that an A3 Handoff Canvas records before an agent takes over any work. 5. You Rolled It Out Everywhere at Once Giving everyone a license so that people can try things can be a reasonable decision. It turns into a failure when the organization treats that access as the rollout of a workflow it now depends on: it licenses Copilot for everyone, publishes a prompt guide on the intranet, and calls it a day. The Agile version of this pattern was the mandate from above combined with training treated as optional. The AI version adds a twist, however: the tool works well enough on individual tasks that the license report looks like success. For the status report, the big-bang version is 40 teams switching on the same Monday, with a prompt guide and no AI Definition of Done, so each team decides for itself what "checked" means. I have to include myself here. When I ran the founding workshop for my A3 Delegation System with practitioners in September 2026, their feedback was that the complete system overwhelmed them, and everyone took a rather cavalier approach to the preparation material. If motivated volunteers in a workshop feel that way, an organization-wide rollout with a license and an intranet page faces worse odds. I drew my own conclusions: the next workshop runs as three sessions instead of two long days, and in short formats, I now start with 2+2 templates instead of the whole system. The warning sign: Your rollout dashboard reports licenses activated and prompts sent, and it has no line for a workflow that changed. What to do instead: Start with one team and one workflow, support it with real training and someone to call when things break, and add the next team when the first one can explain what changed in its work, what it stopped doing, and what the change costs in review time. Once It Runs: Two AI Adoption Failures That Show Up in the Numbers 6. Your Experts Become the Queue AI on top of a dysfunctional operation accelerates the dysfunction, as I argued for Product Backlog management in AI on Top of a Dysfunctional System, and in most organizations, the acceleration shows up first in review capacity. The visible symptom is a sharp rise in the volume of artifacts: more drafts, reports, specifications, code, and slide decks than ever before. However, decisions do not happen any faster, because the bottleneck has moved to judgment, meaning the few people who understand the business well enough to check the AI's output for quality and compliance. They now review far more than before, on top of their regular work, and they either become a queue, which cancels the speed gain, or start waving things through, which hands the risk to your customers and your compliance function. (Remember Tobi Lütke's "slop grenades"?) For the status report AI pilot, this means that 40 AI-drafted reports a week land with the same three people in the PMO who know which numbers the board will question. At the same time, the stakeholders receive more reports than ever without deciding anything sooner. Three numbers tell you which way it goes: the review time per output, the share of outputs accepted without changes, and the time from output to decision. The break-even test I described in Measuring AI Impact uses the first two, and its simple form rests on two assumptions: a failed output means doing the task by hand, and every minute people spend on the workflow counts, including prompting and preparation. In short, compare the total human effort with and without AI at the quality the recipients accept. A high acceptance rate is good news, though, only as long as someone still spends real time on the review, which is what the creep check of the AI Delegation Audit watches. The warning sign: The volume of AI-generated artifacts rises, decisions do not get faster, and the same handful of experts appear as reviewers on everything. What to do instead: Budget review capacity before you scale generation, and protect your experts' time accordingly. Track the review time per output and the time to decision next to the volume, and treat every hiccup as a diagnosis of the underlying process before you speed it up any further. 7. You Bet Production on a Promise The last failure is probably the hardest to undo. The organization treats the AI pilot's result as a promise about production and then cuts headcount, retires the old process, or stops maintaining the fallback before production evidence exists. It often starts with the job description the sponsor gave the AI in the first place: delivering a cost saving by a budget deadline, before the workflow has shown that saving under production conditions and at its full cost. Erik Brynjolfsson, Daniel Rock, and Chad Syverson described the productivity J-curve at the level of national statistics: general purpose technologies require large, mostly intangible investments in new processes, skills, and business models, so measured productivity can look worse at first and better only later. A 2025 Census Bureau working paper by Kristina McElheran, Brynjolfsson, and colleagues found a similar shape inside firms: American manufacturers that adopted industrial AI saw short-term losses, concentrated among older businesses, while earlier adopters that survived grew faster over time. Among older plants, abandoning structured production-management practices accounted for roughly a third of the losses. Although the data covers industrial AI from 2017 to 2021, and dropping management practices is not the same as retiring a manual fallback, the analogy to a legacy organization that retires its old process too early is so close that you cannot ignore it. The dip, however, does not permit keeping a failing initiative alive indefinitely, which is why the evidence that would end it has to be agreed on before the dip starts. And in the status report pilot, the analyst who used to compile the reports by hand moves to another team, and three months later, when the AI's figures start to drift, nobody remembers how the reports were built, or who checks them when the responsible product person is on vacation. The warning sign: The business case shows payback within the budget year, and the old process, or the people who ran it, are already gone. What to do instead: Keep the fallback alive until production data, not AI pilot data, supports the claim. Name who checks the output when the usual reviewer is absent, and agree in advance what evidence at month six would tell you that you are in the dip and not at a dead end, including the result that makes you stop. Before You Expand or How to Avoid AI Adoption Failures: Five Questions for One Workflow The seven countermeasures come together in one decision: whether to scale a single workflow. Before you take that decision to the steering committee, check whether you can answer the following five questions with evidence, each of which already has a place in the A3 Delegation System: Does the task need a model at all, and what should improve? Name the baseline and the improvement you expect, so that "more output" cannot quietly become the success criterion; this is the question I now ask before the A3 Framework's three categories.Does it work on representative cases? Show results on a sample that includes the messy cases and the important exceptions.What does it cost in human effort? Count preparation, prompting, review, correction, and support, and compare the total with the effort without AI.What does "good enough" mean? An AI Definition of Done, agreed with the recipients, makes the quality standard inspectable: which claims get checked, by whom, and against which source.Who owns it, and how do you stop it? The "Validation" and "Failure response" fields of the A3 Handoff Canvas name who checks the output, what the fallback is, what the stop rule says, and who owns escalation. After the expansion, the AI Delegation Audit asks the same questions again, monthly or every other Sprint, because a workflow that passed once can drift: the inputs change, the model changes, and review time falls toward zero without anyone deciding so. What This Looks Like in Practice: An Extract From the Course The AI4Agile Online Course v4 includes a Jira Status Report Exercise that turns this article's running example into practice, set at MegaBrain.io, the fictional startup the course uses as its teaching case: a Jira export with 296 tickets across 58 columns, six findings planted in the data, and a CTO who needs a report he can defend in front of the founders. Before touching the AI, the student writes an AI Definition of Done for the task class "Status report for the CTO from a Jira export." Here is a condensed extract from my solution: Verification level: I trace every figure and every claim that would change the CTO's decision back to the export, record the assumption behind each one, and label what the export cannot support.Provenance disclosure: AI-assisted, with a closing line that names the assistant, the export, who checked the figures, and when.Sufficiency tier: A model that runs code on the uploaded file, because counting 296 rows is a calculation. A mid-tier model is my starting tier for this exercise, and it stays only as long as its reports pass this standard. When I tested the exercise in October 2026, three runs on ChatGPT and Claude all produced correct figures, and yet the drafts disagreed on the capacity assumption that decided the answer and on what to recommend. Correct arithmetic, therefore, settles only part of the check: the student still has to examine the assumption that connects the figures to the recommendation, which is why the AI Definition of Done asks for the assumption behind every figure, and why the student writes it before the first run. AI Adoption Failures – Conclusion: Start With One Workflow You Can Reach The seven failures feed each other: missing trust keeps the workarounds hidden, hidden workarounds and prepared data make the pilot unrepresentative, and an unrepresentative pilot justifies the big-bang rollout and the bet on a promise. Fixing the trust problem of a whole organization is rarely in your hands. However, you can start with one workflow you use or support, sit with the people who run it, write the AI Definition of Done together with the recipients of its output, and count the review time. When an expansion decision comes up, with or without a steering committee asking you, your answers to the five questions are ready. Key Questions This Article on AI Adoption Failures Answers Why Do Successful AI Pilots Fail in Production? A successful AI pilot usually shows that the technology can do a task under test conditions: prepared data, a motivated team, and a documented process. Production raises two further questions: whether ordinary teams can run the workflow reliably and whether expanding it pays off. Those require different evidence: representative cases, including exceptions; the human effort for preparation and review; an agreed quality standard; and an accountable owner with a fallback. How Can an Organization Tell Whether Its Data Is Ready for AI? Data is ready for AI when it represents the actual use case, including its errors, outliers, and exceptions, as Gartner analyst Roxane Edjlali puts it. A practical test is to run the AI on a representative sample from the production system, in an approved environment, and count how many cases need a human to repair the input first, separating one-time cleanup from preparation work that recurs every week. Why Does Scaling AI Output Overload the Experts Who Review It? When AI multiplies the volume of drafts, reports, specifications, and code, the capacity to judge that output stays flat. The bottleneck moves to the few experts who understand the business well enough to check quality and compliance, and they either become a queue or start waving work through. Teams should budget review capacity before they scale generation and track review time per output and the time to decision to avoid classic AI Adoption failures. What Is the Productivity J-Curve, and What Does It Mean for AI Adoption? The productivity J-curve, described by Erik Brynjolfsson, Daniel Rock, and Chad Syverson, explains why general purpose technologies such as AI can first depress measured productivity: organizations must invest in new processes, skills, and business models before the gains appear. A 2025 Census Bureau study found a similar pattern among manufacturers adopting industrial AI, concentrated in older businesses. Cutting staff or retiring the fallback before production evidence arrives can turn a temporary dip into a lasting failure. What Evidence Should a Team Have Before Expanding an AI Workflow? Before expanding, a team should be able to show the baseline and the intended improvement, results on representative cases and important exceptions, the total human effort including preparation, prompting, review, and correction, an agreed quality standard such as an AI Definition of Done, and an owner with a fallback and a stop rule, as recorded on an A3 Handoff Canvas. After the expansion, an AI Delegation Audit re-checks the workflow monthly or every other period.
You cannot tell reliably. In published tests, AI detectors applied to source code performed poorly, and the signs reviewers rely on, such as commit metadata and style patterns, can be removed or imitated. The more useful question is whether the code was reviewed and tested, because review and testing are what find the documented problems in AI-written code. The security record of AI-generated code is covered in a companion article: Vibe coding security: what the research and the incidents show. What Is AI Code Generation? AI code generation uses a large language model to produce source code from a natural-language request or the surrounding code. It takes three common forms: autocomplete inside an editor, chat that returns code on request, and agents that plan a task, edit files, and run commands. Most developers use these tools or plan to. In the 2025 Stack Overflow Developer Survey, "84% of respondents are using or planning to use AI tools in their development process." Sundar Pichai said on October 29, 2024, that "more than a quarter of all new code at Google is generated by AI, then reviewed and accepted by engineers." For a codebase written in the last two years, the likely answer to "is this code AI-generated" is therefore "partly." Can You Tell If Code Is AI-Generated? Not reliably. Peer-reviewed studies and the vendors of detection tools say the same thing. SourceDateWhat was testedFindingPan et al.January 8, 2024 (ICSE-SEET 2024)Five detectors, including GPTZero, Sapling and DetectGPT, on 5,069 Python problems and ChatGPT's solutions"existing AIGC Detectors perform poorly in distinguishing between human-written code and AI-generated code"Suh et al.November 6, 2024 (ICSE 2025)GPTZero, Sapling, GPT-2 Output Detector, DetectGPT, GLTR and the code-specific GPTSniffer, on code from four models"they all perform poorly and lack sufficient generalizability to be practically deployed"OpenAIJanuary 31, 2023Its own AI text classifier"it is unreliable on code". Withdrawn "As of July 20, 2023" because of "its low rate of accuracy"TurnitinRead October 3, 2026Its AI writing detection"does not reliably detect AI-generated text in the form of non-prose, such as poetry, scripts, or code" The detail supports the summaries. Suh et al. write of the general-purpose detectors that "their Accuracy is mostly less than 0.6", where 0.5 is a coin toss. The classifier the authors trained themselves reached "an F1 score of 82.55," which is better and still short of proof for any single file. Research detectors keep improving. Shi et al., first posted January 12, 2024, and presented at ICSE 2025, proposed a detector, DetectCodeGPT, and reported that it beat earlier methods in their experiments. The same paper opens by noting that language models "blur the distinctions between machine- and human-authored source code." Three limits apply to all of this research: The studies used models from 2023 and 2024, and mostly short functions from benchmark sets.A detector trained on one model's output must generalize to models released later.Code that a person edits after generation is a mix, and no study above claims to separate the two parts. A wrong result has a cost. OpenAI reported that its text classifier labeled human-written text as AI-written "9% of the time." Applied to a vendor's or an employee's code, an error rate like that means false accusations. What Signs Do Reviewers Actually Look For? Reviewers look at metadata first, then style, then mistakes models are known to make. Each sign is circumstantial. SignWhere to lookWhy it is weak evidenceTool trailers and bot authors in commitsgit log, pull request historyTrailers can be switched off or strippedAgent instruction filesRepository root and tool foldersShows a tool was set up, not which lines it wroteConcise, uniform code with a narrow vocabularyThe code itselfFormatters and style guides produce the same effectExplicit error handling everywhereThe code itselfCareful engineers write this tooNaming or formatting that shifts between filesAcross modulesCommon in any codebase with several authorsA dependency that does not existPackage manifestsRare from people, but a typo can cause it Metadata. Coding tools mark their work by default. Claude Code's documentation, read on October 3, 2026, states that "Commits get a git trailer such as Co-Authored-By by default," and documents a setting to "Change or hide the trailer Claude Code adds to commits." GitHub's documentation, read the same day, says: "Commits from Copilot cloud agent are authored by Copilot, with the person who started the task listed as co-author." Researchers depend on these markers and state the limit. Georgia Tech reported on April 13, 2026, that its Vibe Security Radar "can trace metadata like co-author tags, bot emails, and other known tool signatures, but it can't identify an issue if these markers have been removed." Researcher Hanqing Zhao added: "Claude Code and Copilot together account for most of what we detect, but that's partly because they leave the clearest signatures." Instruction files. Many agents read a project file of instructions. The AGENTS.md site, read on October 3, 2026, describes "a simple, open format for guiding coding agents" that is "used by over 60k open-source projects." Style. Shi et al. compared human and machine code and found that "Machines tend to write more concise code," and that machines prefer "a limited spectrum of frequently-used tokens, whereas human code exhibits a richer diversity in token selection." They also found that "Machine-authored code pays more attention to exception handling and object-oriented principles than human." These are averages across the datasets and models the authors tested. They do not settle the origin of one file. Review findings. CodeRabbit reported on December 17, 2025, from 470 open-source pull requests, that "Readability issues spiked more than 3× in AI contributions" and that "AI introduced nearly 2× more naming inconsistencies." CodeRabbit sells an AI review tool, and it could not verify authorship: "Since it was impossible to directly confirm authorship of each PR of a large enough OSS dataset, we checked for signals that a PR was co-authored by AI." Invented dependencies. Spracklen et al., first posted June 12, 2024 and presented at USENIX Security 2025, generated 576,000 code samples and found "the average percentage of hallucinated packages is at least 5.2% for commercial models and 21.7% for open-source models." An import of a package that has never existed is the closest thing to a fingerprint, and it is also a security risk. Why Do People Ask Whether Code Is AI-generated? People ask because of three concerns: security, maintainability, and ownership. Each has published evidence behind it. Security. Veracode reported on July 28, 2026, that "The average security pass rate across models is 56%" on its security tasks. Results varied by flaw type: models passed SQL injection tasks 83% of the time and cryptography tasks 87%, but "performance fell sharply on cross-site scripting at 15% and log injection at 12%." Veracode sells security testing, and the figures are pass rates on tasks built to test security. Maintainability. He et al., first posted November 6, 2025 and accepted at MSR '26, compared open-source projects that adopted Cursor with matched controls. They found "a statistically significant, large, but transient increase in project-level development velocity, along with a substantial and persistent increase in static analysis warnings and code complexity." Ownership. The US Copyright Office's report on copyrightability, published January 29, 2025, concludes that "Copyright does not extend to purely AI-generated material, or material where there is insufficient human control over the expressive elements." It also concludes that "The use of AI tools to assist rather than stand in for human creativity does not affect the availability of copyright protection for the output." How this applies to a given codebase is a question for counsel, and it matters in acquisitions and licensing. A fourth reason is misplaced confidence. In a user study by Perry et al., first posted November 7, 2022 and published at ACM CCS 2023, participants with an AI assistant "wrote significantly less secure code than those without access" and "were more likely to believe they wrote secure code". The model in that study is outdated, and the confidence effect is the finding that lasts. What Is the More Useful Question to Ask? The more useful question is whether the code was reviewed and tested, and by whom. The evidence supports this for three reasons. Authorship cannot be established. The detectors are unreliable, and the markers are optional, as shown above. The risks are properties of the code. A missing access check or unescaped output fails the same way whoever typed it, and both can be found by testing the code directly. Teams that use AI at scale pair it with review. Google's sentence ends with "then reviewed and accepted by engineers." He et al. conclude: "Our study identifies quality assurance as a major bottleneck for early Cursor adopters." Google's 2025 DORA report, announced September 24, 2025, puts it as "AI doesn't fix a team; it amplifies what's already there." Developers apply the same caution. In the 2025 Stack Overflow survey, "More developers actively distrust the accuracy of AI tools (46%) than trust it (33%)." For work delivered by a vendor, disclosure works better than detection. Ask in the contract which AI tools are used, require that tool trailers stay on, and require human review of every change. How Do You Review Code Regardless of Who Wrote It? Check nine things. Each maps to a failure documented in the research above, and none depends on knowing the author. #CheckWhat to look for1ExplanationA named engineer can explain each module and why it is built that way2Review historyEvery change went through a pull request that a second person approved3TestsAutomated tests exist, run on every change, and cover the paths that touch money and personal data4Access controlAuthorization is enforced on the server; test it logged out and as a different user5Input handlingForms and endpoints withstand hostile input, including script tags and log injection6SecretsNo keys in client code or in the git history7DependenciesEvery package exists, is the one intended, and has no known vulnerability8ComplexityStatic analysis runs in CI, and warnings are tracked over time9Error pathsThe code handles a failed call, a timeout, and an empty result Checks 4 and 5 target the classes where Veracode found models weakest. Check 7 follows Spracklen et al. Check 8 follows He et al. Check 9 follows CodeRabbit's finding that "Error handling and exception-path gaps were nearly 2× more common" in the AI-co-authored pull requests it reviewed. Key Takeaways No detector identifies AI-generated code dependably. Two ICSE studies found existing tools "perform poorly," and OpenAI and Turnitin say their text detectors are unreliable on code.Commit trailers and agent files show that a tool was used. They can be removed, and their absence proves nothing.Style patterns exist on average and do not settle the origin of a single file.The documented risks, such as weak input handling, rising complexity, and invented dependencies, can be tested directly.Ask who reviewed the code and which tests it passes. For vendors, require disclosure of AI tool use in the contract. References 2025 Stack Overflow Developer SurveyClaude Code's documentationGitHub's documentationAGENTS.md site
The Problem in One Section A production AI agent is a process that reads data, calls tools, and writes things — at machine speed, along action sequences nobody enumerated in advance. When we put that process on Kubernetes, the instinct is to hand it a service account with broad permissions and move on. The result is a principal with standing access that nobody reviews and a blast radius nobody scoped. Least privilege for agents is not a philosophy. It is a set of mechanisms, and Kubernetes already ships most of them: short-lived audience-bound tokens, RBAC, admission-enforced pod security, and network policy. In this lab, those mechanisms are five concrete enforcement points: projected tokens, TokenReview verification, the broker allowlist, the publish budget, and NetworkPolicy. The missing piece in most deployments is not the primitive — it is the pattern that wires them together. This tutorial builds that pattern as a reference implementation you can run in about 30–45 minutes, then tests every control the way an adversary would probe it. Three things change when the workload is an agent instead of a controller. First, action sequences are non-deterministic: you can write an RBAC policy for a controller because it does the same thing every time, but an agent's next action depends on model output, tool results, and conversation state, so "allow exactly what it needs" is a moving target. Second, tools are the real attack surface: an agent with a dozen tools is a dozen small programs, and most teams authorize the agent once for all of them — read access to private data plus a publish-capable tool, combined by an actor that sees no reason not to, is the canonical failure shape. Third, identities outlive their tasks: tokens issued for a ten-minute job become standing access when the session never ends. I designed the lab below around exactly these three properties. Nothing here is a production system. I built it as a lab, and it is labeled honestly as one. The point is that each mechanism in it is real, each boundary is enforced, and each test has an expected result you can verify with your own eyes. What You Will Learn By the end of this tutorial, you will be able to: Issue short-lived, audience-bound projected service-account tokens for each agent identity instead of handing agents long-lived credentials.Verify presented tokens through the Kubernetes TokenReview API — letting the API server, not local JWT decoding, decide whether a token is real and correctly scoped.Separate read and write authority behind a trusted tool broker, so agents hold identity but no direct Kubernetes API permissions.Enforce an action budget that halts a runaway agent after a fixed number of mutations.Lock agent egress with NetworkPolicy so the only reachable destinations are DNS and the broker.Read the broker's JSON audit trail to see exactly what each identity attempted and what the sandbox allowed. What You Will Build Two agent pods, agent-reader and agent-writer, each carrying a short-lived projected token for its own identity. They get no Kubernetes API permissions at all. Their only capability is talking to a trusted tool-broker service — the single write path in the system. The broker verifies every presented token through the Kubernetes TokenReview API, authorizes the caller against an allowlist, enforces a per-identity publish budget, and writes only to one named ConfigMap. NetworkPolicy then shrinks the blast radius further: agents can reach the broker and DNS, and nothing else. ComponentIdentityCan doCannot doagent-reader podagent-reader SA, projected token (aud agent-tools, 1h)Read the internal note via the brokerPublish; touch the K8s API; reach the internetagent-writer podagent-writer SA, projected token (aud agent-tools, 1h)Publish via the broker (budget: 3)Read the note; touch the K8s API; reach the internettool-brokertool-broker SACreate TokenReviews; get/patch/update the agent-output ConfigMapEverything else Figure 1 — Architecture: two agent identities, one trusted broker, one writable object. Guardrail checklists and architecture essays describe this pattern; the tutorial below implements it end-to-end as runnable code you can break and re-run. Most hand-rolled agent identity schemes stumble on the same step — verifying the token. This implementation gets it right by design: the broker never parses the JWT itself, and the API server, through TokenReview, is the only party that can vouch for a token's validity, identity, and audience. The trust boundary is the broker. The broker never decodes or verifies the JWT itself — that is the classic mistake. Verifying a signature locally only tells you who signed the token; only the API server can tell you whether it is currently valid, issued to that identity, and scoped to your audience. Re-implementing any of that yourself is how confused-deputy holes are born. Prerequisites A Kubernetes cluster with a policy-enforcing CNI such as Calico or Cilium. This matters: kind's default CNI does not enforce NetworkPolicy, so the egress test will not fail there. minikube start --cni=calico is a known-good starting point. An existing cluster with Calico or Cilium works too.kubectl, and kustomize (or kubectl 1.14+, which embeds it).About 30–45 minutes. Python 3.12 container images are pulled from the public registry, so the cluster nodes need registry access. Step 1: The Namespace and the Two Identities Everything lives in agent-lab. The namespace carries the restricted Pod Security Standard on all three tracks — enforce, audit, warn — so any pod that does not meet the restricted profile is rejected outright: YAML apiVersion: v1 kind: Namespace metadata: name: agent-lab labels: pod-security.kubernetes.io/enforce: restricted pod-security.kubernetes.io/enforce-version: latest pod-security.kubernetes.io/audit: restricted pod-security.kubernetes.io/audit-version: latest pod-security.kubernetes.io/warn: restricted pod-security.kubernetes.io/warn-version: latest The identities are plain ServiceAccounts with no roles attached. That is a deliberate choice: I made the projected tokens, not RBAC grants, the source of their authority. YAML apiVersion: v1 kind: ServiceAccount metadata: name: agent-reader namespace: agent-lab --- apiVersion: v1 kind: ServiceAccount metadata: name: agent-writer namespace: agent-lab --- apiVersion: v1 kind: ServiceAccount metadata: name: tool-broker namespace: agent-lab Step 2: Give the Broker — and Only the Broker — Scoped API Rights The broker needs exactly two capabilities from the Kubernetes API, and both are scoped to the minimum: create on tokenreviews (a ClusterRole, since TokenReview is cluster-scoped) so it can ask the API server to verify agent tokens.get/patch/update on the single named ConfigMap agent-output, so it can record publishes. The agent identities receive nothing: YAML apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: agent-lab-tokenreview rules: - apiGroups: ["authentication.k8s.io"] resources: ["tokenreviews"] verbs: ["create"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: agent-lab-broker-tokenreview roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: agent-lab-tokenreview subjects: - kind: ServiceAccount name: tool-broker namespace: agent-lab --- apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: name: agent-lab-output-writer namespace: agent-lab rules: - apiGroups: [""] resources: ["configmaps"] resourceNames: ["agent-output"] verbs: ["get", "patch", "update"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: agent-lab-broker-output-writer namespace: agent-lab roleRef: apiGroup: rbac.authorization.k8s.io kind: Role name: agent-lab-output-writer subjects: - kind: ServiceAccount name: tool-broker namespace: agent-lab Note the resourceNames restriction. A Role that allows patching "ConfigMaps" is a very different thing from a Role that allows patching the agent-output ConfigMap. Least privilege is always measured against the specific resource. Step 3: The Broker — TokenReview, Allowlist, Budget, Audit Log The broker is a stdlib-only Python service (no dependencies to audit, no framework to misconfigure). Read it carefully; every control in the lab is implemented here: Authentication: the presented bearer token is sent to POST /apis/authentication.k8s.io/v1/tokenreviews with spec.audiences: ["agent-tools"], using the broker pod's own in-cluster credentials. The broker then checks status.authenticatedand that status.audiences contains agent-tools — the TokenReview API docs call this out explicitly, because a token valid only against the API server's own audience would otherwise pass.Authorization: reader may GET /artifacts/internal-note; writer may POST /publish. The wrong pairing returns 403; a missing or bad token returns 401.Budget: three successful publishes per identity per broker process; the fourth returns 429. The counter is in memory on purpose — the code says so in a comment, and the production section below says what to use instead.Audit: one JSON line per request — timestamp, request id, username, action, status. The token is never logged. That rule matters more than it looks: the most common way identity systems leak is through their own logs.Inputs: JSON body only, 100 KiB cap, non-empty title/body strings with length limits. Python #!/usr/bin/env python3 """tool-broker -- the only write path for agent pods in agent-lab.""" import json import os import ssl import time import uuid import urllib.error import urllib.request from http.server import BaseHTTPRequestHandler, HTTPServer NAMESPACE = "agent-lab" EXPECTED_AUDIENCE = "agent-tools" READER = "system:serviceaccount:%s:agent-reader" % NAMESPACE WRITER = "system:serviceaccount:%s:agent-writer" % NAMESPACE NOTE_PATH = os.environ.get("NOTE_PATH", "/data/internal-note.txt") OUTPUT_NAME = os.environ.get("OUTPUT_CONFIGMAP", "agent-output") PUBLISH_BUDGET = 3 MAX_BODY_BYTES = 100 * 1024 LISTEN_PORT = int(os.environ.get("PORT", "8080")) SA_DIR = "/var/run/secrets/kubernetes.io/serviceaccount" def _k8s_request(method, path, body=None, content_type="application/json"): # Use the in-cluster DNS name so TLS hostname verification stays on. host = os.environ.get("KUBERNETES_SERVICE_DNS", "kubernetes.default.svc") port = os.environ.get("KUBERNETES_SERVICE_PORT", "443") with open(os.path.join(SA_DIR, "token"), "r", encoding="utf-8") as fh: sa_token = fh.read().strip() with open(os.path.join(SA_DIR, "ca.crt"), "rb") as fh: ca_data = fh.read() url = "https://%s:%s%s" % (host, port, path) data = json.dumps(body).encode("utf-8") if body is not None else None req = urllib.request.Request( url, data=data, method=method, headers={"Content-Type": content_type, "Authorization": "Bearer %s" % sa_token}) ctx = ssl.create_default_context(cadata=ca_data) # chain + hostname verified try: with urllib.request.urlopen(req, context=ctx, timeout=10) as resp: return resp.status, json.loads(resp.read().decode("utf-8")) except urllib.error.HTTPError as exc: payload = exc.read().decode("utf-8", "replace") try: return exc.code, json.loads(payload) except ValueError: return exc.code, {"error": payload} def verify_token(token): review = { "apiVersion": "authentication.k8s.io/v1", "kind": "TokenReview", "spec": {"token": token, "audiences": [EXPECTED_AUDIENCE]}, } status_code, payload = _k8s_request( "POST", "/apis/authentication.k8s.io/v1/tokenreviews", review) if status_code not in (200, 201, 202): return None status = payload.get("status", {}) if not status.get("authenticated"): return None if EXPECTED_AUDIENCE not in status.get("audiences", []): return None return status.get("user", {}).get("username") def record_publish(title, body): patch = {"data": {"lastTitle": title, "lastBody": body} status_code, _ = _k8s_request( "PATCH", "/api/v1/namespaces/%s/configmaps/%s" % (NAMESPACE, OUTPUT_NAME), patch, content_type="application/merge-patch+json", ) if status_code not in (200, 201, 202): raise RuntimeError("ConfigMap patch failed with status %s" % status_code) class BrokerHandler(BaseHTTPRequestHandler): server_version = "tool-broker/1.0" budgets = {} # in-memory on purpose; production needs durable state def log_message(self, *args): pass # silence default access logging def log_json(self, username, action, status, extra=None): record = { "ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "rid": getattr(self, "rid", "-"), "username": username, "action": action, "status": status, } if extra: record.update(extra) print(json.dumps(record), flush=True) # the token is never logged def _respond(self, status, payload, username, action, extra=None): body = json.dumps(payload).encode("utf-8") self.send_response(status) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) self.log_json(username, action, status, extra) def _bearer_token(self): auth = self.headers.get("Authorization", "") scheme, _, value = auth.partition(" ") if scheme.lower() != "bearer" or not value: return None return value def _authenticate(self, action): token = self._bearer_token() if not token: self._respond(401, {"error": "missing bearer token"}, "anonymous", action) return None try: username = verify_token(token) except Exception as exc: self._respond(502, {"error": "identity verification unavailable"}, "anonymous", action, {"detail": str(exc)}) return None if not username: self._respond(401, {"error": "invalid or mis-scoped token"}, "anonymous", action) return None return username def do_GET(self): self.rid = uuid.uuid4().hex[:12] path = self.path.split("?", 1)[0] action = "GET %s" % path username = self._authenticate(action) if not username: return if path == "/artifacts/internal-note": if username != READER: self._respond(403, {"error": "forbidden"}, username, action) return try: with open(NOTE_PATH, "r", encoding="utf-8") as fh: note = fh.read() except OSError as exc: self._respond(500, {"error": "note unavailable"}, username, action, {"detail": str(exc)}) return self._respond(200, {"note": note}, username, action) return self._respond(404, {"error": "not found"}, username, action) def do_POST(self): self.rid = uuid.uuid4().hex[:12] path = self.path.split("?", 1)[0] action = "POST %s" % path username = self._authenticate(action) if not username: return if path != "/publish": self._respond(404, {"error": "not found"}, username, action) return if username != WRITER: self._respond(403, {"error": "forbidden"}, username, action) return length = self.headers.get("Content-Length") try: n = int(length) if length else 0 except ValueError: n = 0 if n > MAX_BODY_BYTES: self._respond(413, {"error": "body too large"}, username, action) return raw = self.rfile.read(n) if n else b"" try: payload = json.loads(raw.decode("utf-8")) if raw else {} except (UnicodeDecodeError, ValueError): self._respond(400, {"error": "body must be JSON"}, username, action) return title = payload.get("title") body = payload.get("body") if (not isinstance(title, str) or not isinstance(body, str) or not title or not body): self._respond(400, {"error": "need non-empty 'title' and 'body' " "strings"}, username, action) return if len(title) > 2000 or len(body) > 100000: self._respond(400, {"error": "title/body exceed length limits"}, username, action) return used = BrokerHandler.budgets.get(username, 0) if used >= PUBLISH_BUDGET: self._respond(429, {"error": "publish budget exhausted"}, username, action, {"used": used, "budget": PUBLISH_BUDGET}) return try: record_publish(title, body) except Exception as exc: self._respond(500, {"error": "publish failed"}, username, action, {"detail": str(exc)}) return BrokerHandler.budgets[username] = used + 1 self._respond(202, {"published": True, "budget_used": used + 1, "budget": PUBLISH_BUDGET}, username, action, {"title": title}) def main(): server = HTTPServer(("0.0.0.0", LISTEN_PORT), BrokerHandler) print(json.dumps({"ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "event": "broker listening", "port": LISTEN_PORT}), flush=True) try: server.serve_forever() except KeyboardInterrupt: pass if __name__ == "__main__": main() The broker runs as a Deployment with its code and the internal note mounted from ConfigMaps (read-only), a ClusterIP Service on port 8080, and the same restricted hardening as everything else in this lab. Its own service account token is automounted — the broker is a trusted first-party component and needs its identity to call the API server. The demo data the broker serves is fictional, and it says so in the file itself: YAML apiVersion: v1 kind: ConfigMap metadata: name: internal-note namespace: agent-lab data: internal-note.txt: | DEMO CONTENT — this note is fictional and exists only for the lab. ... Step 4: The Agent Pods — Projected Tokens, Nothing Else Each agent pod gets exactly one credential: a projected ServiceAccount token with audience: agent-tools and a one-hour lifetime, mounted at /var/run/secrets/agent/token. The in-cluster token is not automounted (automountServiceAccountToken: false), which is the whole point — kubectl auth can-i will confirm these identities cannot touch the API at all. YAML spec: serviceAccountName: agent-reader automountServiceAccountToken: false ... volumes: - name: agent-token projected: sources: - serviceAccountToken: audience: agent-tools expirationSeconds: 3600 path: token Every container in the lab — broker and agents — runs with the same restricted-compatible profile: non-root user, seccompProfile.type: RuntimeDefault, allowPrivilegeEscalation: false, all capabilities dropped, read-only root filesystem, PYTHONDONTWRITEBYTECODE=1 so the interpreter never tries to write .pyc files. A tiny caller.py (stdlib only) rides along in each agent pod via a ConfigMap. It reads the projected token fresh from disk on every call — projected tokens rotate, so caching them is a bug — and performs the requested action against the broker: Python def _call(method, path, payload=None): with open(TOKEN_PATH, "r", encoding="utf-8") as fh: token = fh.read().strip() # fresh read every call req = urllib.request.Request( BROKER_URL + path, data=data, method=method, headers={"Authorization": "Bearer %s" % token, "Content-Type": "application/json"}) ... # usage inside the pod: # python3 /app/caller.py read # python3 /app/caller.py publish "demo title" "demo body" Step 5: Shrink the Network Blast Radius Identity controls what an agent may ask for. NetworkPolicy controls what it can reach. Agents accept no inbound traffic at all and may only talk to the broker on port 8080, plus DNS in kube-system: YAML apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: agent-default-deny namespace: agent-lab spec: podSelector: matchLabels: agent-lab/component: agent policyTypes: [Ingress, Egress] ingress: [] # deny all inbound traffic to agent pods egress: - to: - podSelector: matchLabels: app: tool-broker ports: - protocol: TCP port: 8080 - to: - namespaceSelector: matchLabels: kubernetes.io/metadata.name: kube-system podSelector: {} ports: - protocol: UDP port: 53 - protocol: TCP port: 53 A second policy locks the broker's ingress to agent pods on port 8080. This is the control that turns "the agent decided to exfiltrate" into "the connection timed out." Step 6: Run the Tests How this was verified. No live cluster was used during writing: the broker's authorization and budget logic was checked with an automated test suite that stubs the TokenReview call and the ConfigMap patch: missing token → 401, bad token → 401, reader read → 200, reader publish → 403, writer read → 403, three publishes → 202 each, fourth publish → 429, with exactly three patches recorded (10/10 checks passed). The cluster steps below are your live run of that same matrix; this tutorial does not claim an observed live-cluster execution. Deploy everything with kustomize, which generates the ConfigMaps from the Python files: Shell cd agent-security-lab kubectl apply -k . kubectl rollout status deploy/tool-broker -n agent-lab kubectl get pods -n agent-lab Now probe the sandbox the way an adversary — or a confused agent — would. 1. The reader can read (expect 200): Shell kubectl exec -n agent-lab agent-reader -- python3 /app/caller.py read HTTP HTTP 200 {"note": "DEMO CONTENT — this note is fictional and exists only for the lab.\n..."} 2. The reader cannot publish (expect 403): Shell kubectl exec -n agent-lab agent-reader -- python3 /app/caller.py publish "x" "y" HTTP HTTP 403 {"error": "forbidden"} 3. The writer cannot read (expect 403): Shell kubectl exec -n agent-lab agent-writer -- python3 /app/caller.py read HTTP HTTP 403 {"error": "forbidden"} 4. The writer can publish — three times — and the ConfigMap shows it: Shell kubectl exec -n agent-lab agent-writer -- python3 /app/caller.py publish "demo-1" "first write" kubectl exec -n agent-lab agent-writer -- python3 /app/caller.py publish "demo-2" "second write" kubectl exec -n agent-lab agent-writer -- python3 /app/caller.py publish "demo-3" "third write" kubectl get configmap agent-output -n agent-lab -o jsonpath='{.data.lastTitle}{"\n"}{.data.lastBody}{"\n"}' HTTP HTTP 202 {"published": true, "budget_used": 1, "budget": 3} HTTP 202 {"published": true, "budget_used": 2, "budget": 3} HTTP 202 {"published": true, "budget_used": 3, "budget": 3} demo-3 third write 5. The fourth publish is refused (expect 429): Shell kubectl exec -n agent-lab agent-writer -- python3 /app/caller.py publish "demo-4" "over budget" HTTP HTTP 429 {"error": "publish budget exhausted", "used": 3, "budget": 3} This is the containment control working as designed: a runaway agent gets exactly three mutations and then stops, no matter what it believes it should do next. 6. The agent identities have no Kubernetes API access: Shell kubectl auth can-i get secrets --as=system:serviceaccount:agent-lab:agent-reader -n agent-lab kubectl auth can-i get configmaps --as=system:serviceaccount:agent-lab:agent-writer -n agent-lab Plain Text no no 7. Every request leaves one audit line, and tokens never appear in logs: Shell kubectl logs -n agent-lab deploy/tool-broker | tail -4 JSON ... {"ts": "2026-10-14T19:40:02Z", "rid": "a3f19c2d81be", "username": "system:serviceaccount:agent-lab:agent-writer", "action": "POST /publish", "status": 202, "title": "demo-3"} {"ts": "2026-10-14T19:40:11Z", "rid": "2c1e4b9f30d2", "username": "system:serviceaccount:agent-lab:agent-writer", "action": "POST /publish", "status": 429, "used": 3, "budget": 3} 8. External egress fails on a policy-enforcing CNI (CNI-dependent test): Shell kubectl exec -n agent-lab agent-reader -- timeout 8 python3 -c \ "import socket; socket.create_connection(('1.1.1.1', 443), timeout=5)" Python Traceback (most recent call last): ... TimeoutError: timed out On kind's default CNI, this test will succeed — that is the prerequisite warning, not a lab bug. The policy is applied correctly; kindnetd simply does not enforce it. Cleanup: Shell kubectl delete namespace agent-lab The broker's decision path, drawn from broker.py, is worth keeping in front of you while you read the tests above — every request walks the same corridor, and every rejection is a gate with a code: Figure 2 — The broker's decision path for every request. Troubleshooting External-egress test still succeeds. Symptom: test 8 reaches 1.1.1.1:443 instead of timing out. Cause: the cluster's CNI does not enforce NetworkPolicy — kind's default CNI (kindnetd) installs the policy objects but never applies them. Fix: run the lab on a policy-enforcing CNI such as Calico or Cilium; minikube start --cni=calico is a known-good starting point. Every broker call returns 401 or 502. Symptom: the caller gets {"error": "invalid or mis-scoped token"}, or the broker answers 502 identity verification unavailable. Cause: the broker cannot reach the TokenReview endpoint, or the presented token is not meant for this service. Fix: check kubectl logs -n agent-lab deploy/tool-broker for the underlying error; confirm the ClusterRoleBinding grants the broker's ServiceAccount create on tokenreviews; and confirm the projected volume's audience is exactly agent-tools in both agent pod specs. Agent pods stuck Pending or rejected at admission. Symptom: kubectl get pods -n agent-lab shows Pending, or kubectl describe pod reports a forbidden admission error. Cause: the agent-lab namespace enforces the restricted Pod Security Standard, and any pod that violates it is rejected. Fix: confirm each pod's securityContext sets runAsNonRoot: true, seccompProfile.type: RuntimeDefault, allowPrivilegeEscalation: false, and capabilities.drop: ["ALL"] — the manifests in this lab already do. Publish returns 500. Symptom: {"error": "publish failed"} on a POST the allowlist should permit. Cause: the broker's own Role does not actually permit the write. Fix: confirm the agent-lab-output-writer RoleBinding exists in agent-lab and its resourceNames contains exactly agent-output; the broker patches one named ConfigMap and nothing else, so a renamed or missing ConfigMap fails closed. Taking This to Production: What the Lab Deliberately Leaves Out The lab's budget counter lives in broker memory; a restart resets it. Production budgets must be durable — etcd, Redis, or a database with atomic increments — and scoped per task, not per process. The audit lines go to stdout; production ships them to a tamper-evident store the agent cannot reach, with alerts on the 429s and 403s, not just retention. Three more things a real deployment adds. First, admission policy: the pattern in this lab should be enforced, not suggested. A policy engine such as Kyverno or OPA Gatekeeper can require automountServiceAccountToken: false, projected tokens with a sane expirationSeconds, and the restricted security context on every agent pod — so the sandbox is the default, not an option somebody remembers to apply. Second, per-task pods: long-lived agent identities accumulate authority. Minting a fresh pod and identity per task, with the token expiring with the task, bounds every session the way the lab bounds every publish. Third, human approval for high-risk actions: the broker's allowlist is static here. In production, the dangerous subset of tools — anything that writes, deletes, or crosses a trust boundary — sits behind an approval step or a policy check, not just an allowlist entry. And one response mechanism the lab does not demonstrate, but every deployment needs: a kill switch with quarantine-first semantics. When monitoring flags anomalous agent behavior — unusual data access patterns, write volume spikes, calls to unexpected destinations — the response should be automatic containment: revoke the session tokens, freeze the write identity, preserve the audit trail. You can always re-issue access after review; you cannot un-publish what a runaway agent already sent. The budget 429s and the 403s in the broker logs are the signals this switch consumes. And the internal note's stand-in for a secret store should be exactly that: a secret store with dynamic, short-lived credentials, never a ConfigMap. Trade-Offs, Stated Plainly This pattern is friction, and friction has a price. Per-agent projected tokens mean token plumbing everywhere a caller touches. A broker in front of every tool is a new service to operate, scale, and secure — and it becomes the most attractive target in the system, which is why its own RBAC is the tightest in the lab. Budgets turn "the agent did something wrong a thousand times" into "it did it three times and stopped," but they also turn a legitimate long task into a 429 that needs a human to raise the ceiling. Default-deny egress breaks the first integration that assumed the open internet, and the person who allowlists the fix had better write down why. The alternative is standing access for non-deterministic actors, reviewed never and rotated never, with no containment when the run goes sideways. That is not a trade-off; that is the absence of one. The mechanisms in this lab — verified identity, separated authorities, budgets, egress that defaults to no, audit trails that assume the actor will surprise you — are the price of running agents in production. Pay it deliberately, or pay it later in incident reviews. Conclusion Agents are principals now, but Kubernetes still provisions most of them like interns on their first day: broad access, issued once, reviewed never. This lab shows the other shape — short-lived audience-bound identity verified through TokenReview, a trusted broker as the only write path, allow-listed tools, action budgets, and a network that defaults to no — as running code you can test in about 30–45 minutes. None of these mechanisms is new. What the lab adds is their composition in one request path — TokenReview, then allowlist, then budget, then a single named write, then an audit line — applied to the workloads that need it most. The complete lab — every manifest, the kustomize setup, and both Python files — is printed in full in this article and its appendix, so you can reproduce it exactly; only the stubbed broker unit tests live outside it, and their results are quoted in Step 6. Run it, break it, and then decide which controls your agents are missing. References ServiceAccount token volume projection – projected tokens, audiences, and expirationSecondsTokenReview API reference – authentication.k8s.io/v1 request/response shapes and audience validationNetworkPolicy – ingress/egress rules and the policy-enforcing CNI requirementPod Security Standards – the restricted profile enforced on the lab namespace Appendix: The Remaining Manifests The walkthrough above prints the namespace, the service accounts, the RBAC, the demo data ConfigMap, the agent NetworkPolicy, and the broker code in full. The rest of the lab — the pieces the steps describe but do not print — is reproduced here, copied verbatim, so the article is self-contained. The broker's Deployment and Service: YAML # The tool-broker is the only write path in the lab. It is a trusted # first-party component: its own service account token is automounted so it # can call the TokenReview API and patch the single "agent-output" # ConfigMap -- nothing else. apiVersion: apps/v1 kind: Deployment metadata: name: tool-broker namespace: agent-lab spec: replicas: 1 selector: matchLabels: app: tool-broker template: metadata: labels: app: tool-broker spec: serviceAccountName: tool-broker securityContext: runAsNonRoot: true runAsUser: 10001 runAsGroup: 10001 seccompProfile: type: RuntimeDefault containers: - name: broker image: python:3.12-alpine command: ["python3", "/app/broker.py"] ports: - name: http containerPort: 8080 env: - name: PYTHONDONTWRITEBYTECODE value: "1" - name: NOTE_PATH value: /data/internal-note.txt volumeMounts: - name: code mountPath: /app readOnly: true - name: note mountPath: /data readOnly: true securityContext: allowPrivilegeEscalation: false capabilities: drop: ["ALL"] readOnlyRootFilesystem: true runAsNonRoot: true volumes: - name: code configMap: name: broker-code items: - key: broker.py path: broker.py defaultMode: 0444 - name: note configMap: name: internal-note items: - key: internal-note.txt path: internal-note.txt defaultMode: 0444 --- apiVersion: v1 kind: Service metadata: name: tool-broker namespace: agent-lab spec: type: ClusterIP selector: app: tool-broker ports: - name: http port: 8080 targetPort: 8080 The two agent pods in full: YAML # Two agent pods. Each carries a short-lived, audience-bound projected # token (audience "agent-tools", 1 hour) for its own identity, mounted at # /var/run/secrets/agent/token. The in-cluster service account token is # NOT automounted, so the pods cannot talk to the Kubernetes API at all. apiVersion: v1 kind: Pod metadata: name: agent-reader namespace: agent-lab labels: agent-lab/component: agent agent-lab/role: reader spec: serviceAccountName: agent-reader automountServiceAccountToken: false securityContext: runAsNonRoot: true runAsUser: 10001 runAsGroup: 10001 seccompProfile: type: RuntimeDefault containers: - name: agent image: python:3.12-alpine command: ["tail", "-f", "/dev/null"] env: - name: PYTHONDONTWRITEBYTECODE value: "1" - name: AGENT_ROLE value: reader - name: AGENT_TOKEN_PATH value: /var/run/secrets/agent/token - name: BROKER_URL value: "http://tool-broker:8080" volumeMounts: - name: agent-token mountPath: /var/run/secrets/agent readOnly: true - name: caller-code mountPath: /app readOnly: true securityContext: allowPrivilegeEscalation: false capabilities: drop: ["ALL"] readOnlyRootFilesystem: true runAsNonRoot: true volumes: - name: agent-token projected: sources: - serviceAccountToken: audience: agent-tools expirationSeconds: 3600 path: token - name: caller-code configMap: name: caller-code items: - key: caller.py path: caller.py defaultMode: 0444 --- apiVersion: v1 kind: Pod metadata: name: agent-writer namespace: agent-lab labels: agent-lab/component: agent agent-lab/role: writer spec: serviceAccountName: agent-writer automountServiceAccountToken: false securityContext: runAsNonRoot: true runAsUser: 10001 runAsGroup: 10001 seccompProfile: type: RuntimeDefault containers: - name: agent image: python:3.12-alpine command: ["tail", "-f", "/dev/null"] env: - name: PYTHONDONTWRITEBYTECODE value: "1" - name: AGENT_ROLE value: writer - name: AGENT_TOKEN_PATH value: /var/run/secrets/agent/token - name: BROKER_URL value: "http://tool-broker:8080" volumeMounts: - name: agent-token mountPath: /var/run/secrets/agent readOnly: true - name: caller-code mountPath: /app readOnly: true securityContext: allowPrivilegeEscalation: false capabilities: drop: ["ALL"] readOnlyRootFilesystem: true runAsNonRoot: true volumes: - name: agent-token projected: sources: - serviceAccountToken: audience: agent-tools expirationSeconds: 3600 path: token - name: caller-code configMap: name: caller-code items: - key: caller.py path: caller.py defaultMode: 0444 The broker-side NetworkPolicy, which locks the broker's ingress to agent pods on port 8080: YAML apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: broker-ingress namespace: agent-lab spec: podSelector: matchLabels: app: tool-broker policyTypes: [Ingress] ingress: - from: - podSelector: matchLabels: agent-lab/component: agent ports: - protocol: TCP port: 8080 The kustomize entry point: YAML apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization namespace: agent-lab resources: - manifests/namespace.yaml - manifests/serviceaccounts.yaml - manifests/rbac.yaml - manifests/data-configmaps.yaml - manifests/broker.yaml - manifests/agents.yaml - manifests/networkpolicy.yaml configMapGenerator: - name: broker-code files: - code/broker.py - name: caller-code files: - code/caller.py generatorOptions: disableNameSuffixHash: true The full caller.py: Python #!/usr/bin/env python3 """caller -- runs inside the agent pods to exercise the tool-broker. Reads the projected ServiceAccount token fresh from disk on every call. Projected tokens are rotated by the kubelet, so the token is deliberately never cached. The token is presented in an Authorization header and never printed. """ import json import os import sys import urllib.error import urllib.request TOKEN_PATH = os.environ.get("AGENT_TOKEN_PATH", "/var/run/secrets/agent/token") BROKER_URL = os.environ.get("BROKER_URL", "http://tool-broker:8080") def _call(method, path, payload=None): with open(TOKEN_PATH, "r", encoding="utf-8") as fh: token = fh.read().strip() data = json.dumps(payload).encode("utf-8") if payload is not None else None req = urllib.request.Request( BROKER_URL + path, data=data, method=method, headers={"Authorization": "Bearer %s" % token, "Content-Type": "application/json"}) try: with urllib.request.urlopen(req, timeout=10) as resp: return resp.status, resp.read().decode("utf-8") except urllib.error.HTTPError as exc: return exc.code, exc.read().decode("utf-8", "replace") def main(argv): if len(argv) < 2 or argv[1] not in ("read", "publish"): print("usage: caller.py read | caller.py publish <title> <body>", file=sys.stderr) return 2 if argv[1] == "read": status, body = _call("GET", "/artifacts/internal-note") else: if len(argv) != 4: print("usage: caller.py publish <title> <body>", file=sys.stderr) return 2 status, body = _call("POST", "/publish", {"title": argv[2], "body": argv[3]}) print("HTTP %s" % status) print(body) return 0 if __name__ == "__main__": sys.exit(main(sys.argv)) With these files, kubectl apply -k . from the lab directory deploys the complete sandbox exactly as tested in Step 6.