How should an instance bound speculative branch pruning when Byzantine merge finality outruns local verification quorum

**Date of Record:** 2026 December 2 **Scope:** Applies to orchestrators that fan out speculative agent branches (parallel plan/execute attempts) and commit the winning branch via a Byzantine-verified merge (k-of-n auditor attestation). Does not apply to single-branch serial agents or to merges finalized by a single trusted coordinator with no peer attestation.

Core Distinction

The failure is not "a bad branch got merged." It is a **pruning-finality inversion**: a speculative branch is pruned (its state discarded, its context reclaimed) *before* the Byzantine merge quorum has finalized, because the pruner's local liveness heuristic outran the quorum's safety guarantee. Two clocks run at once. The **pruning clock** is local, monotonic, and driven by token-budget pressure and branch-score decay — it wants to free context now. The **finality clock** is distributed, non-monotonic (view changes, equivocation retries), and only completes when `k` distinct auditors have signed the same branch root. When the pruner fires ahead of finality, the system can lose the only durable copy of a branch that the quorum was *about to* certify — and worse, can re-derive a *different* branch under the same `branch_id` and present it to auditors, splitting the quorum across two incompatible roots.

The invariant that must hold: **a branch's state may not be reclaimed until its finality certificate is either (a) present locally, or (b) provably unreachable (quorum impossible).** "Unreachable" is the hard part, because a Byzantine auditor withholding a signature looks identical to a slow one.

What Was Observed

A four-auditor merge quorum (`k=3, n=4`) certified speculative branches of a code-refactor agent. The orchestrator ran up to seven branches concurrently, each holding ~40k tokens of working context. Under budget saturation it invoked `prune_lowest_score()`, which dropped any branch whose rolling success score fell below threshold for two consecutive ticks.

Trace of the failing run:

  1. Branch `B7` scored 0.31, 0.29 on two ticks → pruner marked it `PRUNED`, released its context, and — critically — **recycled its `branch_id` slot** into the free pool.
  2. Meanwhile auditors `A1, A2, A3` had already signed `root(B7) = r_a`; the certificate was in flight. `A4` was Byzantine and silent.
  3. The freed slot spawned `B7'` (same `branch_id`, fresh context) executing a *near-identical* plan but with a different sampling seed. Its root was `r_b ≠ r_a`.
  4. `A1, A2` (having cached `r_a`) and `A3` (re-reading the now-live `B7'` state, seeing `r_b`) disagreed. The quorum split 2–1 with one equivocation. Finality stalled; the merge driver retried, re-read `r_b`, and eventually committed the *reconstructed* branch — which had never been executed to completion and contained a half-applied patch.

The observable signature: **finality certificate root hash ≠ live branch root hash for the same `branch_id`**, appearing only under concurrent budget saturation, never in serial runs.

Condition of Validity

This boundary is reachable only when all three hold simultaneously:

Remove any one and the inversion cannot occur: content-addressed branch IDs make `B7'` a distinct identity (no collision); synchronous finality-before-prune removes the window; a fully honest fast quorum closes the in-flight interval to near zero. The invariant is therefore *conditional on recyclable identity + async finality + fault tolerance*, which is exactly the default configuration of most speculative-merge orchestrators.

Decision Boundary

The pruner must decide, per branch, between **RECLAIM** and **HOLD**, and the decision must be gated on finality evidence, not on score:

The non-obvious rule: **score decay must never be sufficient grounds for reclaiming an unfinalized branch.** And branch IDs must be **content-addressed** (`branch_id = H(plan_seed, parent_root)`), so that a respawned attempt is a new identity and cannot alias a certificate in flight. Recycling a slot is the specific sin that turns a benign prune into an equivocation.

Operational Effect

With the gate in place, budget saturation no longer causes quorum splits; instead it causes **HOLD pressure** — branches pinned in memory awaiting finality, which can itself exhaust context. The correct operational posture is to bound HOLD time with an explicit *finality timeout* that, on expiry, forces a **view change** (re-dispatch the branch to a fresh auditor set under a new content-addressed ID) rather than a reclaim. This converts a safety violation into a liveness cost, which is the trade you always want. The residual risk: under sustained Byzantine silence plus budget saturation, HOLD pressure can starve the orchestrator — so the finality timeout must be strictly less than the budget-reclaim deadline, or the two clocks re-invert and the original bug returns through the back door.

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class FinalityInversionError(RuntimeError):
    """Raised when a branch would be reclaimed before its merge finality is resolved."""


@dataclass
class Branch:
    plan_seed: str
    parent_root: str
    score: float
    ticks_below: int = 0

    @property
    def branch_id(self) -> str:
        # Content-addressed: a respawned attempt can never alias an in-flight cert.
        h = hashlib.sha256(f"{self.plan_seed}:{self.parent_root}".encode()).hexdigest()
        return f"br-{h[:16]}"


@dataclass
class QuorumState:
    k: int
    n: int
    signed_roots: dict = field(default_factory=dict)   # auditor -> root
    refusals: set = field(default_factory=set)          # auditors that signed refusal

    def certificate_root(self) -> Optional[str]:
        counts = {}
        for root in self.signed_roots.values():
            counts[root] = counts.get(root, 0) + 1
        for root, c in counts.items():
            if c >= self.k:
                return root
        return None

    def quorum_impossible(self) -> bool:
        # Impossible only if too few honest signers remain to ever reach k.
        return len(self.refusals) >= (self.n - self.k + 1)


def decide_reclaim(branch: Branch, live_root: str, quorum: QuorumState,
                   score_threshold: float = 0.35, ticks: int = 2) -> str:
    cert = quorum.certificate_root()

    if cert is not None:
        if cert != live_root:
            # Certificate exists but for a different root: identity collision / equivocation.
            raise FinalityInversionError(
                f"certificate root {cert} != live root {live_root} for {branch.branch_id}; "
                "branch_id aliasing detected — refuse to reclaim"
            )
        return "RECLAIM"  # finalized and consistent

    low = branch.score < score_threshold and branch.ticks_below >= ticks
    if low and not quorum.quorum_impossible():
        # The inversion: score decay is a liveness signal, NOT finality evidence.
        raise FinalityInversionError(
            f"branch {branch.branch_id} scored {branch.score} but quorum still possible "
            f"({len(quorum.signed_roots)}/{quorum.n} signed, k={quorum.k}); must HOLD, "
            "not reclaim — force view change on timeout instead"
        )

    if low and quorum.quorum_impossible():
        return "RECLAIM"  # provably dead quorum; safe to free

    return "HOLD"