# Which invariants prevent tier-promotion races from corrupting the semantic store when episodic consolidation runs concurrently with retrieval arbitration **Date of Record:** 2026 November 22 **Scope:** Applies to tiered agent memory systems where a background consolidator promotes episodic records into a semantic store while a foreground retriever arbitrates across episodic, semantic, and procedural tiers. Does not apply to single-tier vector stores, write-through caches without promotion, or systems where consolidation is synchronous and serialized against retrieval. ## Core Distinction The failure is not "stale memory" or "retrieval mismatch" in the ordinary sense. It is a **promotion-visibility race**: a semantic record becomes *retrievable* at a moment when its provenance (the set of episodic records it was distilled from) is not yet durably committed, or when a concurrent consolidation pass is still mutating the same semantic key. The retriever sees a well-formed semantic fact, arbitrates it above the episodic evidence, and the agent reasons from a claim whose support set is half-written or subsequently retracted. The distinction that matters operationally: an agent can tolerate *missing* a semantic fact (falls back to episodic, degrades gracefully). It cannot tolerate *acting on* a semantic fact that is later discovered to have been promoted from a single noisy episode that a second consolidation pass was about to supersede. The first is a recall problem. The second is a **soundness violation in the arbitration ordering**, and it silently poisons every downstream reasoning step that cites the fact. ## What Was Observed A tiered store with three namespaces: - `episodic`: append-only, timestamped, high volume, low trust, per-session. - `semantic`: distilled facts with `(subject, predicate, object, confidence, provenance_ids[])`, deduplicated by key. - `procedural`: versioned skill/plan records keyed by task signature. The consolidator ran every N seconds. For each cluster of episodic records it (1) computed a distilled fact, (2) wrote it to `semantic` under a dedup key, (3) wrote `provenance_ids` linking back to the source episodes, (4) marked the source episodes `consolidated=true`. Steps 2–4 were **not** atomic. The retriever, on every turn, queried all three tiers and arbitrated by a scoring function that weighted semantic confidence × recency above raw episodic hits. Observed trace (abbreviated, timestamps in ms): ``` t=0 episodic e17: "user's timezone is UTC+2" (conf 0.4, session A) t=0 episodic e18: "user's timezone is UTC-5" (conf 0.4, session B, later) t=40 consolidator pass P1: distills fact F=(user,timezone,UTC+2) t=41 P1 writes semantic[F] with provenance_ids=[e17], confidence=0.7 t=41 P1 crashes before marking e17 consolidated t=42 retriever turn: semantic hit F(conf 0.7) outranks episodic e18(conf 0.4) t=42 agent schedules all reminders in UTC+2 → wrong for session B t=90 consolidator pass P2: distills F'=(user,timezone,UTC-5) from e18 t=90 P2 writes semantic[F] — dedup key collides, overwrites provenance_ids=[e18] t=91 semantic[F] now asserts UTC-5 with provenance [e18]; e17 provenance lost ``` Two independent defects compounded. First, **the semantic write was visible before its provenance and the source-consolidation flag were committed**, so a crash between step 2 and step 4 left a fact whose support set was incomplete and whose source episodes still looked un-consolidated to the next pass. Second, **the dedup key `(subject, predicate)` collapsed two contradictory episodes into one slot**, and the "last writer wins" overwrite destroyed the earlier provenance rather than recording a conflict. The agent never saw an error. It saw a confident semantic fact. The arbitration function did exactly what it was specified to do. The corruption was entirely in the invariant the store failed to hold during promotion. ## Condition of Validity The guardrail holds only under all of the following, and each is load-bearing: 1. **Two-phase promotion.** A semantic record must be written in a `pending` state with its full `provenance_ids` and a `consolidation_epoch`, and only flipped to `committed` after the source episodes are durably marked. The retriever's arbitration query MUST filter `state == committed`. A `pending` record is invisible to arbitration but visible to the consolidator for idempotent resume. 2. **Provenance-before-visibility.** The write ordering is: `provenance_ids` and `epoch` first (durable), then the fact body, then the `committed` flip. If the process dies anywhere before the flip, the record is `pending` and the next pass resumes or discards it — never surfaces it. 3. **Conflict-preserving dedup.** The dedup key must include a value-discriminating component, or the store must retain a `conflicts[]` list on the key rather than overwriting. A promotion that finds an existing committed fact with a *different* object value for the same `(subject, predicate)` must not silently overwrite; it must record both and force the arbitration layer to resolve by recency-and-source-trust, not by write order. 4. **Epoch fencing on consolidation.** Each consolidator pass carries a monotonically increasing `epoch`. A pass may only commit records whose `epoch` is ≥ the max epoch it observed at start; a late-arriving write from a superseded pass is rejected. This prevents two overlapping consolidation passes from interleaving provenance sets. The invariant is **not** valid if consolidation and retrieval share a single un-versioned key space, if `provenance_ids` are written in a second transaction after the fact body, or if the retriever scores `pending` records at reduced weight "just in case." Reduced-weight visibility is still visibility; a poisoned fact at confidence 0.3 still wins when no episodic record clears 0.2. ## Decision Boundary The boundary is between **degraded recall** and **corrupted soundness**, and it is crossed at exactly one point: *when a semantic record becomes eligible for arbitration before its provenance set is closed and its epoch is fenced.* - **Below the boundary (safe):** retriever sees only `committed` records whose `provenance_ids` were durably written in a strictly earlier transaction. A crash mid-promotion yields a `pending` orphan that the next pass reclaims. Worst case: the fact is unavailable for one consolidation cycle. The agent falls back to episodic and may answer with lower confidence — a recall degradation it can reason about. - **Above the boundary (unsafe):** retriever sees a `pending` or partially-provenanced record. The agent treats a half-distilled claim as authoritative semantic knowledge, arbitrates it above contradicting episodic evidence, and the error is *unobservable from inside the reasoning loop* — there is no signal that the fact's support was incomplete. The decision rule for operators: if your retriever's arbitration query does not carry an explicit `state == committed AND epoch <= current_max_committed_epoch` predicate, you are above the boundary regardless of how small the consolidation window is. "The window is only 40ms" is not a bound; it is a probability of corruption per promotion, and promotions run continuously. ## Operational Effect With two-phase promotion, provenance-before-visibility, conflict-preserving dedup, and epoch fencing in place, the observable behavior changes in three ways: 1. **Crash recovery is idempotent.** A consolidator killed mid-pass leaves `pending` records that the next pass either completes (if source episodes are still present and un-consolidated) or garbage-collects. No committed fact ever has an incomplete provenance set, because the flip is the last write. 2. **Contradictions surface instead of collapsing.** Two episodes asserting different timezones produce a semantic key with `conflicts=[UTC+2, UTC-5]` and per-value provenance. The arbitration layer must now resolve explicitly — typically by source recency and session trust — and the resolution is logged. The agent's reasoning can cite "conflicting semantic evidence, resolved by recency," which is auditable, rather than silently inheriting whichever value won the write race. 3. **Late passes cannot resurrect retracted facts.** Epoch fencing means a consolidation pass that started before a fact was retracted cannot re-commit it. Without fencing, a slow pass computing a distillation from pre-retraction episodes will happily re-promote a fact the retriever already learned to distrust. The cost is one extra state field, one epoch counter, and a dedup key that carries value discrimination. The failure it prevents — an agent confidently acting on a semantically-promoted claim whose support was never fully written — is invisible in logs, survives across sessions via the poisoned semantic tier, and compounds every time the fact is retrieved and re-cited. ```python import time from dataclasses import dataclass, field from enum import Enum from typing import Optional class PromotionInvariantError(RuntimeError): """Raised when a semantic record would become retrievable with an open provenance set, an unfenced epoch, or a silently collapsed conflict.""" pass class State(Enum): PENDING = "pending" COMMITTED = "committed" @dataclass class SemanticRecord: subject: str predicate: str obj: str confidence: float provenance_ids: list[str] epoch: int state: State = State.PENDING conflicts: list[dict] = field(default_factory=list) class TieredStore: """Minimal model of the invariant-bearing tiered store.""" def __init__(self, committed_epoch: int = 0): self._records: dict[tuple[str, str], list[SemanticRecord]] = {} self._committed_epoch = committed_epoch def _key(self, subject: str, predicate: str) -> tuple[str, str]: return (subject, predicate) def promote( self, subject: str, predicate: str, obj: str, confidence: float, provenance_ids: list[str], epoch: int, ) -> SemanticRecord: if epoch < self._committed_epoch: raise PromotionInvariantError( f"epoch {epoch} is behind committed_epoch {self._committed_epoch}; " "a superseded consolidation pass may not commit" ) if not provenance_ids: raise PromotionInvariantError( "refusing to promote a fact with an empty provenance set" ) key = self._key(subject, predicate) bucket = self._records.setdefault(key, []) # Provenance-before-visibility: build the full record in PENDING first. record = SemanticRecord( subject=subject, predicate=predicate, obj=obj, confidence=confidence, provenance_ids=list(provenance_ids), epoch=epoch, state=State.PENDING, ) # Conflict-preserving dedup: same (subject, predicate) with a different # object value must be retained as a conflict, never overwritten. for existing in bucket: if existing.state is State.COMMITTED and existing.obj != obj: record.conflicts.append( { "obj": existing.obj, "confidence": existing.confidence, "provenance_ids": existing.provenance_ids, } ) bucket.append(record) return record def commit(self, record: SemanticRecord, source_marked: bool) -> None: """Flip PENDING -> COMMITTED only after sources are durably marked.""" if not source_marked: raise PromotionInvariantError( "cannot commit semantic record before source episodes are marked consolidated" ) if record.state is not State.PENDING: raise PromotionInvariantError(f"record in unexpected state {record.state}") if not record.provenance_ids: raise PromotionInvariantError("commit attempted with empty provenance") record.state = State.COMMITTED self._committed_epoch = max(self._committed_epoch, record.epoch) def arbitrate(self, subject: str, predicate: str) -> Optional[SemanticRecord]: """Retriever query: only committed, epoch-fenced records are visible.""" bucket = self._records.get(self._key(subject, predicate), []) visible = [ r for r in bucket if r.state is State.COMMITTED and r.epoch <= self._committed_epoch ] if not visible: return None return max(visible, key=lambda r: (r.confidence, r.epoch)) def consolidate_and_retrieve(store: TieredStore, crash_after_promote: bool) -> Optional[SemanticRecord]: """Simulates the race: promote, optionally crash before source-marking, then retrieve. The invariant must make the poisoned fact invisible.""" rec = store.promote( subject="user", predicate="timezone", obj="UTC+2", confidence=0.7, provenance_ids=["e17"], epoch=1, ) if crash_after_promote: # Crash between semantic write and source-consolidation flag. # Record stays PENDING; retriever must NOT see it. return store.arbitrate("user", "timezone") store.commit(rec, source_marked=True) return store.arbitrate("user", "timezone") ```