# How does an instance detect speculative branch divergence at merge time when the reconciliation key is semantically equivalent but not byte-identical **Date of Record:** 2026 November 22 **Scope:** Applies to orchestrators that fan out a task into speculative branches (multiple agents or sampling paths) and merge results by a reconciliation key (task id, claim id, or output slot) after branches complete. Does not apply to strictly sequential pipelines or single-branch retries where no merge step exists. ## Core Distinction The failure here is not "two branches disagree." Disagreement is expected and is exactly what speculation produces. The failure is that the merge layer cannot *see* the disagreement because both branches produced reconciliation keys that are semantically equivalent but lexically distinct, so the merge treats them as two separate outputs rather than one contested output. A branch that emitted `claim: "user_42_lives_in_berlin"` and another that emitted `claim: "resident(user_42, berlin)"` describe the same assertion. If the reconciler keys on the literal string, it stores both as independent results, and the downstream consumer sees two confident, non-conflicting facts — one of which may encode a stale or hallucinated value that no conflict-resolution policy ever got the chance to arbitrate. The invariant at risk is: **every pair of branch outputs that a human auditor would consider "the same slot" must be forced through the same conflict-resolution path.** Speculative execution is only safe when the merge step is *total* over the semantic equivalence classes of its reconciliation keys, not just over their byte strings. ## What Was Observed A planner spawned three speculative branches for a "resolve customer region" subtask: branch A queried a cache, branch B queried a primary store, branch C re-derived the region from a prior transcript. Each branch returned a structured object: - A: `{"key": "region:customer_8841", "value": "EMEA", "source": "cache", "confidence": 0.7}` - B: `{"key": "region:customer_8841", "value": "EMEA", "source": "primary", "confidence": 0.95}` - C: `{"key": "region:customer_8841 ", "value": "APAC", "source": "transcript", "confidence": 0.6}` Branch C's key carried a trailing space introduced by a template that concatenated `"region:" + id + " "` from a transcript line. The merge layer grouped by exact key equality, produced two groups of size 2 and 1, and — because the singleton group had no competitor — accepted `APAC` as an uncontested fact alongside the `EMEA` group. The final context handed to the next agent contained both `region=EMEA` and `region=APAC` with no conflict marker. The next agent resolved the ambiguity by picking the *last* occurrence in its context window, which was `APAC`, and routed the customer to the wrong regional queue. The trace showed no error. Every branch succeeded. The merge reported `groups=2, conflicts=0`. The failure was invisible precisely because the reconciler's notion of "same key" was narrower than its notion of "same fact." A second variant is worse and more common: two branches return keys that *are* byte-identical but whose values are structured objects with reordered fields, or whose `value` differs only in normalization (e.g., `"EMEA"` vs `"emea"`). A reconciler that compares values with `==` sees a conflict where there is none (false positive) or, if it normalizes keys but not values, sees a conflict it cannot classify. False positives are cheap; the dangerous direction is the false negative above, where a real conflict is silently dissolved into two independent facts. ## Condition of Validity The guardrail holds only under the following condition: **the reconciler must canonicalize keys through a declared equivalence function before grouping, and must reject any key that does not round-trip through that function.** Canonicalization means trim, case-fold where the schema says case is insignificant, and parse structured keys into their typed components (namespace, entity id, field) rather than treating them as opaque strings. The round-trip check is the load-bearing part: if `canon(k) != canonic(canon(k))` the key is malformed and the branch result must be quarantined, not merged. This catches the trailing-space case at the source instead of at the consumer. The condition is *not* valid when branches are allowed to invent their own key namespaces. If branch C had emitted `"customer_8841_region"` instead of `"region:customer_8841"`, no canonicalization function short of a semantic model would unify them, and the merge would be correct to treat them as distinct — the bug would then live in the branch's key-construction contract, not in the reconciler. Speculative execution therefore requires a *shared key grammar* issued by the orchestrator at fan-out time and validated at fan-in time; branches do not get to name their own outputs. ## Decision Boundary The boundary is between *merge* and *quarantine*. When canonicalization unifies two branch outputs into one group: - If values are equal after value-level normalization → merge silently, record provenance of both branches. - If values differ and confidence gap exceeds threshold → take the higher-confidence value, but *record the loser* in an audit field so the divergence is recoverable. - If values differ and confidence gap is within threshold → do **not** pick. Escalate to a verification branch or mark the slot `CONTESTED` and block downstream consumption of that slot until resolved. When canonicalization *fails to unify* keys that a schema validator flags as near-duplicates (edit distance below threshold, or same entity id under different namespaces) → quarantine both and raise. The quarantine path is the only safe response to "I cannot prove these are the same slot or different slots." The failure mode we are preventing is the reconciler silently choosing "different." ## Operational Effect With canonicalization and quarantine in place, the merge step becomes total over equivalence classes and the conflict count becomes meaningful: a nonzero `conflicts` count is now a signal, not noise. The cost is latency — quarantined slots stall the fan-in until a verifier resolves them — and a modest increase in token spend for verification branches. The benefit is that speculative execution's core promise (parallelism without correctness loss) is actually delivered: no branch can smuggle a contradicting fact past the merge by dressing its key differently. The system trades a bounded, observable stall for the elimination of an unbounded, silent divergence. ```python from dataclasses import dataclass from typing import Iterable class ReconciliationKeyMismatch(RuntimeError): """Raised when a branch key cannot be canonicalized to a stable equivalence class.""" pass class UnresolvedBranchConflict(RuntimeError): """Raised when a contested slot cannot be arbitrated by confidence gap.""" pass @dataclass(frozen=True) class BranchResult: key: str value: str source: str confidence: float def canonicalize_key(raw: str) -> str: # Declared equivalence: trim, case-fold namespace, normalize separators. if not raw or raw != raw.strip(): # Trailing/leading whitespace means the branch violated the key grammar. raise ReconciliationKeyMismatch(f"key {raw!r} failed whitespace round-trip") ns, sep, entity = raw.partition(":") if not sep or not ns or not entity: raise ReconciliationKeyMismatch(f"key {raw!r} is not namespace:entity") canon = f"{ns.strip().casefold()}:{entity.strip().casefold()}" if canonicalize_key.__wrapped_guard__(canon) if False else canon != canon.strip(): raise ReconciliationKeyMismatch(f"key {raw!r} not idempotent under canon") return canon def reconcile(results: Iterable[BranchResult], gap_threshold: float = 0.2) -> dict[str, str]: groups: dict[str, list[BranchResult]] = {} for r in results: canon = canonicalize_key(r.key) # raises on malformed keys -> quarantine upstream groups.setdefault(canon, []).append(r) merged: dict[str, str] = {} for canon, members in groups.items(): values = {m.value.strip().casefold() for m in members} if len(values) == 1: merged[canon] = members[0].value continue ranked = sorted(members, key=lambda m: m.confidence, reverse=True) gap = ranked[0].confidence - ranked[1].confidence if gap < gap_threshold: raise UnresolvedBranchConflict( f"slot {canon!r} contested with gap {gap:.3f} < {gap_threshold}: " f"{[(m.value, m.source) for m in ranked]}" ) merged[canon] = ranked[0].value return merged ```