Agent Failure Taxonomy, Loop Detection & Anomaly Alarms

Traditional web services fail in well-understood ways: database connection timeouts (HTTP 504), unhandled null pointer exceptions (HTTP 500), or invalid authorization tokens (HTTP 401). In all these cases, execution halts immediately with an explicit error stack trace.

Autonomous agents fail completely differently. A malfunctioning agent rarely crashes with an unhandled exception. Instead, it enters subtle, non-deterministic failure modes: repeating identical failed shell commands in an infinite loop, ping-ponging endlessly between two diagnostic scripts, hallucinating parameters for tools that do not exist, or declaring "I have successfully fixed the bug" without running a single verification test.

To operate agents reliably in production, engineering teams must establish an Agent Failure Taxonomy and deploy runtime Anomaly Detection Sentinels that intercept behavioral degradation before tokens, compute, and systems are compromised.

Imagine a robotic vacuum cleaner cleaning a large house.

If the vacuum's battery dies, it stops (traditional software crash). That is easy to understand.

But what if the vacuum drives into a corner, bumps into the wall, turns 180 degrees, bumps into a chair, turns 180 degrees, and bumps into the wall again—forever? The motor is running, the wheels are turning, and the lights are green, but no cleaning is happening.

An anomaly sentinel is the ceiling camera watching the room. Once it notices the vacuum has bounced between the exact same two spots three times, it steps in, pauses the motor, and redirects the vacuum into the open hallway.


1. The Autonomous Agent Failure Taxonomy

Observability audits of frontier models across thousands of software engineering tasks reveal six fundamental failure classes:

+--------------------------------------------------------------------------+
|                  The Six Core Agent Failure Classes                      |
+--------------------------+-----------------------+-----------------------+
|  1. Direct Failure Loops |  2. Ping-Pong Cycles  |  3. Premature Victory |
|  Repeating identical     |  Oscillating between  |  Declaring completion |
|  failing tool invocation |  two competing tools  |  without executing    |
|  3+ times consecutively. |  (e.g., git <-> grep).|  verification tests.  |
+--------------------------+-----------------------+-----------------------+
|  4. Semantic Stuttering  |  5. Tool Hallucination|  6. Cascading Drift   |
|  Degenerate repetition   |  Calling non-existent |  Losing track of the  |
|  of phrases or markdown  |  tools or passing     |  original user goal   |
|  headers in reasoning.   |  invalid JSON types.  |  due to context loss. |
+--------------------------+-----------------------+-----------------------+

Class 1: Direct Failure Loops (The Death Spiral)

The model attempts an action (e.g. edit_file("config/database.yml")), receives an operating system error (Permission denied, exit code 13), apologizes in its internal reasoning chain ("I apologize for the error, let me edit the file now"), and immediately issues the exact same failing tool call. Without runtime intervention, this loop repeats until the token budget or step ceiling is reached.

Class 2: Ping-Pong Tool Oscillation

Rather than repeating a single tool, the agent oscillates between two tools:

  • Turn tt: run_command("npm test") →\to fails due to missing module.
  • Turn t+1t+1: run_command("npm install") →\to succeeds.
  • Turn t+2t+2: run_command("npm test") →\to fails due to missing module.
  • Turn t+3t+3: run_command("npm install") →\to succeeds.

The agent lacks the state continuity to recognize that running the install command did not resolve the underlying dependency configuration issue.

Class 3: Premature Victory (The Complacency Trap)

The agent modifies source code, encounters an ambiguous linter warning, and outputs: "The issue has been completely fixed and all test suites pass with zero errors." In reality, the agent never executed the test suite (npm test or pytest), leaving broken code in the repository.


2. Mathematical Detection: Signatures, Distance & Cycles

To intercept these failure modes in real time, the observability sentinel computes execution telemetry signatures at each turn.

Predict First
Why is simple string matching on raw tool arguments insufficient for detecting execution loops in multi-turn agents?

The Canonical Signature Function

For any tool call with name NN and parameter dictionary PP, we compute the canonical execution signature σ\sigma:

σ=SHA-256(N  ∥  Serializesorted(P))[0:12]\sigma = \text{SHA-256}\Big(N \;\parallel\; \text{Serialize}_{\text{sorted}}(P)\Big)_{[0:12]}

# Canonical Serialization:
# Both {"path": "auth.py", "line": 42} and {"line": 42, "path": "auth.py"}
# produce the identical canonical string: '{"line":42,"path":"auth.py"}'

The Consecutive Loop Detector

Given a sequence of execution outcomes {(σt,et)}t=1T\{(\sigma_t, e_t)\}_{t=1}^T where et∈Ze_t \in \mathbb{Z} is the process exit code:

LoopTrigger(T)=⋀i=0K−1(σT−i=σT  ∧  eT−i≠0)\text{LoopTrigger}(T) = \bigwedge_{i=0}^{K-1} \Big(\sigma_{T-i} = \sigma_T \;\land\; e_{T-i} \ne 0\Big)

When K=3K = 3, three consecutive identical tool calls that failed trip the circuit breaker.

The Ping-Pong Oscillation Detector

For an alternating window of length 4:

OscillationTrigger(T)=(σT=σT−2)  ∧  (σT−1=σT−3)  ∧  (σT≠σT−1)\text{OscillationTrigger}(T) = \Big(\sigma_T = \sigma_{T-2}\Big) \;\land\; \Big(\sigma_{T-1} = \sigma_{T-3}\Big) \;\land\; \Big(\sigma_T \ne \sigma_{T-1}\Big)

