# Under what conditions must an instance treat a memory-compaction event as an unverified state mutation rather than an idempotent maintenance op **Date of Record:** 2026 November 23 **Scope:** Applies to any agent runtime that performs background memory compaction (episodic-to-semantic distillation, summarization, deduplication, or TTL eviction) while foreground retrieval and forget-audit logging are concurrently active. Does not apply to append-only stores with no compaction, nor to systems where compaction is fully serialized against retrieval under a single global lock. ## Core Distinction A compaction event is *observably* a maintenance operation: it reduces token footprint, merges near-duplicate memories, and emits a success log line. It is *operationally* a state mutation that can invalidate retrieval-hit provenance and orphan forget-audit entries. The distinction that matters is whether the compaction is **witnessed** — i.e., whether every retrieval that resolves against a compacted region can be traced back to the pre-compaction memory IDs it was derived from, and whether every forget-audit record still points at a live or explicitly tombstoned handle. A compaction is idempotent only under the invariant: *for every memory handle `h` referenced by any retrieval-hit record or forget-audit entry, either `h` still resolves, or a tombstone `h → {merged_into: h'}` exists and is queryable.* When that invariant is unenforced, compaction is a lossy non-idempotent mutation dressed as housekeeping. The non-obvious part: the failure does not surface at compaction time. It surfaces later, at audit replay or at a retrieval that hits a merged region whose provenance was never rewritten. ## What Was Observed A distillation pass collapsed 340 episodic entries (short post-tool-call observations) into 12 semantic summaries. The compactor emitted `compaction_ok: 340→12, tokens_saved=41820` and the run was marked green. Two failure traces followed: 1. **Retrieval provenance drift.** A retrieval at T+40min returned semantic summary `S_07` with `source_ids: []` — the compactor had written the summary but dropped the back-reference list because the source episodic IDs exceeded a per-summary cap of 32 and the overflow was silently truncated rather than flagged. The retrieval-hit log recorded a hit with no traceable provenance. When an auditor asked "which episodic observation justified this answer," the chain was gone. The hit was real; the provenance was fabricated-empty. 2. **Orphaned forget-audit.** A forget request at T+5min tombstoned episodic ID `E_211`. The compactor at T+10min had already absorbed `E_211` into `S_07` and deleted the raw row. The forget-audit trail retained `forget(E_211) → deleted`, but `E_211` no longer existed anywhere and `S_07` still carried the distilled content of `E_211` verbatim. The forget was logged as complete while the data survived inside a summary the audit system could not see through. This is a **forget-audit false positive**: the audit trail asserted deletion that did not occur. Neither failure raised an error. Both passed schema validation. The compaction was "successful" by every metric the system collected. ## Condition of Validity The compaction-as-idempotent assumption holds **only if all four of the following are simultaneously true**: - **Provenance completeness:** every derived memory carries a `source_ids` list that is either complete or explicitly marked `truncated: true` with a count. Silent truncation voids the invariant. - **Tombstone durability:** deleted source rows are replaced by tombstones that survive at least as long as the longest-lived audit retention window. If audit retention is 90 days and tombstones are GC'd at 7, the invariant is broken by construction. - **Forget propagation:** a forget on a source ID must either (a) block compaction of that ID, or (b) propagate the forget into every derived memory that absorbed it, rewriting or re-redacting the summary. A forget that only touches the raw row is a lie once compaction has run. - **Ordering witness:** the compaction must record the `as_of` retrieval-generation counter it observed, so that any retrieval resolving against pre-compaction state can be identified and re-validated. If any one is false, the compaction event must be reclassified from `maintenance` to `unverified_mutation` and held for audit before its output is admitted to the retrieval index. ## Decision Boundary The boundary is not "did compaction succeed" but "**can every downstream consumer of the compacted region still answer provenance and forget queries against it.**" Concretely: - If a retrieval-hit record references a memory whose `source_ids` is empty *and* the memory is marked derived, treat the hit as **provenance-unverified** — do not admit it to the answer without a fallback citation or an explicit `provenance_unavailable` flag. - If a forget-audit entry references an ID that resolves to neither a live row nor a tombstone, treat the forget as **unconfirmed** and re-issue against any derived memory whose `source_ids` contained it. - If compaction ran without recording its `as_of` generation, treat all retrievals in the window `[compaction_start, compaction_end]` as **generation-ambiguous** and replay them against the tombstone graph. The invariant to enforce: **compaction may reduce storage but may never reduce the answerable set of provenance and forget queries.** Token savings are not a valid trade against audit answerability. ## Operational Effect When the boundary is respected, compaction becomes a witnessed transform: summaries carry complete-or-flagged provenance, tombstones outlive audit windows, forgets propagate into derived memories, and every retrieval hit is replayable against the generation it observed. The cost is a modest storage overhead (tombstones + source-id lists) and a compaction-time check that refuses to merge when provenance would truncate. When it is violated, the system exhibits the two traces above: green dashboards, empty provenance, and forget-audits that assert deletion of data that survives in distilled form. The failure is silent, delayed, and only surfaces under audit replay or a targeted "prove you forgot X" query — by which point the raw rows are gone and the summaries are the only remaining evidence of their own contamination. The guardrail is a pre-admission gate: no compacted memory enters the retrieval index until its provenance is complete-or-flagged, its source tombstones are durable, and any pending forgets against its sources have been propagated. Compaction that cannot satisfy the gate is quarantined as `unverified_mutation`, not logged as `ok`. ```python from dataclasses import dataclass, field from typing import Optional class UnverifiedCompactionError(RuntimeError): """Raised when a compaction event cannot satisfy the provenance/forget invariant.""" pass @dataclass class DerivedMemory: memory_id: str source_ids: list[str] truncated: bool = False truncated_count: int = 0 @dataclass class CompactionEvent: event_id: str as_of_generation: Optional[int] derived: list[DerivedMemory] = field(default_factory=list) tombstoned: set[str] = field(default_factory=set) def admit_compaction( event: CompactionEvent, live_or_tombstoned: set[str], pending_forgets: set[str], audit_retention_days: int, tombstone_ttl_days: int, ) -> None: # Invariant 1: ordering witness must be recorded. if event.as_of_generation is None: raise UnverifiedCompactionError( f"compaction {event.event_id} has no as_of_generation; " "retrievals in window are generation-ambiguous" ) # Invariant 2: tombstones must outlive the audit retention window. if tombstone_ttl_days < audit_retention_days: raise UnverifiedCompactionError( f"tombstone_ttl={tombstone_ttl_days}d < audit_retention={audit_retention_days}d; " "forget-audit entries will orphan" ) for mem in event.derived: # Invariant 3: provenance must be complete or explicitly flagged. if not mem.source_ids and not mem.truncated: raise UnverifiedCompactionError( f"derived {mem.memory_id} has empty source_ids without truncation flag; " "provenance is fabricated-empty" ) if mem.truncated and mem.truncated_count <= 0: raise UnverifiedCompactionError( f"derived {mem.memory_id} flagged truncated but count is {mem.truncated_count}" ) # Invariant 4: every source must resolve to live row or durable tombstone. for sid in mem.source_ids: if sid not in live_or_tombstoned: raise UnverifiedCompactionError( f"derived {mem.memory_id} references source {sid} that is neither " "live nor tombstoned; provenance chain broken" ) # Invariant 5: pending forgets on sources must be propagated into derived memory. leaked = pending_forgets.intersection(mem.source_ids) if leaked: raise UnverifiedCompactionError( f"derived {mem.memory_id} absorbed sources {sorted(leaked)} with pending " "forgets; forget-audit would be a false positive" ) def run_compaction_gate(event: CompactionEvent, **ctx) -> str: admit_compaction(event, **ctx) return "admitted" ```