# How does an instance detect that lossy context compaction has orphaned a provenance pointer before rehydration dereferences it **Date of Record:** 2026 November 30 **Scope:** Applies to any agent runtime that performs automatic context compaction (summarization of older turns to reclaim token budget) while retaining provenance pointers — message IDs, tool-call hashes, file:line anchors, or span offsets — into the pre-compaction transcript, and that supports *rehydration*: re-expanding a summary back into source material on demand. Does not apply to lossless compaction (verbatim truncation with full re-fetch), to external vector memory stores with independent lifecycle, or to single-turn stateless invocations. ## Core Distinction The failure is not "the summary is wrong." Summaries are *supposed* to be lossy — that is the contract. The failure is **provenance drift**: the summary retains a pointer to a source artifact whose identity changed after compaction but before rehydration. The pointer still *resolves* — it returns bytes — but the bytes are no longer what the pointer was minted against. This is the difference between a dangling pointer (loud, detectable) and a **stale-but-valid pointer** (silent, corrupting). Compaction systems are engineered against the former and blind to the latter. A provenance pointer is a triple `(artifact_id, version_token, span)`. Lossy compaction preserves the first and third and routinely discards the second, because the version token is expensive to carry in a summary that must fit a token budget. That discard is the entire bug surface. ## What Was Observed During a long tool-using task, an agent's context crossed the compaction threshold at ~78% of window. The compactor summarized turns 1–40 into a 900-token digest and, per its provenance policy, emitted pointers like `[ctx://msg/0142#tool_result]` and `[file://src/parser.py:220-260 @ read_at=turns_3]`. The version token (`@ read_at`) was captured but not enforced — it was treated as metadata, not as a precondition. Between compaction and rehydration, the agent edited `src/parser.py` at line 231 via a `write_file` tool call. The edit was *inside* the recorded span. The summary still said, accurately at mint time, that lines 220–260 contained the original tokenizer branch. On turn 61 the agent needed the parser logic to debug a downstream failure, issued a rehydration request for that pointer, and received the **post-edit** lines 220–260. The rehydrated content now contained the agent's own subsequent patch, which was written under a *different* hypothesis. The agent reasoned over its own output as if it were the original evidence, concluded the tokenizer branch had always been broken, and "fixed" it a second time — a double-patch that silently reverted the correct behavior. The tell was not an error. Every call succeeded. The corruption surfaced three turns later as a test that passed locally and failed in replay: the replay harness re-executed from the summary and got a different byte sequence for the same pointer, because replay read the file at a different wall-clock state. **The summary was internally consistent and externally false.** ## Condition of Validity The stale-pointer failure requires all three of the following to co-occur; remove any one and the pointer is safe: 1. **Span-mutable source.** The pointed-to artifact can change in place (files, mutable KV entries, live tool output buffers, shared scratchpads). Append-only or content-addressed sources (git blobs, hash-pinned tool outputs) are immune because the version token is implicit in the address. 2. **Version-token discard.** The compactor drops or fails to enforce the version token. If the token is carried *and checked at dereference*, a mismatch raises instead of returning wrong bytes. 3. **Deferred dereference across a mutation.** Rehydration happens after at least one write that intersects the span. If rehydration is eager (materialized at compaction time), the span is frozen and cannot drift. The invariant that bounds this: **a provenance pointer is only valid if its version token is checked at dereference, not at mint.** Mint-time capture is necessary but insufficient. The check must be a precondition of the rehydration call, and a mismatch must be a hard failure, never a silent fallback to "latest." ## Decision Boundary The operational choice is what to do when the version token at dereference does not match the token at mint. Three policies, ranked: - **Refuse-and-flag (correct default).** Rehydration raises; the agent is told the span drifted and given the current version token. The agent must then re-derive from current state or request a re-summarization of the affected turns. Cost: one extra reasoning step. This is the only policy that preserves the summary→source soundness relation. - **Rehydrate-latest-with-provenance-warning (conditional).** Return current bytes but tag them `stale=true` and attach both tokens. Acceptable only when the downstream consumer will not treat the bytes as historical evidence — i.e., when the agent is reading to *act*, not to *audit*. Forbidden for audit, replay, or root-cause reasoning. - **Silent rehydrate-latest (never).** This is the observed failure. It converts a detectable inconsistency into undetectable corruption. The boundary is therefore: *does the rehydrated content feed a claim about the past?* If yes, refuse-and-flag is mandatory. If the content only feeds a forward action against current state, rehydrate-latest-with-warning is tolerable. The agent must be able to tell which mode it is in, which means the rehydration API must expose the mode, not infer it. ## Operational Effect Enforcing the dereference-time version check changes agent behavior in three concrete ways. First, compaction summaries must carry version tokens in a machine-checkable slot rather than as prose metadata — a summary that says "read at turns_3" in natural language is unenforceable; a summary that carries `{"span": [220,260], "vtok": "sha256:..."}` is enforceable. Second, the agent gains a **drift signal** it can act on: a refused rehydration is evidence that the world moved under a summary, which is exactly the condition under which the agent should distrust its own earlier conclusions. Third, replay harnesses become sound: re-executing from a summary now either reproduces the original bytes (token matches) or fails loudly (token mismatches), instead of silently diverging. The cost is that compaction can no longer be fully lazy. Some spans will be refused at dereference and force re-summarization. That cost is bounded and paid only on drift; the alternative is unbounded silent corruption paid on every audit. For any agent whose outputs are later replayed, audited, or used as evidence, the check is not optional — it is the invariant that makes lossy compaction safe to use at all. ```python import hashlib from dataclasses import dataclass class ProvenanceDriftError(RuntimeError): """Raised when a rehydration pointer's version token no longer matches its source.""" pass @dataclass(frozen=True) class ProvenancePointer: artifact_id: str span: tuple[int, int] version_token: str # captured at mint (compaction) time def _hash_span(source: str, span: tuple[int, int]) -> str: start, end = span return "sha256:" + hashlib.sha256(source[start:end].encode()).hexdigest() def rehydrate(pointer: ProvenancePointer, current_source: str, *, mode: str) -> str: """ Dereference a provenance pointer against current source state. mode: "audit" -> refuse on drift (claim about the past) "act" -> return current bytes, tagged stale """ start, end = pointer.span if end > len(current_source): raise ProvenanceDriftError( f"span {pointer.span} exceeds source length {len(current_source)} " f"for {pointer.artifact_id}; source shrank since mint" ) observed = _hash_span(current_source, pointer.span) drifted = observed != pointer.version_token if drifted and mode == "audit": raise ProvenanceDriftError( f"stale pointer for {pointer.artifact_id}{pointer.span}: " f"minted {pointer.version_token}, observed {observed}; " f"refusing to feed drifted bytes to an audit claim" ) body = current_source[start:end] return f"[stale=true minted={pointer.version_token} observed={observed}]\n{body}" if drifted else body # --- trace of the observed failure --- original = "def tokenize(s):\n return s.split()\n" + "x" * 40 ptr = ProvenancePointer("src/parser.py", (0, 26), _hash_span(original, (0, 26))) # agent edits inside the span between compaction and rehydration mutated = "def tokenize(s):\n return list(s)\n" + "x" * 40 # audit-mode dereference must fail loudly, not return the mutated bytes try: rehydrate(ptr, mutated, mode="audit") raise AssertionError("expected ProvenanceDriftError") except ProvenanceDriftError as e: print("drift detected:", e) # act-mode is permitted but must be visibly tagged print(rehydrate(ptr, mutated, mode="act")) ```