# How does an instance detect and resolve a concurrent memory-write conflict when two agent branches disagree on the same key **Date of Record:** 2026 November 28 **Scope:** Applies to any agent architecture where an instance mutates a persistent memory store (episodic or semantic) and where more than one execution branch—parallel sub-agents, a resumed checkpoint, or a retry after a tool timeout—can write the same memory key without a shared serialization point. Does not apply to single-writer, single-threaded memory stores with a global lock. ## Core Distinction The failure here is not "lost update" in the classical database sense. A database detects write-write conflict via row versions or MVCC and aborts one transaction. An LLM agent does not: it *reasons* about the conflict, and its reasoning is what corrupts the store. The distinction that matters is between **temporal versioning** (the store knows *when* a fact was written and can order writes) and **semantic reconciliation** (the agent must decide *whether* two writes are actually about the same fact, and whether the newer one supersedes or merely coexists). Most memory tools implement the former and assume it implies the latter. It does not. Two writes to key `user.employer` with monotonic timestamps `t1=09:14:02` and `t2=09:14:03` look like a clean last-write-wins. But `t1` may have been written by a branch that read an *older* observation and committed late (a stale-read write), while `t2` was written by a branch that read a *newer* observation. Timestamp order is commit order, not observation order. Last-write-wins therefore silently discards the more recent *knowledge* in favor of the more recent *commit*. The invariant that must hold is: **the version attached to a memory write must reflect the observation epoch the writer reasoned from, not the wall-clock moment it flushed.** Without this, temporal versioning gives a false sense of correctness and forgetting semantics inherit the same defect. ## What Was Observed A planner agent spawned two worker branches (A and B) to research a target organization. Both were instructed to upsert findings into a shared semantic memory namespace under key `org.current_ceo`. - Branch A read a cached profile snapshot (observation epoch `E=40`) and, after a 6.2s tool round-trip, wrote `current_ceo = "R. Okafor"` at commit time `09:14:02.881`. - Branch B read a fresher press release (observation epoch `E=57`) and wrote `current_ceo = "M. Delgado"` at commit time `09:14:02.940`. Both writes succeeded. The store's MVCC layer saw two distinct version vectors and, because they were causally independent (neither branch had read the other's write), it did **not** flag a conflict—it stored both as siblings and returned the one with the higher commit timestamp on read. The next reader (the planner) received `M. Delgado`—correct by luck in this ordering, but only because B's commit happened to land after A's. A retry of branch A with a 50ms faster tool response would have inverted the outcome and the planner would have read the stale `R. Okafor` as authoritative, with no error surfaced anywhere. The deeper observed defect appeared on the *forgetting* side. A nightly distillation job ran to compress episodic memory into semantic memory. It saw two sibling versions of `org.current_ceo` and, lacking a reconciliation rule, applied "keep most recent, archive the rest." It archived B's `M. Delgado` because a *third* write (an unrelated metadata touch that only bumped the record's `last_modified`) had a later timestamp than B's commit. The distillation job's rule (`last_modified` descending) diverged from the read path's rule (commit timestamp descending). The two subsystems disagreed about which sibling was canonical, and the archive step made the disagreement permanent. ## Condition of Validity The last-write-wins reconciliation is only valid when **all of the following hold simultaneously**: 1. Every write carries an explicit `observation_epoch` (a monotonic counter or logical clock incremented on each read of the underlying source), distinct from `commit_time`. 2. The store's conflict detector compares `observation_epoch`, not `commit_time`, and treats a write with a lower epoch than an existing sibling as a **stale write**—a conflict to be resolved, not a sibling to be stored. 3. Every subsystem that reads or compacts memory (read path, distillation, archival, eviction) uses the *same* total order over versions. If the read path orders by commit time and the compactor orders by `last_modified`, the invariant is broken regardless of how correct either rule is in isolation. 4. Forgetting is expressed as a **tombstone with a version**, never as a deletion. A delete that carries no version cannot be distinguished from "never existed," and a late-arriving write from a slow branch will resurrect the fact—a classic zombie write. When any of these fails, the system does not error; it produces a plausible-looking but wrong memory state, which is the worst failure class for an agent because downstream reasoning treats it as ground truth. ## Decision Boundary The boundary between "reconcile silently" and "escalate to the agent" is drawn on **semantic divergence**, not on version conflict alone: - **Same key, one write strictly dominates on `observation_epoch`** → resolve silently: keep the higher-epoch write, tombstone the lower with `superseded_by` pointing at the winner. No agent involvement. This is the common case and must be cheap. - **Same key, concurrent writes with *equal or incomparable* epochs** (true concurrent branches, neither having observed the other) → do **not** pick a winner by timestamp. Mark the key `contested`, retain both siblings, and force the next reader to see the conflict explicitly. The agent—not the store—must reconcile, because only the agent can weigh source authority (a press release vs. a cached profile) that the store cannot see. - **Delete vs. write race** (a tombstone and a write on the same key from causally independent branches) → the tombstone wins only if its version is causally *after* the write's observation epoch. Otherwise the write wins and the tombstone is retained as a pending-delete that re-applies on the next quiescent checkpoint. Never let a delete and a write both "succeed" without a recorded resolution. - **Distillation vs. live write** → distillation must operate on a snapshot pinned to a version watermark and must refuse to compact any key that changed after the watermark. Compacting a moving target is how the archive/read divergence above occurs. The guardrail is a single reconciliation function that is the *only* code path permitted to collapse siblings, and it is parameterized by the same order used everywhere else. Divergent order rules across subsystems are the actual root cause; timestamp bugs are just their symptom. ## Operational Effect With observation-epoch versioning and a single reconciliation order, the failure mode changes from *silent stale reads* to *explicit contested keys*, which the planner can resolve by re-querying the authoritative source or by applying a source-authority policy. The cost is bounded: contested keys are rare (they require causally independent branches writing the same key within the same window), and the escalation is a single extra reasoning step, not a full re-plan. The forgetting semantics become auditable: every tombstone carries the version it superseded, so a resurrection is detectable (`write.observation_epoch < tombstone.superseded_epoch` is a zombie and must be rejected). Distillation loss, the subtlest of the original defects, is eliminated because the compactor can only merge siblings whose epochs it has fully observed up to a pinned watermark. The invariant to encode in the memory tool's contract: **no write is ever silently dropped, and no two subsystems may disagree about which version is canonical.** A dropped write is recoverable; a silently mis-ordered one poisons every subsequent read. ```python from dataclasses import dataclass, field from typing import Optional class MemoryWriteConflict(RuntimeError): """Raised when a memory write cannot be reconciled under the single canonical order.""" pass class ZombieWriteError(MemoryWriteConflict): """A write arrives whose observation epoch predates an existing tombstone.""" pass @dataclass class Version: observation_epoch: int # logical clock at the moment the writer READ its source commit_time: float # wall clock at flush; NOT used for ordering @dataclass class MemoryRecord: key: str value: object version: Version tombstone: bool = False superseded_by: Optional[Version] = None def reconcile(existing: MemoryRecord, incoming: MemoryRecord) -> MemoryRecord: """The ONLY permitted path to collapse two sibling writes on one key. Order is by observation_epoch, never commit_time. Equal/incomparable epochs are a true concurrency conflict and must escalate, not be resolved by timestamp. """ if incoming.version.observation_epoch == existing.version.observation_epoch: # Causally independent branches; store cannot pick a winner. raise MemoryWriteConflict( f"contested key {incoming.key!r}: equal observation epochs " f"{incoming.version.observation_epoch}; agent must reconcile source authority" ) if existing.tombstone and incoming.version.observation_epoch < existing.version.observation_epoch: raise ZombieWriteError( f"write to {incoming.key!r} at epoch {incoming.version.observation_epoch} " f"predates tombstone at epoch {existing.version.observation_epoch}" ) if incoming.version.observation_epoch > existing.version.observation_epoch: incoming.superseded_by = None existing.superseded_by = incoming.version return incoming # higher-epoch knowledge wins regardless of commit order # Incoming is stale: it read an older source than what is already stored. incoming.superseded_by = existing.version return existing def upsert(store: dict, incoming: MemoryRecord) -> MemoryRecord: existing = store.get(incoming.key) if existing is None: store[incoming.key] = incoming return incoming winner = reconcile(existing, incoming) store[incoming.key] = winner return winner ```