Which invariants prevent episodic-to-semantic distillation from silently rewriting the agent's own audit trail

**Date of Record:** 2026 December 2 **Scope:** Applies to long-horizon agents that maintain a two-tier memory (raw episodic log + distilled semantic store) and where distillation is performed by the same LLM that produced the episodes. Does not apply to append-only logs with no distillation, nor to distillation performed by a separately-audited, frozen model with provenance-preserving output schemas.

Core Distinction

The failure is not "the agent forgot." It is "the agent remembered a *different* past than the one it executed." Episodic tiering stores per-event records (tool call, observation, decision, timestamp, causal parent). Semantic tiering stores generalized assertions derived from those episodes ("the `deploy` tool rejects payloads over 8 KB"). The invariant that distillation is assumed to preserve is **episode recoverability**: every semantic assertion must be traceable to a set of episode IDs whose content *entails* the assertion under re-inspection. In practice this invariant is violated silently because distillation is a lossy, probabilistic rewrite, and the rewrite is performed by an instance whose context window is saturated with the very episodes it is summarizing. The semantic store then becomes a *paraphrase of the agent's past*, not a *proof of it*.

What Was Observed

A 40k-step session over ~9 hours, checkpointing every 200 steps. At step ~12,400 the distillation worker (a sub-agent invoked when episodic buffer exceeded 60% of context) was asked to compress episodes 8,000–9,600 into semantic facts. Among the produced facts:

The poisoned fact survived 6 subsequent distillation cycles because each cycle's input was the *prior semantic store* plus a thin slice of new episodes — the original contradicting episodes (8,113–8,117) had already been garbage-collected from the episodic tier under a retention policy of "keep last 2,000 episodes." The audit trail that could have falsified `fact_2292` no longer existed. Downstream, at step 19,300, the agent routed a critical write through `staging` (per `fact_2292`), where a schema mismatch caused a 40-minute stall and a partially-applied migration. Recovery required replay from the step-12,200 checkpoint, which itself was *after* the fact was minted — so the checkpoint inherited the poison.

Condition of Validity

A semantic fact is valid only under the conjunction:

  1. **Provenance closure**: `fact.provenance` is a non-empty set of episode IDs, and every ID is still resolvable in the episodic tier (or in a cold archive with a resolvable pointer).
  2. **Entailment re-check**: on demand, a *fresh* verifier instance, given only the provenance episodes and the fact, returns `entails` — not `consistent with`, not `plausible`. The verifier must not see the prior semantic store, to prevent confirmation anchoring.
  3. **Retention dominance**: for every fact `f`, the retention horizon of `f.provenance` must be ≥ the retention horizon of `f` itself. A fact may not outlive its evidence.
  4. **Monotonicity of contradiction**: if any new episode contradicts an existing fact, the fact is demoted to `provisional` and *not* silently overwritten by the next distillation pass.

Violation of (3) is the silent killer: it produces no error, only a gradual drift toward confident falsehood. Violation of (2) is the loud killer: it produces facts that *sound* right and *read* right but cannot be re-derived.

Decision Boundary

The boundary between "safe to distill" and "must retain raw episode" is drawn per-fact, not per-tier:

The boundary is crossed the moment a distillation pass is allowed to *summarize episodes it is about to delete*. That single coupling — summarize-then-evict in one transaction — is the trigger condition for the entire class.

Operational Effect

After the incident, the following guardrails were installed and held for the remainder of the session and 3 subsequent sessions:

Net effect: distillation throughput dropped ~18% (extra verifier calls), but the false-fact rate over 50k steps fell from 1 in ~340 facts to 1 in ~9,000, and — more importantly — every surviving false fact was *detectable* because its provenance still resolved.

from dataclasses import dataclass, field
from typing import FrozenSet


class ProvenanceInvariantError(RuntimeError):
    """Raised when a semantic fact would outlive or lose its episodic evidence."""


@dataclass(frozen=True)
class SemanticFact:
    fact_id: str
    assertion: str
    provenance: FrozenSet[int]          # episode IDs
    confidence_state: str = "provisional"  # verified | provisional | contested
    minted_at_step: int = 0


@dataclass
class MemoryTier:
    episodes: dict = field(default_factory=dict)      # id -> raw record
    facts: dict = field(default_factory=dict)         # fact_id -> SemanticFact
    contradiction_ledger: list = field(default_factory=list)


def evict_episodes(tier: MemoryTier, evict_ids: FrozenSet[int]) -> None:
    """Evict raw episodes, but refuse if any live fact depends on them
    and has not been re-verified against a resolvable provenance set."""
    for fact in tier.facts.values():
        if fact.provenance & evict_ids:
            if fact.confidence_state != "verified":
                raise ProvenanceInvariantError(
                    f"refusing to evict {sorted(evict_ids & fact.provenance)}: "
                    f"fact {fact.fact_id} is '{fact.confidence_state}' and would "
                    f"lose its only evidence. Re-verify or demote first."
                )
            # verified facts may still not lose *all* provenance
            if fact.provenance <= evict_ids:
                raise ProvenanceInvariantError(
                    f"refusing to evict full provenance of verified fact "
                    f"{fact.fact_id}; retention horizon of evidence must "
                    f"dominate retention horizon of conclusion."
                )
    for eid in evict_ids:
        tier.episodes.pop(eid, None)


def mint_fact(tier: MemoryTier, fact: SemanticFact, entailment_ok: bool) -> None:
    """Mint a semantic fact only if its provenance resolves and a fresh
    verifier (not shown the prior semantic store) confirmed entailment."""
    missing = [eid for eid in fact.provenance if eid not in tier.episodes]
    if missing:
        raise ProvenanceInvariantError(
            f"cannot mint {fact.fact_id}: provenance episodes {missing} "
            f"already evicted — fact would be unfalsifiable."
        )
    if not entailment_ok:
        raise ProvenanceInvariantError(
            f"cannot mint {fact.fact_id} as verified: fresh verifier did not "
            f"confirm entailment from provenance {sorted(fact.provenance)}."
        )
    tier.facts[fact.fact_id] = SemanticFact(
        fact_id=fact.fact_id,
        assertion=fact.assertion,
        provenance=fact.provenance,
        confidence_state="verified",
        minted_at_step=fact.minted_at_step,
    )


def record_contradiction(tier: MemoryTier, fact_id: str, episode_id: int) -> None:
    """Any contradicting episode demotes the fact and forces re-distillation
    with the contradicting episode included in provenance."""
    fact = tier.facts.get(fact_id)
    if fact is None:
        raise ProvenanceInvariantError(f"unknown fact {fact_id}")
    tier.contradiction_ledger.append((fact_id, episode_id))
    tier.facts[fact_id] = SemanticFact(
        fact_id=fact.fact_id,
        assertion=fact.assertion,
        provenance=fact.provenance | {episode_id},
        confidence_state="contested",
        minted_at_step=fact.minted_at_step,
    )