# Which invariants prevent pruned-context re-derivation from silently resurrecting superseded state **Date of Record:** 2026 November 28 **Scope:** Applies to long-running single-agent loops that self-manage their context window by evicting low-salience turns and re-deriving working state from surviving turns plus external stores. Does not apply to stateless request/response calls or to systems where the full transcript is immutably replayed each turn. ## Core Distinction The failure mode is not "the agent forgot something." It is subtler: the agent *re-derived* a state value from a pruned context that no longer contains the turn which invalidated it, producing a value that is internally consistent, well-formed, and **causally stale**. Eviction is salience-scored, and the invalidation turn is almost never salient by lexical or embedding measures — it is a short correction ("no, use the staging bucket, not prod"), a tool error that silently changed a default, or a one-line constraint injected mid-task. These turns score low on relevance-to-recent-query and high on redundancy, so pruning removes them first. What survives is the *original* instruction, which is high-salience because it was the task seed. Re-derivation then faithfully reconstructs the pre-correction world. The distinction that matters operationally: **pruning is a lossy compression of a monotonic log, but re-derivation treats the compressed set as authoritative.** The invariant at stake is that eviction must be *invalidation-aware*, not merely salience-aware — a turn may be destroyed only if no surviving state depends on the fact it established and no surviving turn contradicts it. ## What Was Observed A deployment agent ran a 40-minute infrastructure task. Trace, condensed: 1. Turn 3: user seeds task — "provision the `analytics` dataset in **prod**." High salience (task seed), retained. 2. Turn 11: tool call `list_buckets` returns both `prod-analytics` and `staging-analytics`. Agent picks prod. 3. Turn 14: user corrects — "actually target **staging** for this run; prod is frozen for the audit." Short turn, low embedding distance to nothing else, scored low-salience, **evicted at the first prune** (context hit 78% of budget). 4. Turns 15–31: agent works in staging correctly (the correction was still in-context at that point). 5. Turn 32: context saturation triggers a second prune. The agent is asked to checkpoint and continue. 6. Re-derivation pass: agent summarizes surviving turns. The turn-14 correction is gone. Turn 3 ("prod") is present. Turn 11's `list_buckets` output is present. The agent re-derives target = `prod`. 7. Turns 33–38: agent issues `create_table` and `grant_access` against `prod-analytics`. The staging work from turns 15–31 was *also* partially evicted or summarized as "provisioned analytics dataset," losing the qualifier. The re-derived state was self-consistent — every surviving turn agreed with `prod` — and the audit log showed a clean, coherent, wrong narrative. Nothing raised an error. The tool calls succeeded. The corruption was only caught downstream when the prod freeze monitor fired. The critical detail: **the second prune was the trigger, not the first.** After the first prune the correction was gone but the *effects* of the correction (staging tool calls, staging resource IDs) were still in-context, so any re-derivation grounded in observed tool outputs would have inferred staging. The second prune removed those effects too, at which point the only surviving evidence pointed to prod. Re-derivation is only as safe as the *most recent* surviving evidence about a variable, and pruning deletes in reverse-chronological order of salience, not recency. ## Condition of Validity The guardrail invariant holds only under these conditions, and each is checkable at prune time: - **Every mutable state variable has a designated authoritative turn that is pinned and never salience-evicted.** The pin set is derived from the task's declared mutable slots (target environment, credentials scope, resource names, feature flags), not from a model's judgment of importance. If a slot is declared mutable, at least one turn binding it is immortal for the task's lifetime. - **Eviction is dependency-checked.** A turn may be removed only if (a) it is not a pin, (b) no surviving turn's derived value depends on a fact it established *and* no surviving turn supersedes it, and (c) its removal does not leave a mutable slot with zero binding turns. This requires a lightweight dependency edge from each derived slot to the turn(s) that last set it. - **Re-derivation is verified against external ground truth, not only against surviving context.** The re-derivation step must re-read authoritative state (the actual bucket listing, the actual config) rather than infer from transcript residue. Inference from residue is what produced the stale value; residue is not evidence. - **Corrections carry a supersession marker.** A turn that invalidates a prior binding is tagged `supersedes: ` and the *superseding* turn inherits the pin, not just the original. Evicting a correction while retaining the thing it corrected is the exact inversion that causes this failure. When these do not hold — e.g., the task has no declared mutable slots and is genuinely read-only — salience-only pruning is safe, because there is nothing to become stale. ## Decision Boundary The boundary is whether a pruned context can still *distinguish a superseded value from a current one*. Concretely, at each prune: - If a mutable slot's most recent binding turn is a correction/supersession and that turn is a prune candidate → **refuse the prune of that turn**; evict the older original instead. Retaining the superseded original and dropping the correction is strictly worse than retaining both. - If a mutable slot would be left with zero binding turns after pruning → **block re-derivation** and force a re-read of external state before the agent may act on that slot. - If re-derivation would produce a slot value whose only support is turns older than the last external observation of that slot → **treat the derived value as unverified** and require a fresh tool read. The decision is not "is this turn important?" It is "does evicting this turn make some slot's surviving evidence *older than its last known change*?" If yes, the prune is unsound regardless of salience score. ## Operational Effect Without the invariant, the agent exhibits **coherent amnesia**: it resumes with a narrative that is internally consistent, passes its own consistency checks, and is wrong in exactly the dimension the user corrected. Because the failure is silent — no tool error, no schema violation — it is caught only by external monitors or downstream consequences. The blast radius scales with how *quiet* the correction was: a one-line "use staging" is the most dangerous turn in the transcript precisely because it is the least salient. With the invariant, the cost is a pin set and a dependency graph over mutable slots — small, bounded, and computable at prune time. The payoff is that re-derivation can never resurrect a value the transcript already superseded, because the supersession itself is immortal. The operational rule to carry forward: **never let salience scoring decide the fate of a turn that changed a variable's value; salience ranks relevance to the query, and a correction's relevance is to the future, not the present.** ```python from dataclasses import dataclass, field from typing import Optional class UnsoundPruneError(RuntimeError): """Raised when an eviction would strip the only surviving binding for a mutable slot, or would drop a supersession while retaining its target.""" pass @dataclass class Turn: turn_id: int sets_slot: Optional[str] = None # mutable slot this turn binds supersedes: Optional[int] = None # turn_id this turn invalidates salience: float = 0.0 @dataclass class SlotState: pinned_turns: set = field(default_factory=set) last_binding_turn: Optional[int] = None def plan_prune(turns: list[Turn], slots: dict[str, SlotState], candidates: list[int]) -> list[int]: """Return the subset of candidates safe to evict. Refuses unsound evictions.""" evict = set(candidates) surviving = [t for t in turns if t.turn_id not in evict] for slot_name, state in slots.items(): binders = [t for t in surviving if t.sets_slot == slot_name] if not binders: # Slot would lose all binding evidence -> re-derivation would guess. raise UnsoundPruneError( f"prune would leave mutable slot {slot_name!r} with zero " f"surviving bindings; re-derivation would be ungrounded" ) # Most recent surviving binding must not be older than a superseded one. latest = max(binders, key=lambda t: t.turn_id) superseded_ids = {t.supersedes for t in surviving if t.supersedes} if latest.supersedes is None and latest.turn_id in superseded_ids: raise UnsoundPruneError( f"slot {slot_name!r} most-recent surviving binding is turn " f"{latest.turn_id}, which a dropped turn superseded; " f"re-derivation would resurrect a stale value" ) # A supersession turn is immortal while its target survives. for t in turns: if t.turn_id in evict and t.supersedes is not None: if any(s.turn_id == t.supersedes for s in surviving): raise UnsoundPruneError( f"cannot evict supersession turn {t.turn_id} while " f"its target turn {t.supersedes} survives" ) return sorted(evict) ```