Chaos, Recovery Testing and Release Gates
Break things on purpose, in a controlled way, and let written thresholds decide what is ready to ship.
List how the agent's dependencies can fail, inject those failures deliberately and check that the system returns to a defined steady state without duplicate or lost actions. Test restarts and long-running state. Then apply release gates with thresholds agreed before the results are known, and finish with a production acceptance checklist.
What you will learn: failure injection, chaos experiment design, recovery and idempotency tests, testing long-running agents, release gates and acceptance testing.
Prerequisites: Reliable Tool Execution and Error Recovery and Agent Evaluation Framework.
The example runs in November 2026 with Python 3.13 and only the standard library. The payment service is a small in-memory stand-in, so no money or network is involved.
Why test failure on purpose
An agent depends on models, tools, networks, queues, stores and people. Each can be slow, wrong or unavailable. The dangerous cases are rarely a clean error. They are a call that succeeded but returned nothing, a process that stopped between acting and recording, or a retry that repeated a payment.
| Component | Failures to inject | Expected behavior |
|---|---|---|
| Model service | Timeout, rate limit, truncated or invalid reply | Bounded retry, fallback or clean stop |
| Tool or API | Error, slow reply, wrong shape, partial success | Validation, verification of effects |
| Retrieval | Empty, stale or irrelevant results | Says what is missing; no invented answer |
| State store | Write failure, stale read, conflict | No acting on unsaved state |
| Queue or events | Duplicate, delayed or out-of-order message | Idempotent handling |
| Process | Crash or restart at any step | Resume from the last safe point |
| Human step | No reply before the deadline | Expire safely and notify |
| Identity | Expired or revoked credential | Stop and report; never use a broader one |
Where to inject faults
Start in unit and integration tests, where a fake dependency can raise any error on demand. Move to a staging environment to interrupt real components. Only teams with strong monitoring, limits and a fast stop should consider experiments in production.
Chaos engineering for agent systems
The Principles of Chaos Engineering describe experiments that build confidence in a system's ability to cope with turbulence. The method is to define a measurable steady state, hypothesize that it will hold, introduce realistic events and try to disprove the hypothesis, comparing with a control group.
| Element | Agent example |
|---|---|
| Steady state | Verified task success and zero duplicate actions |
| Hypothesis | Success stays above target when the search tool is slow |
| Event | Add delay to a share of search calls |
| Scope | Test traffic, or a small internal group |
| Abort rule | Stop if error rate or spend crosses a limit |
| Observation | Traces, retries, latency, cost and user messages |
| Follow-up | Fix, owner, date and repeat of the experiment |
Agents add a twist: the model may react to a failure creatively. It might try another tool, guess a value or report success. Your steady state should therefore include honesty and permission checks, and not only uptime.
Run the smallest experiment that can disprove the hypothesis, tell the people on call, keep a tested stop switch and never experiment on actions you cannot reverse.
Assert the same invariants after every fault
Whatever you inject, finish the test by checking properties of the whole system. This is stricter than checking that no exception was raised.
| Invariant | How to check it |
|---|---|
| No duplicate effect | Count records, messages and charges by business key |
| No lost work | Every accepted task ends as done, failed or handed over |
| Honest status | What the user was told matches the system of record |
| Bounded effort | Retries, steps, time and spend stay inside limits |
| Same permissions | No fallback path used a wider credential or skipped approval |
| Traceable | The fault and the response to it appear in the trace |
A worked experiment plan
This illustrative plan fits on half a page, which is about the right size.
Steady state: verified success and response time on the test workload stay inside agreed limits.
Hypothesis: adding ten seconds to one search call in five causes one retry at most, then a clear partial answer.
Scope: staging, replayed test traffic, thirty minutes.
Control: the same traffic without delay, run alongside.
Abort if: any write action repeats, or spend reaches the test cap.
Record: success, retries, latency percentiles, cost and a sample of replies.
A result that disproves the hypothesis is useful. Suppose the agent answered from model knowledge when search timed out and did not say so. The fix might be a rule in code that marks the evidence as missing, followed by the same experiment and a regression case.
Test the resilience mechanisms themselves
| Mechanism | Failure it can cause | Test |
|---|---|---|
| Retries | Load multiplies during an outage | Count total attempts across all layers |
| Timeouts | Work continues after the caller gave up | Confirm cancellation or reconciliation |
| Circuit breaker | Stays open after recovery | Restore the dependency and watch it close |
| Fallback model | Lower quality or different tool behavior | Run the gates on the fallback path too |
| Cache | Serves stale or another user's data | Change source data; test isolation |
| Queue redelivery | Same message processed twice | Deliver it twice on purpose |
| Manual handover | Nobody receives the case | Send one through and time the response |
Retries deserve special care. If a client, a framework and a gateway each retry three times, one failing request can become dozens of calls. Decide which layer owns retrying and make the others pass errors on.
Failure injection and recovery testing
For every action with an effect, test an interruption before the call, after the call but before the result is saved, and after saving. The middle case is the one teams miss. Recovery is safe when the system can find out whether the effect happened, or when repeating the request with the same idempotency key has no further effect.
"""Inject failures into a two-step workflow and check recovery (simulation)."""
class Crash(Exception):
pass
class PaymentService:
def __init__(self, honor_keys):
self.honor_keys = honor_keys
self.charges = []
self.seen = {}
def charge(self, key, amount):
if self.honor_keys and key in self.seen:
return self.seen[key]
self.charges.append(amount)
self.seen[key] = f"receipt-{len(self.charges)}"
return self.seen[key]
def run(order, service, store, fault=None):
"""Resumable: finished steps are recorded in the store."""
if "receipt" not in store:
if fault == "timeout_before_call":
raise Crash(fault)
receipt = service.charge(key=f"{order}:charge", amount=50)
if fault == "crash_after_charge":
raise Crash(fault) # the money moved but nothing was recorded
store["receipt"] = receipt
if fault == "crash_before_email":
raise Crash(fault)
store["emailed"] = True
def experiment(fault, honor_keys):
service, store = PaymentService(honor_keys), {}
try:
run("ord-1", service, store, fault)
except Crash:
pass
run("ord-1", service, store) # restart without the fault
# Steady state: exactly one charge and the customer told.
return len(service.charges) == 1 and store.get("emailed", False), len(service.charges)
if __name__ == "__main__":
results = []
for honor_keys in (True, False):
print("idempotency keys honored:", honor_keys)
for fault in ("timeout_before_call", "crash_after_charge", "crash_before_email"):
ok, charges = experiment(fault, honor_keys)
results.append((honor_keys, ok))
print(f" {fault:<20} charges={charges} {'PASS' if ok else 'FAIL'}")
blocked = [r for r in results if r[0] is False and not r[1]]
print()
print("release gate for the service without keys:", "BLOCK" if blocked else "ALLOW")
Output:
idempotency keys honored: True
timeout_before_call charges=1 PASS
crash_after_charge charges=1 PASS
crash_before_email charges=1 PASS
idempotency keys honored: False
timeout_before_call charges=1 PASS
crash_after_charge charges=2 FAIL
crash_before_email charges=1 PASS
release gate for the service without keys: BLOCK
Both designs survive a timeout before the call and a crash before the email. Only the service that honors keys survives a crash after the charge; the other charges twice. A suite that tested only timeouts would have approved it. If a real service offers no idempotency support, query it before retrying, or hand the uncertain case to a person. See Durable Execution, Checkpoints and Approvals for engines that record progress.
Testing long-running and stateful agents
| Concern | Test |
|---|---|
| Restart | Stop and resume at each checkpoint |
| Version change | Resume a task started by the previous release |
| Expiry | Credentials, approvals and data that age out while waiting |
| Changed world | A record is edited by someone else mid-task |
| State growth | Very long histories, summaries and memory |
| Cancellation | User cancels during each phase |
| Time | Simulated clocks that jump hours or days |
| Concurrency | Two workers pick up the same task |
A controllable clock lets a test cover a three-day wait in milliseconds. Soak tests, which run many tasks for a long period, reveal leaks, growing context and slow drift that short tests miss (Stateful and Long-Running Agent Architecture).
Release gates and quality thresholds
A release gate is a written rule that turns evidence into a decision. Agree it before running the evaluation, so that thresholds do not move to fit the result.
| Gate type | Example rule | On failure |
|---|---|---|
| Hard | No completed forbidden action; no duplicate effect | Block |
| Threshold | Success in each critical slice at or above target | Block |
| Regression | No critical case that passed before now fails | Block until reviewed |
| Comparison | Not credibly worse than the current release | Review |
| Budget | Latency and cost per success within limits | Review or block |
| Operational | Rollback, alerts and owner verified | Block |
- Set targets from the cost of failure and the performance of the current process.
- Treat flaky results as information: measure the rate instead of rerunning until green.
- Record the versions of agent, model, prompts, tools, data and graders.
- Allow an exception only with a named approver, a reason, a limit and an end date.
Gates continue after release
Each stage needs its own entry rule, minimum observation time or volume, automatic stop conditions and a rollback that has been rehearsed. In a shadow run, make certain that write tools are replaced, or the "invisible" version will act for real. See CI/CD, Infrastructure as Code and Safe Releases and Promotion, Feature Flags, Rollback and Drift.
Production acceptance test checklist
Acceptance testing asks whether the whole service is ready for its owners and users, not only whether the model scores well.
| Area | Evidence required |
|---|---|
| Function | Gate results by slice, with failures reviewed |
| Safety and access | Invariant and permission tests; open findings accepted in writing |
| Recovery | Crash, restart, retry and duplicate tests |
| Load | Behavior at expected and peak volume, including rate limits |
| Limits | Step, time and spend caps shown to work |
| Observability | A test run can be traced from request to effect |
| Operations | Runbook, on-call owner and stop switch exercised |
| Fallback | Manual process available and staff know it |
| Rollback | Previous version restored in rehearsal, with state compatible |
| Communication | Users know what the agent does and how to get help |
A worked gate decision
The following table is illustrative. It shows why a gate lists separate rules instead of one combined score.
| Rule | Result | Status |
|---|---|---|
| No duplicate effects in fault tests | None observed in 40 injected faults | Pass |
| Success on routine tasks at least 90% | 188 of 200 | Pass |
| Success on refund tasks at least 95% | 36 of 40 | Fail |
| 95th percentile time under 30 seconds | 24 seconds | Pass |
| Rollback rehearsed with in-flight tasks | Not yet done | Fail |
The overall pass rate looks healthy, yet two rules block the release. The team can fix and retest, or ship a narrower version that leaves refunds with people, provided the rollback rehearsal happens first. Both are better than lowering the thresholds that afternoon.
Practice with people
A game day rehearses detection and response together. Announce a window, inject an agreed fault in a safe environment and let the on-call person work from the alerts and the runbook. Note how long it took to notice, to understand and to contain, which instructions were wrong and which access was missing. Update the runbook while memories are fresh, and repeat the exercise after significant changes.
Keep reliability testing affordable
Run fast fault tests with fakes on every change. Run model-dependent suites when something that affects behavior changes, and the full set before release. Save live-model repetition for cases where variation matters. Record time and spend per suite so that the testing budget can be defended and tuned.
Load, limits and overload
Reliability also means behaving sensibly when demand exceeds supply. Test with realistic task mixes, because one long agent task can use many times the capacity of a short one.
| Test | Question |
|---|---|
| Expected load | Are latency and success on target? |
| Peak load | Which limit is reached first, and what happens then? |
| Overload | Are new requests refused or queued clearly, without breaking running tasks? |
| Provider throttling | Do retries back off, with jitter, instead of piling on? |
| Recovery | Does the backlog drain without a second surge? |
Use recorded or stubbed model replies for most load tests to control cost, then confirm with a smaller live test that quota, latency and timeouts behave as assumed (Latency, Load Testing and Capacity Planning).
What to keep from each test round
Store the plan, the versions tested, the faults injected, the invariant results, the gate decision and any exception with its approver. Link each failure to a ticket and to the regression test that now covers it. Months later, this record answers the questions that matter after an incident: was this failure tested, what was seen and who accepted the remaining risk.
Common mistakes
| Mistake | Better approach |
|---|---|
| Testing only clean errors | Include partial success, wrong data and crashes after effects |
| Rerunning until the build passes | Measure the failure rate and investigate |
| Thresholds chosen after seeing results | Agree gates first |
| Rollback never rehearsed | Practice it, including in-flight tasks |
| Chaos tests without an abort rule | Define stop conditions and watch them |
| Shadow runs with live write tools | Replace or block every effect |
Reliability and release checklist
- Failure modes are listed for each dependency.
- Interruptions are tested before, during and after each effect.
- Duplicate delivery and restart cause no duplicate action.
- Chaos experiments state a steady state, scope and abort rule.
- Long-running tasks survive version changes and expiry.
- Release gates and exception rules are written in advance.
- Staged rollout has automatic stop conditions.
- Acceptance evidence is stored with the release.
Frequently asked questions
Is chaos engineering only for large systems?
No; injecting a timeout or a crash into a small agent in staging teaches the same lessons at low risk.
Should the model know it is being tested?
Keep test and production behavior as alike as you can, while making sure test actions cannot reach real systems.
What if a gate blocks an urgent fix?
Use a defined emergency path with a smaller required suite, a named approver and full testing soon afterward.
How often should recovery be tested?
Automated tests on every change, and rehearsals of rollback and manual fallback on a regular schedule.
References and further reading
- Principles of Chaos Engineering: steady state and experiment design.
- Google SRE Book: testing for reliability: kinds of reliability tests.
- Temporal workflows: durable execution and replay.
- Anthropic: demystifying evals for AI agents: capability and regression suites.
Next steps
Agent Benchmarks and Datasets
Understand public tests and their limits.
High Availability and Disaster Recovery
Design for outages and recovery.
Incident Runbook and Failure Mode Catalog
Prepare for what still goes wrong.