Migrating My Java Codebase to EE10
Spring AI Migration: From the Vertex AI Gemini Module to the Google GenAI SDK
AI agents are increasingly invoking tools that take longer than a single network request and depend on systems that can fail independently of the agent runtime. A Model Context Protocol (MCP) tool may trigger document generation, code analysis, data synchronization, or infrastructure automation. It may also trigger another operation that runs for minutes rather than milliseconds. Treating such work as an ordinary request-response handler creates a fragile coupling between the lifetime of the MCP connection and the lifetime of the underlying operation. Temporal provides a different execution model: the MCP server can accept a tool request, start a durable Workflow, return a stable execution identifier, and allow later requests to retrieve the result. The operation can then survive MCP client restarts, HTTP disconnects, Worker crashes, transient dependency failures, and process redeployments without restarting completed steps. Temporal calls this model Durable Execution because Workflow progress is reconstructed from persisted Event History when execution moves between Workers. The following examples use the Temporal Java SDK (current published version:1.40.0), together with the MCP Java SDK 2.2.0, which added support for the stateless MCP 2026-07-28 specification. The snippets are documentation-aligned illustrative code and were not executed as part of this article. Java String workflowId = "agent-job-" + request.executionKey(); WorkflowOptions options = WorkflowOptions.newBuilder() .setWorkflowId(workflowId) .setTaskQueue("agent-execution") .build(); AgentWorkflow workflow = workflowClient.newWorkflowStub(AgentWorkflow.class, options); WorkflowClient.start(workflow::run, request); return new StartResult(workflowId, "RUNNING"); Temporal requires a Task Queue when creating a new Workflow stub, and a business-derived Workflow ID is preferable when the same logical request must not create duplicate executions. A Workflow ID identifies the logical Workflow across client interactions and can be used to reconnect to an existing execution instead of tying identity to an MCP socket, HTTP request, or process-local object. This pattern also handles duplicate MCP submissions more cleanly. Retries can occur at proxies, clients, agent frameworks, or application layers. If every retry invents a new Workflow ID, one logical agent instruction can start several independent executions. Deriving the ID from a stable request key moves deduplication into the orchestration boundary. Temporal documents the same principle for durable operations that may be started more than once: stable IDs should be derived from request identity or operation input so retries reuse the intended execution rather than duplicating side effects. Durable Progress Belongs Inside the Workflow A Temporal Workflow should contain orchestration state, branching decisions, timers, and durable coordination, while external calls belong in Activities. Workflow code is replayed from history, so nondeterministic side effects such as HTTP requests, database mutations, or LLM calls should not execute directly inside Workflow logic. Activities are explicitly designed for these operations and can be retried when Workers crash, dependencies time out, or temporary failures occur. A durable agent Workflow might coordinate an LLM planning step, a remote tool invocation, and persistence of the final result: Java public AgentResult run(AgentRequest request) { Plan plan = activities.createPlan(request); ToolResult toolResult = activities.executeTool(plan); return activities.storeResult(request.executionKey(), toolResult); } The relevant Activity options should make failure behavior explicit rather than inheriting assumptions from the MCP request timeout. Java ActivityOptions options = ActivityOptions.newBuilder() .setStartToCloseTimeout(Duration.ofMinutes(2)) .setRetryOptions(RetryOptions.newBuilder() .setInitialInterval(Duration.ofSeconds(1)) .setBackoffCoefficient(2.0) .setMaximumInterval(Duration.ofSeconds(30)) .setMaximumAttempts(8) .build()) .build(); Temporal requires at least one Activity timeout and strongly recommends Start-To-Close for detecting Worker loss or stalled attempts. Retry backoff remains durable even when the Worker process disappears, because retry state is maintained by the Temporal Service rather than an application thread. Retries do not create exactly-once side effects. Temporal guarantees that a completed Activity is observed as completed once by the Workflow, but an Activity may execute more than once before that successful completion is recorded. A remote service could therefore receive the same write twice if the first call succeeds, but the Activity Worker crashes before reporting completion. Temporal recommends idempotent Activity implementations and specifically notes that Workflow Run ID combined with Activity ID can form an idempotency key that remains stable across retry attempts. Java String idempotencyKey = Activity.getExecutionContext().getInfo().getWorkflowRunId() + ":" + Activity.getExecutionContext().getInfo().getActivityId(); return remoteExecutor.execute(command, idempotencyKey); The receiving system should persist that key and return the original outcome when the same operation arrives again. Durable orchestration without idempotent side effects can preserve Workflow progress while still duplicating external mutations. Disconnect, Cancellation, and Result Retrieval Are Different Operations Transport cancellation requires deliberate semantics. Under modern MCP Streamable HTTP, cancellation is represented by closing the in-flight request stream. Earlier MCP revisions use notifications/cancelled for request cancellation, while the current protocol removes session coupling for normal HTTP requests. The Java SDK documentation also distinguishes request timeout from remote cancellation in older client behavior: a caller timing out does not automatically prove that server-side work has stopped. For durable agent execution, an MCP disconnect should normally mean only that the client stopped waiting. It should not automatically cancel the Temporal Workflow. Otherwise a transient Wi-Fi failure, proxy timeout, browser closure, or application restart becomes a business cancellation signal. Cancellation should instead be exposed as an explicit tool such as cancel_agent_job. That handler can target the Temporal Workflow by ID and request cancellation intentionally. Java WorkflowStub workflow = workflowClient.newUntypedWorkflowStub(workflowId); workflow.cancel(); Temporal cancellation is cooperative. A Workflow can observe cancellation and perform cleanup, while Activity cancellation requires additional care because cancellation does not forcibly interrupt arbitrary Activity code. Long-running Activities generally need heartbeats so cancellation can be delivered and progress can be checkpointed. Temporal documents that an Activity without heartbeats may continue until its timeout even after cancellation has been requested. Result retrieval should similarly be independent of the original MCP connection. A later get_agent_job call can reconstruct a Temporal stub from the Workflow ID and wait for or inspect the durable execution. Java WorkflowStub workflow = workflowClient.newUntypedWorkflowStub(workflowId); AgentResult result = workflow.getResult(AgentResult.class); WorkflowStub.getResult waits on the Temporal Service for Workflow completion, and a stub can be recreated from a known Workflow ID after the original application process or connection has disappeared. This makes the execution handle the durable rendezvous point between the MCP layer and the agent job. Security and Failure Testing Still Matter Durability does not replace authorization. A server that exposes get_agent_job or cancel_agent_job must verify that the authenticated principal is permitted to access the referenced Workflow ID. Modern MCP places authentication and authorization outside the core protocol transport and expects server implementations to enforce them at the HTTP or application boundary. The Java SDK explicitly delegates authentication and authorization to application infrastructure such as servlet filters or Spring Security. Workflow IDs therefore should not function as bearer credentials. A stored execution record should bind the Workflow ID to the authenticated tenant, account, or principal, and every retrieval or cancellation request should validate that relationship before contacting Temporal. Legacy MCP session deployments require an additional precaution because session identifiers must also be bound to authenticated identity; the Java SDK warns that session IDs alone do not provide user isolation. Fault testing should exercise failures at the boundaries that durability is expected to survive. A Worker can be terminated after an Activity completes, a dependency can return transient failures until the Retry Policy succeeds, the MCP connection can be closed immediately after Workflow start, and the result can then be retrieved through a fresh client process using the same Workflow ID. Temporal’s replay model is specifically designed so another Worker can reconstruct Workflow state from Event History and continue without re-running already recorded completed steps. Worker shutdown behavior should also be tested under realistic Activity load because abrupt termination can cause running Activity attempts to time out and retry. A fault-tolerant MCP server therefore requires more than retrying HTTP requests. Durable execution emerges when MCP request lifetime, business execution lifetime, and cancellation semantics are modeled separately. MCP provides the interoperable tool boundary; Temporal supplies persisted Workflow state, replay, Activity retries, stable execution identity, and post-disconnect result retrieval. With explicit Workflow IDs, idempotent Activities, intentional cancellation, authorization on every execution handle, and fault tests that include real process and network failures, long-running AI agent operations can continue correctly even after the connection that started them no longer exists.
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.
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.
Two services were sending the raw path for the endpoints “/user/918273” as the attribute for the http.route metric, instead of using the corresponding route template “/user/{unique_id}” for http.route. In the incident described in this case study, the shared OpenTelemetry Collector pods failed and reinitialized. Later, both Prometheus replicas in the HA/Thanos setup failed due to out-of-memory (OOM) terminations. At the same time, a high volume of trace-export errors was stuffed into Sentry, consuming the quotas for the errors there. In this case study, we describe the scenario in detail, explain how to find unsafe dimensions on a metric, investigate cross-signal effects, and finally, explain why a Collector-side rewrite is only an emergency fix for such problems. The First Symptom Was a Sentry Quota Alarm The very first notification in this incident was a hit to the application team’s Sentry event quota limit. The events looked something like this: “Failed to export OpenTelemetry traces via HTTP to /v1/traces”. Plain Text Transient error ... HTTPConnectionPool(host='<redacted>', port=<redacted>): Max retries exceeded with url: /v1/traces ... Failed to establish a new connection ... The /v1/traces path is used to identify OTLP/HTTP trace-export attempts. This connection error indicates that telemetry delivery has failed for some reason. We don’t know yet whether the cause is DNS, network issues, or somewhere else in the delivery path to the Collector. In addition to OpenTelemetry Collector pod failures, we also observed that both Prometheus replicas in our HA/Thanos configuration restarted after running and experiencing out-of-memory (OOM) terminations. This, combined with trace-export errors now filling the Sentry error quotas, created a medium-to-high level of infrastructure pain, along with an unusual set of noisy application-level metrics. The Shared Pipeline and Its Failure Boundaries The two applications in question were instrumenting metrics and traces on the application side. These were then sent to the OpenTelemetry Collectors for the various applications (the shared gateway in the center). In addition to sending metrics to the application-specific monitoring services (in this case, Prometheus for metrics and a tracing back-end for traces), Sentry also collected application errors as events. Figure 1. Conceptual pre-incident telemetry flow and shared failure boundaries; exact ingestion and Thanos components require deployment confirmation. A sketch of the used setup is shown in Figure 1. The issues occurred at the level of the shared telemetry gateway, the gating firewall. However, the two levels are not clearly separate, as both collect and send metrics and traces, and both are ingested by applications for Analytics/Log insight in addition to the alerts already mentioned in the DZone Monitoring article. The Metric Attribute That Broke the Cardinality Budget Application services are emitting raw URI paths in the http.route metric attribute instead of bounded route templates (e.g.,/user/{unique_id} for http.route == "/user/{unique_id}"). This will result in every unique ID being another attribute combination. Plain Text Expected: http.route="/user/{unique_id}" Observed: http.route="/user/918273" Observed: http.route="/user/918274" Observed: http.route="/user/918275" The http.route OpenTelemetry semantic convention for HTTP metrics defines a low-cardinality route template, http.route. The raw URI path is used as the metric value as a last resort. But as mentioned previously, the raw path of a request is not a substitute for a route template for http.route. Each unique user ID is another attribute dimension that results in another time series for each affected metric and all the other labels. This sets out the key metrics that were recorded for the more affected service: Observation Reported value Distinct route values in one snapshot Approximately 4,800 Distinct route values across three hours Approximately 24,000 Metric series associated with one pod More than 38,000 Note that the number of measurements and the original query (e.g., Prometheus query language), as well as the time frame of the measurement (e.g., a specific time window), the name of the measurement (e.g., the name of the metric), and the label definitions have to be provided as well. Distinct route count over time vs. number of time series: They are not equivalent. The Histogram buckets, status-code labels, HTTP method labels, and instance labels can multiply the number of time series a lot. The number to look at for problems is the total number of metric-label combinations, not just the number of URI dimensions. Figure 2. Reported route-cardinality observations, observed restarts and OOM terminations, and possible propagation paths (dashed). Diagnose Cardinality Before Restarting Everything Step 1: Identify the Metric and Raw Route Label Check which metric contains the problematic dimension. With Prometheus naming conventions, http.route may appear as http_route; the metric itself varies with instrumentation and translation settings. Plain Text # Illustration only: replace metric and labels with deployed names. count by (job) ( count by (job, http_route) ( http_server_request_duration_seconds_count ) ) This graph shows the number of distinct route-label combinations, not the total number of series, for each job over time. This can be compared with other services, and the anonymous labels are expanded to look at the ID present on each. Step 2: Check Prometheus TSDB Pressure Shell # Active series in each Prometheus instance prometheus_tsdb_head_series # Rate of new series creation, when exposed rate(prometheus_tsdb_head_series_created_total[5m]) Add both Prometheus replicas to the incident timeline and add a graph for their memory working set (with limits), as well as their restart times and their Kubernetes lastState.terminated.reason. This will let you see whether the URI-label explosion caused the 2 applications to be OOM-killed before they were OOM-killed. Step 3: Inspect Collector Health and Trace-Export Failures Compare application exporter errors with the Collector pod lifecycle, receiver/refusal metrics, exporter queue pressure, and memory utilization. A connection failure to /v1/traces is consistent with a temporarily unavailable gateway, but it is not exclusive proof of OOM or readiness failure. Useful Kubernetes checks (replace labels and namespaces): Shell kubectl -n observability get pods -l app=otel-collector kubectl -n observability describe pod <collector-pod> kubectl -n observability describe pod <prometheus-pod> The termination reasons for the Collector must be recorded separately from those of Prometheus. The case described here includes only Prometheus OOM restarts. Step 4: Understand Why HA and Thanos Did Not Prevent the Outage While Thanos Query can usually deduplicate overlapping series from multiple, healthy Prometheus instances and even fill in some “gaps” left by down instances, Thanos Query cannot prevent two instances of Prometheus from running amok and exhausting their memory when both instances are reading in the same unsafe metric dimensions. This kind of cardinality mitigation happens at query time, not on a per-replica basis. Don’t mistake this for Thanos Crash: Just because two Prometheus hosts went down simultaneously due to OOM, that doesn’t necessarily mean Thanos Query, the Thanos Sidecar, or even Thanos Dashboard went down. Notice the availability of the /v1/traces endpoint (which is a totally separate service) and the two hosts running Prometheus in this case study. The Collector-Side Emergency Mitigation During the incident, we addressed the high-cardinality dimension http.route for the OpenTelemetry Collector by normalizing the ID-like values to /user/{unique_id} as a centralized mitigation on top of the already affected application. Below is an example transform processor to undertake emergency correction for high-cardinality dimension in http.route. YAML processors: transform/normalize_http_route: error_mode: ignore metric_statements: - context: datapoint statements: # /user/918273 -> /user/{unique_id} - replace_pattern(attributes["http.route"], "^/user/[0-9]+$", "/user/{unique_id}") service: pipelines: metrics: receivers: [otlp] processors: [memory_limiter, transform/normalize_http_route, batch] exporters: [prometheus] Note that this is NOT the actual configuration used for the incident and should NOT be deployed without proper testing and verification against your specific scenario. This is just a sample; please test it and make sure all components are up and running (availability of the Collector component, choice of exporter, support for specific functions by the version of the Collector installed). In addition, the processor order may differ. Just because you have normalized your ID-like attributes (e.g. http.route to /user/{unique_id}) does not mean you have correctly aggregated your metrics. Each distinct cumulative counter/histogram will now have the same attributes but be separate series of data. This must then be handled by your downstream pipeline to correctly sum up these series of data. Instead of re-writing safe, existing metric streams from applications with frameworks like Express.js or Django (e.g., their matched route template for /http.route instead of their raw path), a simple configuration change to these existing streams could ensure they are correctly, completely, and precisely aggregated downstream (or dropped if a durable resolution isn’t possible in the midst of an incident). Why Sentry Was Involved The Sentry integration for the Python OpenTelemetry SDK logs the exporter’s errors as application errors in Sentry. This means Sentry error-event quota is consumed for repeated failures of trace-export path /v1/traces errors even though no business requests failed. Note that, although the above path may have occurred for the above-described incident, you should always verify the information (logger name, log level, SDK integration, quota consumption) in Sentry events, and be very careful to distinguish quota exhaustion from Sentry discard/stamping of really erroring business cases. Architectural guardrails that prevent kinds of errors from propagating into application error budgets, even though they are errors in your metrics pipelines, are important. In this case, just silencing the logger is not going to be sufficient. Guardrails That Would Contain the Next Incident As a layered set of checks as opposed to a single line of code. Emit only route templates in http.route. Do not substitute raw paths for unmatched routes.SDK / reporter: check for the correct version of the SDK (plus the metric views, attribute caps, etc. as applicable for the respective programming language + instrumentation used here).At the Collector level, ensure all filtering and transformation are correctly done and that there is sufficient monitoring of refused/dropped metrics as well as pressure on the Collector’s queues; validate that correct aggregation is being done.Monitor active-series growth, new series creation, low memory, and replica restarts; track sample volume per target replica in Prometheus for the health of re-routed and unaffected trace pipelines.In topology: Change layout of noisy workloads vs. critical trace export to prevent failure of one signal type from affecting other signals.In CI/CD tests: Also test routes with lots of unique IDs and assert that the corresponding route-attribute values stay within a reasonable boundary.For Sentry: route telemetry-exporter failures to the operational channel for the product, while keeping all application error events for the product at the quota for defects in the application. These recommendations were not incorporated into the protocol for the above incident. The normalization that was done in the Collector to handle the high volume of data is the “workaround” that is described in the above account. What This Incident Changed About the Design Review There are two lessons in this for high availability of independent replicas, such as two possible OpenTelemetry collector instances. First, high availability alone does not solve the problem of a workload that exceeds the memory of all replicas. Second, shared collectors for metrics and traces couple the two signals, such that high load in metrics and failed delivery of traces can surface as errors in completely different products, like Sentry. In the long run, it might be easier to do the engineering to ensure that the route attribute is created correctly at the application level, enforce a set of contractual obligations for telemetry, track cardinality budgets, and test for failure. One would expect observability to help discover an incident, not cause it. Technical References OpenTelemetry HTTP metrics semantic conventions: https://opentelemetry.io/docs/specs/semconv/http/http-metrics/OpenTelemetry Collector transform processor: https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/processor/transformprocessor/README.mdPrometheus storage: https://prometheus.io/docs/prometheus/latest/storage/Thanos Query and HA replica deduplication: https://thanos.io/tip/components/query.md/Sentry Python logging integration: https://docs.sentry.io/platforms/python/integrations/logging/
Having mapped the system and classified its asynchrony, it's time to move on to the failures that we can expect, their detection, and mitigation. This is the technical core of the article. Ideally, a comprehensive test suite walks every cell of the taxonomy below for every component and network pair in the system map, rather than enumerating failures ad hoc. Safety and Liveness: The Two Properties Behind Everything That Follows The notion of the correct software is notoriously fuzzy: obviously, a system is correct if it does what it is supposed to do. However, this gives no objective criteria for determining whether a system is correct. We need to be able to think rigorously about the system’s guarantees, capabilities, and limitations. We will focus on liveness and safety as described by Leslie Lamport. Every failure in this part matters for one of two reasons: it can make the system do something it must never do, or it can stop the system from doing something it must eventually do. Distributed systems theory gives these two ideas names, and the rest of this part leans on them. It is worth fixing them with simple examples before the taxonomy begins. A safety property says that something bad never happens. A liveness property says that something good eventually happens. The two are independent: a system can satisfy one and violate the other. examplesafety: Something bad never happensLiveness: something good eventually happens Traffic light at a crossing The lights never show green in both directions at once. Every direction eventually gets a green. Elevator The doors never open while the cabin is between floors. Every pressed call button is eventually answered. Order pipeline A customer's card is never charged twice for one order, and never charged without the stock being reserved. Every order eventually ends up confirmed or cancelled. You need both, because each is trivially satisfied by giving up the other. A traffic light stuck on red in every direction is perfectly safe, and useless. An elevator that moves the moment any button is pressed, doors or no doors, is as responsive as it gets, and dangerous. A pipeline that rejects every order never double-charges anyone; a pipeline that retries blindly until something succeeds makes progress and sometimes charges a card twice. Ideally, we want to build systems where every possible system behavior satisfies both properties. Why the Distinction Matters for Testing The two properties are tested in different ways, and confusing them is a common problem. A safety violation can be caught in a finite observation: at some specific moment, two charges exist for one order, and an assertion or invariant check can point at it. Safety tests therefore tend to be exact, and they can run continuously alongside any other test as an invariant. A liveness violation cannot be caught that way. "Eventually" has no deadline, so no finite observation can prove that the good thing will never happen; the system may simply be slow. In practice, a liveness test is always a bounded approximation, such as "the order is confirmed within 30 seconds." The three regimes from Part 1 show how this plays out. In the partially synchronous core, a calibrated bound is meaningful. With a weak notion of time, it is only a suspicion. With no notion of time, it is a business policy about when to escalate to a human, which is why that regime relies on reconciliation rather than on waiting. How Failure Forces a Choice When a failure hits, a system often cannot keep both properties. It can keep safety and give up liveness by stopping rather than risk a mistake. It can keep liveness and give up safety by carrying on and accepting that it may misbehave for a while. Or, at the best and most expensive end, it can hide the failure entirely and keep both. Section 2.3 names these three outcomes (fail-safe, nonmasking, and masking) and explains how to write assertions that match the contract a component actually provides. Section 2 also uses the two properties as its organizing lens: failure detection is what protects safety, because a system that notices trouble can stop doing dangerous things. Failure mitigation is what restores liveness, because it lets the system resume making progress. Failure Modes 1. Component Failure Modes Crash stop, omission, and crash recovery will be covered here. Byzantine failures are not covered but are only mentioned in the table below for completeness. failure typedescriptiontest implication Crash-Stop The component halts permanently and performs no further steps. The simplest to test: kill the process and verify that the rest of the system degrades or routes around it correctly. Omission The component pauses for an arbitrary duration, then resumes exactly where it left off with no state lost. Test with process suspension (SIGSTOP and SIGCONT, or docker pause), not process kill. It is a meaningfully different failure and is often untested. Crash-Recovery The component pauses, resumes, and may have lost some volatile state while keeping durable state. Kill and restart with a controlled subset of state wiped, for example an in-memory cache cleared while the disk volume is intact. This is where "did we persist what we thought we persisted" bugs live. Byzantine The component behaves arbitrarily, including sending contradictory or deceptive messages to different peers. Relevant only where not every participant is trusted (e.g., cryptocurrency). To test for component failures, we could use, for example, fault injection. Stopping, suspending, and restarting components, or exhausting their resources, shows how the rest of the system reacts. Component tests against real dependencies show whether durable state really survives a restart. Transactional-integrity tests check that a write and the message announcing it cannot be separated by a crash. State-transition tests check that a recovering component does not accept events its state machine should refuse. Recovery and failover testing measures how long recovery takes and what, if anything, is lost. Part 4 maps each of these to the level where it is cheapest. 2. Network Failure Modes Message loss: the network does not deliver.Message duplication: the network delivers more than once.Message reordering: the network delivers out of order. A network that exhibits any of these is an unreliable network. An unreliable network is the default assumption for everything except same-process function calls. The model assumes the network does not lie: if it delivers a message, some component in the system really sent it. The three network failures map naturally to families of tests. Duplication is addressed by idempotence and duplicate-delivery tests, which feed the same message to a handler several times. Reordering is addressed by permutation tests, which feed a short event sequence in every order, and by property-based tests, which generate far more orderings than anyone would write by hand. Loss is addressed by reconciliation checks, which compare what was sent with what was acknowledged, and by tests of the retry behavior around it. Network-level fault injection, which adds latency, drops, duplicates, and reorders traffic between components, then confirms in a running system that these defenses hold. Contract tests complement all of this by checking that both sides agree on what a message means in the first place. For more details, the section on examples for message handlers (Part 3, section 1.6) could be useful. 3. Spatial and Temporal Classification Spatial: application-level versus platform-level. A failure is application-level if the application layer is the lowest layer that can meaningfully interpret and resolve it (for example, InsufficientFunds). It is platform-level if a lower layer can and should resolve it (for example, CouldNotConnect, resolved by reconnecting). This is the end-to-end argument: handle a failure at the lowest layer that can handle it correctly and completely. It also tells you where the corresponding test belongs: Application-level failures are tested with business-logic-level cases: does the checkout flow correctly reject and compensate on InsufficientFunds?Platform-level failures are tested with infrastructure-level fault injection: does the HTTP client retry correctly on connection failure, with correct backoff? This usually uses the network tooling above rather than application fixtures. Temporal: transient, intermittent, permanent. These differ by whether a first failure makes a second one more likely, and by how they are repaired. Transient: no elevated recurrence probability, self-repairing quickly (a single dropped packet). Test with single-shot fault injection: fail once, verify that an immediate retry succeeds.Intermittent: elevated recurrence probability, self-repairing but after some delay (a flapping link, a stale routing table). Test with repeated, clustered fault injection over a sustained window. A single-shot test will never surface an intermittent failure mode, which is why soak testing and scheduled chaos matter.Permanent: certain recurrence, requires manual repair (an expired certificate). This is effectively an integration test with the dependency held down for the whole test: verify that the system escalates to fail-safe behavior and alerting rather than retrying forever. Pairing with load. Recurring fault injection ("cut connectivity for 10 seconds every 2 minutes for an hour") is what intermittent failure simulation needs. It should be combined with concurrent load, because intermittent failures may only manifest under load (connection pool starvation, resource exhaustion). So the combination is usually necessary rather than optional. 4. Which Failures Dominate in Which Scenario The taxonomy applies everywhere, but its cells are not equally important in every regime. Use this table to prioritize the first pass of a test plan. failureScenario 1: partially synchronousScenario 2: async, weak timeScenario 3: async, no time Crash-Stop, Crash-Recovery High: autoscaling and rolling deploys are constant Medium: mostly device app kills and region outages Medium: the partner's batch job can crash silently Omission (pauses) High: GC and scheduler pauses are the main source of false failure detection Medium Low: pauses are lost in the noise of arbitrary delay Message loss Low to medium: broker-level durability usually covers it High: sync-on-reconnect and flaky links High: files never picked up or never returned Message duplication Medium: at-least-once consumers and retries Very high: resend-on-reconnect is by design High: repeated file drops and re-sent batches Message reordering Low within a partition; higher across partitions Very high: offline queues and multi-region replication Medium: response files can arrive out of order Clock skew and drift Medium: small but relevant under contention Very high: device clocks are untrusted Not applicable: no shared clock is assumed at all Transient versus permanent Mostly transient and intermittent All three, with long intermittent partitions Mostly permanent or human-repaired Detection and Mitigation as Testable Properties Failure handling splits cleanly into two mechanisms that should be tested separately: detection (recognizing that a failure occurred) and mitigation (recovering from it). Detection is fundamentally about preserving safety: once you suspect trouble, stop doing anything dangerous. Mitigation is about restoring liveness: resume making progress once the trouble is over or has been worked around. 1. Testing Detection Detection mechanisms follow two patterns. In a pull design, the observer polls the observed component and expects a timely answer. In a push design, the observed component emits heartbeats at a set frequency. In both, the failure witness is a timeout. A point worth internalizing, and worth communicating to stakeholders who file bugs against "flaky" tests: in a partially synchronous or asynchronous system over an unreliable network, no failure detector can be both complete (catches every real failure) and accurate (never flags a non-failure). The obstacle is structural, not an engineering gap. The detector simply cannot tell "delayed" from "lost." Practically, that means: Detection tests should verify tuned behavior (does the timeout or heartbeat interval match your actual SLA and network characteristics?), not perfect behavior.Some of the flakiness in async test suites accurately reflects this impossibility and is not evidence that the tests or the system are broken. The fix is often to make the detector's trade-off intentional and documented, not to try to eliminate all false positives.Ask who supervises the supervisor. Every detector is itself a component that can fail. Somewhere the chain ends in human intervention, and that hand-off should be tested too (does the alert actually fire, does the on-call runbook work?). The thresholds of a circuit breaker or health check are testable units. Boundary-value tests with controlled time assert that the circuit opens and closes exactly at the configured thresholds. They are also kept separate from integration tests that verify end-to-end behavior once it does. Mutation testing, which deliberately breaks the comparison operators and counters in that logic, shows whether those tests would notice a regression. Alerting rules are testable too, against synthetic data, so that the hand-off to a human is checked as well. 2. Testing Mitigation Mitigation is either backward recovery (return to a state equivalent to the initial one, via compensation) or forward recovery (push through to a state equivalent to completion, via retries). Test each explicitly: Backward recovery and compensation tests. Inject a failure partway through a multi-step process and assert that compensating actions (refund, release reservation) run correctly. Compensations can fail too, so they must themselves be idempotent and retriable. There must be an escalation path to a human when they cannot complete (the refund that fails is the classic example).Forward recovery and retry tests. Verify retry count and backoff strategy: immediate retry for an assumed transient failure, backoff and retry for an assumed intermittent one, suspend and alert for an assumed permanent one. Critically, verify that a retry does not cause duplicate side effects when the first attempt actually succeeded, but its response was lost. Service virtualization, in which a dependency is scripted to fail N times and then succeed, is the cleanest way to test retry and backoff logic deterministically without depending on real network chaos. Component tests against real dependencies (a real broker, a real database) then close the gap between "my retry logic is unit tested" and "my retry logic works against the real client library's real failure modes." 3. Masking, Nonmasking, and Fail-Safe as a Test-Design Lens Before writing a test against a component under fault injection, decide which of the three failure-tolerance types the component is designed to provide, and write assertions that match that contract. safety heldsafety not held Liveness held Masking: the failure is fully hidden. Assert normal behavior even during fault injection. Nonmasking: progress continues but may misbehave. Assert eventual correctness, not correctness during the fault window. Liveness not held Fail-safe: assert that the system halts or rejects rather than risking a bad state. Not failure tolerant. Generally unacceptable. The classic example is a FIFO queue. A masking queue keeps delivering in order despite the fault. A nonmasking queue keeps delivering but may reorder during the fault. A fail-safe queue stops delivering rather than risk reordering. Asserting "no errors, ever" is an unstated masking assumption that most real components do not provide, and it can keep your suite perpetually and legitimately red. Wrapping Up This part explained liveness and safety in software. It enumerated what can fail, at the component level and the network level. It showed how to test detection and mitigation as separate, independently verifiable properties. Part 3 turns to the messages themselves: what delivery and processing guarantees are actually achievable, how to test idempotence as its own contract, and how to turn all three parts of this series into an observability setup and a checklist you can use directly in a test plan.
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.
Summary After six months of writing microservices with GitHub Copilot, I learned that the quality of generated code correlates directly with prompt specificity. Vague requests like "create a REST endpoint" resulted in code that ignored idempotency, retry logic, and failure scenarios — the exact behaviors that cost me debugging hours in QA. This article walks through a real order-processing example, showing how structured prompts that describe boundaries, failure modes, and test criteria produce production-grade code faster than either one-liners or guesswork. The Wake-Up Call Last spring, our team started using GitHub Copilot to accelerate Java microservice development. At first, I followed the obvious path: describe the feature in a sentence, accept the first suggestion, and move on. It worked until it didn't. I asked Copilot to "publish OrderCreated events to Kafka." It generated code that called producer.send() and hoped the message went through. In testing, I discovered that if the process crashed after saving the order but before publishing the event, the message never left the database. In production, this meant inventory overages and customer complaints about orders that appeared to be placed but never shipped. The real issue wasn't Copilot. It was me. I'd asked a one-line question and gotten a one-line answer. I'd skipped the part where I specify what should happen when infrastructure fails. That lesson drove me to develop a prompt structure that forces me to think clearly before asking Copilot to code. A Prompt Pattern That Works Over the following months, I refined this template and tested it on five microservices in our system: Plain Text Act as a senior Java engineer. In [module], implement [behavior]. Constraints: [Java/Spring versions, architecture, API contract]. Failures: [timeouts, duplicates, invalid input, partial outages]. Tests: [unit, component, contract, performance acceptance criteria]. First show the design and assumptions. Then make a small change. Do not change unrelated files. Explain tradeoffs and how to verify. The key improvements: Constraints force me to state what versions, frameworks, and architectural decisions apply.Failures push me to name specific failure modes before writing a line of code.Tests require me to specify how I'll know the code works under stress. This structure reduced my QA cycle time by roughly 30% because the generated code already anticipated the edge cases I would have caught later. 1. Start With the Domain, Not the Controller The Mistake I Made Early on, I asked Copilot to "create order service, classes." It generated a REST controller, a service, a repository, and a JPA entity all in one go. The code compiled and my first test passed. But when I integrated it with our actual domain model (which had Order aggregates, ValueObjects for OrderId, and explicit domain rules), the generated code was incompatible. The controller was mixing HTTP concerns with business logic. I spent half a day refactoring. The Better Approach Instead, I now ask: Plain Text Review this Spring Boot order module. Identify the Order aggregate, value objects, domain rules, and application ports. Keep HTTP, Kafka, database, and gRPC types outside the domain layer. Apply single-responsibility and dependency-inversion principles. Propose a minimal package structure before generating code. Do not add interfaces unless a real dependency boundary needs one. This time, Copilot proposed interfaces like: Java public interface OrderRepository { Optional<Order> findById(OrderId id); void save(Order order); } public interface InventoryGateway { InventoryDecision reserve(Order order); } When our gRPC client changed later (we switched from a proprietary RPC system to gRPC), the domain layer didn't need to know. We updated the adapter, not the Order class. That's when I realized domain-driven design isn't just academic; it's a practical time-saver when integration details change. Lesson Learned Don't ask for a complete microservice. Ask for the boundaries first. Code generation is faster when you've already sketched the architecture. 2. Make REST Behavior Explicit What I Tested and Found I deployed an idempotent POST endpoint that used an in-memory map to track Idempotency-Key headers. During our first load test with 5 replicas, a customer's retry request hit a different pod and got a duplicate response. The in-memory map only existed on the first pod. Copilot had done what I asked: "support idempotency." I hadn't asked it to think about distributed systems. The Refined Prompt Plain Text Implement POST /v1/orders in Spring Boot. Request: customerId, line items, delivery window. Return 201 with order ID and Location for a new order. Use Jakarta Bean Validation and consistent ProblemDetail errors. Support an Idempotency-Key header with durable deduplication. Return the stored result for a retry with the same key and payload; reject reuse of the same key with a different payload. Add MockMvc tests for 201, 400, 409, and identical retries. State the database uniqueness/transaction assumptions first. This time, Copilot proposed storing the key and request fingerprint in the database, with a unique constraint. It generated a test that simulated two concurrent first requests and verified that only one order was created. That test caught a race condition I would have missed. What Changed API contracts should be explicit before implementation. Include the request/response schema, HTTP status codes, error types, and idempotency strategy. Copilot's code quality jumped when I provided that context. 3. Event Delivery and the Outbox Pattern The Real Problem Telling Copilot to "publish OrderCreated events" results in this anti-pattern: Java orderService.save(order); kafkaProducer.send(orderCreatedEvent); If the second line fails, you have an order in the database but no event. Downstream services waiting for OrderCreated will never process this order. I saw this in production. A Kafka broker went down for 40 seconds. Orders were saved, events were lost, and our fulfillment system got out of sync. The Transactional Outbox Solution I now ask Copilot for the outbox pattern explicitly: Plain Text After order creation, publish OrderCreated using the transactional outbox pattern. Save the order and outbox row in one DB transaction. Use eventId, aggregateId, version, occurredAt, and schemaVersion. Provide a relay design and an idempotent consumer using eventId. Assume at-least-once delivery, retries, and out-of-order arrival. Show duplicate-event and relay-restart component tests. Copilot now produces: Java @Transactional public void createOrder(Order order, OrderCreatedEvent event) { orderRepository.save(order); outboxRepository.save(new OutboxEvent( UUID.randomUUID().toString(), // eventId order.getId().value(), // aggregateId order.version(), Instant.now(), event )); } And a relay job that periodically scans for unpublished events and sends them to Kafka. A component test verifies that if the relay crashes mid-send, restarting it publishes the message again without duplication (using eventId idempotence). Impact The outbox pattern takes one extra database round-trip. Our benchmarks showed <2ms overhead per order, negligible compared to network time to Kafka. But it eliminated a class of bugs: lost events. 4. gRPC and Timeout Propagation A Real Scenario Our order service calls an inventory service over gRPC with a 5-second timeout. The inventory service itself calls a warehouse database with a 10-second timeout. During a database slowdown, the inventory service exhausted its connection pool, and every call started timing out. But from the order service's perspective, each gRPC call was simply hitting the 5-second limit. We saw no degradation in error rates—just slow requests. It took three hours of tracing to realize the inventory service was queued up behind connection pool exhaustion. Copilot Prompt for Timeout Propagation Plain Text Implement a gRPC stub that calls inventory-service. Pass the request deadline from the calling context (gRPC deadline). If the context has <500ms left, fail fast instead of sending the RPC. Add observability: log deadline exceeded, pool exhaustion, and retries. Write component tests for: normal operation, deadline exceeded, connection pool exhaustion, and cascading slowdown. Use Micrometer metrics to expose connection pool state. Copilot now generates code that: Respects context deadlines and fails fast when time is running out.Metrics that expose connection pool usage, helping us spot saturation before it causes timeouts.A test that simulates pool exhaustion and verifies the error message and metrics. That test caught a misconfiguration in our test environment where the pool was sized for 10 but we were load-testing with 100 concurrent requests. Key Insight Timeouts are not just about infrastructure. They're about propagating caller intent through the call stack. When Copilot understands that architecture, it generates better code. 5. Testing: Layers and Trade-Offs Where I Went Wrong Initially Copilot can generate end-to-end tests that spin up Kafka, a database, and a gRPC stub. The tests pass and feel reassuring. But they're slow: 30 seconds per test, and they only catch integration bugs, not domain logic bugs. I had end-to-end tests for the idempotent POST endpoint. They passed locally. But when we deployed to staging with real infrastructure, a DNS timeout caused the retry logic to fail. The end-to-end test didn't simulate that. Structured Test Prompts I now ask Copilot to generate tests in layers: Unit tests: Plain Text Write unit tests for OrderService.createOrder(). Test: happy path, zero items (validation), duplicate order ID. Mock all dependencies; verify calls and return values. Use a test fixture factory for Order objects. Component tests: Plain Text Write a component test for POST /v1/orders. Use @WebMvcTest and mock external services (Kafka, inventory). Test: 201 for valid request, 400 for invalid input, 409 for duplicate. Verify the outbox record was created; simulate relay delay. Test idempotency: send same request twice, verify one order. Do not spin up real databases or message queues. Contract tests: Plain Text Write a contract test between order-service and inventory-service. Order sends a gRPC request; inventory responds with a decision. Test: success, timeout (500ms), invalid response. Use Pact to document the contract; publish results to the broker. Performance tests (with SLO context): Plain Text Create a k6 workload for POST /v1/orders. Target: p95 latency <200ms, error rate <0.1%, throughput >100/sec. (These are our actual SLOs from our runbook.) Use realistic unique idempotency keys and payload sizes. Track database latency and Kafka publish latency separately. Run from a staging environment; compare against baseline. Result Each layer catches different bugs. Unit tests catch logic errors. Component tests catch integration wiring errors. Contract tests catch API mismatches. Performance tests catch scaling issues. By being specific about which layer, I got Copilot to generate focused, fast tests that actually caught bugs before production. 6. Kubernetes Deployment With Observability Baked In The Hard Lesson We deployed our order service to Kubernetes without explicitly configuring liveness and readiness probes. The pod looked healthy (processes running), but one instance had an exhausted connection pool and was queued on every request. Kubernetes sent traffic to it anyway. Customers saw timeouts. The Deployment Prompt Plain Text Create a multi-stage Dockerfile for this Java service. Run as non-root; use a small maintained runtime image (e.g., eclipse-temurin:21-jre). Then generate Kubernetes Deployment, Service, and probes. Separate startup, readiness, and liveness checks. Startup: just verify the application has started. Readiness: verify the service can accept traffic (check pool, dependencies). Liveness: verify the process is alive; avoid false restarts. Add resource requests and limits based on our measurements: - requests: CPU 500m, memory 512Mi - limits: CPU 1000m, memory 1Gi Graceful shutdown: 30-second termination grace period. Do not put secrets in images or manifests. Document the deployment assumptions and how to roll back. Copilot generated a Deployment that: Used separate probe endpoints (the readiness probe actually checked the connection pool).Set an appropriate grace period for draining in-flight requests.Exposed metrics and environment variables for configuration. When we deployed this to staging, readiness probes started failing when the connection pool approached saturation, and Kubernetes automatically removed the pod from service. No more timeouts from saturated instances. 7. Service Mesh Configuration and Retry Budgets Where Layers Collided Our infrastructure team added a service mesh (Istio) to handle mutual TLS and observability. The default configuration retried failed requests at the mesh layer. Our order service was also configured to retry on 503. Customers were seeing duplicate orders because we were retrying POSTs twice. The Proper Prompt Review the order-service mesh configuration for retries. Do NOT retry non-idempotent POSTs at the mesh layer. Only retry GET and idempotent operations. Set mesh timeout to 10s, app timeout to 5s (so app timeout fires first). For each outbound route, document why retries are/are not safe. Explain how retries interact with the outbox pattern relay. Show a staged rollout plan with observable signals (error rate, latency). Copilot proposed a configuration where: The mesh did NOT retry POSTs.The app (order service) did NOT retry the Kafka publish (handled by the outbox relay instead).Each timeout was explicitly documented with justification. When a new engineer joined, they could read the config and understand the design intent, not just the mechanics. 8. Observability From the Start Operational Insight Six months into production, we realized our dashboards didn't show us what we actually needed to know. We had request latency (good), but not whether latency was from database queries, Kafka, or gRPC calls. We had error rates, but not which downstream service was failing most often. Copilot Prompt for Observability Plain Text Instrument the order-service with OpenTelemetry. Track: request rate, errors (with type), latency (p50/p95/p99), database query duration, Kafka publish latency, gRPC call latency. Use low-cardinality labels (e.g., operation, status). Do NOT add orderId as a metric label (too high cardinality). DO add orderId to traces and logs. Create an OpenTelemetry collector config and a Grafana dashboard. Document SLOs: p95 latency <200ms, error rate <0.1%. Show alerting rules for SLO violations. Copilot generated Prometheus metrics and a dashboard that showed: Order creation latency broken down by component (database, Kafka, gRPC).Kafka lag (how far behind the relay was).gRPC deadline exceeded errors vs. actual errors. That visibility let us spot that our inventory gRPC calls were taking 150ms on average, while database queries took 20ms. We optimized the gRPC client (connection pooling, deadlines), and p95 latency dropped from 350ms to 150ms. 9. Use Copilot as a Skeptic, Not a Final Authority The Mindset Shift The most valuable prompt isn't "Is this production-ready?" It's "Find the bugs": Plain Text Review this change as a skeptical senior engineer. Find: contract changes, race conditions, retry amplification, PII leaks, missing negative tests, and SOLID violations. For each issue cite file/line, risk, and a focused fix. Separate confirmed findings from assumptions. Do not claim tests passed unless you ran them yourself. Copilot actually flagged a subtle bug in our idempotent POST: if two concurrent requests with the same Idempotency-Key arrived while the first was still processing, the database unique constraint would cause a collision, but the error handling code assumed a parse error, not a collision. We would log it as a client error when it was a collision. A human senior engineer would have caught this in code review. But Copilot caught it when I asked it to think like a skeptic. What I'd Do Differently Now For a Brand New Microservice Sketch the domain model first (Order, OrderId, OrderStatus).Define the external contracts (REST API schema, events, gRPC proto).Ask Copilot to propose package structure and interfaces.Prompt for implementations one behavior at a time (create, update, cancel).For each behavior, ask for domain logic, then REST layer, then event publishing.Ask for tests before asking for code (test-driven).Review the generated code with the same skepticism you'd use for a new team member. For an Existing Microservice Identify a behavior you want to change (e.g., add retries, change a timeout).Ask Copilot to review the current code and propose changes.Specify the constraints and failure modes for the change.Ask for a test that verifies the change under stress.Run the test locally and against staging before merging. For Team Knowledge Copilot is a force multiplier for teams with clear architecture and design patterns. If your team has well-documented domain models, API contracts, and deployment standards, Copilot will amplify those. If you don't have those things, Copilot will amplify confusion.
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!
Agile
Career Development
Methodologies
Team Management
Staff Engineers in the Age of AI: Rethinking Technical Leadership
December 2, 2026
by Otavio Santana
CORE
Seven AI Adoption Failures and How to Overcome Them
December 1, 2026
by Stefan Wolpers
CORE
The Agent Returned the Right Answer but Took the Wrong Path
November 30, 2026 by Subhashini Raman
AI/ML
Big Data
Databases
IoT
API Regression Testing for Event-Driven Systems: Catching Breaking Changes in Async APIs
December 2, 2026 by Sancharini Panda
Telling a Language Model What a Fraud Ring Looks Like: A Snowflake Experiment
December 2, 2026
by Akmal Chaudhri
CORE
Building Fault-Tolerant MCP Servers With Temporal for Durable AI Agent Execution
December 2, 2026
by Akhil Madineni
CORE
Cloud Architecture
Integration
Microservices
Performance
Part 5: Automated Agent Evaluation and Regression Testing for MCP Tool Services
December 2, 2026
by Daniel Oh
CORE
API Regression Testing for Event-Driven Systems: Catching Breaking Changes in Async APIs
December 2, 2026 by Sancharini Panda
When One HTTP Metric Took Down Our Observability Stack
December 2, 2026 by Abhishake Reddy Onteddu
Frameworks
Java
JavaScript
Languages
Tools
Part 5: Automated Agent Evaluation and Regression Testing for MCP Tool Services
December 2, 2026
by Daniel Oh
CORE
Telling a Language Model What a Fraud Ring Looks Like: A Snowflake Experiment
December 2, 2026
by Akmal Chaudhri
CORE
Deployment
DevOps and CI/CD
Maintenance
Monitoring and Observability
Part 5: Automated Agent Evaluation and Regression Testing for MCP Tool Services
December 2, 2026
by Daniel Oh
CORE
API Regression Testing for Event-Driven Systems: Catching Breaking Changes in Async APIs
December 2, 2026 by Sancharini Panda
When One HTTP Metric Took Down Our Observability Stack
December 2, 2026 by Abhishake Reddy Onteddu
AI/ML
Java
JavaScript
Open Source
Building Fault-Tolerant MCP Servers With Temporal for Durable AI Agent Execution
December 2, 2026
by Akhil Madineni
CORE
Spec-Driven Delegation: Governing Uneven AI Coding Capacity
December 2, 2026 by Wallace Espindola