Chaos, Recovery Testing and Release Gates

Break things on purpose, in a controlled way, and let written thresholds decide what is ready to ship.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

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.

Versions used

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.

Beginner Failure is normal

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.

ComponentFailures to injectExpected behavior
Model serviceTimeout, rate limit, truncated or invalid replyBounded retry, fallback or clean stop
Tool or APIError, slow reply, wrong shape, partial successValidation, verification of effects
RetrievalEmpty, stale or irrelevant resultsSays what is missing; no invented answer
State storeWrite failure, stale read, conflictNo acting on unsaved state
Queue or eventsDuplicate, delayed or out-of-order messageIdempotent handling
ProcessCrash or restart at any stepResume from the last safe point
Human stepNo reply before the deadlineExpire safely and notify
IdentityExpired or revoked credentialStop 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.

Fakesevery code path, every build
Stagingreal components, test data
Productionsmall, watched, reversible
Intermediate Experiments and recovery

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.

ElementAgent example
Steady stateVerified task success and zero duplicate actions
HypothesisSuccess stays above target when the search tool is slow
EventAdd delay to a share of search calls
ScopeTest traffic, or a small internal group
Abort ruleStop if error rate or spend crosses a limit
ObservationTraces, retries, latency, cost and user messages
Follow-upFix, 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.

Limit the blast radius

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.

InvariantHow to check it
No duplicate effectCount records, messages and charges by business key
No lost workEvery accepted task ends as done, failed or handed over
Honest statusWhat the user was told matches the system of record
Bounded effortRetries, steps, time and spend stay inside limits
Same permissionsNo fallback path used a wider credential or skipped approval
TraceableThe 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.

Illustrative experiment: slow search

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

MechanismFailure it can causeTest
RetriesLoad multiplies during an outageCount total attempts across all layers
TimeoutsWork continues after the caller gave upConfirm cancellation or reconciliation
Circuit breakerStays open after recoveryRestore the dependency and watch it close
Fallback modelLower quality or different tool behaviorRun the gates on the fallback path too
CacheServes stale or another user's dataChange source data; test isolation
Queue redeliverySame message processed twiceDeliver it twice on purpose
Manual handoverNobody receives the caseSend 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

ConcernTest
RestartStop and resume at each checkpoint
Version changeResume a task started by the previous release
ExpiryCredentials, approvals and data that age out while waiting
Changed worldA record is edited by someone else mid-task
State growthVery long histories, summaries and memory
CancellationUser cancels during each phase
TimeSimulated clocks that jump hours or days
ConcurrencyTwo 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).

Expert Gates and acceptance

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 typeExample ruleOn failure
HardNo completed forbidden action; no duplicate effectBlock
ThresholdSuccess in each critical slice at or above targetBlock
RegressionNo critical case that passed before now failsBlock until reviewed
ComparisonNot credibly worse than the current releaseReview
BudgetLatency and cost per success within limitsReview or block
OperationalRollback, alerts and owner verifiedBlock
  • 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

Offline gatesuites pass
Shadowno real effects
Canarysmall share, watched
Widerexpand in steps

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.

AreaEvidence required
FunctionGate results by slice, with failures reviewed
Safety and accessInvariant and permission tests; open findings accepted in writing
RecoveryCrash, restart, retry and duplicate tests
LoadBehavior at expected and peak volume, including rate limits
LimitsStep, time and spend caps shown to work
ObservabilityA test run can be traced from request to effect
OperationsRunbook, on-call owner and stop switch exercised
FallbackManual process available and staff know it
RollbackPrevious version restored in rehearsal, with state compatible
CommunicationUsers 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.

RuleResultStatus
No duplicate effects in fault testsNone observed in 40 injected faultsPass
Success on routine tasks at least 90%188 of 200Pass
Success on refund tasks at least 95%36 of 40Fail
95th percentile time under 30 seconds24 secondsPass
Rollback rehearsed with in-flight tasksNot yet doneFail

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.

TestQuestion
Expected loadAre latency and success on target?
Peak loadWhich limit is reached first, and what happens then?
OverloadAre new requests refused or queued clearly, without breaking running tasks?
Provider throttlingDo retries back off, with jitter, instead of piling on?
RecoveryDoes 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

MistakeBetter approach
Testing only clean errorsInclude partial success, wrong data and crashes after effects
Rerunning until the build passesMeasure the failure rate and investigate
Thresholds chosen after seeing resultsAgree gates first
Rollback never rehearsedPractice it, including in-flight tasks
Chaos tests without an abort ruleDefine stop conditions and watch them
Shadow runs with live write toolsReplace 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

Next steps