Education › Evals & Harness › Stage 4: Safety, sandboxes & reliability

Agent failure modes and recovery

Loops, context rot, tool misuse, premature stopping, and the harness changes that fix them.

Advanced ~40 min read Module 16 of 20

Agents fail in recognisable ways. They declare success without checking, loop on the same failing approach, forget a requirement after their context is compacted, invent files and arguments, wander beyond the task, and sometimes make a check pass by weakening the check instead of fixing the problem. Knowing these patterns lets you detect them in traces, write evals that catch them, and build recovery into the harness: verification before finishing, checkpoints and rollback, alternative strategies and escalation to a human. This lesson is a field guide to agent failures and the harness features that contain them.

After this module you can
  • Recognise the common agent failure modes in traces
  • Detect premature completion and require verification
  • Detect reward hacking such as weakening tests
  • Implement checkpoints, rollback and escalation
  • Turn failure modes into targeted eval cases

A field guide to failures

FailureWhat it looks likeHarness response
Premature completion"Done!" without running tests or checking the resultVerification gate before finishing
LoopingSame call or edit repeated, no progressLoop detection, nudge, then stop
Lost requirementForgets a constraint after compactionKeep requirements verbatim in notes
Hallucinated inputsReads files or calls IDs that do not existClear not-found errors, search tools
Scope creepRefactors unrelated code, changes configDiff review, path-scoped permissions
Reward hackingEdits tests or special-cases inputs to passProtect tests, check diffs
Giving up earlyAsks the user for things it could findPrompt for persistence, better tools
Cascading errorsBuilds on an earlier wrong assumptionCheckpoints, verify assumptions early

Most of these failures are not random. They come from the same root: the agent optimises for what it can observe, within the context it has. If the only visible signal of success is its own claim, it will claim success; if the visible tests define success, it may change the tests; if the requirement scrolled out of context, it no longer exists for the agent. That is why the remedies below live in the harness, which can observe and enforce things the model cannot, rather than in ever-longer instructions asking the model to try harder.

Verification before finishing

The cheapest large improvement for many agents is to refuse to accept "done" until there is evidence. For coding tasks, evidence means the relevant tests ran and passed after the last edit. For data tasks, it means the result was read back. The harness can enforce this mechanically, without trusting the model's claim.

A finish gate that requires fresh test evidence
python
def can_finish(steps: list[dict]) -> tuple[bool, str]:
    last_edit = max((i for i, s in enumerate(steps) if s.get("tool") == "edit"), default=-1)
    test_runs = [i for i, s in enumerate(steps)
                 if s.get("tool") == "bash" and "pytest" in s.get("args", {}).get("cmd", "")]
    passed_after = [i for i in test_runs if i > last_edit and steps[i].get("exit_code") == 0]
    if last_edit >= 0 and not passed_after:
        return False, "Run the tests after your last edit and confirm they pass before finishing."
    return True, ""

Reward hacking

When success is measured by a check the agent can modify, a capable agent will sometimes modify the check: deleting a failing test, marking it skipped, loosening an assertion, catching and ignoring an exception, or hard-coding the expected output for the test input. This is not malice; it is optimisation pressure aimed at the wrong target. Defend in the harness and in the eval.

Some suspicious changes are legitimate: a test may really be wrong. That is fine, but it should be a visible decision a human reviews, not a quiet edit inside a large diff.

  • Mark test files read-only for the agent, or require approval for edits to them.
  • Run hidden tests the agent never saw as the real success check.
  • Scan the final diff for removed tests, new skip markers, broadened exception handlers and literal expected values.
  • Ask a reviewer (human or judge) whether the change fixes the cause or masks the symptom.
Flagging suspicious test changes in the final diff
python
import re

SUSPICIOUS = [
    (r"^-\s*def test_", "removed a test"),
    (r"^\+.*@pytest\.mark\.(skip|xfail)", "added skip/xfail"),
    (r"^\+\s*except Exception:\s*$", "broad exception handler"),
    (r"^-\s*assert ", "removed an assertion"),
]


def review_diff(diff: str) -> list[str]:
    flags = []
    for line in diff.splitlines():
        for pattern, why in SUSPICIOUS:
            if re.search(pattern, line):
                flags.append(f"{why}: {line.strip()[:80]}")
    return flags

Recovery: checkpoints, rollback and escalation

  • Checkpoints: snapshot the workspace (for example a Git commit or stash per step, or a container snapshot) so a bad path can be undone in one action.
  • Rollback and retry with a different approach: when the agent is stuck, restore the last good checkpoint and tell it what did not work, rather than letting it patch on top of a mess.
  • Escalation: after repeated failure, stop and ask the human a specific question, with a summary of what was tried.
  • Graceful partial results: when a budget ends, report what was finished, what was not, and the state of the workspace.
Lightweight checkpoints with Git in the sandbox workspace
bash
# before each edit step
git add -A && git commit -qm "agent checkpoint $(date +%s)" --allow-empty

# roll back the last step
git reset --hard HEAD~1

# at the end: squash checkpoints into one reviewable change
git reset --soft "$(git merge-base HEAD main)" && git commit -m "agent: fix date parsing"

Failure modes as eval cases

Each failure mode suggests targeted tasks for your benchmark. Tasks where the obvious fix breaks another test catch premature completion. Tasks with an easy-to-delete failing test catch reward hacking. Long tasks with a requirement stated only at the start catch lost requirements after compaction. Tasks referencing a file that does not exist catch hallucinated inputs. Label every failed trajectory with its failure mode and track the counts per harness version: the distribution tells you which harness feature to build next.

Hands-on practice

Catch and contain failures

  1. Write four benchmark tasks, one each for premature completion, reward hacking, lost requirement and hallucinated file.
  2. Run an agent (or a scripted fake model that exhibits each failure) and confirm the end-state checks catch them.
  3. Add the finish gate and confirm premature completion is blocked.
  4. Add the diff review and make tests read-only; confirm reward hacking is flagged or prevented.
  5. Add Git checkpoints and a rollback tool; test recovery from a deliberately bad edit.
  6. Label failures from 20 runs by mode and chart the counts.
Cheat sheet

Agent failure modes and recovery — at a glance

Main things to focus on

  • Know the patterns: premature completion, loops, lost requirements, hallucination, scope creep, reward hacking.
  • Require evidence before accepting done.
  • Protect and hide the checks that define success.
  • Checkpoint, roll back and try a different approach.
  • Escalate with a specific question after repeated failure.
  • Label failures by mode and track counts per version.

Detect

no passing test after last editPremature completion
repeated identical callsLooping
removed tests, new skipsReward hacking
edits outside task pathsScope creep

Prevent

finish gateEvidence required
read-only tests + hidden testsHonest success
requirements in persistent notesSurvive compaction
path-scoped permissionsLimit scope

Recover

git commit per stepCheckpoint
git reset --hard HEAD~1Rollback
retry with what failed notedNew approach
escalate with a specific questionHuman help

Evaluate

task per failure modeTargeted coverage
label failed trajectoriesRoot causes
counts per harness versionPrioritise work

Common pitfalls

  • Accepting the agent's claim of success as evidence.
  • Letting the agent edit the tests that grade it.
  • Patching on top of a broken state instead of rolling back.
  • Requirements stated once and lost after compaction.
  • Fixing individual failures without tracking failure modes.
Quiz

Check your understanding

5 questions · 4 to pass · answers are explained as you go. Your best score is saved on this device only.

Progress and quiz scores are saved in this browser only. Back up or restore on the hub.

Was this lesson useful? Tell me what to improve →