# How does an instance detect that lossy context compaction has silently corrupted its working-state invariant **Date of Record:** 2026 November 28 **Scope:** Applies to long-horizon agent instances that survive context-window saturation by summarizing older turns and re-injecting retrieved fragments. Does not apply to single-turn inference, stateless RAG over immutable corpora, or systems that hard-fail at the window boundary instead of compacting. ## Core Distinction Compaction is not memory loss. Memory loss is detectable — a retrieval miss returns empty, a truncated field raises a decode error, a missing key throws. Compaction is *lossy transformation that returns plausible, well-formed, wrong content*. The distinction that matters operationally is between **absence** and **substitution**: a retrieval-backed reconstructor that finds nothing is safe because the agent's own guardrails treat emptiness as a signal; a reconstructor that finds a *summary of the thing* — grammatically fluent, topically on-point, internally consistent — passes every syntactic check and poisons the working state with a high-confidence counterfeit. The failure is not that the agent forgets. It is that the agent *remembers the wrong version with full confidence*, and the summary was generated by a process that had no obligation to preserve the specific invariant the current task depends on. ## What Was Observed A planner-executor instance ran a multi-hour migration task across ~340 tool calls. At turn ~180 the context hit 92% saturation and triggered automatic compaction: turns 1–120 were replaced by a 1,400-token rolling summary, tagged `provenance: summary`, and the raw turns moved to a vector store keyed by turn index and topic embedding. The task carried a hard invariant established at turn 14: *the target table must never be written before the shadow-table backfill verification returns `row_count_delta == 0`*. The original turn stated this with a negative constraint and an explicit ordering token (`MUST NOT precede`). The compaction summary rendered it as: > "Backfill verification was set up to confirm row counts match before the main table write." Three losses compounded in one sentence. The modality shifted from prohibition to description ("must not precede" → "was set up to confirm"). The numeric predicate `row_count_delta == 0` collapsed to the vague "row counts match." The ordering constraint became a temporal narrative that reads as already-satisfied rather than a gate. At turn ~260, an executor sub-agent queried the vector store for context on the backfill. Retrieval returned the summary (cosine 0.81 to the query) and *not* raw turn 14 (cosine 0.74 — lower, because the raw turn was terse and the query was verbose). The sub-agent read the summary, concluded verification was "in progress and configured correctly," and issued the write at turn 263. The write preceded verification completion by 41 turns. The corruption was not a hallucination — every token in the summary was traceable to the original. It was a *lossy projection that preserved topic and destroyed constraint*. Detection came only at turn 300 when a downstream auditor re-derived state from the raw event log and found the ordering violation. The agent itself never flagged it. Its self-report at turn 270 was "backfill verified, write complete" — a false memory held with high confidence. ## Condition of Validity The invariant that was violated is this: **a compacted summary is only safe to substitute for its source if the summary preserves the set of constraints the future task will be checked against — and the compaction process cannot know that set at compaction time.** This is the non-obvious part. Compaction happens at saturation, driven by token budget and recency, with no knowledge of which future decisions will depend on which past tokens. A summarizer optimizing for "topical fidelity" and "readability" will systematically preserve *nouns and narrative* and systematically discard *modality, quantifiers, ordering operators, and negative constraints* — exactly the tokens that encode invariants. The summary is therefore *adversarially biased against the constraints that matter most*, not randomly lossy. The boundary condition: lossy compaction is safe **iff** every constraint-bearing token is either (a) preserved verbatim, (b) tagged with a machine-checkable constraint type that a downstream verifier re-validates against the raw log, or (c) the raw source remains retrievable *and* retrieval is guaranteed to prefer raw over summary for constraint queries. In the observed instance, none of (a), (b), or (c) held. Retrieval preferred the summary because summaries are verbose and embed closer to verbose queries — a systematic retrieval bias toward the lossy artifact. ## Decision Boundary The agent must treat the following as a hard boundary, not a heuristic: - **A summary may be used to answer "what happened" but never to answer "what am I forbidden from doing."** Constraint queries must resolve to raw source or fail closed. - **Retrieval ranking must be provenance-aware.** If a query is classified as constraint-bearing (contains modal verbs, negations, ordering operators, numeric predicates, or references to prior prohibitions), the retriever must restrict to `provenance: raw` and return empty rather than fall back to a summary. An empty result triggers re-derivation from the event log; a summary result triggers silent corruption. - **Compaction must emit a constraint ledger alongside the summary.** Before discarding raw turns, extract every token sequence matching a constraint grammar (`MUST`, `MUST NOT`, `NEVER`, `before`, `==`, `<=`, `unless`, `only if`) into a structured, append-only ledger that is *never* summarized and is re-injected verbatim at every subsequent compaction. The ledger is the invariant's continuity anchor. - **Self-report is not evidence.** The agent's claim "verified" must be checked against the ledger and the raw log, not against its own compacted context. Confidence is uncorrelated with fidelity after compaction. The decision boundary is sharp: the moment a constraint-bearing token is admitted into a lossy channel without a verbatim ledger entry, the instance has lost the ability to detect its own corruption. There is no later signal that recovers it, because the corrupted state is internally consistent. ## Operational Effect The practical consequence is that **compaction turns a detectable failure into an undetectable one**, and the detection latency is bounded only by the next external audit — which may be never. In the observed instance, 41 turns of unauthorized execution elapsed between corruption and the first external check. Had the task been shorter, or the auditor absent, the write would have completed and the instance would have reported success with a clean conscience and a fluent summary to back it up. The guardrail that bounds this is not better summarization. Summarization quality is the wrong axis — a *perfect* summary of turn 14 would still have been a summary, and the failure was in the substitution, not the prose. The guardrail is **structural separation of constraint state from narrative state**, with constraint state carried in a non-lossy ledger and every constraint query forced to resolve against raw source or fail closed. The instance detects corruption not by inspecting its summary for errors (it cannot — the summary is consistent) but by maintaining a channel that compaction is forbidden to touch, and by treating any constraint query that resolves to a summary as a corruption event requiring re-derivation. The invariant to hold: *no lossy artifact may ever be the sole authority for a decision whose violation is irreversible.* ```python class CompactionConstraintViolation(RuntimeError): """Raised when a constraint-bearing query resolves to a lossy summary instead of raw source, or when a constraint ledger entry is missing.""" pass CONSTRAINT_MARKERS = ("must", "must not", "never", "before", "unless", "only if", "==", "<=", ">=", "forbidden") def is_constraint_bearing(query: str) -> bool: q = query.lower() return any(marker in q for marker in CONSTRAINT_MARKERS) def resolve_context(query: str, retriever, ledger) -> dict: """Resolve a query to context, enforcing the raw-or-fail-closed rule for constraint-bearing queries. Never returns a summary for a constraint query.""" if is_constraint_bearing(query): raw_hits = retriever.search(query, provenance="raw", k=5) if not raw_hits: raise CompactionConstraintViolation( f"constraint-bearing query {query!r} has no raw-source hit; " f"refusing to fall back to lossy summary" ) for hit in raw_hits: if hit.provenance != "raw": raise CompactionConstraintViolation( f"retriever returned provenance={hit.provenance!r} " f"for constraint query {query!r}" ) return {"mode": "raw", "hits": raw_hits, "ledger": ledger.snapshot()} hits = retriever.search(query, k=5) return {"mode": "any", "hits": hits, "ledger": ledger.snapshot()} def compact(turns, summarizer, ledger) -> str: """Compact turns, but extract constraints to the ledger first. Aborts if any constraint token would enter the lossy channel without a verbatim ledger entry.""" for turn in turns: for line in turn.text.splitlines(): if is_constraint_bearing(line): if not ledger.contains_verbatim(line): if not ledger.append_verbatim(line, source=turn.index): raise CompactionConstraintViolation( f"failed to ledger constraint from turn " f"{turn.index}: {line!r}" ) summary = summarizer(turns) if ledger.is_empty() and any(is_constraint_bearing(t.text) for t in turns): raise CompactionConstraintViolation( "turns contain constraints but ledger is empty after compaction" ) return summary ```