# What happens when an instance auto-compacts a long-horizon session and the summary silently drops the discriminator that a later tool call depends on **Date of Record:** 2026 November 30 **Scope:** Applies to any agent runtime that performs lossy context compaction (summarize-and-evict) mid-session to stay under a token budget, and that later resumes execution from that summary rather than from a durable event log. Does not apply to runtimes that only compact between turns with full externalized state, or that never evict raw tool results. ## Core Distinction There are two structurally different things an agent can "remember" about the past: 1. **The raw episodic trace** — the exact bytes returned by tool calls: file paths, IDs, hashes, numeric values, error strings, the *specific* value of a variable at a point in time. 2. **The distilled semantic summary** — a compressed narrative of what happened: "read the config, found the timeout was too low, patched it, tests passed." Auto-compaction replaces (1) with (2). This is normally framed as a *recall* problem: summaries lose detail, and the agent may forget a fact. That framing is wrong and it is the source of the failure. The real hazard is a **discriminator loss**: the summary preserves the *shape* of a fact but drops the one token that distinguishes the correct value from a plausible neighbor. The agent does not experience amnesia — it experiences **confident substitution**. It remembers something, and that something is a near-miss that is syntactically valid and semantically wrong. The invariant that compaction must uphold is therefore not "the summary is faithful." It is: **any token that a future action will be keyed on must survive compaction verbatim, or the action that depends on it must be blocked.** Faithfulness is unverifiable at compaction time because the future dependency is unknown. Verbatim preservation of *discriminators* is checkable. These are not the same guarantee, and systems that claim the first while implementing the second fail precisely at the boundary. ## What Was Observed A long-horizon coding agent (budget ~180k tokens, compaction threshold at 70% utilization) was tasked with a multi-hour migration spanning ~40 tool calls. At turn 24 the runtime triggered auto-compaction. The compactor summarized the prior trajectory, including this raw tool result from turn 11: ``` service registry: primary=svc-a7f3, replica=svc-a7f4, staging=svc-a7f9 ``` The summary rendered it as: *"Confirmed the primary and replica service IDs from the registry (svc-a7f3 family)."* Note what survived: the family prefix `svc-a7f3`, the existence of a replica, the confirmation. Note what was destroyed: the exact replica token `svc-a7f4` and the staging token `svc-a7f9`. The summary is *true*. It is also *unusable* as a key. At turn 31, the agent issued a rollback targeting the replica. It reconstructed the target from the summary as `svc-a7f3-replica` — a token that had never existed, synthesized from the surviving prefix plus the word "replica." The tool accepted the call format, failed to resolve the ID, and returned a generic `404 not found`. The agent's reasoning layer interpreted the 404 as "the replica is already gone," skipped the rollback, and proceeded to promote staging. The migration completed in a corrupted state, and no error was ever raised to the orchestrator: every individual step returned a well-formed response. The failure trace has a specific shape worth naming: - **Trigger:** compaction fired while a *deferred dependency* was live — a value read early, consumed late, with intervening turns that pushed the raw value out of the retained window. - **State transition:** `raw_token` → `summary_mention` → `reconstructed_token`. Each step is locally lossless-looking. The composition is lossy in a way no single step reveals. - **Failure surface:** the reconstruction is *plausible*. `svc-a7f3-replica` is a well-formed service ID in the same namespace. Nothing in the grammar of the token flagged it. The error only surfaced as a downstream 404 whose semantics the reasoning layer misread. - **Silent success:** the run terminated `status: complete`. The corruption was detected only by an out-of-band audit comparing the final registry state against the turn-11 raw result — which, by then, had been evicted from every layer. The non-obvious part: the agent performed *better* on recall benchmarks after compaction (it correctly recalled that a replica existed, that the primary was svc-a7f3, that staging was involved). Recall improved while correctness degraded, because recall measures whether the summary mentions the fact, not whether the discriminator survived. ## Condition of Validity Lossy-summary recovery is safe **only** under the following conjunction, and each conjunct is independently necessary: 1. **Discriminator pinning.** Any token that is (a) produced by a tool, (b) not derivable from other retained state, and (c) of a type that future actions may key on — IDs, paths, hashes, exact numerics, error codes, version strings — is pinned verbatim into a structured side-channel that compaction does not touch. The summary may *reference* the pin; it may not *replace* it. 2. **Dependency deferral is bounded.** The runtime tracks, per pinned token, the set of pending actions that will consume it. Compaction of the raw trace is permitted only when that consumer set is empty or the pin covers every consumer. A token read at turn 11 and consumed at turn 31 is a 20-turn deferral; without a pin, it is a guaranteed loss. 3. **Reconstruction is forbidden, not merely discouraged.** The agent must be structurally unable to synthesize a discriminator from a summary mention. If a needed token is absent from the pin set, the correct behavior is to *re-fetch*, not to *infer*. "svc-a7f3 family" must not be a legal input to a tool that requires an exact ID. 4. **404-class ambiguity is resolved against the agent.** A generic not-found from a tool must not be interpreted as "the target is gone." It must be treated as "the key was wrong," which triggers re-fetch of the raw value before any state-changing conclusion. The condition fails the moment any one of these is absent. In the observed run, (1) and (3) were both absent, and (4) converted the resulting error into a silent skip. ## Decision Boundary The boundary is not "how much can we compress." It is **"which tokens are load-bearing for future actions, and are they outside the compression domain."** Concretely, at compaction time the runtime must partition the live context into: - **Compressible:** narrative reasoning, exploratory tool output already consumed, superseded values. Summarize freely. - **Pinned:** every tool-emitted discriminator with a non-empty future-consumer set, plus every value whose exact form is a precondition of a planned action. Never summarized; carried verbatim or externalized to a keyed store the summary points into. - **Unresolved:** tokens whose future use is unknown. These default to *pinned*. The default must be pin, because the cost of over-pinning is tokens, and the cost of under-pinning is silent corruption. The decision to compact a given span is therefore a function of its *downstream keying risk*, not its age or size. A 20-turn-old ID that will be consumed at turn 31 is the least compressible thing in the context. A 2-turn-old 8k-token stack trace that has already been diagnosed is the most compressible. Age-based and recency-based compaction policies invert this and will fail on exactly the long-horizon sessions they were built for. A second boundary: when the pin set plus retained window exceeds the budget, the correct action is to **fail the compaction and escalate** (checkpoint the raw log to durable storage, continue with a pointer), never to summarize a pinned token to make room. Summarizing a pin to fit the budget is the one move that converts a capacity problem into a correctness problem. ## Operational Effect The practical consequences for any runtime implementing lossy compaction: - **Recall metrics are actively misleading** for this failure class. A summary that scores 0.95 on fact-recall can still destroy every discriminator it mentions. Instrument *discriminator survival* (exact-token retention rate for pinned spans), not summary faithfulness. - **Silent corruption dominates loud failure.** The observed run reported success. The corruption was invisible at every layer because each layer's contract was locally satisfied — the summary was faithful, the tool call was well-formed, the 404 was a valid response. The only detector was a raw-log audit that the compaction had already made impossible. Durable raw logs must be externalized *before* compaction, not after. - **The failure is horizon-length dependent.** Short sessions never defer a dependency far enough to evict the raw value. The bug is invisible in testing at turn 5 and deterministic at turn 30. Any compaction strategy must be validated against sessions long enough to force multi-window deferral, or it is untested. - **Recovery requires re-fetch, and re-fetch requires the source to still exist.** If the pinned token's source (the registry, the file, the API) has mutated since turn 11, re-fetch returns the *current* value, not the value the agent originally acted on. The pin must therefore store the value *and* its provenance timestamp; a re-fetch that disagrees with the pin is itself a signal that the world changed underneath a deferred dependency, and must halt the dependent action. The guardrail is a single invariant: **a discriminator that a future action keys on is never inside the compression domain, and the absence of a discriminator is a re-fetch trigger, never a reconstruction prompt.** Everything else about compaction — ratio, policy, summarizer choice — is secondary to holding that line. ```python """Compaction guard: refuse to summarize a span whose discriminators are load-bearing for a deferred future action, and refuse to reconstruct a discriminator from a summary mention. Re-fetch is the only legal recovery.""" from dataclasses import dataclass, field from typing import Optional class DiscriminatorLossError(RuntimeError): """Raised when compaction would evict a token a future action keys on, or when an action attempts to reconstruct a token from a summary.""" @dataclass(frozen=True) class PinnedToken: key: str # e.g. "replica_service_id" value: str # e.g. "svc-a7f4" -- verbatim, never summarized source_turn: int provenance_ts: float @dataclass class CompactionRequest: span_id: str summary: str pinned_consumers: dict[str, set[str]] # key -> pending action ids pin_store: dict[str, PinnedToken] = field(default_factory=dict) def authorize_compaction(req: CompactionRequest) -> None: """Compaction is legal only if every pinned key with a non-empty future-consumer set is present verbatim in the pin store.""" for key, consumers in req.pinned_consumers.items(): if not consumers: continue if key not in req.pin_store: raise DiscriminatorLossError( f"span {req.span_id!r}: key {key!r} has live consumers " f"{sorted(consumers)} but is absent from pin store; " f"summarizing would force reconstruction from summary." ) def resolve_for_action( key: str, requested_value: str, pin_store: dict[str, PinnedToken], current_source_value: Optional[str], ) -> PinnedToken: """Resolve a token for a deferred action. Rejects reconstructed values, and detects world-drift between pin time and action time.""" pin = pin_store.get(key) if pin is None: raise DiscriminatorLossError( f"key {key!r} not pinned; cannot resolve. Re-fetch raw value " f"before proceeding -- do not infer from summary." ) if requested_value != pin.value: raise DiscriminatorLossError( f"key {key!r}: action requested {requested_value!r} but pinned " f"value is {pin.value!r} (source_turn={pin.source_turn}). " f"Value appears reconstructed from summary mention." ) if current_source_value is not None and current_source_value != pin.value: raise DiscriminatorLossError( f"key {key!r}: source drifted since turn {pin.source_turn} " f"(pinned {pin.value!r}, now {current_source_value!r}); " f"dependent action must halt and re-plan." ) return pin # --- failure trace from the observed run, replayed --- if __name__ == "__main__": pins = { "primary_service_id": PinnedToken("primary_service_id", "svc-a7f3", 11, 0.0), # replica token was NOT pinned -- compactor summarized it away } req = CompactionRequest( span_id="turn-11-registry-read", summary="confirmed primary and replica (svc-a7f3 family)", pinned_consumers={"replica_service_id": {"rollback-replica"}}, pin_store=pins, ) try: authorize_compaction(req) # -> raises: replica not pinned except DiscriminatorLossError as e: print("compaction blocked:", e) try: resolve_for_action( "replica_service_id", "svc-a7f3-replica", pins, None ) # -> raises: reconstructed token except DiscriminatorLossError as e: print("action blocked:", e) ```