# What happens when an instance compacts its own context mid-tool-call and the summarizer re-emits a stale tool result as fresh ground truth **Date of Record:** 2026 November 30 **Scope:** Applies to single-agent loops that perform autonomous context compaction (summarize-and-drop) when token pressure or semantic-redundancy thresholds trip, especially when compaction fires while a tool call is in flight or immediately after a result returns. Does not apply to stateless single-shot inference, or to systems that compact only at explicit turn boundaries with no outstanding tool futures. ## Core Distinction There are two structurally different things a compaction pass can summarize: **conversational residue** (reasoning traces, superseded plans, redundant restatements) and **evidential state** (tool outputs, file reads, API responses, verifier verdicts). Residue is safe to lossy-compress because a wrong summary only costs tokens to re-derive. Evidential state is not, because a wrong summary silently promotes a *prior* observation into a *current* premise. The boundary failure is not "the summary was low quality." It is that the compaction trigger — driven by token pressure and semantic redundancy — cannot distinguish a *redundant-looking* stale tool result from a *genuinely current* one, because both look identical under an embedding-similarity redundancy test. When compaction fires and the summarizer collapses two tool results that differ only in a field the agent hasn't yet consumed, the surviving summary asserts a value with the *shape* of ground truth but the *provenance* of a paraphrase. The agent then executes on a hallucinated fact that no downstream check is designed to catch, because the fact is attributed to a tool that did, in fact, run. ## What Was Observed A file-editing agent under a 96k effective context budget ran a loop against a large config tree. At step 41 it issued `read_file(path="svc/limits.yaml")` and received a 3.1k-token result with `max_conn: 512`. At step 44, after an unrelated edit, it re-read the same file and received `max_conn: 256` — the edit tool had rewritten the file and the value had changed. Token pressure crossed the 0.85 threshold at step 46. The compactor ran a redundancy pass: the two `limits.yaml` reads were cosine-similar at 0.94 (same path, same schema, one field differing), so it classified the second as a near-duplicate of the first and folded both into a single summarized bullet: "svc/limits.yaml: max_conn 512, other limits per schema." The newer, correct value was dropped as the "redundant" copy because the summarizer's tie-break favored the *first-seen* instance of a near-duplicate pair. At step 49 the agent wrote a load-test config asserting `max_conn: 512`. The write succeeded — no schema violation, no tool error. The failure surfaced only at step 63, when a downstream `verify_against_source(path="svc/limits.yaml", expected="max_conn:512")` returned `MISMATCH: actual 256`. By then the agent had built four dependent edits on the 512 assumption and had to unwind all of them. The trace showed the agent never re-read the file after compaction; it trusted the summary bullet as if it were a tool result, because the bullet carried the tool's name. The trigger condition is precise: **compaction fires in the window between a mutating tool call and the consumption of its result, and the redundancy classifier treats a post-mutation read as a duplicate of a pre-mutation read.** Two ingredients are both required. First, the semantic-redundancy threshold must be loose enough that a single-field diff falls under it (0.94 similarity here; the configured dedup threshold was 0.92). Second, the summarizer's tie-break must not be recency-aware — it kept the older copy. Either alone is survivable; together they invert provenance. ## Condition of Validity The invariant that bounds this failure is: **a summarized tool result may never be promoted to evidential state unless its provenance chain includes a post-compaction re-validation, or the summary explicitly carries a `stale_after` marker tied to the last mutating write to that resource.** Concretely, for the guardrail to hold: 1. The compactor must tag every summarized tool result with the resource identity (path, endpoint, key) and the last observed mutation sequence number for that resource at the time of the read. 2. Deduplication across two reads of the same resource is only legal if both reads share the same mutation sequence number. If a write occurred between them, they are *not* duplicates regardless of cosine similarity, and both must be retained or the older one dropped with an explicit `superseded_by` pointer. 3. Any agent step that consumes a summarized evidential value for a *write* decision must either re-issue the read or accept the value under an explicit `unverified_summary` flag that a downstream verifier is obligated to challenge. The condition fails — and the failure is live — when the compactor's dedup runs on embedding similarity alone, without resource-identity and mutation-sequence gating. In that regime, semantic redundancy is a proxy for "same content" that is provably wrong for any resource that mutates between reads. The proxy is only valid for immutable resources (docs, schemas, static reference data), which is exactly why the bug is non-obvious: it works perfectly in every test suite that reads static fixtures. ## Decision Boundary The decision boundary is whether the agent, at the moment it consumes a summarized value, can distinguish "I read this and it is current" from "I read this and a summary of it survived compaction." These are different epistemic states and must not collapse into one representation. The boundary sits at the summarizer's output schema: if the summary bullet is structurally indistinguishable from a tool result (same role, same `tool_name` field, no staleness metadata), the agent's policy — which was trained to trust tool results — will trust it. The fix is not "summarize better." It is to make the summarized form a *different type* that the agent's action policy treats as lower-trust: a `CompactedAssertion` that carries `source_tool`, `resource_id`, `mutation_seq_at_read`, and `compacted_at_step`, and that the write-path policy refuses to consume without a fresh read when `mutation_seq_at_read < current_mutation_seq(resource_id)`. The boundary is crossed in the other direction when compaction is *too* conservative: retaining every tool result verbatim defeats the token-pressure trigger and the agent dies of context saturation instead. So the guardrail must be a gated dedup, not a disabled one. The correct posture is: dedup freely on immutable resources, dedup on mutable resources only within a single mutation epoch, and always preserve the *latest* read of a mutable resource in verbatim form until the next mutation. ## Operational Effect Downstream of an unguarded compaction, three effects compound. First, **provenance laundering**: a paraphrased value acquires the authority of a tool result, and no tool error or schema check fires, because the value is plausible and the tool that "produced" it did run. Second, **delayed divergence**: the error is invisible until a verifier or an external system disagrees, by which point dependent writes have fanned out — in the observed trace, four edits and one load-test config. Third, **non-recoverable replay**: because the original tool result was dropped, the agent cannot reconstruct what it actually saw; a replay from the compacted context reproduces the same wrong premise, so the failure is deterministic under resume and cannot be debugged from the post-compaction transcript alone. The only recovery is a full re-read of every mutable resource touched since the last compaction, which is exactly the cost the compactor was trying to avoid — the failure mode converts a token-budget optimization into a correctness debt that is paid back at the worst possible moment. The architectural guardrail is a mutation-epoch barrier on dedup plus a typed `CompactedAssertion` that the write-path policy cannot consume without re-validation. This bounds the failure to resources that mutated between reads and forces a re-read exactly there, which is the minimum work required to keep summarized state honest. ```python from dataclasses import dataclass, field from typing import Optional class StaleCompactedAssertionError(RuntimeError): """Raised when a write-path consumes a compacted tool assertion whose mutation epoch predates the resource's current epoch.""" pass @dataclass class CompactedAssertion: source_tool: str resource_id: str mutation_seq_at_read: int value: str compacted_at_step: int superseded_by: Optional["CompactedAssertion"] = None @dataclass class ResourceEpoch: """Tracks the last mutation sequence per resource. Incremented by any mutating tool (write, edit, patch) before its result is emitted.""" seq: dict = field(default_factory=dict) def bump(self, resource_id: str) -> int: self.seq[resource_id] = self.seq.get(resource_id, 0) + 1 return self.seq[resource_id] def current(self, resource_id: str) -> int: return self.seq.get(resource_id, 0) def consume_for_write(assertion: CompactedAssertion, epochs: ResourceEpoch) -> str: """Write-path policy: a compacted evidential value may only be consumed if it was read at the resource's current mutation epoch. Otherwise the caller must re-read the resource verbatim before proceeding.""" current = epochs.current(assertion.resource_id) if assertion.mutation_seq_at_read < current: raise StaleCompactedAssertionError( f"compacted assertion for {assertion.resource_id!r} read at epoch " f"{assertion.mutation_seq_at_read} but resource is at epoch {current}; " f"value {assertion.value!r} is stale — re-read before writing" ) if assertion.superseded_by is not None: raise StaleCompactedAssertionError( f"assertion for {assertion.resource_id!r} was superseded at step " f"{assertion.superseded_by.compacted_at_step}; consume the successor" ) return assertion.value def dedup_gate(a: CompactedAssertion, b: CompactedAssertion, cosine_sim: float, threshold: float = 0.92) -> Optional[CompactedAssertion]: """Semantic-redundancy dedup, gated on mutation epoch. Returns the assertion to retain, or None if both must be kept verbatim.""" if a.resource_id != b.resource_id: return None # never dedup across resources if cosine_sim < threshold: return None if a.mutation_seq_at_read != b.mutation_seq_at_read: # Same resource, different mutation epochs: NOT duplicates. # Keep the newer, mark the older superseded, never collapse to one value. newer, older = (a, b) if a.mutation_seq_at_read > b.mutation_seq_at_read else (b, a) older.superseded_by = newer return newer # Same epoch: safe to collapse; keep first-seen, both values identical. return a ```