Agents II: Harness Engineering
Validation, retries, guardrails, sandboxing, budgets and durable execution.
The loop in Chapter 18 is ten lines. An agent you can put in front of customers is mostly the code around those ten lines: validation, retries, budgets, guards, sandboxes and fallbacks. That surrounding code is the harness, and it is where the reliability that the loop lacks is bought.
The chapter’s experiment is a simulation. A scripted stand-in for a model makes mistakes at stated rates, and a real harness is built around it one layer at a time. The model is simulated; the harness code and its measured effect are not.
19.1The harness
The deterministic shell that makes a stochastic loop shippable.
Section 18.6 did the arithmetic: a step that is right 95% of the time gives a 20-step task a 36% chance. For a given model and prompt, that per-step rate is roughly fixed. The harness is what multiplies it. Validation turns silent failures into caught ones. Retries turn transient failures into successes. Budgets turn runaway failures into bounded ones.
To see how much each layer buys, I simulated a four-step task: find a customer, list their refunds, email a report, and state the total. The stand-in model makes four kinds of mistake at fixed rates per step: malformed arguments (6%), an invented customer ID (5%), a repeated call (4%) and an arithmetic slip (3%). The environment adds tool timeouts (5%). Then I added harness layers one at a time and ran 40,000 tasks at each stage.
- correct, with exactly one email sent
- stopped with an error
- finished, but wrong
- duplicate emails
| Layers in place | Correct, with one email | Finished but wrong | Stopped with an error | Duplicate emails | Model steps per task |
|---|---|---|---|---|---|
| 0. Bare loop | 59.9% | 8.9% | 28.7% | 2.9% | 3.5 |
| 1. Add validation and retries | 81.6% | 12.6% | 0.2% | 6.5% | 4.5 |
| 2. Add reality checks; totals computed in code | 93% | 0% | 0.4% | 6.6% | 4.6 |
| 3. Add loop detection and a step budget | 97.1% | 0% | 0.4% | 2.5% | 4.5 |
| 4. Add idempotency keys | 99.6% | 0% | 0.4% | 0% | 4.5 |
The second row is the instructive one. Adding validation and retries cut crashes from 29% to almost nothing. It also raised the share of runs that finished with a wrong answer, and more than doubled duplicate emails. Runs that used to crash now complete, including the ones carrying a bad value, and retries resend things. A harness layer converts one kind of failure into another, and you have to follow each conversion to its end.
The remaining sections take the layers one at a time.
Common take“To make the agent reliable we need a better model.”
Sharper take“The model’s per-step accuracy is close to fixed. The harness is what turns it into system reliability, and it is deterministic code that a reliability engineer would recognize.”
19.2Validation at every joint
Check every joint, because one bad value corrupts everything after it.
The middle check is the one that gets skipped. A schema says an order ID is a string. The model invents one that looks right. The schema passes, and the database has no such order. In a bare loop that does not crash anything. The empty result enters the transcript as fact and every later step builds on it. In the simulation, checking identifiers against the data, and computing the total in code instead of letting the model add, took wrong answers from 13% to zero.
Two rules follow. Validate against your data layer, not only against the schema. And wherever a value can be computed or looked up in code, do that in preference to asking the model to produce it.
Common take“The tool call matched the schema, so it was valid.”
Sharper take“It was well-formed. Whether the order ID exists is a separate check against the database, and I do that one too, because an invented ID passes every schema.”
19.3Retry with error feedback
A bounded loop in which the error message is the fix instruction.
for attempt in range(3): # the cap is the feature
output = model(messages)
try:
return Schema.model_validate_json(output)
except ValidationError as error:
messages.append(user(
f"Your output failed validation:\n{trim(error)}\n"
f"Return corrected JSON only."))
raise EscalateToFallbackThis is what “self-healing” means once the marketing is removed. It works because the error text changes what the model is conditioned on: after “the field amount must be a number, not a string”, the corrected output is the likely one. It repairs format errors and simple constraint violations. It does not repair being wrong. A model that misread an invoice will misread it again, in valid JSON.
The same pattern runs through the whole harness. A failed tool call returns an error written as an instruction, and the model tries again. Code that does not compile returns the compiler’s output. That last case is most of the mechanism of a coding agent.
- Cap it at two or three attempts. The chance of success falls quickly after the second, and each retry bills the whole transcript again.
- Trim the error. One relevant line is an instruction. A four-kilobyte traceback is a distractor.
- Track the retry rate. It is an early warning: a retry rate that climbs with no deployment on your side often means the model or its inputs have shifted, days before quality metrics show it.
Common take“Our agent is self-healing.”
Sharper take“It has a retry loop that feeds the error back, capped at three attempts. That fixes malformed output. It doesn’t fix a wrong reading of the input, so I don’t describe it as more than it is.”
19.4Guardrails and action gates
Deterministic gates at the edges, and the model never certifies itself.
Input guards run before the loop spends anything: is the request in scope, is it within size limits, does the caller have access, does it match known injection patterns? Output guards run before the user sees a result: policy checks, a scan for personal data, a check that citations exist. Between them sits the gate that matters most, on actions.
| Kind of action | Gate | Reason |
|---|---|---|
| Read-only, such as looking up an order | None | Nothing can be damaged |
| Reversible write, such as adding a note | Validate and log | It can be undone |
| Irreversible, financial or external, such as sending an email, issuing a refund or deleting a record | A person confirms, or hard limits apply: a ceiling per refund, one per customer per day | Sooner or later the model will attempt it |
The principle behind all of these: guards are plain code and small separate classifiers, never the same model grading its own output in the same context. A loop that has been manipulated or has drifted is compromised in its judgment too. Asking it “was that safe?” consults the judge that was just fooled. A small classifier asked one narrow question, such as whether a text contains a promise of a refund, is cheap, fast, and outside the loop’s influence.
Guardrails reduce rates. They do not prove safety. Layered, they turn “usually doesn’t” into “cannot ship without tripping three alarms” (Chapter 26).
Common take“We ask the model to double-check its answer for policy violations.”
Sharper take“The check runs outside the loop: code where a rule can be written, and a small separate classifier where it can’t. The model that produced the output doesn’t get to approve it.”
19.5Fallback chains
Every dependency gets a next-worse option, chosen in advance.
Two rules, each with a reason.
- Degrade capability, never correctness. Falling back to a smaller model on a drafting task is invisible. On an extraction task it is a silent drop in accuracy. So fallback policy is set per route, not globally.
- Partial results beat theatrical failure. “Completed three of five sub-tasks; blocked because the CRM is down” preserves the work and the user’s trust. It requires progress to be recorded as the run goes.
Retries and fallbacks have a known side effect, which the simulation showed: they repeat things. A timeout does not tell you whether the email went out. The fix is not a smarter agent. It is an idempotency key on every tool with a side effect, so that a repeated request is recognized and ignored. In the simulation that one change removed every duplicate email.
A circuit breaker completes the set. A tool that has failed half the time for five minutes is taken out of the tool list for a while, and the model is told why, so the loop stops spending its budget on a dead dependency.
Common take“The customer received three confirmation emails. The agent is buggy.”
Sharper take“A retry wrapped a send that wasn’t idempotent. I put an idempotency key on every tool that has a side effect, and then retries and fallbacks are safe.”
19.6Sandboxing
Assume the loop is hostile, because through injection it sometimes is.
An agent’s tool calls are shaped by everything in its context, including retrieved documents, web pages and tool results that outsiders wrote. So the executor has to enforce limits that the model’s intent cannot exceed.
| Layer | Mechanism | What it rules out |
|---|---|---|
| Least-privilege credentials | The agent’s database user can read three tables and write none. Keys are scoped per tool and per customer | The whole class of “the agent ran an UPDATE”. It cannot, whatever it emits |
| Isolated code execution | Generated code runs in a container or small virtual machine: no network or an allow-list, a read-only file system with a scratch directory, limits on CPU, memory and time | Data theft and resource abuse by generated code |
| Outbound network control | Requests are allowed only to listed domains | An injected page saying “send the conversation to this address” |
| Limits inside the tool | The refund tool enforces its own ceiling. The email tool sends only to the ticket’s requester | Prompt-level rules being talked around: the tool is the last line and the only deterministic one |
| Tenant scoping in the data layer | Queries take the customer identifier from the authenticated session, never from model output | One customer’s data reaching another: the model never chooses whose data it reads |
In one sentence: capabilities are enforced where the model cannot reach, in credentials, containers and query scoping, because anything enforced only in a prompt is a suggestion (section 11.2).
Common take“The system prompt forbids the agent from deleting anything.”
Sharper take“The agent’s credentials can’t delete anything. I answer ‘what’s the worst it can do’ by listing its permissions, not its instructions.”
19.7Budgets and cancellation
Every layer’s limit fits inside its parent’s.
Three budgets apply at once: steps, time and money. Each layer’s limit must fit inside the one above it. If a tool is allowed 60 seconds inside a step allowed 25, the step’s timeout will fire while the tool is still running, and the work it does afterward is paid for and thrown away.
- Count steps and tokens, not only seconds. A loop can stay within its time limit while spending far more than intended, since every step re-reads the transcript.
- Make cancellation real. When a user closes the page or a deadline passes, the signal has to reach the model call and the running tool, or the system keeps paying for work nobody will see.
- Detect loops. The same call with the same arguments twice in a row is nearly always a stall. Return “you already did this, and the result was…” without running it again. In the simulation, loop detection and a step budget took correct results from 93% to 97%.
- Exit honestly. A run that hits its budget should hand off with what it achieved, not present a partial result as complete.
Common take“We set a 60-second timeout on the agent.”
Sharper take“There are budgets for steps, time and cost at every level, each fitting inside its parent’s, with cancellation that reaches the running tool. A single outer timeout leaves work running after everyone has stopped waiting.”
19.8Durable execution and approval
Durable execution, and approval as product design.
An agent that works for an hour will outlive a deployment, a server restart or a rate-limit pause. If its state exists only in a process’s memory, any of those sends it back to the beginning, with the side effects of its first attempt already in the world.
Durable execution is the remedy. After every step, the harness records the transcript, the plan and each tool result to storage. On restart, the run resumes from the last recorded step, and steps already completed are not executed again. Workflow engines provide this as a service: they record each step’s outcome and replay a run deterministically after a failure. The requirement on your side is the one from section 19.5: steps with side effects must be idempotent, since a step can be attempted more than once around a crash.
Durability is also what makes human approval workable, because a person may take hours to respond. Approval is usually drawn as a pause in a diagram. It is better treated as a piece of product design.
- Show the consequence, not the tool call. “Refund €84 to Priya Shah for order A1B2” can be judged. A blob of JSON cannot.
- Tier by risk. Approve the irreversible and the expensive. Asking about everything trains people to click yes without reading.
- Decide what happens on silence. A request with no response needs a timeout and a default, normally not to act.
- Prefer undo where it exists. A reversible action with a clear undo often serves better than a confirmation before it.
- Record who approved what, with what they were shown.
Common take“We added a human-in-the-loop step, so it’s safe.”
Sharper take“An approval is only as good as what the approver is shown and how often they are asked. I gate the irreversible actions, show the consequence in plain words, and keep the run’s state durable so it can wait for an answer.”
19.9Multi-agent systems
An org chart for context windows.
The pitch is a team of specialist agents collaborating. The mechanism is several loops with separate transcripts, passing messages. What that buys, and on what condition:
| Benefit | Mechanism | It pays when |
|---|---|---|
| Context isolation, the one that matters most | Each sub-agent gets a clean window holding only its sub-task | A single transcript cannot hold the job: deep research, work across a large codebase (section 20.7) |
| A smaller tool list per agent | Forty tools become eight per specialist | Often a router achieves the same (section 16.5) |
| Parallelism | Independent sub-tasks run at once | The sub-tasks are truly independent |
| Separation of duties | A checker with different context and tools reviews the doer | The checker is truly independent, not the same context approving itself |
The costs are rarely advertised. Every handoff is a lossy summary: the worker lacks the mission’s context, and the coordinator lacks the worker’s detail. The most common multi-agent failure is a sub-agent solving the wrong sub-problem perfectly. Errors now compound across agents as well as steps. Cost multiplies, since each agent re-reads its own transcript. And debugging means reading several interleaved traces.
Inside one application, “agents talking” are function calls (section 18.8). The agents are partitions of context, not colleagues. So the rule: use several agents when one context window measurably cannot hold the task, or when verification has to be independent. Do not use them because the diagram looks like a team.
Common take“We built a crew of five specialist agents.”
Sharper take“I build one loop, read its traces, and split off a sub-agent only where the single context demonstrably fails. Each split adds a lossy handoff, so it has to buy something.”
19.10The maturity ladder
What production-ready means, level by level.
| Level | Adds | Converts |
|---|---|---|
| L0 | The bare loop | The demo |
| L1 | Validation at every joint | Silent failures into caught ones |
| L2 | Capped retries with error feedback | Transient failures into successes |
| L3 | Nested budgets, timeouts and cancellation | Runaway failures into bounded ones |
| L4 | Guardrails at the edges; sandboxed tools with least privilege | Policy failures into alarms; the worst case into a list |
| L5 | Fallback chains, partial results, durable execution | Hard failures into degraded successes |
| L6 | Several agents, only if traces demand it | Failures of scale into partitioned ones |
At every level the system is traced (Chapter 24) and gated by evaluation (Chapter 23), and the whole thing sits behind a router, so that the agent runs only where it earns its cost (section 18.10).
Read down the right-hand column. Each layer converts one class of failure into a cheaper class. None of it makes the model more intelligent. All of it makes the system more reliable. Most of a good harness is code that a reliability engineer from any other field would recognize, attached at the points where a model’s output enters the system.
Common take“Is our agent production-ready? It works on our test cases.”
Sharper take“I answer with a level. It validates every joint, retries with a cap, has nested budgets and gated actions, and degrades instead of failing. Agents did not invent reliability engineering. They made it compulsory.”
Key takeaways
- The harness is the deterministic code around the loop. It turns a roughly fixed per-step accuracy into system reliability.
- In a simulation with fixed model error rates, five harness layers took correct results from 60% to 99.6%.
- Each layer converts one failure into another: adding retries cut crashes and raised wrong answers and duplicate emails until later layers dealt with those.
- Validate against reality, not only the schema, and compute in code what code can compute.
- “Self-healing” is a capped retry loop with the error fed back. It fixes format, not wrong readings.
- Guards are code and small separate classifiers. The model never approves its own output.
- Put an idempotency key on every tool with a side effect, and retries become safe.
- Enforce limits where the model cannot reach: credentials, containers, query scoping.
- Budgets for steps, time and cost nest, and cancellation must reach the running tool.
- Long runs need durable state, and approval is product design: show the consequence, gate by risk.
- Use several agents for context isolation or independent checking, not for the diagram.
Check your understanding
-
After you add automatic retries to an agent, its crash rate falls from 20% to 1%. Two weeks later, customers complain of duplicate charges and support finds answers that are confidently wrong. Explain both using the simulation in section 19.1, and say what to add.
Answer outline
Retries converted failures; they did not remove them. Runs that used to crash now finish, including those carrying an invented or misread value, so finished-but-wrong results rise. And a retry after a timeout repeats a call whose first attempt may have succeeded, which duplicates side effects. Add reality checks on values before they are used, compute in code what can be computed, and put idempotency keys on every tool that charges, sends or writes. Then watch three numbers separately: stopped runs, wrong results and duplicated effects.
-
A security reviewer asks: “What is the worst thing this agent can do if a web page it reads contains malicious instructions?” Give the structure of a good answer for an agent that can browse, query a customer database and send email.
Answer outline
Answer from permissions, not prompts. List each credential and its scope: the database user reads named tables for the current customer only, with the customer identifier taken from the session; outbound requests go only to allow-listed domains, so data cannot be posted elsewhere; the email tool sends only to the ticket’s requester and is rate-limited inside the tool; code, if any, runs in an isolated container without network access. Then state what remains possible within those limits, such as a misleading reply to the requester, and what catches it: output guards, logging and review. An answer that starts “the system prompt says” is not an answer.
-
Your agent runs for up to forty minutes and must get manager approval before issuing refunds above a threshold. During a deployment, in-flight runs restart from the beginning and some customers are refunded twice. Design the fix.
Answer outline
Make execution durable: persist the transcript, the plan and each tool result after every step, and resume from the last recorded step after a restart, without re-running completed steps. Give the refund tool an idempotency key derived from the task and the order, so that a repeated attempt is ignored. Store pending approvals with the run, showing the approver the consequence in plain terms, with a timeout whose default is not to refund, and a record of who approved. Test by killing the process at each step and confirming exactly one refund.
Further reading
- Anthropic, “Writing effective tools for agents”: tool design from the point of view of the model that has to use the tools.
- Micheal Lanham, AI Agents in Action, 2nd edition (Manning, 2026): agent systems built step by step, including guardrails and multi-agent designs.
- Chip Huyen, AI Engineering, chapter 6: the section on agents, including planning failures and their evaluation.