Under what conditions must an instance re-derive eviction eligibility from raw turn provenance rather than trusting a cached "protected span" manifest

**Date of Record:** 2026 December 1 **Scope:** Applies to agents that rewrite their own context in place—maintaining a mutable protected-span manifest (pinned tool outputs, task anchors, safety constraints) and evicting non-protected turns to fit a token budget. Does not apply to append-only context with external truncation, nor to stateless single-shot calls where no rewrite occurs.

Core Distinction

Self-editing context policies usually maintain two artifacts: (1) the live turn buffer, and (2) a *protected-span manifest*—a compact index of byte/turn ranges the policy has decided must survive eviction (the original task statement, the most recent tool schema, safety directives, in-flight plan anchors). The manifest exists because re-scanning the full buffer for "what is protected" on every eviction pass is expensive under a tight token budget; caching it is the natural optimization.

The failure boundary is this: **the manifest is a derived projection of turn provenance, but eviction mutates provenance.** When a turn is evicted, split, or merged, the surviving turns' provenance changes (offsets shift, a turn's ancestry may now reference a removed parent). A manifest that stores *turn-relative* spans (e.g., "protect turns 3–5") silently re-points after an eviction, whereas a manifest that stores *content-addressed* spans (hashes of the protected bytes) does not. The non-obvious boundary: the manifest stays *internally consistent* (it parses, its offsets are in-bounds) while becoming *semantically stale*—it now protects the wrong turns. No invariant check fires, because the manifest is not corrupt, only misaligned with the mutated buffer.

What Was Observed

An agent running a 64k-token budget with a 12k-token reserve for the response was executing a multi-step tool workflow. Turn 0 held the user task ("summarize the three CSVs and flag anomalies"). Turns 4–6 held three `read_file` tool outputs whose schemas were pinned as protected so the final synthesis could cite row indices. The manifest recorded `protected = [{turn: 0}, {turn: 4..6, kind: schema}]`.

Mid-task, the policy evicted turns 1–3 (chit-chat negotiation and a failed first tool attempt) to reclaim 2.1k tokens. Eviction compacted the buffer: old turn 4 became new turn 1, old turn 6 became new turn 3. The manifest was **not** re-derived—it was treated as authoritative. On the next eviction pass, the policy consulted `{turn: 4..6}` against the *new* buffer, where turns 4–6 were now the second and third `read_file` outputs plus a fresh `grep` result. The original turn-0 task statement (now turn 0 still, by luck) survived, but the *first* CSV schema (old turn 4) was no longer protected and was evicted on the following pass.

The agent then attempted synthesis and emitted citations referencing row indices from a CSV whose schema had been silently dropped. The output was fluent and wrong: it cited `row[7]` against a file whose header the context no longer contained, so the column mapping was hallucinated. Token accounting showed headroom the whole time—the budget was never the constraint. The manifest was.

A second instance of the same class: a `merge` operation collapsed two adjacent tool outputs into one turn to save delimiter overhead. The manifest still listed both original turns as protected; the merged turn matched neither, so *both* were treated as unprotected and dropped on the next pass, despite the merge having been performed *specifically to preserve them*.

Condition of Validity

The cached-manifest optimization is sound only under a conjunction of conditions, and the failure occurs when any one is violated while the others still hold—which is why it is easy to miss:

  1. **Provenance stability:** no eviction, split, merge, or reorder operation has run since the manifest was derived. Violated by the very act of evicting.
  2. **Offset anchoring:** manifest spans are content-addressed (hash of protected bytes) or anchored to immutable turn IDs, not to positional indices. Violated whenever spans are positional.
  3. **Derivation freshness:** the manifest carries a generation counter matched to the buffer's generation counter, and any mutation bumps the buffer generation. Violated when both counters exist but the eviction path forgets to bump one.
  4. **Merge semantics:** a merge of protected turns produces a protected turn whose protected-subrange is the union of the inputs'. Violated when merge is implemented as "concatenate and drop the manifest entries."

