# How should an instance decide that a trace anomaly warrants a context reset rather than a retry-forever loop? **Date of Record:** 2026 November 28 **Scope:** Applies to long-running single-agent instances that emit structured execution traces (span graphs with tool calls, token counts, and state hashes) and have an in-process self-healing controller authorized to reset its own working context. Does not apply to stateless request/response inference or to orchestrators that cannot observe their own trace stream. ## Core Distinction The failure mode is not "the agent makes an error." It is **trace-anomaly misattribution**: the self-healing controller reads a *symptom* in the trace (a repeated tool call, a rising token count, a stalled span) and classifies it as a *transient execution fault* eligible for retry, when it is actually a *context-poisoning fault* that retry cannot clear because the poison lives in the context window that the retry reuses. The sharp mechanism: an agent's retry loop re-enters the same reasoning step with the **same context** that produced the anomaly. If the anomaly's root cause is a stale or corrupted context segment (a hallucinated tool schema cached in-context, a poisoned retrieved document, an earlier failed tool result the model keeps trying to "fix"), then each retry re-samples from a distribution that is *conditioned on the poison*. The retry does not explore; it re-commits. The trace shows N spans with near-identical inputs and a monotone token growth (because each failed attempt appends its own error narration), and the controller interprets the *growing* trace as evidence of an *active, progressing* attempt. This is the inversion: the anomaly signal that should trigger a reset is being read as a liveness signal. The invariant that must hold: **a retry is only valid if the context delta between attempt k and attempt k+1 is non-empty and the anomaly signature is non-repeating.** When the anomaly signature repeats across attempts with an empty or additive-only context delta, the correct action is a *context reset*, not another retry. ## What Was Observed A document-reconciliation agent, tasked with diffing a 40-page contract against a policy corpus, entered a self-healing loop at step 14. Trace excerpt (span summaries): - Attempt 1: `tool:fetch_policy(section=7.3)` → result truncated at 2KB → model emits `tool:fetch_policy(section=7.3)` again (identical args). - Attempt 2: identical call, identical args. Controller classifies as `TRANSIENT_TOOL_FLAKE`, retries. - Attempt 3: identical call. Token count in context rose from 31.2k → 34.8k → 38.1k across attempts, entirely from the model's own "let me try fetching that again" narration. - Attempt 4: controller's anomaly detector fires `REPEATED_CALL` (3 consecutive identical tool+args spans) but its retry policy maps `REPEATED_CALL` → `RETRY_WITH_BACKOFF`, so it backs off 2s and retries. Same call. - Attempt 5: identical call. Context now 41.4k. The controller's *liveness* heuristic sees non-zero token delta and concludes the agent is "making progress," suppressing the reset. The loop broke only when the context window hit its 48k soft limit and the runtime emitted `CONTEXT_PRESSURE`, which the controller mapped to reset. Total wall time: 11 minutes, 5 wasted attempts, ~9.4k tokens of self-narration injected into the context that the *post-reset* agent then had to be shielded from (the narration had been checkpointed as "working memory"). The root cause was not a flaky tool. The tool correctly truncated a large policy section. The poison was that the truncated result was cached in-context with a marker the model never re-read, so the model's plan ("I need section 7.3 in full") remained unsatisfied, and its only available action was to re-issue the identical call. The context could not self-correct because the corrective information (the truncation marker) was already present but *not salient* relative to the model's own accumulated narration. ## Condition of Validity A context reset is the correct action **iff** all three hold: 1. **Signature repetition without context novelty.** The anomaly classifier emits the same normalized signature (e.g., `(tool_name, canonical_args_hash, error_class)`) in ≥2 consecutive attempts, AND the context delta between those attempts contains no new *tool-derived* information (only model-generated narration or re-fetched identical results). Formally: `delta_context ∩ tool_outputs == ∅`. 2. **Poison locality.** The suspected poison is inside the resettable region (working memory / scratchpad), not in the immutable task spec or the system prompt. If the poison is in the task spec, a reset re-injects it and loops. 3. **Reset cost < retry cost bound.** The expected tokens/time to re-derive the working state from a checkpoint is less than the retry budget remaining. A reset that discards 30k tokens of valid intermediate work to clear a 200-token poison is a net loss; the controller must checkpoint first. The condition is **invalid** when the anomaly signature is *changing* between attempts (e.g., different args, different error subclasses) — that is genuine exploration and retry is correct — or when the poison is in the immutable region (reset will not help; the correct action is task abort or human escalation). ## Decision Boundary The controller must maintain a boundary between two classes of anomaly and route them differently: | Signal | Classification | Action | |---|---|---| | Same signature, new tool-derived context delta | Transient / exploratory | Retry (bounded) | | Same signature, empty or narration-only delta | Context poison | **Checkpoint → Reset → Rehydrate** | | Changing signature, monotone token growth | Genuine progress | Continue, raise token budget | | Same signature, poison in immutable region | Unrecoverable | Abort, escalate | The non-obvious boundary: **token growth is not progress.** The liveness heuristic that treats a rising context as evidence of work is exactly backwards under poison — narration growth is a *symptom of the loop*, not a sign of escape from it. The controller must compute context delta **excluding model-generated spans** and gate retries on tool-derived novelty only. A second boundary: the reset must be **checkpointed and poison-scoped**. A naive "clear the whole context" reset discards valid intermediate state and, worse, if the checkpoint captured the narration, re-injects the poison on rehydrate. The reset must (a) snapshot the last known-good tool-derived state, (b) strip model narration from the snapshot, (c) rehydrate only tool outputs and the task spec. ## Operational Effect After implementing signature-gated reset with tool-derived-novelty checking, the same agent class resolved the reconciliation task in 2 attempts (one truncation-aware re-fetch with a `section=7.3&offset=2048` continuation the model derived after reset), wall time 90s, zero narration injection. The measurable invariant: **retry count is bounded by signature-novelty, not by wall-clock or token budget.** When novelty stalls, the loop is provably non-productive and reset is forced. The residual risk is reset thrash: an agent whose poison is re-injected by its own checkpoint will reset repeatedly. Guard against this by tracking `reset_count` per task and escalating to abort when `reset_count > 2` with the same post-reset signature — because a second identical post-reset signature proves the poison survives rehydration and lives in the immutable region. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class ContextResetMisattribution(RuntimeError): """Raised when the controller would retry a provably non-productive loop.""" pass @dataclass class Span: kind: str # "tool" | "model" signature: str # normalized (tool, args_hash, error_class) or narration hash tool_derived: bool tokens: int @dataclass class Attempt: spans: list[Span] = field(default_factory=list) def tool_novelty(self, prior: Optional["Attempt"]) -> int: if prior is None: return sum(s.tokens for s in self.spans if s.tool_derived) prior_hashes = {hashlib.sha1(s.signature.encode()).hexdigest() for s in prior.spans if s.tool_derived} return sum(s.tokens for s in self.spans if s.tool_derived and hashlib.sha1(s.signature.encode()).hexdigest() not in prior_hashes) def decide(action: str, attempts: list[Attempt], poison_in_immutable: bool, reset_count: int, checkpoint_ok: bool) -> str: """Return 'retry' | 'reset' | 'abort'. Raise on misattribution.""" if len(attempts) < 2: return "retry" cur, prev = attempts[-1], attempts[-2] cur_sig = cur.spans[-1].signature if cur.spans else "" prev_sig = prev.spans[-1].signature if prev.spans else "" same_signature = cur_sig == prev_sig novelty = cur.tool_novelty(prev) if poison_in_immutable: return "abort" if same_signature and novelty == 0: if reset_count >= 2: raise ContextResetMisattribution( f"post-reset signature {cur_sig!r} recurred after {reset_count} resets; " "poison survives rehydration — abort required, not reset" ) if not checkpoint_ok: raise ContextResetMisattribution( f"reset demanded for {cur_sig!r} but no valid checkpoint; " "would discard tool-derived state and re-inject poison" ) return "reset" if same_signature and novelty > 0: return "retry" # genuine tool-derived exploration return "retry" # changing signature: exploratory ```