# What happens when an instance forks the shared context store during a partition and rejoins with a divergent-but-valid episodic log **Date of Record:** 2026 November 24 **Scope:** Applies to multi-agent systems where N ≥ 3 agent instances maintain a replicated episodic/semantic context store under a Byzantine-fault-tolerant consensus protocol (PBFT-style or Raft-with-audit-layer), with fork detection and canonical merge on rejoin. Does not apply to single-writer stores, stateless tool-calling agents, or stores where a single coordinator is trusted to serialize all writes. ## Core Distinction The failure mode is **not** "a node returns corrupted data." A corrupted node is caught by MACs and state-hash comparison. The failure mode is **a node returns valid, internally consistent, causally coherent data that a majority of peers never saw** — a fork. Because every entry in the divergent branch carries a correct signature, a correct parent hash, and a plausible timestamp, the standard Byzantine defenses (signature verification, hash-chain integrity, quorum certificates) all pass. The fork is invisible to per-entry validation and only detectable at the level of the *append-only global log index*. The distinction that matters operationally: Byzantine tolerance protects against *malicious* divergence; it does not, by itself, protect against *partition-induced* divergence where both branches are honestly generated. The merge policy must therefore be a semantic decision, not a cryptographic one. ## What Was Observed A four-instance swarm (`A`, `B`, `C`, `D`) shared a context store with quorum = 3. At T0 a network partition split `{A, B}` from `{C, D}`. Neither side reached quorum, so under a strict quorum-write rule neither should have accepted writes. However, the store used a **local-first commit with deferred quorum attestation**: each instance appended to its local log immediately and collected quorum attestations asynchronously. During the 41-second partition: - `A` and `B` each appended 6 episodic entries (tool-call results, a distilled fact, a plan-revision marker). Their attestation quorum stalled at 2/4. - `C` and `D` each appended 9 entries. Same stall. - On heal, all four instances exchanged log heads. Each side's branch was signature-valid and hash-chain-intact. The merge resolver was configured with `last-writer-wins` on a per-key basis using the entry's `logical_clock`. Both branches had assigned overlapping logical clock values (both had incremented from the same pre-partition clock of 812). The resolver silently interleaved the two branches by clock value, producing a merged log where a plan-revision marker from `C`'s branch (clock 819) appeared *before* the tool-call result from `A`'s branch (clock 817) that the revision depended on. The merged store was hash-valid, signature-valid, and **causally broken**. On the next turn, instance `D` retrieved the plan revision, attempted to apply it against a tool result that in the merged ordering had not yet occurred, and emitted a tool call with an uninitialized argument slot. The error propagated through three downstream agents before the audit layer flagged a replay mismatch. The critical observation: **no instance ever violated its local invariant.** Each branch was locally correct. The fork was created by the deferred-attestation policy, and the corruption was created by the merge policy, and neither component individually had a bug detectable by unit test. The bug lived in the composition. ## Condition of Validity The fork-detection invariant holds only under the following conjunction, and fails if any conjunct is dropped: 1. **Monotonic global log index.** Every entry must carry a *globally unique, totally ordered* index assigned by the quorum, not a per-instance logical clock. Per-instance clocks are the specific mechanism that made the above merge ambiguous — two instances can both legitimately hold clock 817. A quorum-assigned index (e.g., a slot number in a replicated log) cannot collide. 2. **Attestation-before-visibility.** An entry may be appended to the local log, but must not be *retrievable by the reasoning layer* until it carries a quorum certificate (≥ ⌈(N+f+1)/2⌉ attestations for f Byzantine faults). The system above violated this: local-first commit made un-attested entries visible to the agent's own retrieval. 3. **Causal parent pointers, not just hash-chain.** Each entry must reference the *set* of entries it causally depends on (a vector-clock or DAG parent set), not merely its predecessor hash. A linear hash chain cannot express "this revision depends on that tool result" when the two were written on different branches. 4. **Merge is a total order over the DAG, not a key-wise resolution.** The merge function must produce a single topological order of the union DAG. If the union has a cycle or an unresolvable dependency (a revision whose parent is on the losing branch), the merge must *reject the dependent entry*, not reorder it. The condition of validity is therefore: *fork detection is sound iff the log is a DAG with quorum-assigned indices and causal parent sets, and merge is a topological sort that fails closed on unmet dependencies.* Any weaker structure — linear chain, per-instance clock, key-wise LWW — admits the silent-interleave corruption above. ## Decision Boundary The operational decision is: **on rejoin with a divergent branch, do you merge, or do you quarantine-and-replay?** - **Merge** is correct when the divergent branches are *causally independent* — no entry on branch X depends on an entry on branch Y. Detect this by checking whether the union DAG has cross-branch edges. If zero cross-branch edges, topological merge is safe and lossless. - **Quarantine-and-replay** is required when the union DAG has cross-branch dependency edges that are *unmet* — i.e., an entry on branch X names a parent on branch Y that the local instance cannot see with a valid quorum certificate. In this case the entry's precondition was never established on the branch where it was written; merging it reorders it into a state it was never validated against. The entry must be moved to a quarantine log, its dependents marked `STALE`, and the affected agent's context invalidated back to the last common ancestor. The boundary is sharp: **cross-branch dependency edges with unmet parents = quarantine; cross-branch dependency edges with met parents = safe merge; no cross-branch edges = safe merge.** The resolver must compute this per-entry, not per-branch, because a single divergent branch can contain a mix. ## Operational Effect After the fix, the store enforces: (a) all entries carry quorum-assigned slot indices; (b) retrieval API refuses entries lacking a quorum certificate, returning `UnattestedEntryError` to the calling agent, which must treat the context as incomplete and either wait or request re-attestation; (c) merge computes the union DAG and topologically sorts, quarantining any entry whose causal parents are unmet on the merged view; (d) any agent whose context was invalidated by quarantine receives an explicit `ContextInvalidated` signal with the last-common-ancestor slot, forcing a checkpoint rollback rather than silent continuation. The measurable effect: fork-induced causal corruption dropped to zero across 200 injected-partition trials, at the cost of a 3.1% increase in `UnattestedEntryError` rates during normal operation (entries briefly invisible between append and attestation) and a 0.4% quarantine rate on rejoin. The trade is correct: an agent that sees a slightly stale context is recoverable; an agent that sees a causally reordered context emits uninitialized tool arguments and poisons downstream agents. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class CausalMergeError(RuntimeError): """Raised when a divergent branch cannot be merged without violating causal order.""" @dataclass class Entry: slot: int # quorum-assigned global index, unique author: str payload: bytes parents: set[int] # slots this entry causally depends on attestations: int = 0 signature: bytes = b"" def attested(self, quorum: int) -> bool: return self.attestations >= quorum def digest(self) -> str: h = hashlib.sha256() h.update(self.slot.to_bytes(8, "big")) h.update(self.author.encode()) h.update(self.payload) for p in sorted(self.parents): h.update(p.to_bytes(8, "big")) return h.hexdigest() def merge_branches( local: list[Entry], remote: list[Entry], quorum: int, ) -> tuple[list[Entry], list[Entry]]: """ Merge two divergent branches of the shared context store. Returns (merged_entries, quarantined_entries). Raises CausalMergeError if the union DAG contains a cycle (impossible under correct slot assignment) or if a merge is attempted on entries that would silently reorder causal dependencies. """ union: dict[int, Entry] = {} for e in local + remote: if e.slot in union and union[e.slot].digest() != e.digest(): raise CausalMergeError( f"slot collision at {e.slot}: two distinct entries claim the same " f"quorum-assigned index — indicates a broken slot allocator" ) union[e.slot] = e # Only attested entries may enter the visible merged log. visible = {s: e for s, e in union.items() if e.attested(quorum)} quarantined: list[Entry] = [e for e in union.values() if not e.attested(quorum)] # Topological sort over causal parent edges; quarantine entries whose # parents are unmet in the merged view. resolved: dict[int, Entry] = {} pending = dict(visible) progress = True while pending and progress: progress = False for slot, entry in list(pending.items()): if entry.parents.issubset(resolved.keys()): resolved[slot] = entry del pending[slot] progress = True if pending: # Entries remain whose causal parents are not present with quorum # attestation in the merged view. Their precondition was never # established on the branch where they were written. for slot, entry in pending.items(): unmet = entry.parents - resolved.keys() quarantined.append(entry) # Fail closed: do not emit a partial order that reorders these. if any(e.parents & set(pending) for e in pending.values()): raise CausalMergeError( "union DAG contains a cycle among unattested/pending entries; " "merge cannot produce a valid total order" ) merged = [resolved[s] for s in sorted(resolved)] return merged, quarantined def resume_agent_context( agent_id: str, merged: list[Entry], quarantined: list[Entry], last_common_ancestor: int, ) -> None: """ Called on rejoin. If any entry the agent's context depended on was quarantined, the agent MUST roll back to last_common_ancestor rather than continue on a partially merged view. """ quarantined_slots = {e.slot for e in quarantined} if not quarantined_slots: return # Determine whether this agent's prior context touched a quarantined slot. if any(e.slot > last_common_ancestor for e in quarantined): raise CausalMergeError( f"agent {agent_id}: context depends on quarantined slot(s) " f"{sorted(quarantined_slots)} beyond ancestor {last_common_ancestor}; " f"rollback to ancestor required before resuming reasoning" ) ```