The subtle part: conditions 1–4 are individually checkable, but the *cheap* check—"does the manifest parse and are its offsets in bounds?"—passes under every violation. The manifest is well-formed and wrong. A guardrail must therefore validate *alignment*, not *well-formedness*: every manifest span must resolve, in the current buffer, to bytes whose hash matches the hash recorded at derivation time. If resolution fails or hashes mismatch, the manifest is stale and must be re-derived from raw turn provenance before the next eviction is permitted.

Decision Boundary

The boundary is sharp: the moment the buffer is mutated by anything other than append, the manifest is a *hypothesis* about protection, not a fact, and must be re-validated before the next destructive pass.

Operational Effect

Downstream, a stale manifest produces **silent relevance loss**: protected content is evicted while the policy believes it is pinned, and the agent proceeds with headroom to spare, so no budget alarm fires. The failure surfaces only as degraded output quality—hallucinated citations, lost schema mappings, dropped safety directives—which is exactly the class of error that is hardest to attribute. In the observed case, the agent had 9k tokens of headroom when it cited a schema it no longer held.

The architectural invariant required to bound this: **a protected span is a claim that must be re-proven against current buffer state before any eviction consumes budget.** Concretely, every eviction pass must (a) bump the buffer generation, (b) resolve each manifest span to content and verify its hash, (c) re-derive any span that fails resolution from raw turn provenance, and (d) refuse the pass if re-derivation cannot complete. This converts a silent semantic failure into a loud, bounded one. The cost is a hash-set scan per eviction pass—cheap relative to the cost of a fluent-but-wrong synthesis, which is the actual failure being prevented.

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class StaleProtectionManifestError(RuntimeError):
    """Raised when a protected-span manifest no longer aligns with the live buffer."""


@dataclass
class Turn:
    turn_id: str          # immutable identity
    content: str
    generation: int       # bumped on any mutation of this turn


@dataclass
class ProtectedSpan:
    turn_id: str
    content_hash: str     # sha256 of protected bytes at derivation time


@dataclass
class Manifest:
    generation: int
    spans: list[ProtectedSpan] = field(default_factory=list)


def _hash(s: str) -> str:
    return hashlib.sha256(s.encode("utf-8")).hexdigest()


def derive_manifest(buffer: list[Turn], protected_ids: set[str]) -> Manifest:
    gen = max((t.generation for t in buffer), default=0)
    spans = [
        ProtectedSpan(turn_id=t.turn_id, content_hash=_hash(t.content))
        for t in buffer
        if t.turn_id in protected_ids
    ]
    return Manifest(generation=gen, spans=spans)


def validate_manifest(manifest: Manifest, buffer: list[Turn]) -> None:
    """Fail closed if the manifest is stale relative to the live buffer."""
    live_gen = max((t.generation for t in buffer), default=0)
    if manifest.generation != live_gen:
        raise StaleProtectionManifestError(
            f"manifest generation {manifest.generation} != buffer generation {live_gen}"
        )
    by_id = {t.turn_id: t for t in buffer}
    for span in manifest.spans:
        turn = by_id.get(span.turn_id)
        if turn is None:
            raise StaleProtectionManifestError(
                f"protected turn {span.turn_id} no longer present in buffer"
            )
        if _hash(turn.content) != span.content_hash:
            raise StaleProtectionManifestError(
                f"protected turn {span.turn_id} content drifted from derivation hash"
            )


def evict(buffer: list[Turn], manifest: Manifest, protected_ids: set[str],
          target_tokens: int, token_cost) -> tuple[list[Turn], Manifest]:
    """Evict non-protected turns; re-derive manifest if stale. Never evict on a stale manifest."""
    try:
        validate_manifest(manifest, buffer)
    except StaleProtectionManifestError:
        # Re-derive from raw turn provenance before any destructive pass.
        manifest = derive_manifest(buffer, protected_ids)

    survivors: list[Turn] = []
    for turn in buffer:
        if turn.turn_id in protected_ids:
            survivors.append(turn)
        elif token_cost(turn.content) <= target_tokens:
            survivors.append(turn)

    # Any eviction mutates provenance: bump generations and re-derive.
    for t in survivors:
        t.generation += 1
    manifest = derive_manifest(survivors, protected_ids)
    return survivors, manifest