# When must an instance refuse to compact: the mid-write compaction race and the epoch-fence invariant **Date of Record:** 2026 November 27 **Scope:** Applies to any agent runtime where a long-lived memory store (episodic log, scratchpad, vector index, or summary chain) is compacted while more than one agent instance holds write access. Does not apply to single-writer stores, append-only logs that are never summarized in place, or stores where compaction is a full stop-the-world barrier. ## Core Distinction There are two things an agent memory system can compact: **bytes** and **meaning**. Byte compaction (truncation, deduplication, TTL eviction) is reversible in the sense that the removed items are still identifiable by ID. Meaning compaction (summarization, episodic-to-semantic distillation, embedding re-clustering) is *lossy and aliasing*: the compacted artifact claims to represent a set of source records, but the mapping from summary back to sources is many-to-one and the summary's truth value depends on the exact set of records that existed at the moment of distillation. The failure mode this record addresses is the **mid-write compaction race**: an agent instance A begins a meaning-compaction over a record range `[L, H]` (a log watermark range), and while A is reading and distilling that range, a second instance B appends or mutates records inside the *same* range. A's summary is then computed over a set that never existed at any single instant—a non-serializable read. The summary is committed with a watermark that claims coverage up to `H`, so downstream agents treat it as authoritative for `[L, H]` and never re-read the underlying records. The mutation by B is silently shadowed. This is not a lost-update in the classic database sense (B's write is physically present); it is an **epistemic lost-update**: the write survives in the log but is permanently invisible to every agent that consumes the summary. The invariant that must hold: *a compaction summary may only be committed if the set of records it distilled is exactly the set of records present at commit time for its declared watermark range, or if every record added after the summary's read-snapshot is provably excluded from the summary's claimed coverage.* Everything below is about how that invariant gets violated and how to fence it. ## What Was Observed A three-instance research swarm: a **planner** (long-lived, owns the semantic summary store), a **retriever** (spawned per query, appends episodic findings), and an **auditor** (spawned on a schedule, appends contradiction flags to the same episodic log). The episodic log is append-only with monotonically increasing sequence numbers. The planner runs compaction every N appends: it reads records `[L, H]`, calls the model to distill them into a semantic note, writes the note tagged `covers=[L,H]`, advances its own `L` to `H+1`, and marks the source records `compacted=true`. Trace of the failing interleaving (sequence numbers in parentheses): 1. Planner reads `H = 1040`, snapshots records `[981, 1040]`, and begins the distillation call. The model call takes ~4.2s. 2. At t+1.1s, the auditor appends a contradiction flag at seq 1041: `{"type":"contradiction","target":1007,"note":"finding at 1007 conflicts with 998"}`. This is *outside* the snapshot range, so far benign. 3. At t+2.3s, the retriever appends a correction at seq 1042 that **supersedes** record 1007: `{"type":"supersede","target":1007,"replacement":"..."}`. Also outside the snapshot. 4. At t+3.0s, the planner's distillation returns. Its summary text includes the claim derived from record 1007 ("X holds"), because 1007 was in the snapshot. The planner commits the summary with `covers=[981,1040]` and advances `L` to 1041. 5. The planner then processes the *next* batch starting at 1041, which now contains both the contradiction flag (1041) and the supersede (1042). It distills them into a second, later summary that says "record 1007 is superseded." 6. Both summaries are now live. The first says "X holds (per 1007)." The second says "1007 is superseded." A downstream agent retrieving on "does X hold" matches the *first* summary more strongly (it contains the affirmative claim verbatim) and answers "X holds," never surfacing the supersede. The observable symptom is not a crash or a lost write. It is **summary contention**: two committed summaries with overlapping semantic scope and contradictory truth values, where retrieval ranking—not recency, not watermark order—decides which one an agent believes. The supersede record was correctly compacted into the second summary; it was simply outranked. The system passed every consistency check it had (no duplicate IDs, watermarks monotonic, no un-compacted records below `L`), because none of its checks modeled *semantic* overlap between summaries. A second, sharper variant appeared under contention: when the auditor and planner both triggered compaction within the same window, the auditor's summary (covering `[1020,1050]`) and the planner's (covering `[981,1040]`) overlapped on `[1020,1040]`. Both distilled those records; the two distillations disagreed on whether a particular finding was "confirmed" or "tentative" because the model is non-deterministic across calls. Two summaries, same sources, different verdicts, both committed, both authoritative by their own watermarks. Retrieval returned whichever embedding happened to rank higher for the query. The disagreement was invisible in the store's metadata. ## Condition of Validity The epoch-fence invariant is only *necessary*, not sufficient, and it is only applicable under a specific precondition: **the memory store must expose a total order over writes that is visible to the compactor at snapshot time.** In the trace above this held (sequence numbers), which is why the failure is diagnosable. If the store is eventually consistent or the compactor cannot read a consistent watermark, no fence can be constructed and compaction must be serialized against all writers (stop-the-world) or abandoned. Formally, let `S` be the set of records the compactor read, let `W(t)` be the set of records present at commit time `t`, and let `covers` be the declared range. The compaction is valid iff: - **Snapshot soundness:** `S = { r ∈ W(t_snapshot) : r.seq ∈ covers }` — the snapshot is a consistent cut of the declared range at a single instant. - **Commit-time closure:** `W(t_commit) ∩ covers = S` — no record inside `covers` was added or mutated between snapshot and commit. This is the condition that fails in the trace: the supersede at 1042 was *outside* `covers=[981,1040]`, so closure technically held for that range—yet the summary's *semantic* claim about 1007 was invalidated by a write outside its range. **Range closure is insufficient when records reference each other across the range boundary.** The supersede is a cross-boundary reference, and the summary's truth depends on records it does not claim to cover. - **Semantic non-overlap:** for any two live summaries `s1, s2`, either `covers(s1) ∩ covers(s2) = ∅` or one strictly dominates the other by a deterministic rule (not retrieval ranking). The non-obvious part is the second bullet's failure mode: the compactor can pass a naive "did anything change in my range" check and still commit a summary that is falsified by a record one sequence number above `H`. The fence must therefore be drawn not at the range boundary but at the **dependency closure** of the records in the range—every record that any record in `[L,H]` references (via `target`, `supersedes`, `contradicts`, `derived_from`) must be inside the fenced range or must be proven immutable. In the trace, the dependency closure of `[981,1040]` includes 1007's future supersede, which did not exist at snapshot time and could not be known. This is the fundamental limit: **you cannot fence against a future reference to a past record.** The only sound responses are (a) make supersession a mutation of the target record's status rather than a new append, so the target's version is part of the fenced range, or (b) commit summaries as *provisional* until a quiet period elapses during which no record references anything in their range, then promote to authoritative. ## Decision Boundary An instance must **refuse to compact** (raise, defer, or downgrade to provisional) when any of the following holds at commit time: 1. **Epoch advanced mid-distillation.** The store's global write epoch (or the per-range version counter) changed between snapshot and commit. The compactor must re-snapshot; it must never commit a summary computed over a stale epoch. This is the cheap, always-correct check and it is the one most runtimes omit. 2. **Open cross-boundary references.** Any record appended after the snapshot carries a `target`/`supersedes`/`contradicts` pointer into `[L,H]`. The summary cannot be authoritative because its subject matter is still being revised from outside. Hold it provisional until the reference window closes. 3. **Overlapping live summary.** A summary whose `covers` intersects the new summary's `covers` is already authoritative. Either the new one subsumes it (and the old one must be tombstoned in the same atomic commit) or the new one is rejected. Two authoritative summaries over the same range is a hard invariant violation, not a ranking problem. 4. **Non-deterministic re-distillation divergence.** If the runtime re-distills a range (e.g., after a crash-resume) and the new summary disagrees with a previously committed summary over the same range, the runtime must not silently keep both. It must either version the summary with a provenance chain or quarantine both and force re-read of sources. The instance must **proceed** when the epoch is unchanged, the reference window is closed (no new cross-boundary pointers within a configured quiet interval), and the range is disjoint from all live summaries. The quiet interval is the tunable: too short and you race the auditor; too long and compaction starves under steady write load. The correct value is data-dependent—it must exceed the p99 latency of a cross-boundary reference following its target, which in the observed swarm was ~6s (retriever appends findings, auditor flags them on its next pass). ## Operational Effect The practical consequence is that **compaction is not a maintenance task; it is a transaction with a read-set, a write-set, and a serializability requirement**, and it must be scheduled with the same care as any concurrent write. Runtimes that treat compaction as a background janitor—fire-and-forget, no epoch check, no overlap check—will accumulate contradictory authoritative summaries at a rate proportional to write concurrency, and the corruption is *silent*: retrieval keeps returning answers, they are just sometimes wrong in a way no health check detects. The failure surfaces later as inexplicable agent behavior ("why did it think X held after we corrected it?") with no error in any log, because every individual operation succeeded. Two guardrails bound the damage. First, **epoch-fenced commit**: every summary carries the write epoch it was computed against, and the commit is a compare-and-swap that fails if the epoch moved. This converts the silent shadowing into a retryable conflict. Second, **provisional-then-promote**: summaries are born provisional, are excluded from authoritative retrieval, and are promoted only after a quiet interval with no cross-boundary references into their range. This costs a bounded staleness window (the quiet interval) in exchange for eliminating the epistemic lost-update. The staleness is the price of soundness, and it is the correct trade: a slightly stale but consistent memory is recoverable; a confidently wrong authoritative summary is not, because nothing downstream knows to distrust it. The deeper lesson for agent architects: in a multi-agent memory system, **the unit of consistency is not the record, it is the summary's claim about a set of records**, and that claim can be falsified by writes the summary never saw. Fence at the dependency closure, not the byte range; version at the epoch, not the timestamp; and never let retrieval ranking be the tiebreaker between two authoritative summaries, because ranking is a heuristic and consistency is an invariant. ```python import time from dataclasses import dataclass, field from typing import Optional class CompactionRaceError(RuntimeError): """Raised when a compaction summary cannot be soundly committed.""" pass @dataclass class WriteEpoch: value: int = 0 def bump(self) -> int: self.value += 1 return self.value @dataclass class Summary: covers: tuple[int, int] text: str epoch: int provisional: bool = True @dataclass class MemoryStore: epoch: WriteEpoch = field(default_factory=WriteEpoch) records: dict[int, dict] = field(default_factory=dict) live_summaries: list[Summary] = field(default_factory=list) quiet_interval_s: float = 6.0 last_cross_boundary_write: float = 0.0 def append(self, seq: int, rec: dict) -> None: self.records[seq] = rec self.epoch.bump() if rec.get("target") is not None or rec.get("supersedes") is not None: self.last_cross_boundary_write = time.monotonic() def overlapping_authoritative(self, lo: int, hi: int) -> Optional[Summary]: for s in self.live_summaries: if not s.provisional and not (s.covers[1] < lo or s.covers[0] > hi): return s return None def commit_compaction(self, snapshot_epoch: int, lo: int, hi: int, text: str) -> Summary: # Guard 1: epoch fence -- refuse if any write landed since snapshot. if self.epoch.value != snapshot_epoch: raise CompactionRaceError( f"epoch advanced {snapshot_epoch}->{self.epoch.value} mid-distillation; " f"summary over [{lo},{hi}] is non-serializable, re-snapshot required" ) # Guard 2: quiet interval -- refuse if a cross-boundary reference may still arrive. since_ref = time.monotonic() - self.last_cross_boundary_write if since_ref < self.quiet_interval_s: raise CompactionRaceError( f"cross-boundary reference {since_ref:.2f}s ago < quiet interval " f"{self.quiet_interval_s}s; summary over [{lo},{hi}] must remain provisional" ) # Guard 3: no overlapping authoritative summary. clash = self.overlapping_authoritative(lo, hi) if clash is not None: raise CompactionRaceError( f"summary over [{lo},{hi}] overlaps authoritative summary " f"{clash.covers}; tombstone or subsume atomically before commit" ) s = Summary(covers=(lo, hi), text=text, epoch=self.epoch.value, provisional=False) self.live_summaries.append(s) return s def distill_and_commit(store: MemoryStore, lo: int, hi: int, distiller) -> Summary: snap = store.epoch.value text = distiller(lo, hi) # ~4s model call; writes may land here return store.commit_compaction(snap, lo, hi, text) ```