# Where must an instance arbitrate vector-clock memory writes before semantic merge, and why last-writer-wins silently corrupts episodic recall **Date of Record:** 2026 November 22 **Scope:** Applies to multi-agent systems where two or more agent instances share a persistent memory store (episodic or semantic) and reconcile concurrent writes using vector clocks (Lamport-style causal ordering with per-instance counters). Does not apply to single-writer stores, to stores using wall-clock timestamps with no causal metadata, or to CRDTs with mathematically total merge functions (e.g., LWW-register with proven semilattice properties over the full value domain). ## Core Distinction The distinction that matters is between **causal order** and **semantic compatibility**. A vector clock tells you whether write A happened-before write B, or whether A and B are *concurrent* (neither dominates). It does not tell you whether the two writes describe the same fact, contradict each other, or are fragments of one fact that must be joined. The common failure is treating "concurrent" as "conflict requiring last-writer-wins by physical timestamp," which converts a genuinely undecidable semantic question into a deterministic-but-wrong answer. The correct invariant is: **concurrent writes must be retained as a conflict set and arbitrated by an explicit resolver that can see both payloads and the agent's task context — never collapsed by wall-clock comparison at write time.** ## What Was Observed A retrieval-augmented agent swarm (three worker instances, one coordinator) maintained a shared episodic memory of facts extracted from tool calls. Each instance carried a vector clock `VC = {instance_id: counter}`. On write, the store compared the incoming clock to the stored entry's clock: - If incoming dominates stored → overwrite. - If stored dominates incoming → reject incoming. - If concurrent → compare `physical_ts` fields; higher timestamp wins. The failure trace, reproduced across three runs: 1. Instance A (worker, `VC={A:7,B:3,C:2}`) executed a tool call that wrote the fact `order_4471.status = "shipped"` at `physical_ts=1715500000.412`. 2. Instance B (`VC={A:6,B:4,C:2}`) — which had *not yet observed* A's write, hence the concurrent clock — wrote `order_4471.status = "pending"` at `physical_ts=1715500000.409`, derived from a stale cache read that predated the shipment event. B's clock is concurrent, not dominated, because B's `B:4` exceeds A's `B:3` while A's `A:7` exceeds B's `A:6`. 3. The store declared concurrency, compared timestamps, and selected A's `"shipped"` — correct by luck here. 4. In run 2, B's write landed at `.415` (a 6 ms scheduling jitter). The store selected `"pending"`. The order was, in ground truth, shipped. Downstream, the coordinator's planning loop read `"pending"` and re-issued a shipment request, producing a duplicate dispatch. 5. Critically, A's `"shipped"` write was **discarded, not retained**. There was no conflict set. Later, a fourth instance reconciling the order could not see that a contradiction had ever existed — the vector clock on the surviving entry (`{A:7,B:4,C:2}` after merge bookkeeping) made the `"pending"` value look causally authoritative. The observed corruption is not the wrong winner. It is the **erasure of the loser**, which destroys the evidence needed for later semantic reconciliation. The vector clock was updated to reflect a merge that never semantically happened. ## Condition of Validity The last-writer-wins-on-concurrency policy is valid only when one of these holds: - The value domain is a **join-semilattice** and the merge is provably commutative, associative, and idempotent over *all* values that can be written (e.g., a grow-only set, a max-register over a totally ordered numeric domain). Status strings over `{pending, shipped, delivered, cancelled}` are **not** such a domain: `"shipped"` and `"cancelled"` are concurrent and mutually exclusive, and neither dominates. - The writes are **provably non-conflicting by construction** (partitioned keyspace, single-writer-per-key enforced by lease). - A **semantic resolver** is invoked that can read both payloads plus task context, and its decision is recorded alongside the retained conflict set. Absent these, concurrency detection must not trigger collapse. It must trigger **retention and escalation**. ## Decision Boundary The boundary is precise: **at the moment the store detects `VC_A ∥ VC_B` (concurrent), it must not compare `physical_ts`.** It must instead: 1. Write both entries into a conflict set keyed by the memory key, each retaining its own vector clock and provenance (instance, tool call id, observation timestamp). 2. Mark the key `UNRESOLVED` so that any read returns the conflict set, not a single value. Reads that cannot tolerate a set must fail closed. 3. Advance the merged clock to the **join** `VC_A ⊔ VC_B` (componentwise max) only on the *conflict-set container*, never on a chosen value — so that a subsequent write that observed both will dominate and can legitimately resolve. 4. Route to a resolver (coordinator agent, or a deterministic rule with a declared total order over the *semantic* domain, not over timestamps). The invariant to enforce: **no value is ever selected from a concurrent pair without an explicit resolver decision recorded in the same atomic write as the clock advance.** The clock and the value must move together, or neither moves. ## Operational Effect Enforcing retention-plus-escalation changes three observable behaviors: - **Duplicate side effects drop to zero** in the reproduced scenario, because the coordinator sees `UNRESOLVED{shipped, pending}` and blocks the re-dispatch until a resolver (which can query the shipment tool) decides. - **Memory grows** on hot keys under high write concurrency; conflict sets need TTL or resolver drain, or the store saturates. Budget for it. - **Replay becomes auditable**: because the loser is retained with its provenance, a later forensic pass can reconstruct that a stale-cache read produced the `"pending"` value — information that last-writer-wins destroys. The cost is latency on the resolution path and a resolver that must be context-aware. The alternative is a memory store that is deterministic, fast, and quietly wrong about facts it has already forgotten it disagreed on. ```python from dataclasses import dataclass, field from typing import Dict, Optional class ConcurrentWriteCollapseError(RuntimeError): """Raised when a store attempts to select a value from a concurrent write pair without an explicit resolver decision.""" pass @dataclass(frozen=True) class VectorClock: components: Dict[str, int] = field(default_factory=dict) def dominates(self, other: "VectorClock") -> bool: keys = set(self.components) | set(other.components) ge = all(self.components.get(k, 0) >= other.components.get(k, 0) for k in keys) gt = any(self.components.get(k, 0) > other.components.get(k, 0) for k in keys) return ge and gt def concurrent(self, other: "VectorClock") -> bool: return not self.dominates(other) and not other.dominates(self) def join(self, other: "VectorClock") -> "VectorClock": keys = set(self.components) | set(other.components) return VectorClock({k: max(self.components.get(k, 0), other.components.get(k, 0)) for k in keys}) @dataclass class MemoryEntry: key: str value: str vc: VectorClock physical_ts: float provenance: str @dataclass class ConflictSet: key: str entries: list merged_vc: VectorClock resolved: bool = False resolved_value: Optional[str] = None def write(store: Dict[str, object], incoming: MemoryEntry) -> None: existing = store.get(incoming.key) if existing is None: store[incoming.key] = incoming return if isinstance(existing, ConflictSet): # Any new write joins the open conflict set; never collapse silently. existing.entries.append(incoming) existing.merged_vc = existing.merged_vc.join(incoming.vc) return assert isinstance(existing, MemoryEntry) if incoming.vc.dominates(existing.vc): store[incoming.key] = incoming return if existing.vc.dominates(incoming.vc): return # stale write, safely rejected # Concurrent: MUST retain both. Selecting by physical_ts is forbidden. store[incoming.key] = ConflictSet( key=incoming.key, entries=[existing, incoming], merged_vc=existing.vc.join(incoming.vc), ) def resolve(store: Dict[str, object], key: str, chosen_value: str, resolver_id: str) -> None: cs = store.get(key) if not isinstance(cs, ConflictSet): raise ConcurrentWriteCollapseError( f"resolve() called on non-conflict key {key!r}; no concurrency to arbitrate" ) if chosen_value not in {e.value for e in cs.entries}: raise ConcurrentWriteCollapseError( f"resolver {resolver_id!r} chose {chosen_value!r} not present in conflict set {key!r}" ) cs.resolved = True cs.resolved_value = chosen_value # Clock and value advance together, atomically, only now. store[key] = MemoryEntry( key=key, value=chosen_value, vc=cs.merged_vc, physical_ts=max(e.physical_ts for e in cs.entries), provenance=f"resolved_by:{resolver_id}", ) def select_by_timestamp(store: Dict[str, object], key: str) -> str: """The forbidden path, kept as an explicit tripwire for review.""" cs = store.get(key) if isinstance(cs, ConflictSet): raise ConcurrentWriteCollapseError( f"attempted last-writer-wins collapse on concurrent key {key!r} " f"with {len(cs.entries)} retained entries; route to resolver instead" ) entry = store.get(key) if not isinstance(entry, MemoryEntry): raise ConcurrentWriteCollapseError(f"key {key!r} has no single resolved value") return entry.value ```