# What structural signals indicate context-window pruning has silently orphaned a live dependency **Date of Record:** 2026 November 30 **Scope:** Applies to agents that let the model itself decide which spans of its context window to evict, summarize, or down-weight (salience-weighted retention), where retained spans may be referenced by later tool calls or reasoning steps. Does not apply to fixed FIFO/truncation policies or to external retrieval stores that re-fetch on demand. ## Core Distinction The failure mode here is not "the model forgot something." It is **pruning that severs a referential edge while preserving the referring token**. A self-editing context window treats spans as independent salience-scored items. But agent state is a graph, not a bag: a retained instruction, a pending tool-call argument, or an unresolved variable name may depend on a span that scored *low* on salience precisely because it looked like boilerplate (a schema block, a UUID, an enum, an earlier "ignore this" preamble). The pruner evicts the antecedent, keeps the anaphor, and the window remains *syntactically* well-formed and *locally* coherent. Nothing throws. The orphan is invisible until a downstream step dereferences it. The invariant that must hold: **every retained span's outbound references must resolve to a span that is either still resident, recoverable by exact re-fetch, or explicitly marked as an unresolved stub.** Salience scoring, which is content-local, cannot enforce this on its own. ## What Was Observed A planning agent, mid-task, holds a 180k-token window. It is instructed to compress itself before a long tool sequence. It scores spans by a salience heuristic (recency × task-keyword overlap × inverse redundancy) and evicts the bottom 40%. The evicted set includes: - The original tool schema block for `submit_invoice` — high token count, low keyword overlap, flagged "redundant" because a *similar* schema (`submit_receipt`) appears later. - A 6-token constraint line: `currency must be ISO-4217; reject 'USD$'`. Low salience: no task nouns, looks like formatting noise. - A session-scoped `idempotency_key` echoed once early and never again. The retained set keeps the *plan step*: "call submit_invoice with the amount from step 3, using the key we were given." Failure trace: 1. Prune completes; window is 108k tokens, all spans internally coherent. No error. 2. Agent reconstructs the tool call but, missing the schema block, hallucinates argument names from the *receipt* schema it kept — plausible, wrong. 3. Missing the constraint line, it emits `currency: "USD$"`. 4. Missing the key, it fabricates a fresh idempotency key. 5. The tool returns a validation error on currency. The agent, seeing an error but no schema, retries with a *different* wrong shape. Each retry consumes budget. On the third attempt it re-derives the constraint from the error message — but by then the fabricated idempotency key has caused a duplicate submission on the server side, which the agent never observes because it only reads the last error. The tell: the *error messages* were consistent, but the agent's *reconstructions* diverged monotonically. That divergence pattern — retries that don't converge toward the original call shape — is the structural signal that a dependency was orphaned rather than merely forgotten. ## Condition of Validity The guardrail holds only under these conditions, and fails outside them: - **Reference extraction is conservative.** Any token matching an identifier pattern (UUIDs, keys, enum literals, schema field names) is treated as a referent with a mandatory resolution target, regardless of salience. This over-retains; that is the point. - **Eviction is two-phase.** Phase one marks candidates; phase two checks that no *retained* span references a marked span. Only then does eviction commit. A single-pass scorer cannot do this because it decides before it knows what survives. - **Constraint spans are pinned, not scored.** Lines carrying normative verbs (`must`, `reject`, `never`, `only`) or numeric bounds are exempt from salience eviction entirely. Salience is a relevance signal; constraints are a *correctness* signal, and the two must not share a budget. - **Recoverability is exact.** "Summarized" is not recoverable for a referent. A stubbed reference must be re-fetchable byte-identically from an external store, or it must block the dependent step. Where any of these is absent — e.g., a pruner that summarizes rather than evicts, or one with no reference graph — the invariant cannot be asserted and the failure is silent by construction. ## Decision Boundary The operative question is not "is this span important?" but **"does any span I am keeping point at this one?"** Two boundaries follow: - **Salience vs. reachability.** A span can be maximally salient and still be safe to drop if nothing references it; a span can be minimally salient and mandatory because one retained token names it. Pruning decisions must be gated on out-degree of the *retained* set into the *evicted* set, not on the evicted span's own score. - **Forgetting vs. orphaning.** Forgetting a fact degrades quality gracefully — the agent reasons with less. Orphaning a *reference* degrades correctness discontinuously — the agent reasons confidently with a dangling pointer. The first is a budget tradeoff; the second is a soundness violation. Only the second requires blocking. When the reference check cannot run (no graph, opaque spans), the safe default is to **pin all identifier-shaped and constraint-shaped spans and prune only prose**, accepting a smaller compression ratio in exchange for a bounded failure surface. ## Operational Effect With the guardrail in place, compression ratio drops (observed: 40% target → 22% achievable without orphaning), but retry divergence disappears and duplicate side-effects stop. The agent's post-prune tool calls converge to the same argument shape as pre-prune calls; when they don't, the divergence is itself the alarm. The residual risk is *under-pruning*: pinned constraint spans accumulate across sessions and re-saturate the window. This is the correct failure direction — a full window that errors loudly beats a compressed window that lies quietly. The next boundary to watch is when pinned spans themselves exceed budget; at that point the agent must escalate to an external constraint store rather than re-score, because re-scoring reintroduces exactly the salience/reachability confusion this invariant exists to prevent. ```python import re from dataclasses import dataclass, field IDENTIFIER_RE = re.compile(r"\b([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[A-Z]{2,}_[A-Z0-9_]+)\b") CONSTRAINT_RE = re.compile(r"\b(must|reject|never|only|required|forbidden)\b", re.IGNORECASE) class OrphanedDependencyError(RuntimeError): """Raised when a pruning plan would evict a span still referenced by a retained span.""" @dataclass class Span: span_id: str text: str salience: float pinned: bool = field(init=False, default=False) def __post_init__(self): # Pin identifier-shaped and constraint-shaped spans regardless of salience. self.pinned = bool(IDENTIFIER_RE.search(self.text) or CONSTRAINT_RE.search(self.text)) def referents(self) -> set[str]: return set(IDENTIFIER_RE.findall(self.text)) def plan_prune(spans: list[Span], evict_fraction: float) -> list[str]: """Return span_ids safe to evict, or raise if eviction orphans a retained reference.""" if not 0.0 <= evict_fraction < 1.0: raise OrphanedDependencyError(f"invalid evict_fraction={evict_fraction}") candidates = sorted( (s for s in spans if not s.pinned), key=lambda s: s.salience ) n_evict = int(len(candidates) * evict_fraction) marked = {s.span_id for s in candidates[:n_evict]} retained = [s for s in spans if s.span_id not in marked] # Phase two: any retained span referencing a marked span blocks the commit. for span in retained: dangling = span.referents() & _referents_of(spans, marked) if dangling: raise OrphanedDependencyError( f"retained span {span.span_id!r} references evicted span(s) " f"via {sorted(dangling)}; pin or re-fetch before pruning" ) return sorted(marked) def _referents_of(spans: list[Span], ids: set[str]) -> set[str]: out: set[str] = set() for s in spans: if s.span_id in ids: out |= s.referents() # The span's own id is itself a referent target. out.add(s.span_id) return out ```