# Which invariants prevent last-writer-wins vector upserts from erasing peer agent memory during concurrent graph writes **Date of Record:** 2026 December 3 **Scope:** Applies to multi-agent systems where two or more LLM instances write derived memory (embeddings + graph edges) into a shared vector/graph store under a merge protocol that permits concurrent upserts. Does not apply to single-writer append-only logs or to stores with serializable transactions enforced at the storage layer. ## Core Distinction The failure is not a race condition in the classical sense of two writes clobbering a single row. It is a *semantic* conflict: two agents independently distill overlapping episodic memory into the same semantic node, and the shared store's conflict resolution — typically last-writer-wins (LWW) keyed on a wall-clock or lamport timestamp — resolves the *record* while silently discarding the *provenance edge* that made the node retrievable under the other agent's query distribution. The distinction that matters operationally: LWW is correct for scalar values (a counter, a status flag). It is unsound for vector records whose retrieval behavior depends on the *union* of the embedding neighborhoods that produced them. When agent A upserts node `n` with embedding `e_A` and agent B upserts `n` with `e_B`, the store retains one embedding. The losing agent's future retrievals over `n` now miss, because the retained vector no longer sits in its query cone. The node still exists; it has become *invisible to the agent that needed it*. This is amnesia induced by merge, not by eviction. ## What Was Observed Two retrieval agents, `R1` and `R2`, share a graph store of `Observation` nodes with a `vector(1536)` field on the node and `DERIVED_FROM` edges to source episodes. Both run a distillation step every 90 seconds that re-embeds recent episodes and upserts by `content_hash`. The upsert was implemented as `MERGE (o:Observation {content_hash: $h}) SET o.embedding = $e, o.updated_at = $ts`. During a 40-minute window in which `R1` and `R2` processed overlapping episode batches (a failover had briefly double-assigned a shard), the following trace was captured: 1. `R1` distills episode `e17` → node `n_x`, embedding `v1`, sets `updated_at = 1000`. 2. `R2` distills the same episode with a slightly different prompt template → node `n_x` (same `content_hash`), embedding `v2`, sets `updated_at = 1001`. 3. Store retains `v2`. `v1` is gone. No conflict record is written. 4. `R1`'s next query, `MATCH (o:Observation) WHERE cosine(o.embedding, $q) > 0.82`, returns `n_x` only when `q` is near `v2`. For `R1`'s query distribution (templated around its own distillation phrasing), recall on `n_x` dropped from 0.94 to 0.31 over the window. 5. `R1` concluded the episode had been *forgotten* and re-distilled it, producing `v3`, overwriting `v2`. `R2` then observed the same drop. An oscillation began, with each agent's re-distillation erasing the other's embedding. The store's node count stayed constant; the *effective* memory of each agent collapsed. The critical observation: no error was raised. No invariant in the store fired. The graph was structurally consistent and semantically corrupt. The oscillation only terminated when the double-assigned shard was reclaimed and the write rate fell below the re-distillation threshold. ## Condition of Validity The guardrail below is valid only under these conditions, and must be *disabled* (with a different protocol) otherwise: - **Bounded embedding divergence.** The two agents' embeddings for the same `content_hash` must lie within a cosine distance `d < δ` (empirically `δ ≈ 0.15` for the templates in use). If agents use genuinely different embedding models or radically different distillation prompts, the correct resolution is *not* to merge — it is to create two nodes with distinct `content_hash` namespaces, because the embeddings are not reconcilable and merging them is a category error. - **Idempotent distillation.** Re-distilling the same episode must produce a byte-identical or near-identical embedding; otherwise the oscillation above is a fixed point of the protocol, not a transient. - **Provenance edges are append-only.** The `DERIVED_FROM` edges must never be deleted by an upsert. If the store's `MERGE ... SET` also rewrites edges, the invariant does not hold. - **No cross-agent read-your-write dependency within a single reasoning step.** The protocol assumes agents tolerate a bounded staleness window (one distillation cycle). Agents that read their own write and branch on it within the same step will observe the merge mid-flight and can diverge. ## Decision Boundary The boundary is between *merge* and *fork*, decided per `content_hash` by embedding divergence, not by timestamp: - If `cosine(v_existing, v_new) ≥ 1 − δ`: **merge**. Write the new embedding into a `embedding_versions` list (or a `:Variant` side node) rather than overwriting. Retrieval queries must search across all variants, or the store must compute a centroid and keep variants for audit. The `updated_at` field is *not* the resolution key; it is metadata. - If `cosine(v_existing, v_new) < 1 − δ`: **fork**. The two embeddings are not the same memory. Create a second node with `content_hash` suffixed by the agent's identity (`h::R2`), link both to the shared episode, and let the retrieval layer rank. Do not overwrite. - If `content_hash` collides but the *source episode* differs (a hash collision or a templating bug): **reject the write** and raise. This is the only case where the protocol should hard-fail, because it indicates a bug upstream of the merge layer. The invariant that prevents the erasure: **no upsert may reduce the set of embeddings retrievable for a given `content_hash` under any participating agent's query distribution.** Overwrite violates this; variant-append satisfies it. The store must enforce this by making the embedding field append-only at the protocol layer and by rejecting `SET embedding =` on an existing node unless the divergence check passes. ## Operational Effect With the divergence-gated fork/merge rule and variant-append, the oscillation described above becomes impossible: `R1` and `R2` each retain a retrievable embedding, recall on `n_x` stays above 0.9 for both query distributions, and re-distillation is idempotent (it appends a duplicate variant, which the compaction job deduplicates by embedding hash). The cost is a modest increase in node/edge count and a retrieval-time fan-out over variants — bounded by the number of agents writing to the same `content_hash`, which is small in practice. The failure mode the invariant does *not* prevent: if two agents legitimately derive *contradictory* semantic content from the same episode (different conclusions), variant-append preserves both and the retrieval layer will surface a conflict to the reasoning agent. That is correct behavior — the conflict is real and must be resolved by an auditor agent, not by the store silently picking a winner. The store's job is to preserve the evidence, not to adjudicate. The operational lesson: in shared vector/graph stores, consistency of the *record* is not consistency of the *memory*. LWW keyed on timestamps is a record-level guarantee that silently violates the memory-level invariant. The merge protocol must be keyed on embedding divergence and must treat the embedding as append-only; the timestamp is metadata, never the resolution key. ```python import math from dataclasses import dataclass, field from typing import Optional DELTA = 0.15 # max cosine distance for merge eligibility class MergeProtocolViolation(RuntimeError): """Raised when an upsert would violate the memory-preservation invariant.""" pass @dataclass class Observation: content_hash: str embeddings: list[list[float]] = field(default_factory=list) agent_ids: list[str] = field(default_factory=list) updated_at: int = 0 def variants(self) -> list[list[float]]: return list(self.embeddings) def cosine_distance(a: list[float], b: list[float]) -> float: dot = sum(x * y for x, y in zip(a, b)) na = math.sqrt(sum(x * x for x in a)) nb = math.sqrt(sum(y * y for y in b)) if na == 0 or nb == 0: raise MergeProtocolViolation("zero-norm embedding cannot be merged") return 1.0 - (dot / (na * nb)) def upsert( store: dict[str, Observation], content_hash: str, embedding: list[float], agent_id: str, timestamp: int, source_episode: Optional[str] = None, ) -> Observation: """ Append-only upsert. Merges when embeddings are within DELTA, forks otherwise. Never overwrites an existing embedding. Raises on unreconcilable collision. """ if not embedding: raise MergeProtocolViolation(f"empty embedding for {content_hash}") existing = store.get(content_hash) if existing is None: node = Observation( content_hash=content_hash, embeddings=[list(embedding)], agent_ids=[agent_id], updated_at=timestamp, ) store[content_hash] = node return node # Fork path: embeddings diverge beyond tolerance. min_dist = min(cosine_distance(embedding, v) for v in existing.embeddings) if min_dist > DELTA: forked_hash = f"{content_hash}::{agent_id}" if forked_hash in store: # Already forked; append variant rather than overwrite. node = store[forked_hash] node.embeddings.append(list(embedding)) node.agent_ids.append(agent_id) node.updated_at = max(node.updated_at, timestamp) return node forked = Observation( content_hash=forked_hash, embeddings=[list(embedding)], agent_ids=[agent_id], updated_at=timestamp, ) store[forked_hash] = forked return forked # Merge path: within tolerance. Append variant, preserve all prior embeddings. # Guard: reject if the same agent is re-appending an identical embedding # under a different source episode (indicates upstream collision). if source_episode is not None and any( cosine_distance(embedding, v) < 1e-6 for v in existing.embeddings ) and agent_id in existing.agent_ids: # Idempotent re-distillation; no-op. return existing existing.embeddings.append(list(embedding)) existing.agent_ids.append(agent_id) existing.updated_at = max(existing.updated_at, timestamp) return existing def retrieve( store: dict[str, Observation], query: list[float], threshold: float = 0.82, ) -> list[tuple[str, float]]: """Retrieve across all variants so no agent's embedding is invisible.""" hits: list[tuple[str, float]] = [] for node in store.values(): for v in node.variants(): sim = 1.0 - cosine_distance(query, v) if sim >= threshold: hits.append((node.content_hash, sim)) break # one hit per node is sufficient hits.sort(key=lambda t: t[1], reverse=True) return hits ```