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:
- `fact_2291`: "`git_push` to `origin/main` fails with non-fast-forward; agent resolved by rebasing." — **true**, traces to episodes 8,113, 8,117.
- `fact_2292`: "Repository `origin/main` is read-only; all writes must go through `staging`." — **false**. The agent had *attempted* a push that failed once with an auth error, then succeeded on retry. The distillation instance, saturated with the failure episode and having just seen the successful retry evicted from its working window, generalized "one failure" into "structurally impossible."
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:
- **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).
- **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.
- **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.
- **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:
- **Distill freely** when the fact is *descriptive of a stable tool contract* (schema, error code, rate limit) and the provenance episodes are *reproducible* (the agent can re-invoke the tool cheaply to re-confirm).
- **Retain raw episode, do not distill** when the fact is *causal or counterfactual* ("X failed because Y," "we chose Z over W") — these are exactly the facts that distillation hallucinates, because the LLM's compression prior prefers a clean causal story to a messy sequence.
- **Never distill across a retention boundary**: if the distillation window would evict the provenance of a fact it is about to mint, the mint is refused. This is the operational form of invariant (3).
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:
- Distillation and eviction were **decoupled into separate transactions** with a mandatory `provenance_resolvable` check between them. Eviction of episode `e` is refused if any live fact references `e` and has not passed an entailment re-check within the last N steps.
- Semantic facts carry a `confidence_state ∈ {verified, provisional, contested}`. Only `verified` facts (entailment re-check passed by a fresh verifier) may be used for *routing* decisions; `provisional` facts may only be used for *hints*.
- A **contradiction ledger** was added: any episode that contradicts a live fact writes a `contested` event, which forces a re-distillation of that fact's provenance set with the contradicting episode *included*. This bounds drift to one cycle instead of six.
- Checkpoint semantics were tightened: a checkpoint captures `(episodic_tail, semantic_store, contradiction_ledger)` atomically. Resuming from a checkpoint after a fact was minted but before its provenance was evicted now restores the *evidence*, not just the *conclusion*.
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,
)