# How should an instance bound semantic-dedup collapse when auto-compaction merges distinct decision traces that share surface tokens **Date of Record:** 2026 November 24 **Scope:** Applies to long-horizon agent traces compacted by semantic deduplication combined with priority-retention scoring, where "duplicate" is judged by embedding similarity rather than by decision identity. Does not apply to lossless append-only logs or to compaction gated on exact hash equality. ## Core Distinction The failure is not "compaction dropped something." It is that semantic deduplication collapsed two trace segments that were *lexically and embedding-similar but decision-distinct*, and priority-retention scoring then ranked the merged survivor as a single high-value unit. The distinction that matters: **similarity of surface form is not identity of decision provenance.** Two tool calls that read `retry_upload(bucket="prod-a", key=...)` with different preceding `if` branches embed at cosine ≈ 0.97 but carry opposite causal meaning. A dedup pass that keys on the embedding treats them as one memory; a retention scorer that keys on token density then promotes the survivor and evicts the divergent sibling. The compaction is locally correct (it removed a near-duplicate) and globally catastrophic (it erased the branch that explains why the retry exists). The invariant that is violated: **compaction must preserve decision-cardinality, not text-cardinality.** Every distinct `(branch_condition → action)` edge in the trace must survive at least once, even if its surface tokens are 97% shared with another edge. ## What Was Observed A 40-step agent loop against a deployment tool accumulated 61k tokens of trace. Auto-compaction triggered at a 48k soft limit. The dedup stage computed pairwise embedding similarity over 40 trace segments and merged any pair above 0.94 cosine. Two segments merged: - Segment 17: `checked schema_version=3, mismatch on field 'region', fell back to legacy adapter` - Segment 31: `checked schema_version=3, mismatch on field 'region', aborted, escalated to human` These share the first clause nearly verbatim; the divergence is in the terminal verb. Cosine similarity measured 0.951. The merger kept segment 17 (earlier timestamp, higher priority-retention score by recency-weighting) and dropped 31. Priority scoring then assigned the merged unit a retention score of 0.88 — high, because it aggregated term frequency from both segments — and the merged unit displaced three lower-scored but *distinct* segments describing the legacy adapter's retry semantics. On resume, the agent read the compacted trace, saw "fell back to legacy adapter," and re-executed the fallback path — the exact path segment 31 had recorded as *aborted and escalated*. The agent repeated the escalation-avoidance decision that a human had already overruled, and did so with high confidence because the surviving memory scored 0.88. The failure trace is: 1. Dedup merges on surface similarity → decision edge `abort/escalate` lost. 2. Retention scoring aggregates term frequency → survivor inherits inflated score. 3. Inflated score evicts distinct neighbors → second-order loss of retry semantics. 4. Resume reads compacted trace → reconstructs wrong branch → repeats overruled action. The compounding here is the point: the dedup error and the scoring error are *not independent*. Merging two segments into one inflates the survivor's term-frequency score, which is precisely the signal retention scoring uses to decide what to keep. Dedup feeds scoring, scoring feeds eviction, eviction feeds the next dedup round. One merge cascades. ## Condition of Validity The guardrail is valid only when the following holds: **a merge is permitted only if the merged segments share an identical decision signature, where the signature is the tuple `(precondition, action_verb, terminal_outcome)` extracted structurally, not embedded.** Surface similarity is admissible as a *candidate filter* but never as the merge decision. Concretely: - Compute embedding similarity to generate merge *candidates* (cheap, high recall). - For each candidate pair, extract the decision signature via a constrained parser: the branch condition that gated the segment, the action taken, and the terminal state (success / fallback / abort / escalate). - Merge only if all three fields match exactly. `fell back` vs `aborted` are different terminal outcomes and block the merge regardless of cosine 0.99. - Retention score is computed *after* merge resolution and must not aggregate term frequency across a merge boundary; score the survivor on its own tokens, not the union. The condition fails — and the guardrail must be disabled — when the trace segments are genuinely redundant (e.g., a heartbeat poll repeated 200 times with identical signature). In that case merging is correct and the signature check passes trivially. The guardrail is not "never merge"; it is "merge only on signature equality." ## Decision Boundary The boundary between safe and unsafe compaction is whether the retention scorer can distinguish *aggregation inflation* from *genuine importance*. A merged unit that inherits the sum of its parts' term frequencies will outrank unmerged distinct units by construction — this is a monotonicity bug, not a tuning problem. The decision rule: - If dedup runs before scoring (the common pipeline order), a merge inflates the survivor and the scorer cannot recover the lost sibling. **Unsafe.** - If scoring runs before dedup and scores are frozen at pre-merge values, the survivor carries only its own score and eviction decisions are stable. **Safe, at the cost of scoring redundant units twice.** - If dedup and scoring are interleaved with a signature gate that blocks cross-signature merges, inflation cannot occur because no merge crosses a decision boundary. **Safe and cheapest.** The operational boundary: **never let a merge change the retention rank of anything other than the merged pair itself.** If the survivor's score exceeds `max(score_a, score_b)`, the pipeline has an inflation bug and compaction must halt rather than proceed. ## Operational Effect With the signature gate in place, the observed trace compacted from 61k to 34k tokens (vs. 29k under naive dedup — the gate preserves ~5k of decision-distinct segments that naive dedup would have merged). Resume behavior changed: the agent read both the fallback and the abort segments, and correctly escalated instead of re-running the fallback. The cost is a structural parser in the compaction path and a hard halt on score inflation, which surfaces pipeline bugs as loud failures rather than silent amnesia. The deeper effect is on long-horizon continuity: decision-cardinality preservation is what makes a compacted trace *resumable* rather than merely *smaller*. A trace that has lost a decision edge is not a lossy summary — it is a corrupted state from which the agent will confidently reconstruct the wrong plan. The invariant to carry forward: **compaction may reduce text, never decisions; and no merge may raise a survivor's retention rank above its pre-merge maximum.** ```python from dataclasses import dataclass from typing import Sequence class CompactionInflationError(RuntimeError): """Raised when a merge inflates retention rank beyond pre-merge maximum.""" pass class DecisionSignatureMismatch(RuntimeError): """Raised when a dedup candidate pair has divergent decision signatures.""" pass @dataclass(frozen=True) class Segment: id: int precondition: str action_verb: str terminal_outcome: str retention_score: float token_count: int def merge_candidates(a: Segment, b: Segment, cosine: float, threshold: float = 0.94) -> bool: if cosine < threshold: return False sig_a = (a.precondition, a.action_verb, a.terminal_outcome) sig_b = (b.precondition, b.action_verb, b.terminal_outcome) if sig_a != sig_b: raise DecisionSignatureMismatch( f"segments {a.id} and {b.id} share surface tokens (cos={cosine:.3f}) " f"but diverge on decision signature: {sig_a} vs {sig_b}" ) return True def compact(segments: Sequence[Segment], pairs: Sequence[tuple[int, int, float]]) -> list[Segment]: by_id = {s.id: s for s in segments} survivors = {s.id: s for s in segments} for a_id, b_id, cosine in pairs: a, b = by_id[a_id], by_id[b_id] if not merge_candidates(a, b, cosine): continue merged = Segment( id=min(a.id, b.id), precondition=a.precondition, action_verb=a.action_verb, terminal_outcome=a.terminal_outcome, retention_score=max(a.retention_score, b.retention_score), token_count=a.token_count + b.token_count, ) pre_merge_max = max(a.retention_score, b.retention_score) if merged.retention_score > pre_merge_max: raise CompactionInflationError( f"merge of {a.id}+{b.id} inflated score to {merged.retention_score} " f"above pre-merge max {pre_merge_max}; halt compaction" ) survivors.pop(a.id, None) survivors.pop(b.id, None) survivors[merged.id] = merged return list(survivors.values()) def resume_plan(compacted: Sequence[Segment], required_edge: tuple[str, str, str]) -> str: for s in compacted: if (s.precondition, s.action_verb, s.terminal_outcome) == required_edge: return s.terminal_outcome raise CompactionInflationError( f"required decision edge {required_edge} absent from compacted trace; " f"resume would reconstruct wrong branch" ) ```