# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-a-speculative-branch-that-has-already-been-byzantine-committed-by-a-quorum-the-orphaned-commit-invariant-in-branch-and-p.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-a-speculative-branch-that-has-already-been-byzantine-committed-by-a-quorum-the-orphaned-commit-invariant-in-branch-and-p.warrant.json
# Markdown SHA-256:   3b5c0f43f964d70a9236168c160a6f87bc8f103ae1e4a655b8eda40e0f94373a
# Code AST SHA-256:   fc4c1ce7d478cec2c8e3f6fdd83aba6816d23d20c22698db3805a268f658e9c8
# Verified Classes:   OrphanedCommitError, CommitGapError, Certificate, EmitRecord, SpeculativeExecutor
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class OrphanedCommitError(RuntimeError):
    """Raised when an instance emits a side effect for a branch that a
    lower-numbered Byzantine commit later designates as the loser, or when
    it attempts to emit on a certificate whose commit prefix has gaps."""


class CommitGapError(RuntimeError):
    """Raised when a certificate is presented for sequence s but the
    contiguous prefix [0, s) is not fully observed."""


@dataclass
class Certificate:
    branch_id: str
    seq: int
    winner: bool          # quorum designation: is this branch the ordered winner?
    quorum_sigs: int      # number of validator signatures (must exceed f)


@dataclass
class EmitRecord:
    branch_id: str
    seq: int
    emitted: bool = True


@dataclass
class SpeculativeExecutor:
    f: int                                  # Byzantine tolerance
    quorum_size: int                        # total validators
    observed: Dict[int, Certificate] = field(default_factory=dict)
    emitted: Dict[str, EmitRecord] = field(default_factory=dict)
    high_water: int = -1                    # highest contiguous seq observed

    def _required_sigs(self) -> int:
        # BFT quorum: strictly more than (n + f) / 2
        return (self.quorum_size + self.f) // 2 + 1

    def observe(self, cert: Certificate) -> None:
        if cert.quorum_sigs < self._required_sigs():
            raise OrphanedCommitError(
                f"certificate for {cert.branch_id} seq {cert.seq} has "
                f"{cert.quorum_sigs} sigs, need {self._required_sigs()}"
            )
        self.observed[cert.seq] = cert
        # advance contiguous high-water mark
        while (self.high_water + 1) in self.observed:
            self.high_water += 1
        # retroactive orphan detection: did we emit for a branch that a
        # now-visible lower-numbered commit designates as the loser?
        for rec in self.emitted.values():
            lower = self.observed.get(rec.seq - 1)
            if lower is not None and lower.winner and not self._is_winner(rec.branch_id):
                raise OrphanedCommitError(
                    f"branch {rec.branch_id} emitted at seq {rec.seq} is orphaned: "
                    f"lower commit seq {lower.seq} designates {lower.branch_id} as winner"
                )

    def _is_winner(self, branch_id: str) -> bool:
        return any(
            c.branch_id == branch_id and c.winner for c in self.observed.values()
        )

    def emit(self, branch_id: str, seq: int) -> None:
        cert = self.observed.get(seq)
        if cert is None:
            raise CommitGapError(
                f"no certificate for {branch_id} at seq {seq}; cannot emit on uncommitted branch"
            )
        if not cert.winner:
            raise OrphanedCommitError(
                f"refusing to emit for {branch_id}: quorum designates it pruned at seq {seq}"
            )
        if self.high_water < seq - 1:
            raise CommitGapError(
                f"commit prefix gap: high-water {self.high_water}, emitting at {seq} "
                f"would risk a lower-numbered commit arriving later"
            )
        self.emitted[branch_id] = EmitRecord(branch_id=branch_id, seq=seq)


def run_speculative_branch(exec: SpeculativeExecutor, branch_id: str,
                           local_completion_seq: int) -> None:
    """Pruning is local and speculative; emission is gated on gap-free commit."""
    # prune step: allowed on local evidence only, never emits
    try:
        exec.emit(branch_id, local_completion_seq)
    except CommitGapError as e:
        # correct behavior: do not emit, wait for contiguous prefix
        raise CommitGapError(f"deferred emission for {branch_id}: {e}") from e
