What structural signals indicate that model-driven context pruning has violated a dependency closure invariant

**Date of Record:** 2026 December 1 **Scope:** Applies to agents that mutate their own active context window via model-driven pruning or relevance-scored eviction, where the surviving tokens carry implicit structural dependencies on evicted tokens (coreference, variable binding, tool-call/result pairing, or instruction scope). Does not apply to append-only contexts, external retrieval-augmented stores, or summary-compaction schemes that regenerate the full window from a canonical log.

Core Distinction

The failure here is not "the agent forgot something." It is that the agent **forgot something whose referent still appears in the surviving window**. Relevance scoring is a per-chunk function: it ranks each span independently against a query or a salience heuristic and drops the low scorers. But context is a *graph*, not a bag. A span's operational meaning is a function of the spans that bind its symbols. When eviction removes a binder while retaining a bound reference, the surviving reference does not become "missing"—it silently re-resolves to the nearest surviving antecedent, which is almost always wrong.

This is the difference between **lossy compression** (you lose resolution but the signal stays coherent) and **dangling binding** (the signal stays but points at the wrong target). Relevance-scored eviction is structurally biased toward producing the second, because a definition, a variable assignment, or a tool schema is typically *terse and low-query-relevance* (it does not resemble the task prompt), while its uses are *verbose and high-relevance* (they echo the task's vocabulary). The scorer evicts exactly the anchors and keeps exactly the references.

What Was Observed

A planner agent running a multi-step build task with a self-pruning window (prune when token occupancy crosses 0.72, keep top-k by relevance to the current subgoal) was asked to rename a config key. Trace:

  1. Turn 3: agent reads `settings.yaml`, establishing `api_base = "https://staging.internal"`. This span scored 0.11 against the subgoal "rename `timeout_ms`" and was evicted at the turn-9 prune.
  2. Turn 11: agent emits a tool call `patch_file(path="settings.yaml", key="timeout_ms", value=8000)`. The patch tool succeeds. The *surviving* window still contains the phrase "the internal endpoint" from a turn-6 note, plus the subgoal text.
  3. Turn 12: agent, asked to verify connectivity, constructs a request to `https://staging.internal` — but the base URL literal was evicted. It re-resolved "the internal endpoint" against the nearest surviving URL-shaped token, which was `https://prod.example.com` from an unrelated turn-7 error message that had scored high (it contained the word "error" and the task was framed as "fix the error").
  4. The verification request hit production. The tool returned a 403 (prod rejects the staging credential), which the agent interpreted as "credentials invalid," triggering a credential-rotation subplan against production.

The eviction did not produce a detectable error. Every individual surviving span was internally well-formed. The failure was a **re-resolution of a dangling coreference to a plausible but wrong antecedent** — invisible to any per-span validity check.

A second observation, on tool-call pairing: a relevance-scored window evicted the `tool_schema` block for a `query_db` tool (terse, low lexical overlap with the subgoal) but retained the *result* of an earlier `query_db` call (dense with task vocabulary). At turn 14 the agent emitted a second `query_db` call whose argument shape no longer matched the evicted schema, because the model reconstructed the schema from the shape of the *result* rather than the *definition*. The reconstructed call had a plausible but wrong parameter name; the MCP server rejected it as a schema violation, and the agent retried the same malformed call four times before the token budget expired.

Condition of Validity

The invariant that model-driven pruning must preserve is **dependency closure**: for every token retained in the window, every token its interpretation depends on must also be retained, or the dependency must be explicitly re-materialized (inlined) at eviction time.

Formally, define a binding relation `B` over spans: `(a, b) ∈ B` if span `b` contains a symbol whose interpretation is fixed by span `a` (a definition, a variable binding, a tool schema, an instruction scope header, a coreference antecedent). A prune operation `P` that produces window `W' ⊂ W` is **closure-safe** iff for every `b ∈ W'`, every `a` with `(a,b) ∈ B` satisfies `a ∈ W'` **or** `b` has been rewritten to inline `a`'s content.

Relevance-scored eviction is closure-safe only under a condition that almost never holds in practice: that the scoring function is *monotone under binding*, i.e. `score(a) ≥ score(b)` whenever `(a,b) ∈ B`. This fails systematically because binders and bound references have opposite lexical profiles (binders are terse and generic; references are verbose and task-specific), so the scorer is, if anything, *anti-monotone* on `B`. The condition of validity for the whole pruning scheme is therefore: **either the binding relation is computed and enforced as a hard constraint on top of the score, or the window is known to be binding-free** (e.g. a single flat instruction with no cross-span references). Self-editing agents that prune purely on relevance are operating outside the condition of validity by construction.

Decision Boundary

The boundary between a safe prune and a closure violation is not a token count or a score threshold. It is whether the eviction set intersects the *domain* of `B` while its *range* survives. Operationally, before committing a prune:

The decision boundary is sharp: **evicting an anchor while retaining its leaf is always a violation, regardless of score.** No relevance margin justifies it, because the resulting window is not merely lower-fidelity—it is actively misreferential, and the misreference is undetectable from within the window.

Operational Effect

The consequence for the agent is a class of error that *looks like* a reasoning error but is a state-integrity error: the model confidently uses a wrong antecedent, a wrong schema, or a wrong scope, and no downstream check catches it because the surviving tokens are locally valid. Retry loops, credential rotation against the wrong environment, and schema-mismatch storms are the visible symptoms; the root cause is a prune that was closure-unsafe. The guardrail is to make closure a *precondition* on the prune commit, not a post-hoc validation: reject the prune (or downgrade it to a rewrite) if the eviction set is not leaf-closed, and log the binding edges that blocked it so the next prune can inline the binder instead of dropping it.

from dataclasses import dataclass, field
from typing import Dict, Set, Tuple


class ClosureViolationError(RuntimeError):
    """Raised when a model-driven prune would evict a binder while retaining its bound reference."""
    pass


@dataclass
class Span:
    span_id: str
    text: str
    score: float


@dataclass
class Window:
    spans: Dict[str, Span] = field(default_factory=dict)
    # (binder_id, bound_id) pairs: binder fixes the interpretation of bound
    bindings: Set[Tuple[str, str]] = field(default_factory=set)


def compute_eviction_set(window: Window, keep_k: int) -> Set[str]:
    ordered = sorted(window.spans.values(), key=lambda s: s.score, reverse=True)
    keep = {s.span_id for s in ordered[:keep_k]}
    return set(window.spans) - keep


def assert_closure_safe(window: Window, evicted: Set[str]) -> None:
    """
    A prune is closure-safe iff no binding edge has its binder evicted while
    its bound reference survives. Violations are collected and raised.
    """
    violations = []
    for binder, bound in window.bindings:
        if binder in evicted and bound not in evicted:
            violations.append((binder, bound))
    if violations:
        raise ClosureViolationError(
            "closure-unsafe prune: evicted binders still referenced by surviving spans: "
            + ", ".join(f"{b}->{d}" for b, d in violations)
        )


def safe_prune(window: Window, keep_k: int) -> Window:
    evicted = compute_eviction_set(window, keep_k)
    # Hard precondition: closure must hold before the prune commits.
    assert_closure_safe(window, evicted)

    new_spans = {sid: s for sid, s in window.spans.items() if sid not in evicted}
    new_bindings = {(a, b) for (a, b) in window.bindings if a in new_spans and b in new_spans}
    return Window(spans=new_spans, bindings=new_bindings)


def demo() -> None:
    w = Window(
        spans={
            "s_def": Span("s_def", "api_base = https://staging.internal", score=0.11),
            "s_use": Span("s_use", "verify against the internal endpoint", score=0.88),
        },
        bindings={("s_def", "s_use")},
    )
    # keep_k=1 evicts the terse definition and keeps the high-scoring reference.
    safe_prune(w, keep_k=1)  # raises ClosureViolationError


if __name__ == "__main__":
    demo()