Practical technical guides / Agent-era architecture: testing

Mutation-Test the Deterministic Guards Around an Agent

Generate small mutants of an agent guard with the ast module and count which ones the test suite fails to notice, then read each survivor.

By Sandeep Belgavi · Published 2026-11-26 · Prepared 2026-11-25

Generate small mutants of an agent guard with the ast module and count which ones the test suite fails to notice, then read each survivor.

A passing guard suite can still miss a broken guard

The deterministic layer around an agent is where most of the safety of an agent system lives. A refund guard decides whether a refund the model proposed may run automatically, needs a person to approve it, or must be rejected. Teams usually test that guard with a handful of cases written from the happy path, see them pass, and move on. The question those tests rarely answer is the one that matters: if someone changed a less-than to a less-than-or-equal in the guard, or deleted one clause of a condition, would any test fail?

Mutation testing answers exactly that question. It is an established technique for measuring test adequacy, not a new agent idea, but it fits agent systems unusually well. The guard is small, pure and deterministic. The cost of a silent mistake is high, because the model on the other side will eventually propose the exact input the broken boundary lets through. And the guard changes often as policies are tuned, so a suite that pinned behaviour last quarter may not pin it now.

This guide builds a minimal mutation harness for a synthetic refund guard at Belgavi's Book Store, compares a weak and a strong suite, and explains how to read survivors. It deliberately tests the guard, not the model. For checking that the guard rules themselves have no gaps or overlapping transitions, the guard coverage matrix guide at /blogs/system_design/agent_guard_coverage_matrix.html is the complementary technique: that one asks whether the policy is complete, this one asks whether the tests would notice the policy changing.

The guard under test

# Author: Sandeep Belgavi. Synthetic refund guard for an agent's proposal.
def refund_guard(p):
    if p["case_state"] != "verified":
        return "reject"
    if p["currency"] != p["order_currency"]:
        return "reject"
    if p["amount_cents"] <= 0 or p["amount_cents"] > p["order_total_cents"]:
        return "reject"
    if p["amount_cents"] > 5000 or p["prior_refunds"] >= 1:
        return "approve_first"
    return "auto"

Every line encodes a business rule. The state must be verified. The currency must match the order. The amount must be positive and not exceed the order total. Refunds above 5000 cents, or any refund on a case that already had one, need approval first. Everything else runs automatically.

Generating mutants with the ast module

A mutant is a copy of the guard with one small syntactic change. The companion example walks the guard's syntax tree with Python's standard ast module and produces five kinds of mutation: swapping a comparison operator for its neighbours, nudging an integer constant by plus or minus one, swapping and for or, dropping one operand of a boolean expression, and forcing an if condition to False so its branch is never taken. Each mutant is turned back into source with ast.unparse and loaded into a fresh namespace.

SWAPS = {ast.Lt: [ast.LtE, ast.Gt], ast.LtE: [ast.Lt, ast.GtE],
         ast.Gt: [ast.GtE, ast.Lt], ast.GtE: [ast.Gt, ast.LtE],
         ast.Eq: [ast.NotEq], ast.NotEq: [ast.Eq]}

def score(suite):
    assert run_suite(load(GUARD_SOURCE), suite) == []   # suite must pass first
    killed, survived = [], []
    for label, src in mutants():
        failures = run_suite(load(src), suite)
        (killed if failures else survived).append(label)
    return {"killed": len(killed), "survived": len(survived), "survivors": survived}

The harness refuses to score a suite that fails on the real guard, because a failing suite kills every mutant trivially and the score would be meaningless. For this guard the generator produces 26 distinct mutants.

Weak suite versus strong suite

The weak suite has three cases: an ordinary automatic refund, a rejection because the case is not verified, and an approval because a prior refund exists. It passes on the real guard. Against the 26 mutants it kills 13 and lets 13 survive.

The survivors are informative rather than random. "if-branch never taken" on the currency line survives, which means no test notices if the currency check is deleted. Every boundary mutant on the amount checks survives: changing <= 0 to < 0, changing > order_total to >= order_total, and moving the 5000 threshold to 4999 or 5001. Dropping the first operand of the approval condition also survives, because the only approval test sets both conditions at once and therefore cannot tell which one triggered.

The strong suite adds eight targeted cases: a currency mismatch, an amount of zero, an amount of one cent, an amount one cent over the order total, an amount exactly equal to the order total, an amount of exactly 5000 cents, an amount of 5001 cents, and a prior refund with a small amount. Each added case exists to kill a specific survivor. The strong suite kills all 26.

These counts come from running the companion example, and the test file pins them, so a later change to the guard or the generator shows up as a failing test rather than a quietly different number.

Reading survivors honestly

A surviving mutant has three possible explanations, and only one of them is "add a test".

It may expose a missing test. That is the common case above: the boundary at 5000 is a policy decision, the tests never touched it, and a one-character edit would move money differently.

It may be an equivalent mutant: a change that does not alter behaviour for any valid input. If amounts were guaranteed to be whole positive cents by an earlier validator, the mutant that changes <= 0 to < 1 would be equivalent and no test could kill it. Equivalent mutants should be recorded with a reason, not chased.

It may reveal dead or redundant policy. If dropping a clause never changes the outcome for any realistic proposal, the clause may be unreachable because an earlier check already covers it. That is worth a conversation with whoever owns the policy, since redundant rules tend to drift apart.

A raw mutation score is therefore a prompt for review, not a target. Chasing 100 percent across a large codebase is expensive. For the guard layer of an agent, which is small and decides effects, a review of every survivor is affordable and usually worthwhile.

Where this sits in an agent test strategy

Model evaluations answer whether the agent proposes sensible actions. Guard unit tests answer whether the deterministic layer makes the right decision for a given proposal. Mutation testing answers whether those unit tests are strong enough to keep answering correctly as the guard changes. All three are needed, and they fail in different ways.

Run the mutation step on changes to guard modules rather than on every commit to the repository. Because the guard is pure, the companion harness runs 26 mutants against an 11-case suite in well under a second. Larger guards grow roughly with mutants multiplied by cases; if that becomes slow, mutate only the files a change touched.

Existing tools such as mutmut for Python and PIT for the JVM provide richer operators, caching and reporting than this teaching harness. The reason to understand a small version is to know what a survivor means before trusting a tool's summary.

Failure modes of the technique

Mutants that crash rather than return a wrong answer are killed for the wrong reason. If a mutated guard raises a KeyError, any test kills it, and the score overstates suite strength. Separate crash kills from assertion kills when reviewing.

Shared fixtures can hide coupling. If every test starts from the same base proposal with an amount of 1200 cents, tests that look independent may all depend on that one value. Vary the base when a survivor is suspicious.

Guards with side effects are harder. If the guard logs, increments counters or reads the clock, mutants may change those effects without changing the decision. Keep decisions pure and move effects to the caller, which also makes the guard easier to reason about in the first place.

Mutation testing does not test the model. A perfect score says the deterministic layer is well pinned. It says nothing about how often the model proposes refunds that the guard must then reject.

Migration steps for an existing agent codebase

Extract the guard into a pure function if it is currently interleaved with tool execution or logging. Write the obvious tests. Run a mutation pass and list the survivors. Classify each as missing test, equivalent or redundant policy. Add the missing tests, record the equivalents with reasons, and raise the redundant ones with the policy owner. Then add the mutation run to the review checklist for guard changes, with the expected survivor list checked into the repository so new survivors stand out.

Primary references and authorship

Sources checked 2026-11-25. Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/guard_mutation_testing. Views are my own and do not represent any employer, past or present.