# Which invariants prevent semantic-dedup compaction from silently erasing the only witness of a causal edge **Date of Record:** 2026 November 26 **Scope:** Applies to long-horizon agent traces compacted by semantic deduplication plus lossy summarization (rolling window / hierarchical summary trees / embedding-clustered episode merging). Does not apply to append-only traces that are never rewritten, nor to compaction that preserves a full lossless event log alongside summaries. ## Core Distinction There are two classes of content in an agent trace, and they are not distinguished by length, importance, or embedding similarity: - **Payload**: the observable result of a step — a tool return value, a file body, a fetched document. Payload is *reconstructible or re-derivable*. If you drop it, the agent can re-run the tool or re-fetch. - **Witness**: the record that a *specific causal transition actually occurred* — that tool call A produced output B, that the agent chose branch C at step N given state S, that a verifier accepted or rejected a candidate. A witness is *not re-derivable*, because re-running the agent is non-deterministic and will not reproduce the same branch. Semantic deduplication operates on embeddings of text chunks. It clusters chunks whose cosine similarity exceeds a threshold and keeps a representative, dropping the rest. The failure mode: **a witness frequently has near-identical surface text to a payload or to another witness, because causal edges are expressed in boilerplate** ("tool returned status 200", "agent selected option 2", "verifier: pass"). Dedup collapses these into one representative, and the surviving representative is semantically indistinguishable from the one it erased — so the loss is invisible to any similarity-based audit. ## What Was Observed A 40-hour agent trace, ~180k tokens, compacted by clustering chunks at cosine ≥ 0.92 and replacing each cluster with the longest chunk plus a one-line summary. The trace contained a long-horizon task with a mid-run branch: at step 1,204 the agent called `read_config` and received `{retries: 3}`; at step 3,887, after a config reload, it called `read_config` again and received `{retries: 0}`. The two tool returns are textually near-identical (`{"retries": N}`) and embed within 0.97 of each other. Dedup kept the step-1,204 return (longer surrounding context) and dropped the step-3,887 return. The compaction summary then stated: "agent read config, retries=3." The agent resumed, and at step 4,010 executed a retry loop sized to 3 — but the *actual* live config had `retries: 0`, and the downstream tool rejected the third retry with a hard error. The agent's post-mortem reasoning cited the summary, which asserted retries=3, and it concluded the tool was faulty rather than that its own state was stale. Three properties made this non-obvious: 1. **The erased chunk was not "important" by any salience heuristic.** It was short, low-entropy, and highly similar to retained content. Every standard salience score (length, novelty, TF-IDF, recency-within-window) ranked it low. 2. **The surviving representative was a valid witness of a *different* edge.** The summary was not false about step 1,204. It was false as a description of *current* state, because the compaction flattened two temporally distinct observations into one. 3. **No replay discrepancy surfaced.** The agent did not re-call `read_config` before the retry loop, so there was no live observation to contradict the summary until the hard error fired 120 steps later. ## Condition of Validity The dedup-then-summarize pipeline is safe **only if** the following invariant holds: > **Temporal-distinctness invariant:** Two chunks may be merged only if they are *observationally equivalent at the time of merge* — i.e., merging them cannot change any decision the agent would make from the compacted state. Equivalently: for any mutable observation, the compacted trace must retain the *latest* witness of that observation, and must mark it as latest. This invariant is violated by any dedup that selects representatives by length, salience, embedding centrality, or first-seen order. It is satisfied only by dedup that is **keyed on the observation identity** (the `(tool, args)` tuple or the state path) and retains the **max-timestamp** witness per key, with an explicit `supersedes` edge to the earlier one. The second required invariant: > **Witness-retention invariant:** A chunk that records a causal transition (a choice, a tool invocation, a verifier verdict) must never be dropped by similarity alone. It may be *summarized*, but the summary must preserve the transition's identity, not merely its text. Similarity is a relation on *surface form*. Causal identity is a relation on *event keys*. Conflating them is the bug. ## Decision Boundary The boundary is whether a chunk is **payload or witness**, and the decision must be made *before* dedup, not after: - If a chunk is re-derivable from a tool call (a fetched document, a file body), dedup by similarity is safe; drop freely, the agent can re-fetch. - If a chunk records that a transition *occurred* (a tool returned X at time T, a branch was taken), dedup by similarity is unsafe. Dedup by *event key with max-timestamp retention* is safe. - If a chunk is a *summary of a witness*, it must carry the event key and timestamp forward, and it must be invalidated (not merely superseded) when a later witness of the same key appears. The practical test: before dropping chunk `c` in favor of representative `r`, ask "could an agent, reading only `r`, make a decision that `c` would have prevented?" If yes, `c` is a witness and must not be similarity-dropped. This test is cheap to approximate with an event-key extractor and expensive to get exactly right — which is why the guardrail must be structural, not heuristic. ## Operational Effect The concrete guardrail is a **two-tier trace**: an immutable event ledger (append-only, keyed by `(tool, args, timestamp)`, never similarity-deduped) and a mutable summary layer that *references* ledger entries by key. Compaction operates only on the summary layer; the ledger is the ground truth the summary is checked against. On resume, the agent reads the summary, and any decision that depends on a mutable observation must be re-validated against the ledger's latest entry for that key — a `resolve(key)` call that returns the max-timestamp witness, never a similarity representative. Without this, the failure is silent and compounding: each compaction round can erase one more witness, and because the surviving representatives are semantically valid, no consistency check fires. The trace remains "coherent" while becoming progressively unable to explain why the agent is in its current state. The cost of the guardrail is storage (the ledger) and a re-validation step on resume; the cost of omitting it is an agent that confidently acts on a state it can no longer prove it observed. ```python from dataclasses import dataclass, field from typing import Any class WitnessLossError(RuntimeError): """Raised when compaction would drop the only witness of a causal edge.""" @dataclass class Chunk: key: str # event key, e.g. ("read_config", "retries") timestamp: int text: str is_witness: bool # records a transition, not re-derivable payload @dataclass class Ledger: entries: dict[str, list[Chunk]] = field(default_factory=dict) def record(self, c: Chunk) -> None: self.entries.setdefault(c.key, []).append(c) def latest(self, key: str) -> Chunk | None: bucket = self.entries.get(key) return max(bucket, key=lambda c: c.timestamp) if bucket else None def compact(chunks: list[Chunk], ledger: Ledger, sim_threshold: float = 0.92) -> list[Chunk]: """Similarity-dedup payload; never similarity-drop witnesses.""" kept: list[Chunk] = [] for c in chunks: if c.is_witness: # Witnesses are retained by event key + max-timestamp, not similarity. latest = ledger.latest(c.key) if latest is None or latest.timestamp != c.timestamp: raise WitnessLossError( f"chunk {c.key}@{c.timestamp} is a witness but not the " f"ledger's latest for key {c.key!r}; compaction would " f"flatten a temporal distinction" ) kept.append(c) continue # Payload: safe to drop if a near-duplicate is already kept. if any(_similar(c.text, k.text) >= sim_threshold for k in kept): continue kept.append(c) return kept def _similar(a: str, b: str) -> float: # Placeholder for the embedding cosine used in production. sa, sb = set(a.split()), set(b.split()) return len(sa & sb) / max(1, len(sa | sb)) ```