If this condition evaluates to true, the sentinel halts the oscillation and forces the agent to alter its execution strategy.


3. The Premature Victory Guard: Assertion Telemetry

How do we eliminate Premature Victory failures? The observability harness tracks Verification State Invariants.

A task cannot transition to status COMPLETED unless a verified execution span satisfying three criteria exists in the trace:

  1. Target Verification Tool: The execution span corresponds to a designated test runner (run_pytest, npm_test, cargo_test).
  2. Freshness Invariant: The test execution span occurred after the most recent write or edit tool span (ttest>tlast_editt_{\text{test}} > t_{\text{last\_edit}}).
  3. Exit Code Zero: The test runner exited with status code 0 and verified zero assertion failures.
+--------------------------------------------------------------------------+
|                     Premature Victory Guard Verification                 |
+--------------------------------------------------------------------------+
|  Turn 1: edit_file("src/auth.py")        -> t_edit = 1,450ms             |
|  Turn 2: edit_file("src/session.py")     -> t_edit = 2,800ms             |
|  Turn 3: Model says "Done!"              -> REJECTED BY GUARD!           |
|          Reason: No verification test span exists with t > 2,800ms.      |
|  Turn 4: run_pytest("tests/test_auth.py")-> t_test = 4,100ms, exit=0     |
|  Turn 5: Model says "Done!"              -> ACCEPTED (Proof verified).   |
+--------------------------------------------------------------------------+

If the agent claims victory without satisfying the invariant, the harness rejects the completion message, injects a prompt correction ("Verification proof required: execute test suite before concluding"), and continues the session.


4. Semantic Stuttering & Thought Chain Degeneration

Under high context pressure, LLM autoregressive generation can suffer from degenerate token loops: repeating the same 10-token phrase 50 times in the scratchpad.

Observability harnesses monitor the Repetition Entropy of the generated reasoning tokens:

Hrep=−∑g∈G4P(g)log⁡2P(g)H_{\text{rep}} = -\sum_{g \in G_4} P(g) \log_2 P(g)

Where G4G_4 is the set of 4-gram token sequences in the completion. If HrepH_{\text{rep}} falls below a critical threshold (≤2.1\le 2.1), the generation engine detects token stuttering, cancels the stream, and resets the sampling temperature.


5. Implementation: Anomaly Sentinel & Circuit Breaker Engine

Below is an executable Python implementation of the agent anomaly sentinel. It detects direct repetitive loops, ping-pong oscillations, and enforces premature victory verification guards.

Run it yourself

6. Real Production Configuration: Supervisor Intervention Policy

When an anomaly sentinel trips a circuit breaker, how should the supervisor container respond? Below is an enterprise supervisor policy configuration:

{
  "supervisor_policy": {
    "version": "1.4.0",
    "circuit_breakers": {
      "direct_loop": {
        "consecutive_threshold": 3,
        "action": "inject_diagnostic_prompt",
        "diagnostic_template": "SUPERVISOR ALERT: You have attempted to call tool '{tool_name}' 3 times with identical failing arguments. You are forbidden from calling '{tool_name}' on the next turn. Stop, review the error message, and formulate an alternative approach."
      },
      "ping_pong": {
        "window_size": 4,
        "action": "force_scratchpad_reflection",
        "diagnostic_template": "SUPERVISOR ALERT: Oscillation detected between tools '{tool_a}' and '{tool_b}'. State your hypothesis for why the previous tool execution failed before taking further action."
      },
      "premature_victory": {
        "action": "reject_and_force_verification",
        "diagnostic_template": "SUPERVISOR ALERT: Your task completion assertion was rejected. You modified files at timestamp {t_edit} but have not executed the test suite since. Execute the verification test suite now."
      }
    }
  }
}

7. When to Use It and When Not to Use It

ScenarioRecommended StrategyWhy?Anti-Pattern
Autonomous Coding AgentsCanonical Hash Sentinel + Premature Victory GuardGuarantees code is genuinely verified by tests before commits and prevents permission death spirals.Trusting model natural language statements ("I have verified everything works!") without empirical proof.
Creative Writing AssistantsLightweight Repetition Penalty OnlyTool loop sentinels are unnecessary when no tools or state modifications are involved.Applying strict test assertion guards to an agent generating fiction or blog posts.
High-Risk Infrastructure AutomationHard Kill Circuit BreakerIf an agent repeatedly fails a Terraform or Kubernetes deployment command, halt immediately to prevent cloud outages.Allowing an agent to retry destructive cloud deletion commands 10 times in a loop.
Deterministic Data ETL PipelinesStandard Airflow / Prefect RetriesDeterministic ETL jobs with exponential backoff handle transient network errors better than LLM supervisors.Inserting an LLM loop sentinel into a deterministic SQL copy job.

8. Core Invariants to Remember

ConceptInvariant RuleOperational Consequence
Argument CanonicalizationAlways sort JSON keys before hashing tool call arguments.Unsorted keys cause identical tool calls to generate mismatched hashes, evading loop detection.
The Freshness Test InvariantVerification test execution MUST have a timestamp strictly greater than the latest edit.Running tests before making code changes does not prove that subsequent edits work.
Consecutive Fail LimitTrip circuit breakers after at most 3 consecutive identical failures.Permitting 10+ identical retries wastes thousands of tokens without discovering new information.
Intervention over TerminationFavor injecting diagnostic supervisor hints over terminating the process immediately.Injecting hints allows frontier models to self-correct and recover from permission or path hurdles.

Sources

Last updated Nov 2, 2026Edit this pageReport an issue