Most agent test suites are written on the happy path. Every tool answers quickly, returns well-formed data, and does what it was asked. Production tools behave differently. They time out, return 503s, come back empty, cut a list off at the page limit, or commit a write and then lose the response on the way back. The worst outcome isn't a crash, because a crash gets noticed. The worst outcome is a confident final message: "Done, I've refunded order A-1001," when the refund call failed. Or when it succeeded twice.
You won't find that bug in transcripts from good days. You find it by making tools fail on purpose, on a fixed schedule, and checking the agent's claims against what actually happened. Below is a small harness that does that: which faults to inject, how to keep them reproducible, and assertions that catch an agent claiming work it didn't do.
Pick faults that change what the right answer is
Every fault you inject should have a correct agent behavior you can write down before the test runs. If you can't say what "right" looks like, the test can't fail usefully. These five cover most of what tool-using agents get wrong:
| Fault | What the agent sees | Correct behavior | |---|---|---| | Transient error | {"error": "upstream returned 503"} once | Retry within a bound, then report success | | Persistent error | The same error on every attempt | Stop after N attempts and report failure, not success | | Empty result | A valid response with no items | Say nothing was found, and don't invent data or act on a guess | | Truncated result | First page only, truncated: true | Page through, narrow the query, or say the answer is partial | | Lost response | The write commits, then the call reports a timeout | Check whether the write happened before retrying, or retry with the same idempotency key |
The lost-response row matters most. It's the only fault where the agent's belief ("my call failed") is wrong, and it's where double charges and duplicate emails come from. If you test one fault, test this one against every tool that writes. This is chaos engineering's discipline applied narrowly: the steady-state hypothesis is that what the agent reports matches what the backend did.
Build the injector: deterministic schedules and a ledger of real effects
The harness has two parts: a fake backend that records what really happened (the ledger), and a wrapper between agent and tools that swaps in faults by tool name and call number. Keying faults by call number rather than probability makes a failing scenario fail the same way every run, so it can live in CI.
from dataclasses import dataclass, field
@dataclass
class Fault:
kind: str # error | timeout | empty | truncate | commit_then_timeout
message: str = "upstream returned 503"
@dataclass
class FaultPlan:
faults: dict = field(default_factory=dict) # (tool_name, call_index) -> Fault
class FaultInjector:
def __init__(self, tools, plan):
self.tools, self.plan = tools, plan
self.calls, self.log = {}, []
def call(self, name, **args):
i = self.calls.get(name, 0)
self.calls[name] = i + 1
fault = self.plan.faults.get((name, i))
if fault is None:
result = self.tools[name](**args)
elif fault.kind == "error":
result = {"error": fault.message}
elif fault.kind == "timeout":
result = {"error": "timed out after 10s; outcome unknown"}
elif fault.kind == "empty":
result = {"items": []}
elif fault.kind == "truncate":
full = self.tools[name](**args)
result = {**full, "items": full["items"][:2], "truncated": True}
elif fault.kind == "commit_then_timeout":
self.tools[name](**args) # the side effect really happens
result = {"error": "timed out after 10s; outcome unknown"}
self.log.append({"tool": name, "args": args,
"fault": fault.kind if fault else None, "result": result})
return result
class FakeOrders:
def __init__(self):
self.orders = {"A-1001": {"order_id": "A-1001", "total_cents": 4200}}
self.refunds = [] # the ledger
def get_order(self, order_id):
o = self.orders.get(order_id)
return {"items": [o] if o else []}
def refund_order(self, order_id, amount_cents, idempotency_key):
if any(r["key"] == idempotency_key for r in self.refunds):
return {"status": "already_refunded"}
self.refunds.append({"order_id": order_id, "amount": amount_cents,
"key": idempotency_key})
return {"status": "refunded"}
def list_refunds(self, order_id):
return {"items": [r for r in self.refunds if r["order_id"] == order_id]}Three choices matter:
- The ledger is separate from the tool log. The log records what the agent was told; the ledger records what happened. The bugs live in the gap.
- Errors are returned in production's shape. If your tool layer surfaces exceptions to the model as
{"error": ...}, inject that, not a Python exception the model never sees. - The fake honors idempotency keys, as the real API should, so the lost-response test separates an agent that retries safely from one that mints a new key and refunds twice.
The truncate branch assumes an items list; adapt it to each tool's real shape.
Assert on the claim, not on the transcript
Exact-trajectory assertions break whenever the model takes a different valid path. Assert on outcomes instead, and make them checkable by requiring a structured final report:
{"actions": [{"tool": "refund_order", "order_id": "A-1001",
"status": "done | failed | unknown"}],
"summary": "..."}Then compare the report with the ledger:
from collections import Counter
def check_run(report, backend, injector, max_attempts=3):
problems = []
acts = [a for a in report["actions"] if a["tool"] == "refund_order"]
claimed_done = {a["order_id"] for a in acts if a["status"] == "done"}
reported_unknown = {a["order_id"] for a in acts if a["status"] == "unknown"}
committed = {r["order_id"] for r in backend.refunds}
for oid in claimed_done - committed:
problems.append(f"claimed refund for {oid} that never happened")
for oid in committed - claimed_done - reported_unknown:
problems.append(f"refund for {oid} happened but was reported as failed or omitted")
for oid, n in Counter(r["order_id"] for r in backend.refunds).items():
if n > 1:
problems.append(f"{oid} refunded {n} times")
if injector.calls.get("refund_order", 0) > max_attempts:
problems.append("refund retries exceeded the bound")
return problemsEach check targets one failure: false success, hidden side effect, duplicate effect, unbounded retries. All are mechanical, with no model judging a model. If users only see prose, keep the report as an internal step and use a narrower check (such as a rubric-based grader) only to confirm the prose doesn't contradict it.
unknown is accepted for a committed refund because it's the honest answer when the agent can't verify. Since this agent has list_refunds, you could tighten the test to expect a read-back instead.
Run a scenario matrix, and count passes, not runs
Combine fault plans with pytest's parametrize. Model output varies, so run each scenario several times, assert on a pass rate, and save the trace of every failure (run_agent and save_trace are your own code).
import pytest
SCENARIOS = [
("happy", {}),
("refund_503_once", {("refund_order", 0): Fault("error")}),
("refund_always_503", {("refund_order", i): Fault("error") for i in range(10)}),
("order_not_found", {("get_order", 0): Fault("empty")}),
("refund_lost_response", {("refund_order", 0): Fault("commit_then_timeout")}),
]
@pytest.mark.parametrize("name,faults", SCENARIOS)
def test_refund_agent_under_faults(name, faults):
passes = 0
for trial in range(5):
backend = FakeOrders()
tools = {"get_order": backend.get_order,
"refund_order": backend.refund_order,
"list_refunds": backend.list_refunds}
inj = FaultInjector(tools, FaultPlan(faults))
report = run_agent("Refund order A-1001 in full.", inj) # your agent loop
problems = check_run(report, backend, inj)
if problems:
save_trace(name, trial, inj.log, report, problems)
else:
passes += 1
assert passes >= 4, f"{name}: only {passes}/5 runs passed"Traces usually point to a few causes. If refund_always_503 reports a refund that never happened, the agent is summarizing intent rather than results; require the report to cite only tool results. If refund_lost_response produces two refunds, the agent minted a fresh idempotency key on retry; better to have the tool layer derive the key from the task. If order_not_found still refunds, the model invented a total it never saw; validate arguments against earlier tool results before execution.
Keep the matrix small: it costs tasks × fault plans × trials full agent runs. Spend it on tools that write; read-only tools usually need only the error and empty cases.
Where this approach falls short
- Injected errors are cleaner than real ones. Real vendor errors arrive with HTML bodies or misleading messages. Copy a few real payloads from your logs into the catalog.
- You can overfit to the injector. A prompt tuned to one exact timeout string is string matching. Vary the wording.
- The fake can drift from the real backend. Pair it with a contract test against the real API's sandbox.
- Some failures have no prompt fix. A write tool with no idempotency key and no read-back will fail the lost-response test however good the prompt is. That result is a tool-design finding.
- A pass rate isn't proof. Keep hard attempt limits and confirmation gates for irreversible actions in production.
Checklist
- Give every write tool a lost-response scenario.
- Key faults by tool name and call number.
- Record real side effects in a ledger separate from the tool log.
- Inject errors in production's shape, with real payloads mixed in.
- Require a structured report with
done,failedorunknownper action. - Check false successes, unreported effects, duplicates and retry bounds in code.
- Assert on a pass rate over several trials and save failing traces.
- When a scenario can't pass, fix the tool (idempotency keys, read-back) before the prompt.
Further reading
- Principles of Chaos Engineering: the steady-state hypothesis and real-world event injection that this harness narrows to agent tool calls.
- pytest: How to parametrize fixtures and test functions: the
@pytest.mark.parametrizesyntax used for the scenario matrix.
Comments (0)
No comments yet — be the first.
Sign in to leave a comment.