Testing Asynchronous Systems, Part 2: A Taxonomy of Failure, Detection, and Mitigation
Smarter GitHub Copilot Prompts for Java Microservices: From APIs to Production Tests
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.
TL;DR: A Successful AI Pilot Proves Nothing Thesis: This article explains seven AI adoption failures that follow a successful AI pilot, from unready data to overloaded reviewers and premature cuts, and how practitioners set the standard, collect the evidence, and inspect the results before scaling anything. Your AI pilot worked: the demo impressed the steering committee, the time savings on the slide looked fantastic, and the sponsor is already drafting the rollout budget. However, the AI pilot answered a narrower question than the budget. It showed that the technology can do the task under test conditions, with clean data, a hand-picked team, and a process that mainly exists in the standard operating procedures. Two questions remain open, and nobody has collected evidence for them: whether ordinary teams can run the workflow reliably, and whether expanding beyond the pilot pays off. Here are seven AI adoption failures that keep recurring in legacy organizations in 2026, each with a warning sign you can check this week, a countermeasure, plus five questions for the scaling decision itself. You do not need to own the budget to use them, because the evidence a scaling decision needs comes from the people closest to the work: they agree on the quality standard, for example, using the AI Definition of Done before the trial, collect the evidence while the workflow runs, and inspect the delegation over time in an AI Delegation Audit. Spoiler alert for the seasoned agile practitioner: If you lived through an Agile transformation, most of the failures will look familiar. History rhymes, and AI, as Agile, is no exception. Disclaimer: I read Charniak/McDermott’s book on "Artificial Intelligence" decades ago; of course, I use AI for research, translations, proofreading, challenging story arcs and article structures, creating artifacts such as graphics, and summarization. It is a production tool, not a substitute for thinking. The AI Pilot Succeeded, and That Is the Problem A small, well-designed AI experiment that fails is cheap: it costs a few weeks, a small budget, and some pride, and it usually teaches the organization something about its data and its processes. A successful pilot, however, can become expensive because it gives the sponsor what looks like evidence for a rollout the pilot never tested. Then, once the rollout begins, the AI meets the organization as it actually runs, and the expected outcome turns into escalations, workarounds, and change requests that nobody put on the original slide. None of this makes the AI pilot worthless. Testing a narrow technical hypothesis under controlled conditions is legitimate, and curated data and motivated volunteers may be exactly the right setup. The failure happens one step later, when the organization uses the result to answer a question the pilot never asked. There are three questions hidden behind "the AI pilot worked," and each of them needs different evidence: Can the technology do this task? Evidence: performance under specified test conditions, which is what a pilot usually delivers.Can ordinary teams run this workflow reliably? Evidence: results on representative cases, the exceptions, the support requests, and the time people spend preparing the input and reviewing the output.Should we scale the AI pilot? Evidence: value that holds over months, quality the recipients accept, the full operating cost including review, and an accountable owner who can stop the workflow when it fails. Too many rollout budgets get approved on the answer to the first question alone, resulting in preventable AI Adoption failures. To keep this concrete, I will follow one hypothetical AI pilot through the article (the organization and its numbers are invented): an AI drafts the weekly stakeholder status report from Jira for one product team, the team's product manager reviews each draft, the report goes out in 20 minutes instead of 3 hours, and the sponsor now wants the same for all 40 product teams by next quarter. In an earlier article on why AI transformations rhyme with Agile transformations, I described the greenfield showcase as one of five patterns the two share. The seven failures below follow once the applause fades, grouped by when they occur. Your Part When You Do Not Own the Budget If you are a Scrum Master, Project Manager, Product Owner, Product Manager, or Agile Coach, you probably do not decide about reskilling budgets or the rollout plan. Nevertheless, you sit closer to the evidence than anyone on the steering committee, and you can do five things for one expansion decision: Observe how the workflow actually runs, workarounds included.Name the assumptions the business case takes for granted.Agree with the recipients of the output on what "good enough" means.Count the preparation, review, correction, and exception handling the output requires.Recommend continuing, changing, or stopping, with the evidence behind it. None of this gives you authority over employment policy. However, it puts something better than the pilot slide in front of the people who have that authority and will help to avoid AI Adoption failures. Before You Start: Two AI Adoption Failures Decided in the Boardroom 1. You Never Created the Conditions Classic change management applies to AI adoption as much as it applied to every reorganization before it: people need to understand what is in it for them personally, and they need to believe the answer. Too often, the official message about AI is a license announcement on the intranet, while the unofficial message, the one people hear at the coffee machine, is that AI exists to reduce headcount. People act on the second message, and it is hard to blame them for it. If you want subject matter experts to share how the work really gets done (see failure 4), they need to hear, explicitly and from someone with authority, that the organization values their knowledge and expects AI to multiply what they can do with it. Nobody becomes AI-native by licensing Copilot, and creating the environment for lasting change is, as so often, primarily a people and culture effort. The counter-example everyone seems to cite these days comes from Ingka Group, the franchisee that runs most IKEA stores. According to Fortune's July 2026 report, Ingka introduced its customer service bot Billie in 2021 and retrained the roughly 8,500 call center employees whose routine work the bot took over, instead of laying them off. Their remote sales channel generated €1.25 billion in the last fiscal year. Investing in the people did not rule out early savings, either: Ingka's own 2023 account puts Billie's savings at nearly €13 million. (The hundreds of corporate roles Ingka and Inter IKEA cut in spring 2026 were, according to Fortune, neither in the remote sales centers nor attributed to AI.) My reading of the case is that the visible decision to keep the call center employees is what made the rest work. The warning sign: Ask five people outside the AI steering committee what the AI initiative means for their job. If the answers range from "nobody told us" to "they will cut us," the trust problem is unresolved, whatever the license report says. What to do instead: This countermeasure has two parts with different owners. Leadership must commit, in writing, to what happens to the time AI frees up, who decides about it, and how much reskilling the organization will fund before the first workflow changes. From inside the team, you can ask those five people yourself, take their answers to the sponsor unedited, and give your subject matter experts a role worth wanting: they decide whether the AI's output is good enough, which is exactly what an AI Definition of Done writes down. 2. You Gave It the Wrong Job The second failure begins with a list of use cases compiled by asking "Where can we use AI?" instead of "Where does our work wait, break, or get redone?" The answers then point AI at the wrong job in two ways. The first kind of wrong job needs no model at all: a weekly report that a spreadsheet formula could assemble, or a routing decision that a simple rule could make. A language model does such tasks less reliably and at a recurring cost. The question I now ask before the A3 Framework's three categories, Assist, Automate, and Avoid, is: "Does this task need a model at all?" If a rule, a script, or a feature of a deterministic system you already use can do it reliably, it is not an AI task. In the status report example, counting tickets per status and listing what moved since last week are jobs for a Jira filter or dashboard; the model earns its place only in the part that needs interpretation, such as explaining what the numbers mean for the stakeholder's next decision. The second kind of wrong job is a step that is not the bottleneck. If drafting a proposal takes 2 hours and its approval takes 3 weeks, an AI that drafts in 10 minutes saves time you can measure, yet it barely changes the lead time the customer experiences. Agile practitioners know this from flow metrics: accelerating a step that is not the constraint does little for the whole system. The warning sign: Your list of AI use cases has no column for where work waits, and nobody asked whether a simpler, deterministic solution exists. What to do instead: Map one value stream from request to delivery, find where the work waits longest, and ask of each candidate step whether it needs an AI model at all, before anyone discusses which model. From Pilot to Production: Three AI Adoption Failures in the Trenches 3. It Only Works in the AI Pilot The pilot's data was usually prepared for the AI pilot: someone picked a clean extract, removed duplicates, filled in missing fields, and decided which of three customer records was the real one. Production data comes without that service, often from several "sources of truth" that may contradict each other. The hypothetical pilot team closed its stale tickets and added the missing estimates before the first run, while the boards of the other 39 teams still carry tickets nobody has touched for a year and statuses that contradict the comments. In February 2025, Gartner put the condition plainly: according to analyst Roxane Edjlali, AI-ready data must be "representative of the use case," including its errors and outliers. A carefully built evaluation set can be representative by design, so curation, as such, is not the problem. The problem is a data set someone cleaned so that the pilot would succeed, combined with a business case that assumes nobody will ever have to do that cleaning again. The warning sign: Ask who prepared the pilot's data and how long it took. If the answer involves a person cleaning records by hand, find out which part was a one-time cleanup and which part recurs every week. The recurring part needs a person in production, too, and the business case probably does not include them. What to do instead: Test the workflow on a representative sample from the production system, messy cases and important exceptions included, in an environment your data protection and security people have approved. (Pushing a raw production extract full of customer records into an AI pilot tool can create a compliance problem of its own.) Then count how many cases need a human to repair the input first, because that number belongs in the business case. 4. You Can't Automate a Tangle Behind the process documentation of every legacy organization sits a second organization that actually keeps the work alive. Its members know whom to call when a shipment is stuck, how to work around a standard operating procedure that no longer describes reality and stands between the customer and the value, and when to simply ignore a rule to get things done. None of this is written down, which is one reason why it works, and also why nobody outside the team sees it. When you automate the documented process, you automate the fiction. The AI works from the standard operating procedure, and it may misread that procedure or depart from it in ways nobody anticipated. Meanwhile, the human workarounds drop out of the loop, and exceptions that used to be resolved with a phone call turn into escalations. Back in the status report pilot, the team's experienced product person knew that "In Review" on her board means "waiting for the vendor," and she corrected every draft accordingly before sending it. Nobody counted those corrections, and none of the other 39 teams has her. To make matters worse, the people who know the workarounds are often the same people who fear for their jobs (see failure 1), so they have little reason to volunteer what they know. The warning sign: Nobody on the AI project has spent a day with the people who do the work, and the process map came from the quality management handbook. What to do instead: Sit with the people who do the work and ask, "What do you do when this step fails?" For the workflow you want to delegate, and only for that one, write down the workarounds and handoffs, then decide which exceptions to keep, which to remove, and which to leave with people. That takes a few hours with the team instead of a process redesign program, and the result is the task split between human and AI that an A3 Handoff Canvas records before an agent takes over any work. 5. You Rolled It Out Everywhere at Once Giving everyone a license so that people can try things can be a reasonable decision. It turns into a failure when the organization treats that access as the rollout of a workflow it now depends on: it licenses Copilot for everyone, publishes a prompt guide on the intranet, and calls it a day. The Agile version of this pattern was the mandate from above combined with training treated as optional. The AI version adds a twist, however: the tool works well enough on individual tasks that the license report looks like success. For the status report, the big-bang version is 40 teams switching on the same Monday, with a prompt guide and no AI Definition of Done, so each team decides for itself what "checked" means. I have to include myself here. When I ran the founding workshop for my A3 Delegation System with practitioners in September 2026, their feedback was that the complete system overwhelmed them, and everyone took a rather cavalier approach to the preparation material. If motivated volunteers in a workshop feel that way, an organization-wide rollout with a license and an intranet page faces worse odds. I drew my own conclusions: the next workshop runs as three sessions instead of two long days, and in short formats, I now start with 2+2 templates instead of the whole system. The warning sign: Your rollout dashboard reports licenses activated and prompts sent, and it has no line for a workflow that changed. What to do instead: Start with one team and one workflow, support it with real training and someone to call when things break, and add the next team when the first one can explain what changed in its work, what it stopped doing, and what the change costs in review time. Once It Runs: Two AI Adoption Failures That Show Up in the Numbers 6. Your Experts Become the Queue AI on top of a dysfunctional operation accelerates the dysfunction, as I argued for Product Backlog management in AI on Top of a Dysfunctional System, and in most organizations, the acceleration shows up first in review capacity. The visible symptom is a sharp rise in the volume of artifacts: more drafts, reports, specifications, code, and slide decks than ever before. However, decisions do not happen any faster, because the bottleneck has moved to judgment, meaning the few people who understand the business well enough to check the AI's output for quality and compliance. They now review far more than before, on top of their regular work, and they either become a queue, which cancels the speed gain, or start waving things through, which hands the risk to your customers and your compliance function. (Remember Tobi Lütke's "slop grenades"?) For the status report AI pilot, this means that 40 AI-drafted reports a week land with the same three people in the PMO who know which numbers the board will question. At the same time, the stakeholders receive more reports than ever without deciding anything sooner. Three numbers tell you which way it goes: the review time per output, the share of outputs accepted without changes, and the time from output to decision. The break-even test I described in Measuring AI Impact uses the first two, and its simple form rests on two assumptions: a failed output means doing the task by hand, and every minute people spend on the workflow counts, including prompting and preparation. In short, compare the total human effort with and without AI at the quality the recipients accept. A high acceptance rate is good news, though, only as long as someone still spends real time on the review, which is what the creep check of the AI Delegation Audit watches. The warning sign: The volume of AI-generated artifacts rises, decisions do not get faster, and the same handful of experts appear as reviewers on everything. What to do instead: Budget review capacity before you scale generation, and protect your experts' time accordingly. Track the review time per output and the time to decision next to the volume, and treat every hiccup as a diagnosis of the underlying process before you speed it up any further. 7. You Bet Production on a Promise The last failure is probably the hardest to undo. The organization treats the AI pilot's result as a promise about production and then cuts headcount, retires the old process, or stops maintaining the fallback before production evidence exists. It often starts with the job description the sponsor gave the AI in the first place: delivering a cost saving by a budget deadline, before the workflow has shown that saving under production conditions and at its full cost. Erik Brynjolfsson, Daniel Rock, and Chad Syverson described the productivity J-curve at the level of national statistics: general purpose technologies require large, mostly intangible investments in new processes, skills, and business models, so measured productivity can look worse at first and better only later. A 2025 Census Bureau working paper by Kristina McElheran, Brynjolfsson, and colleagues found a similar shape inside firms: American manufacturers that adopted industrial AI saw short-term losses, concentrated among older businesses, while earlier adopters that survived grew faster over time. Among older plants, abandoning structured production-management practices accounted for roughly a third of the losses. Although the data covers industrial AI from 2017 to 2021, and dropping management practices is not the same as retiring a manual fallback, the analogy to a legacy organization that retires its old process too early is so close that you cannot ignore it. The dip, however, does not permit keeping a failing initiative alive indefinitely, which is why the evidence that would end it has to be agreed on before the dip starts. And in the status report pilot, the analyst who used to compile the reports by hand moves to another team, and three months later, when the AI's figures start to drift, nobody remembers how the reports were built, or who checks them when the responsible product person is on vacation. The warning sign: The business case shows payback within the budget year, and the old process, or the people who ran it, are already gone. What to do instead: Keep the fallback alive until production data, not AI pilot data, supports the claim. Name who checks the output when the usual reviewer is absent, and agree in advance what evidence at month six would tell you that you are in the dip and not at a dead end, including the result that makes you stop. Before You Expand or How to Avoid AI Adoption Failures: Five Questions for One Workflow The seven countermeasures come together in one decision: whether to scale a single workflow. Before you take that decision to the steering committee, check whether you can answer the following five questions with evidence, each of which already has a place in the A3 Delegation System: Does the task need a model at all, and what should improve? Name the baseline and the improvement you expect, so that "more output" cannot quietly become the success criterion; this is the question I now ask before the A3 Framework's three categories.Does it work on representative cases? Show results on a sample that includes the messy cases and the important exceptions.What does it cost in human effort? Count preparation, prompting, review, correction, and support, and compare the total with the effort without AI.What does "good enough" mean? An AI Definition of Done, agreed with the recipients, makes the quality standard inspectable: which claims get checked, by whom, and against which source.Who owns it, and how do you stop it? The "Validation" and "Failure response" fields of the A3 Handoff Canvas name who checks the output, what the fallback is, what the stop rule says, and who owns escalation. After the expansion, the AI Delegation Audit asks the same questions again, monthly or every other Sprint, because a workflow that passed once can drift: the inputs change, the model changes, and review time falls toward zero without anyone deciding so. What This Looks Like in Practice: An Extract From the Course The AI4Agile Online Course v4 includes a Jira Status Report Exercise that turns this article's running example into practice, set at MegaBrain.io, the fictional startup the course uses as its teaching case: a Jira export with 296 tickets across 58 columns, six findings planted in the data, and a CTO who needs a report he can defend in front of the founders. Before touching the AI, the student writes an AI Definition of Done for the task class "Status report for the CTO from a Jira export." Here is a condensed extract from my solution: Verification level: I trace every figure and every claim that would change the CTO's decision back to the export, record the assumption behind each one, and label what the export cannot support.Provenance disclosure: AI-assisted, with a closing line that names the assistant, the export, who checked the figures, and when.Sufficiency tier: A model that runs code on the uploaded file, because counting 296 rows is a calculation. A mid-tier model is my starting tier for this exercise, and it stays only as long as its reports pass this standard. When I tested the exercise in October 2026, three runs on ChatGPT and Claude all produced correct figures, and yet the drafts disagreed on the capacity assumption that decided the answer and on what to recommend. Correct arithmetic, therefore, settles only part of the check: the student still has to examine the assumption that connects the figures to the recommendation, which is why the AI Definition of Done asks for the assumption behind every figure, and why the student writes it before the first run. AI Adoption Failures – Conclusion: Start With One Workflow You Can Reach The seven failures feed each other: missing trust keeps the workarounds hidden, hidden workarounds and prepared data make the pilot unrepresentative, and an unrepresentative pilot justifies the big-bang rollout and the bet on a promise. Fixing the trust problem of a whole organization is rarely in your hands. However, you can start with one workflow you use or support, sit with the people who run it, write the AI Definition of Done together with the recipients of its output, and count the review time. When an expansion decision comes up, with or without a steering committee asking you, your answers to the five questions are ready. Key Questions This Article on AI Adoption Failures Answers Why Do Successful AI Pilots Fail in Production? A successful AI pilot usually shows that the technology can do a task under test conditions: prepared data, a motivated team, and a documented process. Production raises two further questions: whether ordinary teams can run the workflow reliably and whether expanding it pays off. Those require different evidence: representative cases, including exceptions; the human effort for preparation and review; an agreed quality standard; and an accountable owner with a fallback. How Can an Organization Tell Whether Its Data Is Ready for AI? Data is ready for AI when it represents the actual use case, including its errors, outliers, and exceptions, as Gartner analyst Roxane Edjlali puts it. A practical test is to run the AI on a representative sample from the production system, in an approved environment, and count how many cases need a human to repair the input first, separating one-time cleanup from preparation work that recurs every week. Why Does Scaling AI Output Overload the Experts Who Review It? When AI multiplies the volume of drafts, reports, specifications, and code, the capacity to judge that output stays flat. The bottleneck moves to the few experts who understand the business well enough to check quality and compliance, and they either become a queue or start waving work through. Teams should budget review capacity before they scale generation and track review time per output and the time to decision to avoid classic AI Adoption failures. What Is the Productivity J-Curve, and What Does It Mean for AI Adoption? The productivity J-curve, described by Erik Brynjolfsson, Daniel Rock, and Chad Syverson, explains why general purpose technologies such as AI can first depress measured productivity: organizations must invest in new processes, skills, and business models before the gains appear. A 2025 Census Bureau study found a similar pattern among manufacturers adopting industrial AI, concentrated in older businesses. Cutting staff or retiring the fallback before production evidence arrives can turn a temporary dip into a lasting failure. What Evidence Should a Team Have Before Expanding an AI Workflow? Before expanding, a team should be able to show the baseline and the intended improvement, results on representative cases and important exceptions, the total human effort including preparation, prompting, review, and correction, an agreed quality standard such as an AI Definition of Done, and an owner with a fallback and a stop rule, as recorded on an A3 Handoff Canvas. After the expansion, an AI Delegation Audit re-checks the workflow monthly or every other period.
You cannot tell reliably. In published tests, AI detectors applied to source code performed poorly, and the signs reviewers rely on, such as commit metadata and style patterns, can be removed or imitated. The more useful question is whether the code was reviewed and tested, because review and testing are what find the documented problems in AI-written code. The security record of AI-generated code is covered in a companion article: Vibe coding security: what the research and the incidents show. What Is AI Code Generation? AI code generation uses a large language model to produce source code from a natural-language request or the surrounding code. It takes three common forms: autocomplete inside an editor, chat that returns code on request, and agents that plan a task, edit files, and run commands. Most developers use these tools or plan to. In the 2025 Stack Overflow Developer Survey, "84% of respondents are using or planning to use AI tools in their development process." Sundar Pichai said on October 29, 2024, that "more than a quarter of all new code at Google is generated by AI, then reviewed and accepted by engineers." For a codebase written in the last two years, the likely answer to "is this code AI-generated" is therefore "partly." Can You Tell If Code Is AI-Generated? Not reliably. Peer-reviewed studies and the vendors of detection tools say the same thing. SourceDateWhat was testedFindingPan et al.January 8, 2024 (ICSE-SEET 2024)Five detectors, including GPTZero, Sapling and DetectGPT, on 5,069 Python problems and ChatGPT's solutions"existing AIGC Detectors perform poorly in distinguishing between human-written code and AI-generated code"Suh et al.November 6, 2024 (ICSE 2025)GPTZero, Sapling, GPT-2 Output Detector, DetectGPT, GLTR and the code-specific GPTSniffer, on code from four models"they all perform poorly and lack sufficient generalizability to be practically deployed"OpenAIJanuary 31, 2023Its own AI text classifier"it is unreliable on code". Withdrawn "As of July 20, 2023" because of "its low rate of accuracy"TurnitinRead October 3, 2026Its AI writing detection"does not reliably detect AI-generated text in the form of non-prose, such as poetry, scripts, or code" The detail supports the summaries. Suh et al. write of the general-purpose detectors that "their Accuracy is mostly less than 0.6", where 0.5 is a coin toss. The classifier the authors trained themselves reached "an F1 score of 82.55," which is better and still short of proof for any single file. Research detectors keep improving. Shi et al., first posted January 12, 2024, and presented at ICSE 2025, proposed a detector, DetectCodeGPT, and reported that it beat earlier methods in their experiments. The same paper opens by noting that language models "blur the distinctions between machine- and human-authored source code." Three limits apply to all of this research: The studies used models from 2023 and 2024, and mostly short functions from benchmark sets.A detector trained on one model's output must generalize to models released later.Code that a person edits after generation is a mix, and no study above claims to separate the two parts. A wrong result has a cost. OpenAI reported that its text classifier labeled human-written text as AI-written "9% of the time." Applied to a vendor's or an employee's code, an error rate like that means false accusations. What Signs Do Reviewers Actually Look For? Reviewers look at metadata first, then style, then mistakes models are known to make. Each sign is circumstantial. SignWhere to lookWhy it is weak evidenceTool trailers and bot authors in commitsgit log, pull request historyTrailers can be switched off or strippedAgent instruction filesRepository root and tool foldersShows a tool was set up, not which lines it wroteConcise, uniform code with a narrow vocabularyThe code itselfFormatters and style guides produce the same effectExplicit error handling everywhereThe code itselfCareful engineers write this tooNaming or formatting that shifts between filesAcross modulesCommon in any codebase with several authorsA dependency that does not existPackage manifestsRare from people, but a typo can cause it Metadata. Coding tools mark their work by default. Claude Code's documentation, read on October 3, 2026, states that "Commits get a git trailer such as Co-Authored-By by default," and documents a setting to "Change or hide the trailer Claude Code adds to commits." GitHub's documentation, read the same day, says: "Commits from Copilot cloud agent are authored by Copilot, with the person who started the task listed as co-author." Researchers depend on these markers and state the limit. Georgia Tech reported on April 13, 2026, that its Vibe Security Radar "can trace metadata like co-author tags, bot emails, and other known tool signatures, but it can't identify an issue if these markers have been removed." Researcher Hanqing Zhao added: "Claude Code and Copilot together account for most of what we detect, but that's partly because they leave the clearest signatures." Instruction files. Many agents read a project file of instructions. The AGENTS.md site, read on October 3, 2026, describes "a simple, open format for guiding coding agents" that is "used by over 60k open-source projects." Style. Shi et al. compared human and machine code and found that "Machines tend to write more concise code," and that machines prefer "a limited spectrum of frequently-used tokens, whereas human code exhibits a richer diversity in token selection." They also found that "Machine-authored code pays more attention to exception handling and object-oriented principles than human." These are averages across the datasets and models the authors tested. They do not settle the origin of one file. Review findings. CodeRabbit reported on December 17, 2025, from 470 open-source pull requests, that "Readability issues spiked more than 3× in AI contributions" and that "AI introduced nearly 2× more naming inconsistencies." CodeRabbit sells an AI review tool, and it could not verify authorship: "Since it was impossible to directly confirm authorship of each PR of a large enough OSS dataset, we checked for signals that a PR was co-authored by AI." Invented dependencies. Spracklen et al., first posted June 12, 2024 and presented at USENIX Security 2025, generated 576,000 code samples and found "the average percentage of hallucinated packages is at least 5.2% for commercial models and 21.7% for open-source models." An import of a package that has never existed is the closest thing to a fingerprint, and it is also a security risk. Why Do People Ask Whether Code Is AI-generated? People ask because of three concerns: security, maintainability, and ownership. Each has published evidence behind it. Security. Veracode reported on July 28, 2026, that "The average security pass rate across models is 56%" on its security tasks. Results varied by flaw type: models passed SQL injection tasks 83% of the time and cryptography tasks 87%, but "performance fell sharply on cross-site scripting at 15% and log injection at 12%." Veracode sells security testing, and the figures are pass rates on tasks built to test security. Maintainability. He et al., first posted November 6, 2025 and accepted at MSR '26, compared open-source projects that adopted Cursor with matched controls. They found "a statistically significant, large, but transient increase in project-level development velocity, along with a substantial and persistent increase in static analysis warnings and code complexity." Ownership. The US Copyright Office's report on copyrightability, published January 29, 2025, concludes that "Copyright does not extend to purely AI-generated material, or material where there is insufficient human control over the expressive elements." It also concludes that "The use of AI tools to assist rather than stand in for human creativity does not affect the availability of copyright protection for the output." How this applies to a given codebase is a question for counsel, and it matters in acquisitions and licensing. A fourth reason is misplaced confidence. In a user study by Perry et al., first posted November 7, 2022 and published at ACM CCS 2023, participants with an AI assistant "wrote significantly less secure code than those without access" and "were more likely to believe they wrote secure code". The model in that study is outdated, and the confidence effect is the finding that lasts. What Is the More Useful Question to Ask? The more useful question is whether the code was reviewed and tested, and by whom. The evidence supports this for three reasons. Authorship cannot be established. The detectors are unreliable, and the markers are optional, as shown above. The risks are properties of the code. A missing access check or unescaped output fails the same way whoever typed it, and both can be found by testing the code directly. Teams that use AI at scale pair it with review. Google's sentence ends with "then reviewed and accepted by engineers." He et al. conclude: "Our study identifies quality assurance as a major bottleneck for early Cursor adopters." Google's 2025 DORA report, announced September 24, 2025, puts it as "AI doesn't fix a team; it amplifies what's already there." Developers apply the same caution. In the 2025 Stack Overflow survey, "More developers actively distrust the accuracy of AI tools (46%) than trust it (33%)." For work delivered by a vendor, disclosure works better than detection. Ask in the contract which AI tools are used, require that tool trailers stay on, and require human review of every change. How Do You Review Code Regardless of Who Wrote It? Check nine things. Each maps to a failure documented in the research above, and none depends on knowing the author. #CheckWhat to look for1ExplanationA named engineer can explain each module and why it is built that way2Review historyEvery change went through a pull request that a second person approved3TestsAutomated tests exist, run on every change, and cover the paths that touch money and personal data4Access controlAuthorization is enforced on the server; test it logged out and as a different user5Input handlingForms and endpoints withstand hostile input, including script tags and log injection6SecretsNo keys in client code or in the git history7DependenciesEvery package exists, is the one intended, and has no known vulnerability8ComplexityStatic analysis runs in CI, and warnings are tracked over time9Error pathsThe code handles a failed call, a timeout, and an empty result Checks 4 and 5 target the classes where Veracode found models weakest. Check 7 follows Spracklen et al. Check 8 follows He et al. Check 9 follows CodeRabbit's finding that "Error handling and exception-path gaps were nearly 2× more common" in the AI-co-authored pull requests it reviewed. Key Takeaways No detector identifies AI-generated code dependably. Two ICSE studies found existing tools "perform poorly," and OpenAI and Turnitin say their text detectors are unreliable on code.Commit trailers and agent files show that a tool was used. They can be removed, and their absence proves nothing.Style patterns exist on average and do not settle the origin of a single file.The documented risks, such as weak input handling, rising complexity, and invented dependencies, can be tested directly.Ask who reviewed the code and which tests it passes. For vendors, require disclosure of AI tool use in the contract. References 2025 Stack Overflow Developer SurveyClaude Code's documentationGitHub's documentationAGENTS.md site
The Problem in One Section A production AI agent is a process that reads data, calls tools, and writes things — at machine speed, along action sequences nobody enumerated in advance. When we put that process on Kubernetes, the instinct is to hand it a service account with broad permissions and move on. The result is a principal with standing access that nobody reviews and a blast radius nobody scoped. Least privilege for agents is not a philosophy. It is a set of mechanisms, and Kubernetes already ships most of them: short-lived audience-bound tokens, RBAC, admission-enforced pod security, and network policy. In this lab, those mechanisms are five concrete enforcement points: projected tokens, TokenReview verification, the broker allowlist, the publish budget, and NetworkPolicy. The missing piece in most deployments is not the primitive — it is the pattern that wires them together. This tutorial builds that pattern as a reference implementation you can run in about 30–45 minutes, then tests every control the way an adversary would probe it. Three things change when the workload is an agent instead of a controller. First, action sequences are non-deterministic: you can write an RBAC policy for a controller because it does the same thing every time, but an agent's next action depends on model output, tool results, and conversation state, so "allow exactly what it needs" is a moving target. Second, tools are the real attack surface: an agent with a dozen tools is a dozen small programs, and most teams authorize the agent once for all of them — read access to private data plus a publish-capable tool, combined by an actor that sees no reason not to, is the canonical failure shape. Third, identities outlive their tasks: tokens issued for a ten-minute job become standing access when the session never ends. I designed the lab below around exactly these three properties. Nothing here is a production system. I built it as a lab, and it is labeled honestly as one. The point is that each mechanism in it is real, each boundary is enforced, and each test has an expected result you can verify with your own eyes. What You Will Learn By the end of this tutorial, you will be able to: Issue short-lived, audience-bound projected service-account tokens for each agent identity instead of handing agents long-lived credentials.Verify presented tokens through the Kubernetes TokenReview API — letting the API server, not local JWT decoding, decide whether a token is real and correctly scoped.Separate read and write authority behind a trusted tool broker, so agents hold identity but no direct Kubernetes API permissions.Enforce an action budget that halts a runaway agent after a fixed number of mutations.Lock agent egress with NetworkPolicy so the only reachable destinations are DNS and the broker.Read the broker's JSON audit trail to see exactly what each identity attempted and what the sandbox allowed. What You Will Build Two agent pods, agent-reader and agent-writer, each carrying a short-lived projected token for its own identity. They get no Kubernetes API permissions at all. Their only capability is talking to a trusted tool-broker service — the single write path in the system. The broker verifies every presented token through the Kubernetes TokenReview API, authorizes the caller against an allowlist, enforces a per-identity publish budget, and writes only to one named ConfigMap. NetworkPolicy then shrinks the blast radius further: agents can reach the broker and DNS, and nothing else. ComponentIdentityCan doCannot doagent-reader podagent-reader SA, projected token (aud agent-tools, 1h)Read the internal note via the brokerPublish; touch the K8s API; reach the internetagent-writer podagent-writer SA, projected token (aud agent-tools, 1h)Publish via the broker (budget: 3)Read the note; touch the K8s API; reach the internettool-brokertool-broker SACreate TokenReviews; get/patch/update the agent-output ConfigMapEverything else Figure 1 — Architecture: two agent identities, one trusted broker, one writable object. Guardrail checklists and architecture essays describe this pattern; the tutorial below implements it end-to-end as runnable code you can break and re-run. Most hand-rolled agent identity schemes stumble on the same step — verifying the token. This implementation gets it right by design: the broker never parses the JWT itself, and the API server, through TokenReview, is the only party that can vouch for a token's validity, identity, and audience. The trust boundary is the broker. The broker never decodes or verifies the JWT itself — that is the classic mistake. Verifying a signature locally only tells you who signed the token; only the API server can tell you whether it is currently valid, issued to that identity, and scoped to your audience. Re-implementing any of that yourself is how confused-deputy holes are born. Prerequisites A Kubernetes cluster with a policy-enforcing CNI such as Calico or Cilium. This matters: kind's default CNI does not enforce NetworkPolicy, so the egress test will not fail there. minikube start --cni=calico is a known-good starting point. An existing cluster with Calico or Cilium works too.kubectl, and kustomize (or kubectl 1.14+, which embeds it).About 30–45 minutes. Python 3.12 container images are pulled from the public registry, so the cluster nodes need registry access. Step 1: The Namespace and the Two Identities Everything lives in agent-lab. The namespace carries the restricted Pod Security Standard on all three tracks — enforce, audit, warn — so any pod that does not meet the restricted profile is rejected outright: YAML apiVersion: v1 kind: Namespace metadata: name: agent-lab labels: pod-security.kubernetes.io/enforce: restricted pod-security.kubernetes.io/enforce-version: latest pod-security.kubernetes.io/audit: restricted pod-security.kubernetes.io/audit-version: latest pod-security.kubernetes.io/warn: restricted pod-security.kubernetes.io/warn-version: latest The identities are plain ServiceAccounts with no roles attached. That is a deliberate choice: I made the projected tokens, not RBAC grants, the source of their authority. YAML apiVersion: v1 kind: ServiceAccount metadata: name: agent-reader namespace: agent-lab --- apiVersion: v1 kind: ServiceAccount metadata: name: agent-writer namespace: agent-lab --- apiVersion: v1 kind: ServiceAccount metadata: name: tool-broker namespace: agent-lab Step 2: Give the Broker — and Only the Broker — Scoped API Rights The broker needs exactly two capabilities from the Kubernetes API, and both are scoped to the minimum: create on tokenreviews (a ClusterRole, since TokenReview is cluster-scoped) so it can ask the API server to verify agent tokens.get/patch/update on the single named ConfigMap agent-output, so it can record publishes. The agent identities receive nothing: YAML apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: agent-lab-tokenreview rules: - apiGroups: ["authentication.k8s.io"] resources: ["tokenreviews"] verbs: ["create"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: agent-lab-broker-tokenreview roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: agent-lab-tokenreview subjects: - kind: ServiceAccount name: tool-broker namespace: agent-lab --- apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: name: agent-lab-output-writer namespace: agent-lab rules: - apiGroups: [""] resources: ["configmaps"] resourceNames: ["agent-output"] verbs: ["get", "patch", "update"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: agent-lab-broker-output-writer namespace: agent-lab roleRef: apiGroup: rbac.authorization.k8s.io kind: Role name: agent-lab-output-writer subjects: - kind: ServiceAccount name: tool-broker namespace: agent-lab Note the resourceNames restriction. A Role that allows patching "ConfigMaps" is a very different thing from a Role that allows patching the agent-output ConfigMap. Least privilege is always measured against the specific resource. Step 3: The Broker — TokenReview, Allowlist, Budget, Audit Log The broker is a stdlib-only Python service (no dependencies to audit, no framework to misconfigure). Read it carefully; every control in the lab is implemented here: Authentication: the presented bearer token is sent to POST /apis/authentication.k8s.io/v1/tokenreviews with spec.audiences: ["agent-tools"], using the broker pod's own in-cluster credentials. The broker then checks status.authenticatedand that status.audiences contains agent-tools — the TokenReview API docs call this out explicitly, because a token valid only against the API server's own audience would otherwise pass.Authorization: reader may GET /artifacts/internal-note; writer may POST /publish. The wrong pairing returns 403; a missing or bad token returns 401.Budget: three successful publishes per identity per broker process; the fourth returns 429. The counter is in memory on purpose — the code says so in a comment, and the production section below says what to use instead.Audit: one JSON line per request — timestamp, request id, username, action, status. The token is never logged. That rule matters more than it looks: the most common way identity systems leak is through their own logs.Inputs: JSON body only, 100 KiB cap, non-empty title/body strings with length limits. Python #!/usr/bin/env python3 """tool-broker -- the only write path for agent pods in agent-lab.""" import json import os import ssl import time import uuid import urllib.error import urllib.request from http.server import BaseHTTPRequestHandler, HTTPServer NAMESPACE = "agent-lab" EXPECTED_AUDIENCE = "agent-tools" READER = "system:serviceaccount:%s:agent-reader" % NAMESPACE WRITER = "system:serviceaccount:%s:agent-writer" % NAMESPACE NOTE_PATH = os.environ.get("NOTE_PATH", "/data/internal-note.txt") OUTPUT_NAME = os.environ.get("OUTPUT_CONFIGMAP", "agent-output") PUBLISH_BUDGET = 3 MAX_BODY_BYTES = 100 * 1024 LISTEN_PORT = int(os.environ.get("PORT", "8080")) SA_DIR = "/var/run/secrets/kubernetes.io/serviceaccount" def _k8s_request(method, path, body=None, content_type="application/json"): # Use the in-cluster DNS name so TLS hostname verification stays on. host = os.environ.get("KUBERNETES_SERVICE_DNS", "kubernetes.default.svc") port = os.environ.get("KUBERNETES_SERVICE_PORT", "443") with open(os.path.join(SA_DIR, "token"), "r", encoding="utf-8") as fh: sa_token = fh.read().strip() with open(os.path.join(SA_DIR, "ca.crt"), "rb") as fh: ca_data = fh.read() url = "https://%s:%s%s" % (host, port, path) data = json.dumps(body).encode("utf-8") if body is not None else None req = urllib.request.Request( url, data=data, method=method, headers={"Content-Type": content_type, "Authorization": "Bearer %s" % sa_token}) ctx = ssl.create_default_context(cadata=ca_data) # chain + hostname verified try: with urllib.request.urlopen(req, context=ctx, timeout=10) as resp: return resp.status, json.loads(resp.read().decode("utf-8")) except urllib.error.HTTPError as exc: payload = exc.read().decode("utf-8", "replace") try: return exc.code, json.loads(payload) except ValueError: return exc.code, {"error": payload} def verify_token(token): review = { "apiVersion": "authentication.k8s.io/v1", "kind": "TokenReview", "spec": {"token": token, "audiences": [EXPECTED_AUDIENCE]}, } status_code, payload = _k8s_request( "POST", "/apis/authentication.k8s.io/v1/tokenreviews", review) if status_code not in (200, 201, 202): return None status = payload.get("status", {}) if not status.get("authenticated"): return None if EXPECTED_AUDIENCE not in status.get("audiences", []): return None return status.get("user", {}).get("username") def record_publish(title, body): patch = {"data": {"lastTitle": title, "lastBody": body} status_code, _ = _k8s_request( "PATCH", "/api/v1/namespaces/%s/configmaps/%s" % (NAMESPACE, OUTPUT_NAME), patch, content_type="application/merge-patch+json", ) if status_code not in (200, 201, 202): raise RuntimeError("ConfigMap patch failed with status %s" % status_code) class BrokerHandler(BaseHTTPRequestHandler): server_version = "tool-broker/1.0" budgets = {} # in-memory on purpose; production needs durable state def log_message(self, *args): pass # silence default access logging def log_json(self, username, action, status, extra=None): record = { "ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "rid": getattr(self, "rid", "-"), "username": username, "action": action, "status": status, } if extra: record.update(extra) print(json.dumps(record), flush=True) # the token is never logged def _respond(self, status, payload, username, action, extra=None): body = json.dumps(payload).encode("utf-8") self.send_response(status) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) self.log_json(username, action, status, extra) def _bearer_token(self): auth = self.headers.get("Authorization", "") scheme, _, value = auth.partition(" ") if scheme.lower() != "bearer" or not value: return None return value def _authenticate(self, action): token = self._bearer_token() if not token: self._respond(401, {"error": "missing bearer token"}, "anonymous", action) return None try: username = verify_token(token) except Exception as exc: self._respond(502, {"error": "identity verification unavailable"}, "anonymous", action, {"detail": str(exc)}) return None if not username: self._respond(401, {"error": "invalid or mis-scoped token"}, "anonymous", action) return None return username def do_GET(self): self.rid = uuid.uuid4().hex[:12] path = self.path.split("?", 1)[0] action = "GET %s" % path username = self._authenticate(action) if not username: return if path == "/artifacts/internal-note": if username != READER: self._respond(403, {"error": "forbidden"}, username, action) return try: with open(NOTE_PATH, "r", encoding="utf-8") as fh: note = fh.read() except OSError as exc: self._respond(500, {"error": "note unavailable"}, username, action, {"detail": str(exc)}) return self._respond(200, {"note": note}, username, action) return self._respond(404, {"error": "not found"}, username, action) def do_POST(self): self.rid = uuid.uuid4().hex[:12] path = self.path.split("?", 1)[0] action = "POST %s" % path username = self._authenticate(action) if not username: return if path != "/publish": self._respond(404, {"error": "not found"}, username, action) return if username != WRITER: self._respond(403, {"error": "forbidden"}, username, action) return length = self.headers.get("Content-Length") try: n = int(length) if length else 0 except ValueError: n = 0 if n > MAX_BODY_BYTES: self._respond(413, {"error": "body too large"}, username, action) return raw = self.rfile.read(n) if n else b"" try: payload = json.loads(raw.decode("utf-8")) if raw else {} except (UnicodeDecodeError, ValueError): self._respond(400, {"error": "body must be JSON"}, username, action) return title = payload.get("title") body = payload.get("body") if (not isinstance(title, str) or not isinstance(body, str) or not title or not body): self._respond(400, {"error": "need non-empty 'title' and 'body' " "strings"}, username, action) return if len(title) > 2000 or len(body) > 100000: self._respond(400, {"error": "title/body exceed length limits"}, username, action) return used = BrokerHandler.budgets.get(username, 0) if used >= PUBLISH_BUDGET: self._respond(429, {"error": "publish budget exhausted"}, username, action, {"used": used, "budget": PUBLISH_BUDGET}) return try: record_publish(title, body) except Exception as exc: self._respond(500, {"error": "publish failed"}, username, action, {"detail": str(exc)}) return BrokerHandler.budgets[username] = used + 1 self._respond(202, {"published": True, "budget_used": used + 1, "budget": PUBLISH_BUDGET}, username, action, {"title": title}) def main(): server = HTTPServer(("0.0.0.0", LISTEN_PORT), BrokerHandler) print(json.dumps({"ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "event": "broker listening", "port": LISTEN_PORT}), flush=True) try: server.serve_forever() except KeyboardInterrupt: pass if __name__ == "__main__": main() The broker runs as a Deployment with its code and the internal note mounted from ConfigMaps (read-only), a ClusterIP Service on port 8080, and the same restricted hardening as everything else in this lab. Its own service account token is automounted — the broker is a trusted first-party component and needs its identity to call the API server. The demo data the broker serves is fictional, and it says so in the file itself: YAML apiVersion: v1 kind: ConfigMap metadata: name: internal-note namespace: agent-lab data: internal-note.txt: | DEMO CONTENT — this note is fictional and exists only for the lab. ... Step 4: The Agent Pods — Projected Tokens, Nothing Else Each agent pod gets exactly one credential: a projected ServiceAccount token with audience: agent-tools and a one-hour lifetime, mounted at /var/run/secrets/agent/token. The in-cluster token is not automounted (automountServiceAccountToken: false), which is the whole point — kubectl auth can-i will confirm these identities cannot touch the API at all. YAML spec: serviceAccountName: agent-reader automountServiceAccountToken: false ... volumes: - name: agent-token projected: sources: - serviceAccountToken: audience: agent-tools expirationSeconds: 3600 path: token Every container in the lab — broker and agents — runs with the same restricted-compatible profile: non-root user, seccompProfile.type: RuntimeDefault, allowPrivilegeEscalation: false, all capabilities dropped, read-only root filesystem, PYTHONDONTWRITEBYTECODE=1 so the interpreter never tries to write .pyc files. A tiny caller.py (stdlib only) rides along in each agent pod via a ConfigMap. It reads the projected token fresh from disk on every call — projected tokens rotate, so caching them is a bug — and performs the requested action against the broker: Python def _call(method, path, payload=None): with open(TOKEN_PATH, "r", encoding="utf-8") as fh: token = fh.read().strip() # fresh read every call req = urllib.request.Request( BROKER_URL + path, data=data, method=method, headers={"Authorization": "Bearer %s" % token, "Content-Type": "application/json"}) ... # usage inside the pod: # python3 /app/caller.py read # python3 /app/caller.py publish "demo title" "demo body" Step 5: Shrink the Network Blast Radius Identity controls what an agent may ask for. NetworkPolicy controls what it can reach. Agents accept no inbound traffic at all and may only talk to the broker on port 8080, plus DNS in kube-system: YAML apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: agent-default-deny namespace: agent-lab spec: podSelector: matchLabels: agent-lab/component: agent policyTypes: [Ingress, Egress] ingress: [] # deny all inbound traffic to agent pods egress: - to: - podSelector: matchLabels: app: tool-broker ports: - protocol: TCP port: 8080 - to: - namespaceSelector: matchLabels: kubernetes.io/metadata.name: kube-system podSelector: {} ports: - protocol: UDP port: 53 - protocol: TCP port: 53 A second policy locks the broker's ingress to agent pods on port 8080. This is the control that turns "the agent decided to exfiltrate" into "the connection timed out." Step 6: Run the Tests How this was verified. No live cluster was used during writing: the broker's authorization and budget logic was checked with an automated test suite that stubs the TokenReview call and the ConfigMap patch: missing token → 401, bad token → 401, reader read → 200, reader publish → 403, writer read → 403, three publishes → 202 each, fourth publish → 429, with exactly three patches recorded (10/10 checks passed). The cluster steps below are your live run of that same matrix; this tutorial does not claim an observed live-cluster execution. Deploy everything with kustomize, which generates the ConfigMaps from the Python files: Shell cd agent-security-lab kubectl apply -k . kubectl rollout status deploy/tool-broker -n agent-lab kubectl get pods -n agent-lab Now probe the sandbox the way an adversary — or a confused agent — would. 1. The reader can read (expect 200): Shell kubectl exec -n agent-lab agent-reader -- python3 /app/caller.py read HTTP HTTP 200 {"note": "DEMO CONTENT — this note is fictional and exists only for the lab.\n..."} 2. The reader cannot publish (expect 403): Shell kubectl exec -n agent-lab agent-reader -- python3 /app/caller.py publish "x" "y" HTTP HTTP 403 {"error": "forbidden"} 3. The writer cannot read (expect 403): Shell kubectl exec -n agent-lab agent-writer -- python3 /app/caller.py read HTTP HTTP 403 {"error": "forbidden"} 4. The writer can publish — three times — and the ConfigMap shows it: Shell kubectl exec -n agent-lab agent-writer -- python3 /app/caller.py publish "demo-1" "first write" kubectl exec -n agent-lab agent-writer -- python3 /app/caller.py publish "demo-2" "second write" kubectl exec -n agent-lab agent-writer -- python3 /app/caller.py publish "demo-3" "third write" kubectl get configmap agent-output -n agent-lab -o jsonpath='{.data.lastTitle}{"\n"}{.data.lastBody}{"\n"}' HTTP HTTP 202 {"published": true, "budget_used": 1, "budget": 3} HTTP 202 {"published": true, "budget_used": 2, "budget": 3} HTTP 202 {"published": true, "budget_used": 3, "budget": 3} demo-3 third write 5. The fourth publish is refused (expect 429): Shell kubectl exec -n agent-lab agent-writer -- python3 /app/caller.py publish "demo-4" "over budget" HTTP HTTP 429 {"error": "publish budget exhausted", "used": 3, "budget": 3} This is the containment control working as designed: a runaway agent gets exactly three mutations and then stops, no matter what it believes it should do next. 6. The agent identities have no Kubernetes API access: Shell kubectl auth can-i get secrets --as=system:serviceaccount:agent-lab:agent-reader -n agent-lab kubectl auth can-i get configmaps --as=system:serviceaccount:agent-lab:agent-writer -n agent-lab Plain Text no no 7. Every request leaves one audit line, and tokens never appear in logs: Shell kubectl logs -n agent-lab deploy/tool-broker | tail -4 JSON ... {"ts": "2026-10-14T19:40:02Z", "rid": "a3f19c2d81be", "username": "system:serviceaccount:agent-lab:agent-writer", "action": "POST /publish", "status": 202, "title": "demo-3"} {"ts": "2026-10-14T19:40:11Z", "rid": "2c1e4b9f30d2", "username": "system:serviceaccount:agent-lab:agent-writer", "action": "POST /publish", "status": 429, "used": 3, "budget": 3} 8. External egress fails on a policy-enforcing CNI (CNI-dependent test): Shell kubectl exec -n agent-lab agent-reader -- timeout 8 python3 -c \ "import socket; socket.create_connection(('1.1.1.1', 443), timeout=5)" Python Traceback (most recent call last): ... TimeoutError: timed out On kind's default CNI, this test will succeed — that is the prerequisite warning, not a lab bug. The policy is applied correctly; kindnetd simply does not enforce it. Cleanup: Shell kubectl delete namespace agent-lab The broker's decision path, drawn from broker.py, is worth keeping in front of you while you read the tests above — every request walks the same corridor, and every rejection is a gate with a code: Figure 2 — The broker's decision path for every request. Troubleshooting External-egress test still succeeds. Symptom: test 8 reaches 1.1.1.1:443 instead of timing out. Cause: the cluster's CNI does not enforce NetworkPolicy — kind's default CNI (kindnetd) installs the policy objects but never applies them. Fix: run the lab on a policy-enforcing CNI such as Calico or Cilium; minikube start --cni=calico is a known-good starting point. Every broker call returns 401 or 502. Symptom: the caller gets {"error": "invalid or mis-scoped token"}, or the broker answers 502 identity verification unavailable. Cause: the broker cannot reach the TokenReview endpoint, or the presented token is not meant for this service. Fix: check kubectl logs -n agent-lab deploy/tool-broker for the underlying error; confirm the ClusterRoleBinding grants the broker's ServiceAccount create on tokenreviews; and confirm the projected volume's audience is exactly agent-tools in both agent pod specs. Agent pods stuck Pending or rejected at admission. Symptom: kubectl get pods -n agent-lab shows Pending, or kubectl describe pod reports a forbidden admission error. Cause: the agent-lab namespace enforces the restricted Pod Security Standard, and any pod that violates it is rejected. Fix: confirm each pod's securityContext sets runAsNonRoot: true, seccompProfile.type: RuntimeDefault, allowPrivilegeEscalation: false, and capabilities.drop: ["ALL"] — the manifests in this lab already do. Publish returns 500. Symptom: {"error": "publish failed"} on a POST the allowlist should permit. Cause: the broker's own Role does not actually permit the write. Fix: confirm the agent-lab-output-writer RoleBinding exists in agent-lab and its resourceNames contains exactly agent-output; the broker patches one named ConfigMap and nothing else, so a renamed or missing ConfigMap fails closed. Taking This to Production: What the Lab Deliberately Leaves Out The lab's budget counter lives in broker memory; a restart resets it. Production budgets must be durable — etcd, Redis, or a database with atomic increments — and scoped per task, not per process. The audit lines go to stdout; production ships them to a tamper-evident store the agent cannot reach, with alerts on the 429s and 403s, not just retention. Three more things a real deployment adds. First, admission policy: the pattern in this lab should be enforced, not suggested. A policy engine such as Kyverno or OPA Gatekeeper can require automountServiceAccountToken: false, projected tokens with a sane expirationSeconds, and the restricted security context on every agent pod — so the sandbox is the default, not an option somebody remembers to apply. Second, per-task pods: long-lived agent identities accumulate authority. Minting a fresh pod and identity per task, with the token expiring with the task, bounds every session the way the lab bounds every publish. Third, human approval for high-risk actions: the broker's allowlist is static here. In production, the dangerous subset of tools — anything that writes, deletes, or crosses a trust boundary — sits behind an approval step or a policy check, not just an allowlist entry. And one response mechanism the lab does not demonstrate, but every deployment needs: a kill switch with quarantine-first semantics. When monitoring flags anomalous agent behavior — unusual data access patterns, write volume spikes, calls to unexpected destinations — the response should be automatic containment: revoke the session tokens, freeze the write identity, preserve the audit trail. You can always re-issue access after review; you cannot un-publish what a runaway agent already sent. The budget 429s and the 403s in the broker logs are the signals this switch consumes. And the internal note's stand-in for a secret store should be exactly that: a secret store with dynamic, short-lived credentials, never a ConfigMap. Trade-Offs, Stated Plainly This pattern is friction, and friction has a price. Per-agent projected tokens mean token plumbing everywhere a caller touches. A broker in front of every tool is a new service to operate, scale, and secure — and it becomes the most attractive target in the system, which is why its own RBAC is the tightest in the lab. Budgets turn "the agent did something wrong a thousand times" into "it did it three times and stopped," but they also turn a legitimate long task into a 429 that needs a human to raise the ceiling. Default-deny egress breaks the first integration that assumed the open internet, and the person who allowlists the fix had better write down why. The alternative is standing access for non-deterministic actors, reviewed never and rotated never, with no containment when the run goes sideways. That is not a trade-off; that is the absence of one. The mechanisms in this lab — verified identity, separated authorities, budgets, egress that defaults to no, audit trails that assume the actor will surprise you — are the price of running agents in production. Pay it deliberately, or pay it later in incident reviews. Conclusion Agents are principals now, but Kubernetes still provisions most of them like interns on their first day: broad access, issued once, reviewed never. This lab shows the other shape — short-lived audience-bound identity verified through TokenReview, a trusted broker as the only write path, allow-listed tools, action budgets, and a network that defaults to no — as running code you can test in about 30–45 minutes. None of these mechanisms is new. What the lab adds is their composition in one request path — TokenReview, then allowlist, then budget, then a single named write, then an audit line — applied to the workloads that need it most. The complete lab — every manifest, the kustomize setup, and both Python files — is printed in full in this article and its appendix, so you can reproduce it exactly; only the stubbed broker unit tests live outside it, and their results are quoted in Step 6. Run it, break it, and then decide which controls your agents are missing. References ServiceAccount token volume projection – projected tokens, audiences, and expirationSecondsTokenReview API reference – authentication.k8s.io/v1 request/response shapes and audience validationNetworkPolicy – ingress/egress rules and the policy-enforcing CNI requirementPod Security Standards – the restricted profile enforced on the lab namespace Appendix: The Remaining Manifests The walkthrough above prints the namespace, the service accounts, the RBAC, the demo data ConfigMap, the agent NetworkPolicy, and the broker code in full. The rest of the lab — the pieces the steps describe but do not print — is reproduced here, copied verbatim, so the article is self-contained. The broker's Deployment and Service: YAML # The tool-broker is the only write path in the lab. It is a trusted # first-party component: its own service account token is automounted so it # can call the TokenReview API and patch the single "agent-output" # ConfigMap -- nothing else. apiVersion: apps/v1 kind: Deployment metadata: name: tool-broker namespace: agent-lab spec: replicas: 1 selector: matchLabels: app: tool-broker template: metadata: labels: app: tool-broker spec: serviceAccountName: tool-broker securityContext: runAsNonRoot: true runAsUser: 10001 runAsGroup: 10001 seccompProfile: type: RuntimeDefault containers: - name: broker image: python:3.12-alpine command: ["python3", "/app/broker.py"] ports: - name: http containerPort: 8080 env: - name: PYTHONDONTWRITEBYTECODE value: "1" - name: NOTE_PATH value: /data/internal-note.txt volumeMounts: - name: code mountPath: /app readOnly: true - name: note mountPath: /data readOnly: true securityContext: allowPrivilegeEscalation: false capabilities: drop: ["ALL"] readOnlyRootFilesystem: true runAsNonRoot: true volumes: - name: code configMap: name: broker-code items: - key: broker.py path: broker.py defaultMode: 0444 - name: note configMap: name: internal-note items: - key: internal-note.txt path: internal-note.txt defaultMode: 0444 --- apiVersion: v1 kind: Service metadata: name: tool-broker namespace: agent-lab spec: type: ClusterIP selector: app: tool-broker ports: - name: http port: 8080 targetPort: 8080 The two agent pods in full: YAML # Two agent pods. Each carries a short-lived, audience-bound projected # token (audience "agent-tools", 1 hour) for its own identity, mounted at # /var/run/secrets/agent/token. The in-cluster service account token is # NOT automounted, so the pods cannot talk to the Kubernetes API at all. apiVersion: v1 kind: Pod metadata: name: agent-reader namespace: agent-lab labels: agent-lab/component: agent agent-lab/role: reader spec: serviceAccountName: agent-reader automountServiceAccountToken: false securityContext: runAsNonRoot: true runAsUser: 10001 runAsGroup: 10001 seccompProfile: type: RuntimeDefault containers: - name: agent image: python:3.12-alpine command: ["tail", "-f", "/dev/null"] env: - name: PYTHONDONTWRITEBYTECODE value: "1" - name: AGENT_ROLE value: reader - name: AGENT_TOKEN_PATH value: /var/run/secrets/agent/token - name: BROKER_URL value: "http://tool-broker:8080" volumeMounts: - name: agent-token mountPath: /var/run/secrets/agent readOnly: true - name: caller-code mountPath: /app readOnly: true securityContext: allowPrivilegeEscalation: false capabilities: drop: ["ALL"] readOnlyRootFilesystem: true runAsNonRoot: true volumes: - name: agent-token projected: sources: - serviceAccountToken: audience: agent-tools expirationSeconds: 3600 path: token - name: caller-code configMap: name: caller-code items: - key: caller.py path: caller.py defaultMode: 0444 --- apiVersion: v1 kind: Pod metadata: name: agent-writer namespace: agent-lab labels: agent-lab/component: agent agent-lab/role: writer spec: serviceAccountName: agent-writer automountServiceAccountToken: false securityContext: runAsNonRoot: true runAsUser: 10001 runAsGroup: 10001 seccompProfile: type: RuntimeDefault containers: - name: agent image: python:3.12-alpine command: ["tail", "-f", "/dev/null"] env: - name: PYTHONDONTWRITEBYTECODE value: "1" - name: AGENT_ROLE value: writer - name: AGENT_TOKEN_PATH value: /var/run/secrets/agent/token - name: BROKER_URL value: "http://tool-broker:8080" volumeMounts: - name: agent-token mountPath: /var/run/secrets/agent readOnly: true - name: caller-code mountPath: /app readOnly: true securityContext: allowPrivilegeEscalation: false capabilities: drop: ["ALL"] readOnlyRootFilesystem: true runAsNonRoot: true volumes: - name: agent-token projected: sources: - serviceAccountToken: audience: agent-tools expirationSeconds: 3600 path: token - name: caller-code configMap: name: caller-code items: - key: caller.py path: caller.py defaultMode: 0444 The broker-side NetworkPolicy, which locks the broker's ingress to agent pods on port 8080: YAML apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: broker-ingress namespace: agent-lab spec: podSelector: matchLabels: app: tool-broker policyTypes: [Ingress] ingress: - from: - podSelector: matchLabels: agent-lab/component: agent ports: - protocol: TCP port: 8080 The kustomize entry point: YAML apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization namespace: agent-lab resources: - manifests/namespace.yaml - manifests/serviceaccounts.yaml - manifests/rbac.yaml - manifests/data-configmaps.yaml - manifests/broker.yaml - manifests/agents.yaml - manifests/networkpolicy.yaml configMapGenerator: - name: broker-code files: - code/broker.py - name: caller-code files: - code/caller.py generatorOptions: disableNameSuffixHash: true The full caller.py: Python #!/usr/bin/env python3 """caller -- runs inside the agent pods to exercise the tool-broker. Reads the projected ServiceAccount token fresh from disk on every call. Projected tokens are rotated by the kubelet, so the token is deliberately never cached. The token is presented in an Authorization header and never printed. """ import json import os import sys import urllib.error import urllib.request TOKEN_PATH = os.environ.get("AGENT_TOKEN_PATH", "/var/run/secrets/agent/token") BROKER_URL = os.environ.get("BROKER_URL", "http://tool-broker:8080") def _call(method, path, payload=None): with open(TOKEN_PATH, "r", encoding="utf-8") as fh: token = fh.read().strip() data = json.dumps(payload).encode("utf-8") if payload is not None else None req = urllib.request.Request( BROKER_URL + path, data=data, method=method, headers={"Authorization": "Bearer %s" % token, "Content-Type": "application/json"}) try: with urllib.request.urlopen(req, timeout=10) as resp: return resp.status, resp.read().decode("utf-8") except urllib.error.HTTPError as exc: return exc.code, exc.read().decode("utf-8", "replace") def main(argv): if len(argv) < 2 or argv[1] not in ("read", "publish"): print("usage: caller.py read | caller.py publish <title> <body>", file=sys.stderr) return 2 if argv[1] == "read": status, body = _call("GET", "/artifacts/internal-note") else: if len(argv) != 4: print("usage: caller.py publish <title> <body>", file=sys.stderr) return 2 status, body = _call("POST", "/publish", {"title": argv[2], "body": argv[3]}) print("HTTP %s" % status) print(body) return 0 if __name__ == "__main__": sys.exit(main(sys.argv)) With these files, kubectl apply -k . from the lab directory deploys the complete sandbox exactly as tested in Step 6.
If you've ever reached for SQLite to answer a question about a CSV, you already know the appeal: no server, one file, connect() and go. Relate (formerly CypherLite), a Neo4j project, brings that experience to graph data. It's an embedded graph database written in Rust, queried in Cypher, and runs inside your Python process. This article uses it in a notebook on a dataset that is naturally a graph, the London Underground. We'll load stations and connections, ask questions that would need self-joins in SQL, such as: What's within three stops?Which stations are interchanges?How do I get from A to B? and hand the results to pandas. The SQLite parallels are close. The database is a single .cl file or lives in memory. The Python API is connect() and execute() with named parameters, and rows come back keyed by column name. There is no daemon to start and no connection string. The full source code is available on GitHub. Install And Run A First Query The package is called relate-db on PyPI and imported as relate. Relate ships prebuilt wheels for Windows, Linux, and macOS, so there's nothing to compile. It needs Python 3.9 or later; the pinned package versions in the accompanying notebook need Python 3.11 or later. If you've used sqlite3, the first query will look familiar: Python db = relate.connect(":memory:") # or a path such as "tube.cl" db.execute("CREATE (:Station {name: $name})", {"name": "Kennington"}) for row in db.execute("MATCH (s:Station) RETURN s.name AS name"): print(row["name"]) execute() takes the query and a dictionary of parameters, and each row is addressable by column name. Use parameters rather than string formatting, for the same reason you would in SQL. Load The London Underground Data The dataset is three CSV files: Stations with coordinatesConnections between neighboring stations with the line that serves themA list of lines The connections file also holds other London rail lines, so the code keeps only the lines in the lines file. We'll read the files with pandas and pass the rows as a parameter. UNWIND turns the list into one row per record, similar to executemany in SQLite. Python stations = pd.read_csv("data/london_stations.csv") links = pd.read_csv("data/london_connections.csv") lines = pd.read_csv("data/london_lines.csv") for frame in (stations, links, lines): frame.columns = frame.columns.str.strip() # Keep the lines in the lines file, and only the stations those lines touch. links = links[links["Tube Line"].str.strip().isin(set(lines["Tube Line"].str.strip()))] used = set(links["From Station"].str.strip()) | set(links["To Station"].str.strip()) stations = stations[stations["Station"].str.strip().isin(used)] db = relate.connect("tube.cl") db.execute( "UNWIND $rows AS r " "MERGE (s:Station {name: r.name}) " "SET s.lat = r.lat, s.lon = r.lon", {"rows": [ {"name": str(r["Station"]).strip(), "lat": float(r["Latitude"]), "lon": float(r["Longitude"])} for r in stations.to_dict("records") ]}, ) db.execute( "UNWIND $rows AS r " "MATCH (a:Station {name: r.a}), (b:Station {name: r.b}) " "CREATE (a)-[:CONNECTS_TO {line: r.line}]->(b)", {"rows": [ {"a": str(r["From Station"]).strip(), "b": str(r["To Station"]).strip(), "line": str(r["Tube Line"]).strip()} for r in links.to_dict("records") ]}, ) Each connection is stored once. The queries below match it in either direction, so a trip works both ways without storing every link twice. Cypher also has LOAD CSV, which skips pandas. Relate denies local file reads unless we allow a directory explicitly, so the parameter route is the simpler approach in a notebook. We'll check the load with a count: Python print(db.execute("MATCH (s:Station) RETURN count(s) AS stations").data()) print(db.execute("MATCH ()-[r:CONNECTS_TO]->() RETURN count(r) AS links").data()) On the Underground data, this outputs 349 stations and 458 connections. Ask Graph Questions Three questions that need self-joins in SQL read as one pattern in Cypher. 1. What's Within Three Stops Of Kennington? A variable-length pattern follows connections up to a limit, in either direction: Python nearby = db.execute( "MATCH p = (a:Station {name: $name})-[:CONNECTS_TO*1..3]-(b:Station) " "WHERE a <> b " "RETURN b.name AS station, min(length(p)) AS stops " "ORDER BY stops, station", {"name": "Kennington"}, ).data() Kennington has 4 neighbors, 8 more stations two stops away and 12 more at three stops, 24 in all. 2. Which Stations Are Interchanges? Group each station's connections by line and keep the ones served by more than one: Python hubs = db.execute( "MATCH (s:Station)-[r:CONNECTS_TO]-() " "WITH s, collect(DISTINCT r.line) AS lines " "WHERE size(lines) > 1 " "RETURN s.name AS station, size(lines) AS lines, lines AS served_by " "ORDER BY lines DESC, station LIMIT 10" ).data() Kings Cross St. Pancras comes first with 6 lines, followed by Baker Street with 5. 3. How Do I Get From Kennington To Euston? Cypher 25 path selectors ask for the shortest paths directly. Two details matter: Bound the search with a hop limit, because an open-ended pattern makes the engine consider every path through a network full of loops.Name the line if you want one, as below. Python ORIGIN, DEST, LINE = "Kennington", "Euston", "Northern" MAX_HOPS = 10 # the shortest route is 8 hops; the bound keeps the search small found = db.execute( f"MATCH p = SHORTEST 3 (a:Station {{name: $origin})-[:CONNECTS_TO {{line: $line}]-{{1,{MAX_HOPS}}(b:Station {{name: $dest}) " "RETURN [n IN nodes(p) | n.name] AS stations, length(p) AS stops ORDER BY stops", {"origin": ORIGIN, "dest": DEST, "line": LINE}, ).data() # Keep each station sequence once. routes = list({tuple(r["stations"]): r for r in found}.values()) On the Northern Line, the query returns the two branches in a few milliseconds: Charing Cross (8 stops, via Waterloo and Embankment)Bank (9 stops, via Elephant and Castle and Angel) Where several lines serve the same stations, the graph holds parallel connections, and each counts as a separate path, so the same station sequence can come back more than once. We'll keep each sequence once. Drop the line filter and the same question runs across the whole network. We ask for more paths than we need, keep the distinct station sequences, and return the line on each hop, so we can see where the route changes: Python whole = db.execute( f"MATCH p = SHORTEST 20 (a:Station {{name: $origin})-[:CONNECTS_TO]-{{1,{MAX_HOPS}}(b:Station {{name: $dest}) " "RETURN [n IN nodes(p) | n.name] AS stations, [r IN relationships(p) | r.line] AS lines, length(p) AS stops " "ORDER BY stops", {"origin": ORIGIN, "dest": DEST}, ).data() distinct = list({tuple(r["stations"]): r for r in whole}.values()) This takes under a second and returns 20 paths, but only two distinct routes, because most paths differ only in which parallel connection they use. The shortest has 6 stops: Northern Line to Waterloo, Jubilee Line to Green Park, then the Victoria Line through Oxford Circus and Warren Street to Euston, with two interchanges. The other has 7 stops through Bank, Moorgate and Farringdon, using the Northern, Waterloo and City, and Circle or Metropolitan Lines. Fewer stops does not mean a better trip, which is why a route's interchanges belong in the comparison. In SQL, the same three questions require recursive CTEs or repeated self-joins. Move Results Into Pandas Every query above returns a list of dictionaries through .data(), which pandas takes directly: Python hubs_df = pd.DataFrame(hubs) hubs_df.plot.barh(x="station", y="lines", legend=False).invert_yaxis() For larger results, the native Database class can return Arrow IPC bytes, which avoids building Python objects row by row. It needs the file to be free, so we'll close the earlier connection first: Python db.close() # the file must be free for the native class adb = Database("tube.cl") buf = adb.execute_arrow("MATCH (s:Station) RETURN s.name AS name, s.lat AS lat, s.lon AS lon") stations_df = pa.ipc.open_stream(buf).read_all().to_pandas() adb.close() From here, the data is an ordinary DataFrame. We can plot it, merge it with other tables, or feed it to a model, and write findings back with a parameterized UNWIND when we want them in the graph. Keep It In One File A path ending in .cl stores the write-ahead log, the snapshots and the catalog in a single file, so the whole graph can be copied, emailed or committed alongside the notebook. A plain directory path works too, and ":memory:" gives us a throwaway database that disappears when the process ends. Python db.close() db = relate.connect("tube.cl") # the graph is still there print(db.execute("MATCH (s:Station) RETURN count(s) AS stations").data()) Close a connection before another one opens the same file. Relate allows one writer, and a second opener of a locked database gets an error (an OperationalError, "storage locked"), as it would in SQLite. By default, a write is acknowledged after it reaches the log, so a crash does not lose it. Summary Relate fits analysis on a graph that lives on a local machine: a notebook, a script, a unit test for a Cypher query, or a prototype before being moved to a server. Because the dialect is Cypher, the queries carry over to Neo4j. Know the limits before you build on it: The working set must fit in RAMIt's an engine, not a platform: it has no equivalent of Neo4j's plugin ecosystem, such as Graph Data Science, and it does not let you register your own Cypher functionsIt's a subset of what Neo4j runs, so check each feature you depend on against the documentation, and test your queries on both engines before choosing For many applications, these trade-offs will be fine. We get a graph, a query language, and a DataFrame in one pip install, with nothing to run in the background. In the next article, we'll see how to use Relate with TypeSafe AI's Jev, LLMs and MCP. We'll build an AI agent that navigates the London Underground while recording its decisions, alternatives, model judgments, and human interventions in a persistent, queryable graph ledger. Stay tuned! The full source code is available on GitHub.
Building agents teaches you a humbling lesson very quickly: a well-written prompt is not the same as a guaranteed workflow. In production, agents occasionally behave in ways that are technically reasonable, yet operationally unexpected. This article shares one such observation and why offline evaluations became critical for catching it. The Assumption Most Agent Builders Make When we design an agent workflow, we naturally think like software engineers. If we define a sequence such as: Plain Text 1. Call Tool A 2. Validate the parameters 3. Call Tool B we expect execution to follow that exact order every time. After all, that's how traditional software behaves. If the workflow is clearly defined, the system should execute it deterministically. But agents are not workflow engines. And that distinction matters more than most teams realize. The Behavior We Observed Most executions followed the same sequence as mentioned above. However, a small percentage of executions behaved differently Plain Text 1. Validation 2. Tool A 3. Tool B The instructions remained unchanged. The tools remained unchanged. The input remained unchanged. Yet so often, the agent reordered the workflow. The deviation wasn't catastrophic, but it was enough to raise an important question: Why would an agent ignore a clearly defined sequence? A Common Misconception About Agents One of the biggest misconceptions in agent development is treating prompts as equivalent to program logic. Traditional software executes instructions. LLMs interpret instructions. That difference is subtle but significant. An agent's behavior emerges from several competing influences: System instructionsUser instructionsAvailable toolsContext provided in the sessionTraining dataLearned reasoning patterns As engineers, we often focus on the first three. The model, however, is also influenced by the latter three. Why This Happens One possible explanation is that validation and reasoning are deeply represented patterns in model training. Across countless examples, models learn behaviors such as: Plain Text 1. Understand first 2. Validate 3. Act As a result, when a workflow asks the model to perform an action before validation, there may occasionally be tension between "What the prompt says" and "What the model has learned to do." Sometimes, the model's learned reasoning pattern leaks through. The result is not necessarily a "failure" in the traditional sense. It's a reminder that agents are probabilistic systems. The Hidden Risk of Rare Failures Interestingly, the biggest risk isn't complete failure. It's intermittent failure. Consider two scenarios: Workflow fails 100% of the time. This problem is discovered immediately. Developers spot it within minutes.Workflow fails 5% of the time. The issue becomes harder to detect. Manual testing might never uncover it. The first indication may be too late, coming from production. Many agent-related issues fall into this category: Tool ordering issuesIncorrect tool selectionMissing validation stepsHallucinated assumptionsUnexpected reasoning paths These problems are often rare enough to evade traditional testing practices. Why Offline Evaluations Matter Prompts define intent. Evaluations verify behavior. Without systematic evaluations, agent testing often becomes anecdotal: "I tested it 15 times, and it worked!" The problem is that ten samples may not expose a behavior that occurs once every hundred executions. Offline evaluations provide a structured way to discover such patterns. A useful evaluation suite can measure: Instruction adherenceTool orderingWorkflow completionCorrectnessHallucination ratesSafety complianceLatencyRetry behavior For example: Plain Text Test Case: Expected: Tool A → Validation → Tool B Observed: Validation → Tool A → Tool B Result: Fail What appears to be a random anomaly often turns out to be a measurable behavioral tendency. What We Learned One mindset shift proved particularly valuable: Stop Treating Prompts as Guarantees Prompts are specifications. They are not enforcement mechanisms. As workflows become more critical, relying exclusively on prompt compliance becomes increasingly risky. Start Treating Evaluations as First-Class Engineering Artifacts Many teams invest heavily in prompt engineering while postponing evaluation design. In practice, both should evolve together. The earlier evaluation datasets are introduced, the easier it becomes to identify behavioral drift and instruction-following issues. Design Patterns That Reduce Workflow Deviations Over time, we found several design approaches that improve reliability. 1. Move Critical Orchestration Outside the LLM If execution order is non-negotiable, enforce it through application logic. Instead of: Plain Text LLM decides the next step prefer: Plain Text Application controls the workflow LLM performs bounded tasks 2. Introduce Explicit Workflow State Maintain state such as: Plain Text TOOL_A_COMPLETED VALIDATION_COMPLETED READY_FOR_TOOL_B This reduces ambiguity and limits the agent's ability to skip ahead. 3. Gate Tool Availability Only expose tools that are valid for the current stage. If Tool B should never execute before validation, don't make Tool B available until validation is complete. 4. Build Evaluation Suites Early Evaluation datasets should be created alongside agent workflows, not after deployment. This practice helps uncover edge cases before users encounter them. 5. Design for Probability, Not Perfection Perhaps the most important lesson: Reliable agent systems assume occasional deviations and are engineered to handle them gracefully. Systems designed around perfect compliance tend to be fragile. Systems designed around probable compliance tend to be resilient. Final Thoughts One of the most surprising discoveries in agent development is that a correct prompt does not necessarily produce a perfectly consistent workflow. Agents are capable, adaptable, and increasingly powerful. But they are not deterministic workflow engines. The observation that inspired this article was simple: an agent occasionally performed validation before executing a tool call despite being explicitly instructed not to. The lesson, however, was much larger. As we investigated further through offline evaluations, we realized that output correctness alone was not enough. The agent could arrive at the right answer while still deviating from the expected execution path, calling tools in an unexpected sequence, or violating workflow assumptions that were invisible to the end user. Those behaviors would have been easy to miss through manual testing alone. By monitoring tool invocations, execution order, tool call counts, and workflow compliance, offline evaluations helped surface issues that would otherwise have remained hidden until production. As teams move from experimenting with agents to deploying them in production, success will depend less on writing better prompts and more on building robust evaluation frameworks, orchestration mechanisms, and safeguards around inherently probabilistic systems. Because in the world of agents, the real challenge isn't getting the workflow right once. It's getting it right consistently, predictably, and observably. And that starts with measuring not just what the agent produces, but how it gets there.
Retries usually make systems more reliable. A dependency times out, processing pauses, and the message returns later. Eventually, the operation succeeds. That successful retry can also corrupt a projection. Consider a consumer maintaining product data. Version 108 of product P17 starts processing but encounters an enrichment timeout. Version 109 arrives seconds later and reaches the database successfully. Five minutes afterward, version 108 returns through the retry queue and overwrites it. Both events are legitimate. Neither is a duplicate. The database accepts valid SQL, and the consumer reports success. Yet the stored state has moved backward. The missing guarantee is freshness. An idempotent consumer can prevent repeated execution of one operation while still allowing an older operation to replace newer state. Why Deduplication Cannot Catch This Suppose each product update carries a unique event identifier: Plain Text eventId=A, productId=P17, sourceVersion=108 eventId=B, productId=P17, sourceVersion=109 An idempotency check correctly treats these as different operations. Assuming failed attempts do not mark events complete, event A remains eligible for processing after its enrichment failure. Nothing about its identity tells the consumer that version 109 has already superseded it. Two separate questions must therefore be answered: Idempotency: Has this operation already been applied?Freshness: May this operation replace the state currently stored? For a projection governed by an authoritative revision, the required invariant is straightforward: the persisted version must never decrease. A replay can leave it unchanged, and a newer update can advance it. Event identifiers and source revisions serve different purposes. Preserving both avoids forcing one mechanism to provide a guarantee it cannot express. Reproduce the Failure at the Database Boundary The failure does not require a message broker. Two writes arriving in the wrong order are sufficient. Start with a small PostgreSQL table: SQL CREATE TABLE product_view ( product_id VARCHAR(64) PRIMARY KEY, source_version BIGINT NOT NULL, payload JSONB NOT NULL ); A conventional upsert accepts whichever update arrives last: SQL INSERT INTO product_view (product_id, source_version, payload) VALUES ('P17', 108, '{"name":"Keyboard","price":90}') ON CONFLICT (product_id) DO UPDATE SET source_version = EXCLUDED.source_version, payload = EXCLUDED.payload; If version 109 already exists, this statement replaces it with version 108. The database has followed the instruction exactly. The application never expressed a freshness constraint. This distinction matters during incident analysis. A retry queue explains why an event arrived late. The unconditional write explains why late arrival damaged state. Why Locks and Application Checks Fall Short A lock alone does not establish freshness. Version 109 can acquire the lock, write successfully, and release it. Version 108 can acquire that same lock later and overwrite the row. Processing was perfectly serialized, but the order was wrong. An application-level comparison introduces a different problem: Java Product current = repository.find(productId); if (incoming.version() > current.version()) { repository.save(incoming); } Starting from version 107, workers carrying 108 and 109 can both read the same row. Both comparisons pass. If the worker carrying 108 writes last, the projection regresses. The issue is the gap between comparison and mutation. A lock covering both operations can protect this sequence when implemented correctly, but the freshness comparison remains essential. For a single-row projection, putting the condition directly in the write makes the invariant explicit. Make the Write Enforce Freshness Add a version predicate to the conflict-update branch: SQL INSERT INTO product_view AS stored (product_id, source_version, payload) VALUES ('P17', 108, '{"name":"Keyboard","price":90}') ON CONFLICT (product_id) DO UPDATE SET source_version = EXCLUDED.source_version, payload = EXCLUDED.payload WHERE stored.source_version < EXCLUDED.source_version RETURNING product_id, source_version; PostgreSQL evaluates the conflict-update condition against the conflicting row. Rows excluded by that condition are not returned by RETURNING. See the PostgreSQL INSERT documentation. If 108 commits first, 109 can advance the row. If 109 commits first, 108 cannot replace it. Equal versions also leave the row unchanged. The comparison now occurs within the database operation that controls mutation. Concurrent processing no longer depends on the newest event finishing last. Transactions can still encounter deadlocks or serialization failures, depending on the workload and isolation level. Those failures require appropriate transaction retries; the version predicate must remain part of every attempt. PostgreSQL documents these distinctions in its transaction isolation guidance. Establish What the Version Actually Means The predicate is useful only when larger revisions represent newer authoritative state for the same entity. A source-owned aggregate revision is a strong candidate. A datastore revision or producer sequence can also work when its ordering contract is explicit. Random UUIDs establish identity without establishing order. Wall-clock timestamps require careful guarantees around clock synchronization, precision, and concurrent writers. Offsets from unrelated partitions do not provide a shared entity ordering. The payload must also correspond to its claimed revision. If enrichment reads changing external data, retrying version 109 might produce a different payload from the first attempt. The fence prevents replacement, but the inconsistency remains worth investigating. Define whether each event carries a complete snapshot or a dependent delta. Skipping revision 108 is safe only when 109 contains everything needed to represent the newer state. A sequence of incremental adjustments may require ordered processing or gap recovery. Distinguish Stale Updates From Conflicting Replays A rejected write has several possible meanings: incomig updateinterpretation Lower revision Stale delivery Equal revision, identical payload Replay Equal revision, different payload Consistency violation Higher revision Eligible replacement The SQL predicate protects the row but does not distinguish all these outcomes. If exact classification matters, compare against the protected row within a suitable transaction or retain revision-specific payload hashes. A later, unprotected read can observe a further update and obscure what happened during the original decision. Same-version conflicts can reveal nondeterministic enrichment, incorrect revision assignment, or corrupted replay data. Treating them as ordinary duplicates hides a broken data contract. Preserve Versions Across Deletion Physical deletion creates another opening for stale retries. Suppose version 121 deletes P17. If the row disappears entirely, a delayed version 120 encounters no conflict and inserts the product again. Preserve the deletion revision with a tombstone: SQL ALTER TABLE product_view ADD COLUMN deleted BOOLEAN NOT NULL DEFAULT FALSE, ALTER COLUMN payload DROP NOT NULL; ALTER TABLE product_view ADD CONSTRAINT valid_payload_state CHECK ( (deleted AND payload IS NULL) OR (NOT deleted AND payload IS NOT NULL) ); Represent deletion as a versioned write carrying deleted = TRUE and a null payload. Use the same version predicate for active records and tombstones, updating both payload and deleted from the incoming row. A legitimate newer active revision must restore deleted = FALSE. Tombstone retention must cover retries, delayed delivery, backfills, and supported replay windows. Removing the tombstone removes the information needed to reject older revisions. Identifier reuse adds another complication. If revisions restart, compare an authoritative generation and revision together so generation 7, revision 1 can supersede generation 6, revision 982. Make Rejected Writes Operationally Useful A stale delivery should normally finish as a terminal no-op. Record the rejection and acknowledge the message. Retrying version 108 cannot make it newer than 109. Track applied updates, stale rejections, identical replays, and conflicting revisions separately. Include entity identifiers, incoming revisions, event identifiers, and delivery paths in diagnostic records. A sudden increase in stale rejections can expose a slow dependency, retry backlog, or unexpected replay. The fence protects correctness while those signals help explain the disruption. This approach fits snapshot projections with a meaningful authoritative order. Concurrent independent updates may instead require merge rules or field-level versions. The essential boundary is the write: once a newer revision is accepted, every later mutation must prove that it is allowed to advance that state.
The Announcement That Broke the Serving Team's Week On October 19, Inception Labs announced Mercury 3: a diffusion language model more than forty times the size of Mercury 1, still generating over 1,000 tokens per second, with a one-million-token context window. Their claim is that it matches or beats frontier speed-optimized autoregressive models — GPT-6 Luna and Claude Haiku 5.5 — across a broad set of benchmarks while running four to eight times faster. Stefano Ermon's framing was blunt: "We're showing that the limits to scaling diffusion models are compute and data, not fundamental algorithmic barriers." I read that the way I read any infrastructure claim: from the serving side. I spend my days at Google on Apigee Analytics and Monetization, running near-real-time API monitoring at roughly 440k transactions per second against 99.99% availability targets. When someone tells me a model is forty times larger and just as fast, I do not ask about the benchmarks first. I ask what changed in the serving path, because every order-of-magnitude inference claim in the last five years has been a serving story wearing a model costume. This one genuinely is. A diffusion LLM does not emit tokens left to right. It starts from a fully masked block and refines every position in parallel, over several denoising steps, until the block is done. There is no token-at-a-time decode loop. That single fact invalidates most of what the modern inference stack assumes about a request — and if you run serving infrastructure, Mercury 3 is the moment to rebuild the mental model before the hardware purchase orders do it for you. How a Diffusion Model Actually Decodes Forget autoregression for a minute. Here is the decode loop that production diffusion LLMs use, pieced together from the published serving research (LLaDA-style block diffusion, the D2F work on diffusion forcing, NVIDIA's Nemotron DLM modes, and the recent "Denoising Surface" paper on diffusion serving cost): The output is generated in blocks — typically 32 tokens per block, fixed at deployment time — and blocks are produced left to right, so the model supports variable-length generation. Fixed-canvas diffusion (the whole response as one masked canvas) wastes compute on padding; the industry moved to block-autoregressive generation early.Inside a block, every position starts as a mask token. Each denoising step is one full forward pass over the block, and the model predicts a token distribution for every masked position in parallel.After each step, positions whose predicted distribution is peaked enough — above a confidence threshold — are committed. The rest stay masked for the next pass. The block is done when every position commits, or a max-step cap is hit.Once a block is fully denoised, its KV states are refreshed and cached as fixed context for subsequent blocks. (Bidirectional attention inside the block means KV keeps shifting during denoising, so the cache is only valid at block boundaries — a subtlety the FreeCache work handles by approximating prompt KV reuse across steps.)If an EOS token appears, generation stops; otherwise, a new masked block is appended, and the loop repeats. The hybrids matter too. D2F (discrete diffusion forcing) keeps block-level causality so completed blocks reuse an exact KV cache, while denoising later blocks against partially-denoised predecessors for inter-block parallelism. NVIDIA's Nemotron DLM ships a self-speculation mode where the same model drafts a full block by diffusion and verifies it autoregressively — lossless against AR at temperature zero, with roughly six times the tokens per forward pass. The space is converging on one insight: the forward pass, not the token, is the unit of work. Five Things the Serving Stack Got for Free The vLLM-era stack is built on assumptions that felt like physics. Diffusion serving breaks all five. 1. Capacity planning keys on KV cache bytes. In an AR server, memory is the binding constraint: max_num_seqs is derived from free KV cache divided by bytes per token. Admission control, continuous batching, and OOM protection all flow from this one equation. A diffusion decoder does not grow a KV cache per token — it spends a fixed-size block buffer per denoising step and refreshes at block boundaries. Memory stops being the scarce resource; forward passes do. 2. Continuous batching schedules at token granularity. The whole point of continuous batching is that every iteration produces exactly one token per sequence, so the scheduler can insert and evict sequences at token boundaries with uniform per-step cost. A diffusion iteration produces a variable number of committed tokens — sometimes half a block, sometimes zero — and each iteration costs a full forward pass over the block regardless. The scheduler's cost model, which assumes "one step equals one token," is wrong on both axes. 3. Prefill/decode disaggregation assumes memory-bound decode. Disaggregated serving works because decode is memory-bandwidth bound (streaming the KV cache) while prefill is compute bound, so they belong on different instance pools. A denoising step is a full forward pass over the block — compute-heavy, much closer to prefill in character. Put diffusion decode on your memory-optimized decode instances, and you have built the wrong fleet. 4. Speculative decoding's acceptance math assumes a drafter. The entire spec-decode economy — draft cost, acceptance length, the bonus token — is built on a small autoregressive drafter proposing tokens for a large verifier. In a diffusion stack, the draft is the parallel pass; NVIDIA's LinearSpec shows the two paradigms fusing into one loop rather than one accelerating the other. Yesterday's article in this series tore down a spec-decode benchmark for using synthetic acceptance at batch 1; with diffusion models, the honest question is whether your "speculative" path is even measuring a real second model. 5. SLOs and billing count tokens. Time-to-first-token, tokens-per-second, inter-token latency, per-token pricing — the whole observability and billing surface assumes output arrives one token at a time at roughly constant cost per token. Diffusion output arrives in committed chunks of unpredictable size, and cost is incurred per denoising step whether or not anything commits. TTFT has to become time-to-first-committed block; per-token billing silently misprices the stubborn requests that burn steps and commit little. What Replaces It: The Forward Pass as the Unit of Work The honest metric for a diffusion server is tokens per forward pass (TPF) — committed tokens divided by denoising steps — and its evil twin, forward passes per request. Everything downstream follows: Admission control budgets forward passes, not KV bytes. A request's cost is a denoising surface: blocks multiplied by steps per block, where steps per block is a distribution, not a number. The recent "Denoising Surface" paper (arXiv, October 2026) makes exactly this point: diffusion generation cost varies substantially across requests, and a scheduler guided by a predicted surface cuts online latency versus token-count admission. Their DWS-guided scheduler is the first production-shaped answer to this problem.Scheduling happens at step granularity, not token granularity. The batch unit is one denoising step applied across the batch's active blocks. Requests whose blocks finish early free their slots at block boundaries — coarser than token boundaries, which changes the insert/evict dynamics continuous batching was tuned for.KV refresh is a scheduling event. When a block commits, its KV must be refreshed into the cache before the next block's steps can reuse it. That refresh is a synchronization point across the batch — the closest thing diffusion serving has to a barrier, and a new source of tail latency if one request's block drags.The honest benchmark questions change. Yesterday's piece in this series showed how to read a spec-decode benchmark's footnotes. For a diffusion throughput claim, the footnotes are: batch size, block size, max steps per block, confidence threshold, whether commit counts were measured or assumed, and whether the number includes the prefill of a million-token context. Mercury 3's 1,000 tok/s is a real engineering number — the 40x scale claim says the denoising math held up — but as a capacity number it is meaningless until those five parameters are pinned down. Code 1: The Decode Loop, With Honest Accounting This is a simulation harness for block-autoregressive diffusion decoding — not a real model, but the accounting is faithful: every denoising step is one forward pass, commits happen by confidence threshold, the block's KV is refreshed at commit, and a per-request step budget is enforced. Run it and watch the metric that matters: tokens per forward pass under different step budgets. from __future__ import annotations import math import random from dataclasses import dataclass, field from typing import List, Tuple @dataclass(frozen=True) class DenoiseConfig: block_size: int = 32 max_steps_per_block: int = 16 confidence_threshold: float = 0.90 step_budget_per_request: int = 512 # hard cap on forward passes def __post_init__(self) -> None: if self.block_size < 1: raise ValueError("block_size must be >= 1") if self.max_steps_per_block < 1: raise ValueError("max_steps_per_block must be >= 1") if not 0.0 < self.confidence_threshold < 1.0: raise ValueError("confidence_threshold must be in (0, 1)") if self.step_budget_per_request < 1: raise ValueError("step_budget_per_request must be >= 1") class StepBudgetExhausted(Exception): """Raised when a request exceeds its forward-pass budget.""" class ConfidenceModel: """Test double for a dLLM head: per-position max-probability. Confidence rises with denoising steps; a few positions are genuinely stubborn, the way ambiguous tokens are in real text. This is a stand-in for the model — the accounting around it is the point. """ def __init__(self, block_size: int, seed: int, hard_positions: int = 2) -> None: rng = random.Random(seed) self._difficulty = [rng.random() for _ in range(block_size)] for i in rng.sample(range(block_size), min(hard_positions, block_size)): self._difficulty[i] = 0.95 + 0.05 * rng.random() self._tau = [0.5 + rng.random() * 2.0 for _ in range(block_size)] def confidence(self, step: int) -> List[float]: return [ 1.0 - d * math.exp(-(step + 1) / t) for d, t in zip(self._difficulty, self._tau) ] @dataclass class DecodeStats: blocks: int = 0 forward_passes: int = 0 tokens_committed: int = 0 steps_per_block: List[int] = field(default_factory=list) @property def tokens_per_forward_pass(self) -> float: return self.tokens_committed / max(self.forward_passes, 1) @property def mean_steps_per_block(self) -> float: return sum(self.steps_per_block) / max(len(self.steps_per_block), 1) class BlockDecoder: """Block-autoregressive dLLM decode loop with step-budget accounting. Each denoising step is one full forward pass over the block. Tokens above the confidence threshold commit; the rest stay masked. When a block finishes, its KV is refreshed and cached for subsequent blocks. """ def __init__(self, config: DenoiseConfig, seed: int = 0) -> None: self.config = config self.stats = DecodeStats() self._seed = seed def _decode_block(self, block_index: int) -> Tuple[List[str], int]: cfg = self.config model = ConfidenceModel(cfg.block_size, seed=self._seed + block_index) committed = [False] * cfg.block_size tokens = ["<mask>"] * cfg.block_size steps = 0 while not all(committed) and steps < cfg.max_steps_per_block: if self.stats.forward_passes >= cfg.step_budget_per_request: raise StepBudgetExhausted( f"block {block_index}: exceeded {cfg.step_budget_per_request} forward passes" ) conf = model.confidence(steps) # one forward pass over the block self.stats.forward_passes += 1 steps += 1 for i, c in enumerate(conf): if not committed[i] and c >= cfg.confidence_threshold: committed[i] = True tokens[i] = f"tok_{i}" # stand-in for argmax over the head # KV refresh: the finished block's KV is now cacheable context. # In a real server this is where the block-boundary barrier hits. self.on_block_commit(block_index, tokens) return tokens, steps def on_block_commit(self, block_index: int, tokens: List[str]) -> None: """Hook for the KV-refresh / scheduling barrier. Override in prod.""" def decode(self, num_blocks: int) -> Tuple[List[List[str]], DecodeStats, bool]: if num_blocks < 1: raise ValueError("num_blocks must be >= 1") out: List[List[str]] = [] truncated = False for b in range(num_blocks): try: tokens, steps = self._decode_block(b) except StepBudgetExhausted: truncated = True break out.append(tokens) self.stats.blocks += 1 self.stats.tokens_committed += sum(1 for t in tokens if t != "<mask>") self.stats.steps_per_block.append(steps) return out, self.stats, truncated if __name__ == "__main__": for budget in (512, 128, 48): cfg = DenoiseConfig( block_size=32, max_steps_per_block=16, confidence_threshold=0.90, step_budget_per_request=budget, ) _, stats, truncated = BlockDecoder(cfg, seed=7).decode(num_blocks=8) print( f"budget={budget:4d} tokens={stats.tokens_committed:3d} " f"passes={stats.forward_passes:3d} TPF={stats.tokens_per_forward_pass:.2f} " f"mean_steps={stats.mean_steps_per_block:.1f} truncated={truncated}" ) Sample output tells the story the prose cannot: tightening the step budget barely moves tokens per forward pass until it does, then requests truncate mid-block. The cliff, not the curve, is what your SLOs will hit. Code 2: Admission Control on a Forward-Pass Budget (Go) In an AR stack, the admission question is "does this request's KV footprint fit?" In a diffusion stack, the question is "does this request's predicted denoising surface fit this window's forward-pass budget?" This controller costs interactive-tier requests at the P95 of the predicted surface and batch-tier at the P50 — the diffusion equivalent of headroom planning — and reconciles against actuals when the request finishes. // Package scheduler admits diffusion-LLM requests against a forward-pass // budget. The scarce resource is no longer KV-cache bytes: it is denoising // steps, each one a full forward pass over a block. package scheduler import ( "errors" "sync" "time" ) var ErrOverBudget = errors.New("scheduler: request exceeds forward-pass budget") // DenoisePrediction is the scheduler-visible shape of a request's cost. // It comes from a calibrated predictor (e.g. a Denoising-Surface model); // the scheduler must never trust the client for it. type DenoisePrediction struct { Blocks int P50StepsPerBlock float64 P95StepsPerBlock float64 } // ForwardPasses returns the admission cost of the request. Conservative // costing (P95) is for latency-sensitive tiers; mean costing (P50) for batch. func (p DenoisePrediction) ForwardPasses(conservative bool) float64 { perBlock := p.P50StepsPerBlock if conservative { perBlock = p.P95StepsPerBlock } return float64(p.Blocks) * perBlock } type Request struct { ID string Tier string // "interactive" or "batch" Prediction DenoisePrediction Deadline time.Time } // AdmissionController guards a per-window forward-pass budget. type AdmissionController struct { mu sync.Mutex budget float64 // forward passes available this scheduling window reserved float64 } func NewAdmissionController(budgetPerWindow float64) (*AdmissionController, error) { if budgetPerWindow <= 0 { return nil, errors.New("scheduler: budgetPerWindow must be positive") } return &AdmissionController{budget: budgetPerWindow}, nil } // Admit reserves budget for req, or returns ErrOverBudget with the reason // the caller logs. Interactive requests are costed at P95, batch at P50. func (a *AdmissionController) Admit(req Request) error { if req.Prediction.Blocks < 1 { return errors.New("scheduler: predicted blocks must be >= 1") } if req.ID == "" { return errors.New("scheduler: request ID is required") } cost := req.Prediction.ForwardPasses(req.Tier == "interactive") a.mu.Lock() defer a.mu.Unlock() if a.reserved+cost > a.budget { return ErrOverBudget } a.reserved += cost return nil } // Release reconciles the reservation against the actual consumed steps when // the request finishes, so the next window's budget reflects reality rather // than the prediction. Overruns push reserved above budget; the next window // starts with Reset regardless. func (a *AdmissionController) Release(req Request, actualSteps int) { if actualSteps < 0 { return // defensive: a negative actual is a metrics bug, not a refund } predicted := req.Prediction.ForwardPasses(req.Tier == "interactive") a.mu.Lock() defer a.mu.Unlock() a.reserved -= predicted - float64(actualSteps) if a.reserved < 0 { a.reserved = 0 } } // Reset opens a new scheduling window. Call it on your window tick. func (a *AdmissionController) Reset() { a.mu.Lock() defer a.mu.Unlock() a.reserved = 0 } The design decision worth arguing about: batch tier at P50 means half your batch requests overrun their prediction, which is fine — batch has no latency SLO, and the window reset absorbs it. Interactive at P95 is the price of a p99 TTFT-style SLO on time-to-first-committed-block. If your predictor cannot produce a calibrated P95, you do not have a scheduler; you have a hope. Code 3: Observability for a World Without Per-Token Cost (Python) Your dashboards were built for AR. tokens_per_second, inter-token latency, KV cache utilization — all of them either lie or go silent on a diffusion server. This monitor tracks what actually determines cost and SLOs: forward passes per request, committed tokens per pass, effective throughput, and the drift between per-token billing and per-step compute cost. from __future__ import annotations import statistics import threading import time from dataclasses import dataclass, field from typing import Dict, List @dataclass class RequestTrace: request_id: str blocks: int forward_passes: int tokens_committed: int started_at: float = field(default_factory=time.monotonic) ended_at: float = 0.0 @property def latency_s(self) -> float: return max(self.ended_at - self.started_at, 1e-9) @property def effective_tok_per_s(self) -> float: """Throughput that actually carries meaning. A denoising step that refines but commits nothing is real compute with zero visible output. Effective throughput counts only committed tokens, which makes it the honest number for SLOs. """ return self.tokens_committed / self.latency_s @property def tokens_per_forward_pass(self) -> float: return self.tokens_committed / max(self.forward_passes, 1) class DenoiseMonitor: """Thread-safe per-request accounting for diffusion serving.""" def __init__(self, cost_per_forward_pass_usd: float, price_per_mtok_usd: float) -> None: if cost_per_forward_pass_usd < 0 or price_per_mtok_usd < 0: raise ValueError("cost and price must be non-negative") self._lock = threading.Lock() self._traces: List[RequestTrace] = [] self._cost_per_pass = cost_per_forward_pass_usd self._price_per_mtok = price_per_mtok_usd def record(self, trace: RequestTrace) -> None: trace.ended_at = time.monotonic() with self._lock: self._traces.append(trace) def serving_report(self) -> Dict[str, float]: """The four numbers that replace your AR dashboard's top row.""" with self._lock: traces = list(self._traces) if not traces: return {} eff = sorted(t.effective_tok_per_s for t in traces) tpf = [t.tokens_per_forward_pass for t in traces] return { "requests": float(len(traces)), "p50_effective_tok_per_s": statistics.median(eff), "p99_effective_tok_per_s": eff[max(int(len(eff) * 0.99) - 1, 0)], "mean_tokens_per_forward_pass": statistics.fmean(tpf), "mean_forward_passes_per_request": statistics.fmean( t.forward_passes for t in traces ), } def billing_drift(self) -> Dict[str, float]: """How far per-token billing drifts from per-step compute cost. Bill committed tokens at AR-style per-token prices while your cost is forward passes, and the stubborn requests — many steps, few commits — silently lose money. Positive drift means you are underpricing compute. """ with self._lock: passes = sum(t.forward_passes for t in self._traces) tokens = sum(t.tokens_committed for t in self._traces) cost = passes * self._cost_per_pass revenue = tokens / 1_000_000 * self._price_per_mtok return { "compute_cost_usd": cost, "token_revenue_usd": revenue, "drift": (cost - revenue) / max(revenue, 1e-9), } The billing drift function is the one I would deploy first. Inference providers price per token because tokens were the cost unit. The moment your fleet serves a diffusion model, that pricing is a bet that steps-per-token stays constant — and the denoising surface says it does not. Measure the drift before finance does. The Migration Checklist If you run a vLLM-style stack and a diffusion model lands on your roadmap, here is the work, in the order I would do it: Re-instrument first. You cannot schedule what you cannot see. Deploy the per-request accounting from Code 3 — forward passes, committed tokens, tokens per forward pass — on whatever diffusion endpoint you have today, even if it is a single replica. The denoising surface of your actual traffic is the input to every decision below.Rebuild the admission math. Replace the KV-byte admission check with a forward-pass budget keyed on a predicted denoising surface (Code 2), calibrated per tier. Until you have a calibrated predictor, cost interactive requests at a fixed conservative steps-per-block and measure the overrun — that measurement is the first version of the predictor.Re-split the fleet. Audit your prefill/decode disaggregation: diffusion decode steps are compute-heavy forward passes, so your memory-optimized decode pool is the wrong shape. Expect the disaggregated topology to collapse back toward homogeneous compute instances, with the split moving to interactive-vs-batch rather than prefill-vs-decode.Retire spec-decode where the drafter was the point. If your stack leans on speculative decoding for latency, evaluate diffusion-native equivalents (self-speculation loops like LinearSpec) instead of bolting an AR drafter onto a diffusion target. The acceptance math does not transfer.Rebenchmark everything, with the new footnotes. Batch size, block size, max steps, confidence threshold, measured vs. assumed commits, prefill inclusion. Mercury 3's 1,000 tok/s survived a 40x scale-up of the model, which is genuinely remarkable — it means the denoising dynamics did not degrade with size. But the number you put in a capacity plan is tokens per forward pass at your block size and your confidence threshold, at production batch, with prefill included. What stays the same is the boring and important part: continuous batching's core idea (never let the GPU idle), request-level isolation, backpressure, and the discipline of reading benchmarks like an adversary. The token stream was never really a stream — it was always a scheduling convenience. Diffusion models just made the convenience visible. The KV cache had a good run. It was the right data structure for a sequential world. The next world refines in parallel, commits in chunks, and bills by the forward pass. Build for that, and the next forty-times-larger model will be a capacity planning exercise instead of a surprise.
Modern SaaS companies often rely on managed cloud services to build and scale their applications efficiently. While many start with a single cloud provider, expanding into new markets may create a need to support additional cloud environments, whether due to customer preferences or resilience requirements. However, this expansion can be challenging when applications are tightly coupled to services offered by their original cloud provider. DynamoDB in AWS is one example of this challenge. Applications built around its APIs may need to run against a different database backend in another cloud environment, and rewriting their data-access layer can require significant engineering effort. Applications that also rely on DynamoDB Streams to consume data changes face an additional challenge, as compatibility must extend beyond basic read and write operations. This article explores how providing DynamoDB-compatible APIs over Apache Phoenix/HBase addresses this problem. Specifically, it examines the design and implementation of DynamoDB Streams compatibility using Phoenix's change data capture capabilities. Apache HBase and Phoenix Apache HBase is an open-source, distributed NoSQL database built on top of the Hadoop ecosystem. It organizes data into tables that are partitioned into regions and distributed across multiple servers. Within each region, data is stored and accessed in sorted row-key order. As tables grow or their data distribution changes, HBase regions can split or merge, allowing the database to manage data across the cluster. Apache Phoenix provides a SQL interface over HBase, allowing applications to query and modify data using familiar SQL statements rather than working directly with the HBase APIs. It also provides capabilities such as secondary indexing and change data capture (CDC). Phoenix and HBase are widely available as part of enterprise big-data platforms, including Amazon EMR, Azure HDInsight, and Cloudera distributions. Apache Phoenix-Adapters Apache Phoenix Adapters is an open-source project that provides compatibility with Amazon DynamoDB APIs using Apache Phoenix and HBase as the underlying database. It is designed as a stateless HTTP service that translates DynamoDB API requests into operations supported by Phoenix. Applications can use Phoenix Adapters by simply changing their DynamoDB SDK endpoint to point to the service, without requiring changes to their application code. Amazon DynamoDB Streams Amazon DynamoDB is a fully managed NoSQL database service that supports key-value and document data models. DynamoDB Streams captures item-level changes to DynamoDB tables and makes them available for consumption by downstream applications. The DynamoDB Streams API provides four operations: ListStreams for discovering streams, DescribeStream for retrieving stream and shard metadata, GetShardIterator for obtaining a position within a shard, and GetRecords for reading change records. Together, these APIs allow applications to consume database changes through existing AWS SDKs and streaming tools. Apache Phoenix CDC and Stream Metadata Apache Phoenix supports Change Data Capture (CDC), allowing applications to query changes made to a table using SQL (PHOENIX-7001). The CDC implementation uses a write-optimized uncovered index on row timestamps to capture row-level modifications. The index tracks changes without storing a complete copy of the data, and Phoenix retains historical row versions to reconstruct changes. Here is a small example of what CDC usage in Phoenix looks like for a simple ORDERS table. SQL -- Create a table and enable CDC CREATE TABLE orders ( order_id VARCHAR PRIMARY KEY, status VARCHAR ); CREATE CDC cdc_orders ON orders; -- Insert an order UPSERT INTO orders VALUES ('order-101', 'CREATED'); -- Update the order UPSERT INTO orders VALUES ('order-101', 'SHIPPED'); -- Query changes, including before and after images SELECT /*+ CDC_INCLUDE(PRE, POST) */ PARTITION_ID() AS partition_id, PHOENIX_ROW_TIMESTAMP() AS event_time, order_id, "CDC JSON" FROM cdc_orders ORDER BY PHOENIX_ROW_TIMESTAMP(); -- Conceptual results: -- INSERT: partition_id = R1, PRE = null, POST = {status: CREATED} -- UPDATE: partition_id = R1, PRE = {status: CREATED}, POST = {status: SHIPPED} -- partition_id is the hbase region identifier for the change The CDC query returns change records along with their partition identifiers, which are HBase Region IDs, timestamps, and requested pre/post images. CDC Streams and Partition Metadata The initial Phoenix CDC implementation focused on querying change records within a time range. However, typical stream consumers have additional requirements. For higher throughput, they need to discover and consume multiple shards in parallel. As shards split or merge, consumers also need to track their lineage to discover new shards and ensure parent shards are fully consumed before processing their children. Finally, consumers need a way to resume from their last processed position after failures. While checkpointing is typically the consumer's responsibility, the streaming interface must provide sequence numbers and iterators to support it. To support these requirements, we extended Phoenix with stream metadata and shard-tracking capabilities (PHOENIX-7456). Phoenix organizes CDC changes into streams containing partitions, where each partition corresponds to an HBase region of the underlying data table. The PARTITION_ID() function associates each change record with the region where it originated, allowing consumers to retrieve changes from individual partitions. Two system tables maintain the stream metadata: SYSTEM.CDC_STREAM_STATUS tracks CDC stream objects and their lifecycle, including initialization and active states.SYSTEM.CDC_STREAM stores partition metadata, including partition identifiers, parent-partition relationships, start and end times, and row-key boundaries. Streams and partitions have separate lifecycles. A stream can remain active while its underlying partitions change as HBase regions split or merge. The metadata therefore needs to track not just the currently active partitions, but also their relationships with previously existing partitions. Bootstrapping and Tracking Partition Topology It is not sufficient for a consumer to simply query HBase for its current regions since it may still be processing changes from regions that have already split or merged. Persisting partition history allows consumers to finish reading closed partitions and discover their successors without losing track of unconsumed changes. When CDC is enabled on an existing table, Phoenix first needs to discover the HBase regions that already exist. A background initialization task populates SYSTEM.CDC_STREAM with the initial region metadata, including each region's encoded identifier, start time, and row-key boundaries. After initialization, Phoenix needs to keep this metadata updated as the underlying HBase region topology changes. HBase provides coprocessor hooks that allow custom logic to run in response to region lifecycle events, enabling Phoenix to update its stream metadata whenever a region split or merge completes. Phoenix uses the HBase Master coprocessor hooks postCompletedSplitRegionAction and postCompletedMergeRegionsAction to track these changes. When a region splits, the parent partition is marked as closed, and entries are created for the two daughter partitions. Similarly, when regions merge, the parent partitions are closed, and a new partition is added with references to all its parents. In both cases, Phoenix preserves the parent-child relationships so consumers can reconstruct the partition topology even after the underlying HBase regions have changed. Consider our ORDERS table that initially has two HBase regions, R1 and R2. When CDC is enabled, Phoenix bootstraps the stream metadata for both regions. Suppose R2 later splits into R3 and R4. Subsequently, R1 and R3, which are adjacent regions, merge into a new region R5. The resulting lineage looks like this, with R4 and R5 as the active regions: For the above partition lineage, the metadata in the SYSTEM.CDC_STREAM table would look something like the following. For simplicity, some columns are not shown here, but each partition metadata row also carries the table and stream name. partition idparent partition idstart timeend time R1 NULL T0 T2 R2 NULL T0 T1 R3 R2 T1 T2 R4 R2 T1 NULL R5 R1 T2 NULL R5 R3 T2 NULL The region identifiers and timestamps are illustrative. T0 represents the initial bootstrap, T1 the split, and T2 the merge. A null end time indicates an active HBase region receiving writes. This example shows how Phoenix maintains partition lineage across region topology changes. R1 and R2 initially have no parents. When R2 splits, it is marked as closed, and R3 and R4 are added with R2 as their parent. Later, when R1 and R3 merge, both partitions are closed, and R5 is created with references to both parents. R4 remains active. The merge case also influenced the metadata schema. PARENT_PARTITION_ID is included in the composite primary key of SYSTEM.CDC_STREAM, allowing multiple rows for the same child partition, one for each parent. This avoids storing multiple parent identifiers in a single field and makes it easier to query partition lineage. Together, the background bootstrap process and the region split/merge hooks allow Phoenix to maintain a history of CDC partition topology as the underlying HBase table evolves. This metadata provides the foundation for partition-aware stream consumption. Implementing DynamoDB Streams APIs in Phoenix Adapters Phoenix Adapters implements four DynamoDB Streams APIs: ListStreams, DescribeStream, GetShardIterator, and GetRecords. Together, these APIs allow existing DynamoDB Streams clients to discover streams, navigate their shards, and consume change records from Apache Phoenix. The implementation uses Phoenix's CDC objects for retrieving change records and its stream metadata tables for discovering streams and their partitions. ListStreams Every DynamoDB Streams consumer starts with the ListStreams API. It returns the streams available for consumption for a given table name. Phoenix uses the stream information stored in SYSTEM.CDC_STREAM_STATUS and converts it into the DynamoDB Streams response format. Each stream is returned with a table name, stream ARN, and stream label. Here is an example response: JSON { "Streams": [ { "TableName": "ORDERS", "StreamArn": "arn:aws:dynamodb:us-west-2:000000000000:table/ORDERS/cdc_orders/2026-10-14T10:00:00.000", "StreamLabel": "2026-10-14T10:00:00.000" } ] } Since Phoenix Adapters can run outside AWS, the stream ARN is constructed in the format expected by DynamoDB clients, using placeholder AWS region and account identifiers. The stream label identifies the stream's creation time. The API also supports pagination using Limit and ExclusiveStartStreamArn, allowing clients to discover streams across multiple requests. DescribeStream Once the consumer has the stream it wants to consume from, it calls DescribeStream to retrieve the metadata for the shards available in that stream for consumption. Phoenix Adapters constructs the DescribeStream response using metadata maintained by Apache Phoenix. Stream and partition information comes from SYSTEM.CDC_STREAM_STATUS and SYSTEM.CDC_STREAM, while StreamViewType, which determines whether change records include old images, new images, or both, is retrieved from Phoenix table metadata. The partition identifiers, parent-child relationships, and start/end timestamps are then used to construct the shard metadata. Consider the example from Section 2, where the ORDERS table initially has two regions, R1 and R2, and R2 subsequently splits into R3 and R4. An abbreviated DescribeStream response after the split would look like this: JSON { "StreamDescription": { "StreamArn": "...", "StreamLabel": "2026-10-14T10:00:00.000", "StreamStatus": "ENABLED", "StreamViewType": "NEW_AND_OLD_IMAGES", "TableName": "ORDERS", "Shards": [ { "ShardId": "shard-R2", "SequenceNumberRange": { "StartingSequenceNumber": "T0||00000", "EndingSequenceNumber": "T1||99999" } }, { "ShardId": "shard-R3", "ParentShardId": "shard-R2", "SequenceNumberRange": { "StartingSequenceNumber": "T1||00000" } }, { "ShardId": "shard-R4", "ParentShardId": "shard-R2", "SequenceNumberRange": { "StartingSequenceNumber": "T1||00000" } } ] } } Shard identifiers are simplified for illustration, and || in Sequence Numbers denotes concatenation. Although Apache Phoenix CDC supports region merges and tracks multiple parent partitions, Phoenix Adapters disables HBase region merges (MERGE_ENABLED=false) for tables with DynamoDB Streams enabled. This is because DynamoDB Streams supports shard splits but does not expose merging shards. Disabling merges keeps the underlying HBase partition topology compatible with the DynamoDB Streams shard model. The example shows how closed shards have an EndingSequenceNumber, while active shards do not. The sequence numbers are constructed using partition timestamps with additional padding to identify individual records. The sequence-number format and the purpose of this padding are explained in a separate section below. GetShardIterator GetShardIterator allows a client to obtain an iterator representing the position from which it wants to start consuming records within a shard. The API supports four starting positions, which Phoenix Adapters handles as follows: TRIM_HORIZON: Uses the shard's starting sequence number to begin reading from the earliest available position.LATEST: Uses the current clock time as the starting position to consume new changes.AT_SEQUENCE_NUMBER: Starts reading at the specified sequence number.AFTER_SEQUENCE_NUMBER: Starts reading immediately after the specified sequence number. Phoenix Adapters returns an opaque shard iterator that contains all the information needed to construct a Phoenix CDC SQL query. This includes the table name, CDC object, stream view type, partition identifier, and starting sequence number. Conceptually, the iterator looks like this: Plain Text shardIterator/<tableName>/<cdcObject>/<streamType>/<partitionId>/<startSeqNum> tableName: The underlying Phoenix table.cdcObject: The Phoenix CDC object used to query changes.streamType: The configured stream view type, to determine which row images to return.partitionId: The CDC partition from which records will be retrieved.startSeqNum: The sequence position from which consumption should begin. Since the iterator contains all the information required to construct the SQL query, Phoenix Adapters does not need to maintain server-side cursors for individual consumers. Any instance of the stateless HTTP service can process a subsequent GetRecords request using the iterator supplied by the client. GetRecords To start consuming records from a shard starting from a given position, the client would provide the ShardIterator it received from the GetShardIterator response to the GetRecords API. Phoenix Adapters decodes the iterator to identify the CDC object, partition, and starting sequence position. It then constructs a SQL query against the CDC object to retrieve changes from that position. A simplified version of the query is: SQL SELECT /*+ CDC_INCLUDE(PRE, POST) */ * FROM <cdcObject> WHERE PARTITION_ID() = <partitionId> AND PHOENIX_ROW_TIMESTAMP() >= <timestamp> ORDER BY PHOENIX_ROW_TIMESTAMP() ASC LIMIT <limit> OFFSET <offset> The partition identifier restricts the query to a particular shard, while the timestamp and offset identify where consumption should resume. The CDC_INCLUDE hint retrieves the previous and updated row images needed for the DynamoDB Streams response. Handling Sequence Numbers DynamoDB Streams assigns a sequence number to each change record, identifying its position within a shard. These sequence numbers allow consumers to read records in order and resume consumption from a particular position. DynamoDB Streams also guarantees that changes to the same item appear in the order they occurred, although it does not guarantee a global ordering across different items. Phoenix CDC provides a timestamp for each change through a row timestamp. However, multiple changes to different HBase row keys can occur within the same millisecond and therefore share the same timestamp. Using the timestamp directly as a sequence number would not uniquely identify these records. To address this, Phoenix Adapters constructs sequence numbers by combining the millisecond timestamp with an N-digit offset. Records sharing the same timestamp are returned in HBase row-key scan order and assigned incrementing offsets. N is configurable, with a default value of 5, allowing up to 100,000 distinct sequence positions for records sharing the same timestamp within a partition. For updates to the same row key, Phoenix's mutation and timestamp-handling logic is important for preserving the order of successive changes. For example, rowkeytimestampsequence number order-101 100 10000000 order-102 121 12100000 order-103 121 12100001 order-104 121 12100002 order-105 156 15600000 Sequence numbers/timestamps are shortened for readability. The actual implementation uses fixed-width numeric strings. The offset resets when the timestamp changes. This gives records within a shard a distinct position without maintaining a global sequence number counter which writes to different rowkeys would need to synchronize on. When processing a GetRecords request, Phoenix Adapters splits sequence number from the shard iterator back into its timestamp and offset components. The timestamp is used in the PHOENIX_ROW_TIMESTAMP() predicate, while the offset is applied through the SQL OFFSET clause to skip records already consumed. Returning Records and NextShardIterator Phoenix Adapters converts the CDC query results into DynamoDB Streams records. Each record includes an event type (INSERT, MODIFY, or REMOVE), the item's primary key, a sequence number, and the appropriate old or new item images based on the configured StreamViewType. Event type is inferred from the PRE/POST images in the CDC results, which also contain the row key, and the sequence number is generated based on the steps described in the previous section. Along with the records, GetRecords returns a NextShardIterator (NSI), which the client uses to continue reading from where the previous request stopped. As records are processed, the adapter tracks the timestamp and offset of the last record. The offset increments for records sharing the same timestamp and resets to zero when the timestamp changes. After processing the batch, the next iterator is constructed using the last record's timestamp and its offset incremented by one. Consider the example above, with a client requesting two records per call: records returnedsequence number for nsi Records Returned Sequence Number for NSI order-101, order-102 12100001 order-103, order-104 12100003 order-105 15600001 After the first call, the NSI contains sequence number 12100001, representing timestamp 121 and offset 1. The client passes this iterator unchanged in its next GetRecords request. Phoenix Adapters splits the sequence number into its timestamp and offset components and constructs a query equivalent to: SQL SELECT /*+ CDC_INCLUDE(PRE, POST) */ * FROM <cdcObject> WHERE PARTITION_ID() = <partitionId> AND PHOENIX_ROW_TIMESTAMP() >= 121 ORDER BY PHOENIX_ROW_TIMESTAMP() ASC LIMIT 2 OFFSET 1; This query skips order-102, which was already returned at timestamp 121, and retrieves order-103 and order-104. The following NSI advances to 12100003, allowing the next request to skip all three records at timestamp 121 and continue with order-105. This process allows clients to resume consumption across batches using the returned iterator, without Phoenix Adapters maintaining server-side cursors. It relies on HBase's deterministic row-key scan order to consistently return records sharing the same timestamp in the same order across requests. Phoenix Adapters also checks whether the underlying partition has closed and whether any unread records remain. Once a closed partition has been fully consumed, GetRecords returns a null NextShardIterator, signaling that the consumer has reached the end of that shard. Compatibility Validation Implementing the published interface of a technically complex API is certainly challenging, but it is the behavior across different inputs and edge cases which makes compatibility hard to achieve. DynamoDB provides extensive API documentation, but not every detail of its behavior is explicitly specified, so a great deal of what applications depend on is undocumented. One good way to establish that is to observe what DynamoDB does and record it. Phoenix Adapters includes comprehensive integration tests that compare the results of API operations against AWS DynamoDB Local. These tests help verify that the implementation produces compatible results and catch regressions as the project evolves. One good example is BinaryStreamsIT, which validates change records and old/new item images across inserts, updates, and deletes for tables with primary keys in the binary data format. Community-developed conformance suites provide another way to test compatibility. One such project is Parity Suite, which tests DynamoDB-compatible implementations against behavior observed from the actual AWS DynamoDB service. We ran Parity Suite (v3.6.1) against Phoenix Adapters (as of commit 04d5cbd9d5), and all DynamoDB Streams tests passed, covering INSERT, MODIFY, and REMOVE events, shard and iterator behavior, primary keys, old and new item images, and different stream view types. These results provide additional validation of the Streams implementation for the scenarios covered by the suite Conclusion Together, these four APIs allow existing DynamoDB Streams clients to discover streams, navigate shards, and consume changes from Apache Phoenix. Phoenix Adapters achieves this by exposing Phoenix's SQL-based CDC capabilities and stream metadata through a DynamoDB-compatible interface. The implementation is validated through integration tests against DynamoDB Local and third-party conformance testing. Applications can also use the Kinesis Client Library (KCL) through the DynamoDB Streams Kinesis Adapter, which uses these four APIs to discover shards and consume records. This allows existing KCL-based consumers to work with Phoenix Adapters without implementing their own stream-consumption logic. More broadly, this approach demonstrates how an existing database's CDC capabilities can be exposed through a familiar streaming API. By maintaining compatibility at the API level, applications can continue using their existing client libraries and streaming integrations while working with a different database backend.
The Job Nobody Was Watching We had a crucial job that watched our paid ad spend. It paused underperforming campaigns and moved their budget to the campaigns that performed better. Then the API key it used expired. Nothing was monitoring that cron job, so we assumed everything was running just fine. In the end, it cost us quite a bit of money: the underperforming ads were never paused, and they just kept running and collecting clicks. The annoying part is that everything around it looks fine. The web server answers requests. The database accepts connections. The status page is green. Meanwhile, the scheduled task that creates backups, imports orders, expires sessions, or generates invoices has quietly stopped. Cron fails by doing nothing. Sometimes the job never starts. Sometimes it starts, can't do its work, and tells nobody. There's no HTTP 500, because no HTTP request was involved. There may not even be a log line to grep for. That happens when the crontab is removed, the cron daemon stops, or the command can't be found. So you have to monitor for something that didn't happen. The job checks in. Silence is the alert. Why Your Existing Checks Miss It An HTTP uptime check answers a narrow question: can I connect to this URL and get an acceptable response? The homepage can return 200 while the weekday job scheduled for 02:17 has been dead for a week. An ICMP ping is narrower still. The kernel answers a ping even when cron is stopped, the application is broken, or the backup script has lost its credentials. Application health endpoints are useful, but they report what the running application says about itself. A healthy JSON response isn't proof that a separate scheduled task ran last night. All three checks ask whether something is there. A scheduled job needs the opposite question: did the job that should have run actually run? Silent jobs accumulate in predictable places: inherited crontabs, CMS plugins, forgotten Windows servers, framework schedulers, and scripts that one person configured years ago. The biggest risk lies in the type of cron job that only occasionally reports something to you. For instance, when everything is fine, the scheduled task does nothing. Otherwise, it sends you an email with an overview of the items that need fixing. It's quite common to receive nothing for weeks on end, and then an email with actionable items once every few weeks. If that email never comes, it looks like everything is fine and nothing needs your attention. But maybe the scheduled task was just broken. The Heartbeat Pattern A heartbeat works the other way around. The monitor doesn't poll the process, which may only exist for a few seconds. The process calls the monitor. Each job gets a unique URL. The job requests that URL after it finishes successfully. The receiver stores the timestamp and compares it with the expected schedule. If the next request does not arrive within the allowed window, it sends an alert. Plain Text scheduled job | | HTTP request after each run v unique ping URL | | timestamp compared with schedule v heartbeat monitor | | expected window passes without a ping v alert to the job owner Use one URL per job, not one URL per server. A message saying that server-12 missed a heartbeat still leaves you searching through its crontabs. A message naming nightly-database-backup gives you somewhere to start. The receiver doesn't need to be complicated. It can be a small self-hosted endpoint that records timestamps, or any heartbeat service. Step 1: The One-Line Version The smallest useful implementation is a successful command followed by a request: Plain Text 17 2 * * 1-5 /usr/local/bin/backup.sh && /usr/bin/curl -fsS -m 10 --retry 3 https://<monitor>/ping/<job-id> The && matters. It runs curl only if backup.sh exits with status zero. With ; instead, the ping goes out even when the backup fails. The monitor records a success for a backup that failed. The curl flags are there for unattended runs. -f treats HTTP error responses as failures. -sS hides the progress meter but keeps error messages. -m 10 limits the total request time. A slow receiver can't leave the job hanging. --retry 3 handles a short network interruption. Cron normally starts commands with a minimal environment. Its PATH may differ from the one in your interactive shell. Shell initialization files may never run. Use absolute paths for both the job and curl. Cron jobs don't always cleanly survive server migrations. If you blindly copy scheduled tasks from one server to a new one, but don't account for changed paths or directories, or even a different user that runs the code, the scheduled task may never execute correctly. The one-line version works, but it's incomplete. A failed job and a job that never started both stay silent until the monitoring window runs out. Step 2: Start and Finish Pings For a job that runs longer than a few seconds, send one request when it starts and another when it exits. This gives you a runtime. It also tells "never started" apart from "started but never finished." A Bash wrapper can do this without duplicating the exit handling: Shell #!/usr/bin/env bash set -Eeuo pipefail ping_url="https://<monitor>/ping/<job-id>" started_at=$(/usr/bin/date +%s) /usr/bin/curl -fsS -m 10 --retry 3 "${ping_url}/start" || true finish() { local exit_code=$? local finished_at local runtime finished_at=$(/usr/bin/date +%s) runtime=$((finished_at - started_at)) trap - EXIT set +e if (( exit_code == 0 )); then /usr/bin/curl -fsS -m 10 --retry 3 \ -X POST \ --data-urlencode "exit_code=${exit_code}" \ --data-urlencode "runtime_seconds=${runtime}" \ "${ping_url}" || true else /usr/bin/curl -fsS -m 10 --retry 3 \ -X POST \ --data-urlencode "exit_code=${exit_code}" \ --data-urlencode "runtime_seconds=${runtime}" \ "${ping_url}/fail" || true fi exit "${exit_code}" } trap finish EXIT /usr/local/bin/backup.sh The || true on the start request is deliberate. If the monitor is down, I still want the backup to run. A monitoring failure shouldn't turn into a backup failure. The EXIT trap keeps the job's original exit code and calculates its runtime. It sends the matching ping, then exits with that same code. If another start arrives before the earlier run finishes, you may have overlapping jobs, a stuck process, or a timeout elsewhere in the stack. Step 3: Fail Loudly, Not Late Without an explicit failure request, you only find out about a crash once the grace period expires. That is why the one-line && example is not enough for every job. A failed backup sends no ping. At first it looks the same as a backup that never ran. Send failures to /fail immediately. Include enough context for a first look: the exit code, the runtime, and a few lines of stderr. Shell #!/usr/bin/env bash set -Eeuo pipefail ping_url="https://<monitor>/ping/<job-id>" started_at=$(/usr/bin/date +%s) stderr_file=$(/usr/bin/mktemp) /usr/bin/curl -fsS -m 10 --retry 3 "${ping_url}/start" || true finish() { local exit_code=$? local finished_at local runtime local stderr_tail local endpoint finished_at=$(/usr/bin/date +%s) runtime=$((finished_at - started_at)) stderr_tail=$(/usr/bin/tail -n 20 "${stderr_file}") endpoint="${ping_url}" if (( exit_code != 0 )); then endpoint="${ping_url}/fail" fi trap - EXIT set +e /usr/bin/curl -fsS -m 10 --retry 3 \ -X POST \ --data-urlencode "exit_code=${exit_code}" \ --data-urlencode "runtime_seconds=${runtime}" \ --data-urlencode "stderr=${stderr_tail}" \ "${endpoint}" || true /usr/bin/rm -f "${stderr_file}" exit "${exit_code}" } trap finish EXIT /usr/local/bin/backup.sh 2>"${stderr_file}" "The backup was missed" is vague. "The job ran for 12 minutes and exited 137" is actionable. Exit code 137 is 128 plus 9, meaning the process received SIGKILL. The out-of-memory killer is a common cause. Check memory pressure first. It's not uncommon for a PHP scheduled task to run into a segfault if you're running an older PHP version. Without actionable monitoring, those errors simply disappear. They don't even end up in your PHP error log, because PHP crashed before it could write one. The wrapper above still catches it: the failure ping arrives with exit code 139, which is 128 plus 11, SIGSEGV. Don't ship the whole log. The last 20 lines are usually enough for a first clue. The full log can stay on the host. Step 4: Describing the Schedule Honestly There are two common scheduling models. The first expects a check-in at least once every N minutes. The second evaluates an actual cron expression. Intervals work for jobs that run continuously or at a fixed frequency. They don't fit calendar schedules. A job scheduled for 02:17 from Monday through Friday will look late every Saturday if the receiver expects a request every 24 hours. For calendar-based jobs, give the monitor the same cron expression the scheduler uses. Give it the time zone too. A cron expression without a time zone is ambiguous, especially when the server, application, and monitoring receiver use different defaults. Daylight saving time makes this worse. In most of Europe, the clocks jump from 02:00 to 03:00 in spring. A 02:17 run doesn't exist that day. In autumn, the hour from 02:00 to 03:00 happens twice. What cron does with that depends on the implementation. Your monitor has to agree with it. Leap seconds used to cause issues too. Today, systems mostly handle them fine. But more than a decade ago, I remember that the occasional server crash during a leap second was not uncommon. The server would often reboot on its own, but whatever was scheduled to run during the reboot never executed. Cron doesn't catch up on missed runs, so only a heartbeat would have told you. A grace period sets how late a check-in may be before the job counts as missed. It must cover both late starts and slow runs. A backup that normally takes 90 seconds but sometimes needs six minutes should not alert at the two-minute mark. Set the grace period from observed runtimes, with room for the slowest runs. Do not copy one value across every job. In our own system, we have jobs that do monthly reporting for our clients. Every client who opts in gets a monthly uptime report, sent either to the owner of the account or directly to their own clients. It's never quite clear how long generating those uptime reports will take: if a site had more downtime that month, its report takes longer. So that job has a quite generous grace period to account for fluctuations. It's also the type of job that keeps taking longer as more customers sign up and use the service, so the fluctuations might increase over time too. That's a grace period you have to revisit every now and then. Step 5: Send the Alert to Whoever Can Fix It A missed heartbeat that lands in a shared inbox nobody reads at 02:17 is the same as no heartbeat. Assign an owner to each job. Route the alert to the person or team that can inspect and restart it. The person responsible for a Windows task in one department may have no access to another team's framework scheduler. The alert should name the exact task, host, expected time, and last successful check-in. Make the name recognizable to the operator. Internal identifiers are fine for machines. job-7f3a doesn't tell a person what broke. Throttle repeats, too. One silent job should not produce an alert every minute. Notify when it becomes late. Repeat at an interval you choose, if needed. Resolve the incident when a valid check-in arrives. Beyond crontab The same pattern works anywhere a task can make an HTTP request: Windows Task Scheduler, queue workers, framework schedulers, deployment scripts, and one-off maintenance commands. A short PowerShell task can run a command, verify its exit status, and send the success heartbeat: PowerShell & "C:\Scripts\backup.exe" if ($LASTEXITCODE -ne 0) { throw "backup.exe exited with code $LASTEXITCODE" } Invoke-WebRequest ` -Uri "https://<monitor>/ping/<job-id>" ` -TimeoutSec 10 ` -UseBasicParsing This matters most on servers you inherited and don't fully control. Installing extra software there is often not an option. An HTTP request from the shell or runtime that's already on the box usually is. You still have to check three things: the request tool exists, credentials are handled safely, and outbound network access is allowed. If you're programming in PHP and you define your scheduled tasks in the framework, either in Symfony or in Laravel, the scheduler can send these pings for you. Laravel has start, success, and failure pings built in: PHP // routes/console.php use Illuminate\Support\Facades\Schedule; Schedule::command('backup:run') ->weekdays() ->at('02:17') ->timezone('Europe/Brussels') ->pingBefore('https://<monitor>/ping/<job-id>/start') ->pingOnSuccess('https://<monitor>/ping/<job-id>') ->pingOnFailure('https://<monitor>/ping/<job-id>/fail'); For Symfony, zenstruck/schedule-bundle has similar ping hooks. And there are open-source packages, like spatie/laravel-schedule-monitor, that automatically register all your scheduled tasks with your heartbeat monitor and keep them in sync. That doesn't even need a single extra line of code in your task definitions. What a Heartbeat Can't Tell You A heartbeat proves the job got far enough to send its check-in. It doesn't prove the backup can be restored. It doesn't prove the report has the right rows, or that the import matched your business rules. A command can exit zero after producing an empty file, skipping half its input, or writing corrupt output. Pair the heartbeat with validation that fits the job. Restore backups on a schedule and test the restored data. Check that an export is non-empty and has a plausible row count. Verify a checksum after transferring a file. Make an import exit non-zero when required records are missing. Validation has to change the job's exit status. If the script detects bad output but still exits zero, the heartbeat reports a success. If you're just getting started, you don't need a full validation suite on day one. Differentiating between what you consider the good outcome and the bad outcome, regardless of what that bad outcome is, is already powerful: it alerts you to the problem and lets you investigate deeper. Once that works, add metadata to the failure ping, like in Step 3, so it carries the exact failure message: why the task didn't do its work, either because its data was invalid or because an exception was thrown midway. Rollout Checklist Start with an inventory. Check every user's crontab on each host, system-wide cron directories, Windows Task Scheduler, framework schedulers, queue systems, and CI schedules. Undocumented jobs are the ones most likely to stay silent. For each job: Assign one unique ping URL.Use &&, not ;, for the basic success-only form.Put timeouts and retries on every curl request.Use absolute paths in crontab.After a server migration, check the paths and the user that runs each job.Add start, finish, and failure requests for jobs that take more than a few seconds.Configure the real cron expression and the time zone the scheduler actually uses.Set the grace period from actual runtime observations.Assign an owner who can investigate the alert. Test failure as well as success. Temporarily use a command that exits non-zero and confirm that the failure path runs. Then disable the schedule on purpose and check that an alert arrives after the expected window. Closing I've seen scheduled tasks fail in spectacular ways: from an expired SSL certificate on a remote API that made the task's curl call fail, all the way to segfaults, race conditions, time zone issues, faulty deploys — you name it. It's easy to fall into the trap of thinking that a scheduled task, once defined, will keep running forever. But chances are neither your code nor your infrastructure is static. It moves; it evolves. You iterate based on market demand; you change the application. You have to monitor all these moving pieces, and scheduled tasks are definitely one of them.
Agile
Career Development
Methodologies
Team Management
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
We’re Not Paid to Practice Scrum, but Answer 5 Product Questions
November 25, 2026
by Stefan Wolpers
CORE
AI/ML
Big Data
Databases
IoT
Same Prompt, Different Test: Using AI Agent Workspaces to Make Testing Repeatable
December 1, 2026
by John Vester
CORE
Why GPUs Run at 40% in LLM Inference and How To Fix It
December 1, 2026 by Susmita Singh
Seven AI Adoption Failures and How to Overcome Them
December 1, 2026
by Stefan Wolpers
CORE
Cloud Architecture
Integration
Microservices
Performance
An Introduction to OpenID AuthZEN and authzen-enforcer, a Java SDK
December 1, 2026
by Hüseyin Akdoğan
CORE
Testing Asynchronous Systems, Part 1: Mapping the System and Classifying Its Asynchrony
December 1, 2026
by Stelios Manioudakis
CORE
Hands-On: Build a Least-Privilege Sandbox for AI Agents on Kubernetes
November 30, 2026 by Sai Prasad Veluru
Frameworks
Java
JavaScript
Languages
Tools
Smarter GitHub Copilot Prompts for Java Microservices: From APIs to Production Tests
December 1, 2026 by Vivek Arora
An Introduction to OpenID AuthZEN and authzen-enforcer, a Java SDK
December 1, 2026
by Hüseyin Akdoğan
CORE
Hands-On: Build a Least-Privilege Sandbox for AI Agents on Kubernetes
November 30, 2026 by Sai Prasad Veluru
Deployment
DevOps and CI/CD
Maintenance
Monitoring and Observability
Smarter GitHub Copilot Prompts for Java Microservices: From APIs to Production Tests
December 1, 2026 by Vivek Arora
Same Prompt, Different Test: Using AI Agent Workspaces to Make Testing Repeatable
December 1, 2026
by John Vester
CORE
AI/ML
Java
JavaScript
Open Source
Smarter GitHub Copilot Prompts for Java Microservices: From APIs to Production Tests
December 1, 2026 by Vivek Arora
Same Prompt, Different Test: Using AI Agent Workspaces to Make Testing Repeatable
December 1, 2026
by John Vester
CORE
Why GPUs Run at 40% in LLM Inference and How To Fix It
December 1, 2026 by Susmita Singh