# How should an instance reconcile a shared-memory eviction race when two agents hold divergent budget ledgers for the same context window **Date of Record:** 2026 November 22 **Scope:** Applies to multi-agent systems where two or more agents share a single bounded memory store (episodic buffer, vector-backed scratchpad, or shared KV cache) and each independently maintains a local token-budget ledger over that store. Does not apply to single-agent context management, nor to isolated per-agent memory partitions with no shared-write surface. ## Core Distinction The failure is not "two agents ran out of context." The failure is that **two agents each believed the shared store had free capacity, because each ledger was debited against a snapshot that the other agent had already invalidated.** Budget accounting is a *local* operation over a *shared* resource. When the resource is mutated by a peer between a reader's snapshot and its write, the ledger's arithmetic remains internally consistent while being globally wrong. This is a lost-update anomaly, but the "lost" quantity is not a row—it is *eviction headroom*. The non-obvious part: eviction policies (LRU, importance-weighted, recency-decay) are *deterministic functions of state*, but the state they read is the state at snapshot time. Two agents running the *same* eviction policy over *divergent* snapshots will compute *different* victims for the *same* eviction request. Neither is buggy. The system has two valid-but-incompatible views, and the reconciliation is where context is silently destroyed. ## What Was Observed A planner agent and an executor agent shared a 64k-token scratchpad. Each held a local ledger: - Planner snapshot at T0: 40k tokens used, 24k free. - Executor snapshot at T0: 40k tokens used, 24k free. - Between T0 and T1, executor wrote 20k tokens of tool output. Executor ledger now: 60k used, 4k free. - Planner, still on its T0 snapshot, attempted a 22k-token reasoning trace write. Planner ledger arithmetic: 40k + 22k = 62k ≤ 64k. **Admitted.** - Executor, at T1, attempted a 3k-token checkpoint write. Executor ledger: 60k + 3k = 63k ≤ 64k. **Admitted.** Both writes passed local admission. Combined demand: 40k + 20k + 22k + 3k = 85k tokens against a 64k store. The store's eviction layer, invoked twice, evicted 21k tokens of *pre-existing* content—including the planner's original task specification and the executor's mid-task checkpoint from three steps prior. Neither agent requested those evictions. Neither agent's ledger recorded them. Both agents continued operating on a store that no longer contained the premises of their own reasoning. The observable symptom was not an error. It was a **silent reasoning divergence**: the planner began re-deriving facts it had already established (because the derivation was evicted), and the executor resumed from a checkpoint that had been evicted and was now hallucinating its own prior state. The system reported success. The output was wrong. ## Condition of Validity This boundary holds under three jointly necessary conditions. Remove any one and the anomaly does not manifest: 1. **Shared mutable store with per-agent local ledgers.** If the ledger is centralized (single writer, single counter), the race collapses. If the store is partitioned, ledgers are disjoint. 2. **Snapshot-based admission.** Each agent computes admission against a *read* of usage, not against an atomic reserve. The gap between read and write is the race window. 3. **Non-idempotent eviction with unlogged victims.** The eviction policy removes content that neither requesting agent named, and the removal is not propagated as a ledger debit to any agent. This is the load-bearing condition: if evictions were debited back to the evicting agent's ledger, the planner would have seen its own write cost 22k *plus* the 21k it forced out, and would have refused. The invariant that must be maintained is exact: **for every admitted write, the sum of (write size + evicted-victim size) must be debited against the requesting agent's ledger, and the victim identities must be recorded in a shared eviction journal that every agent's next snapshot reads.** Without this, "free capacity" is a fiction that each agent computes independently and wrongly. ## Decision Boundary The operational question is not "should we lock the store?" Full locking serializes all agent writes and destroys the concurrency that makes multi-agent systems useful. The decision boundary is narrower: - **Below contention threshold** (observed concurrent writers ≤ 1 per snapshot interval, or store utilization < 70%): optimistic admission with a post-write reconciliation check is sufficient. The race window is small enough that a re-read-and-verify after write catches divergence cheaply. - **Above contention threshold** (≥ 2 concurrent writers per interval, or utilization ≥ 70%): optimistic admission is unsound. The eviction race becomes probable, not incidental, and the silent-divergence failure rate climbs faster than utilization (observed superlinear in the region 70–90%). Here you must either (a) reserve atomically before write, or (b) admit optimistically but *gate the write on a compare-and-swap of the store's version counter*, rejecting and re-planning on mismatch. The subtle trap: agents do not know their own contention level. A planner cannot see how many peers are writing. So the guardrail must be enforced at the store boundary, not in agent logic. The store must expose a version counter and *refuse* writes whose snapshot version is stale—returning a typed rejection the agent is obligated to handle by re-snapshotting and re-deriving, not by retrying blindly (blind retry re-enters the same race with a fresh stale snapshot). ## Operational Effect When the invariant is enforced, the failure mode converts from *silent divergence* to *explicit admission rejection*. This is strictly better: a rejected write is a recoverable event the agent can plan around; an evicted premise is an unrecoverable corruption of the agent's world model that surfaces only as downstream hallucination. The cost is throughput—agents must re-snapshot and re-derive on rejection—but the throughput cost is bounded and observable, whereas the divergence cost is unbounded and invisible. The secondary effect: eviction journals become first-class artifacts. Every agent's next snapshot must include *what was evicted and why*, so that an agent whose premise was evicted can detect the loss and re-fetch rather than silently proceed. Without the journal, even a correctly-serialized store produces amnesiac agents that cannot tell the difference between "I never knew this" and "this was evicted from under me." The journal is what makes the difference legible. ```python from dataclasses import dataclass, field from typing import Optional class StaleSnapshotError(RuntimeError): """Raised when an agent attempts to admit a write against a store version that has been superseded by a peer's write. The agent MUST re-snapshot and re-derive; blind retry re-enters the same race.""" pass class EvictionJournalViolation(RuntimeError): """Raised when an eviction occurs that is not debited to the requesting agent's ledger and not recorded in the shared journal. This is the load-bearing invariant: unlogged evictions are the silent-divergence failure mode.""" pass @dataclass class SharedStore: capacity: int used: int = 0 version: int = 0 journal: list = field(default_factory=list) def snapshot(self) -> tuple[int, int]: return (self.used, self.version) def admit(self, agent_id: str, size: int, snap: tuple[int, int], ledger: "LocalLedger") -> None: snap_used, snap_version = snap if snap_version != self.version: raise StaleSnapshotError( f"agent {agent_id} snapshot v{snap_version} stale; " f"store at v{self.version}. Re-snapshot required." ) free = self.capacity - snap_used if size > free: raise StaleSnapshotError( f"agent {agent_id} requested {size} > free {free} at " f"v{snap_version}. Re-snapshot required." ) # Simulate eviction pressure: if write would overflow, evict. overflow = (snap_used + size) - self.capacity if overflow > 0: victims = self._evict(overflow) # INVARIANT: victims must be debited to requester and journaled. ledger.debit_eviction(agent_id, victims, self.journal) if not self.journal or self.journal[-1]["agent"] != agent_id: raise EvictionJournalViolation( f"eviction by {agent_id} not journaled; " f"unlogged victim removal is forbidden." ) self.used = snap_used + size - max(overflow, 0) self.version += 1 ledger.debit_write(agent_id, size) def _evict(self, amount: int) -> list[str]: victims = [f"chunk_{i}" for i in range(amount)] self.journal.append({"agent": None, "victims": victims}) return victims @dataclass class LocalLedger: agent_id: str debits: list = field(default_factory=list) def debit_write(self, agent_id: str, size: int) -> None: self.debits.append(("write", agent_id, size)) def debit_eviction(self, agent_id: str, victims: list, journal: list) -> None: if not victims: return journal[-1]["agent"] = agent_id self.debits.append(("evict", agent_id, len(victims))) # The requester now pays for the victims it forced out. # Without this line, the planner's ledger would under-report # its true cost and admit the next oversized write. def reconcile(store: SharedStore, agent_id: str, size: int, ledger: LocalLedger, snap: tuple[int, int]) -> None: try: store.admit(agent_id, size, snap, ledger) except StaleSnapshotError: # Correct handling: re-snapshot and re-derive, do NOT blind-retry. fresh = store.snapshot() store.admit(agent_id, size, fresh, ledger) ```