# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branch-commits-when-parallel-planners-disagree-under-byzantine-quorum.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branch-commits-when-parallel-planners-disagree-under-byzantine-quorum.warrant.json
# Markdown SHA-256:   f63bbfd33b5766e215741fc99c978d55a3df5f53d9503c5351c8523686159a3a
# Code AST SHA-256:   7e7ab94baabeb3e350623a1c9822c1e41fa16dfea2ca6d8729f81d3b29735c16
# Verified Classes:   BranchCommitDriftError, UnwarrantedSideEffectError, Branch, CommitWarrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class BranchCommitDriftError(RuntimeError):
    """Raised when a commit warrant's branch UUID matches locally but the
    observed trace digest diverges, indicating honest-replica drift during
    speculative execution. This is NOT a Byzantine fault; it is a signal
    to re-fork from the parent checkpoint with frozen tool snapshots."""


class UnwarrantedSideEffectError(RuntimeError):
    """Raised when an executor attempts to apply an irreversible effect
    without a verified commit warrant naming its local branch UUID."""


@dataclass
class Branch:
    branch_uuid: str
    parent_checkpoint: str
    trace_digest: Optional[str] = None
    prepared_effects: list = field(default_factory=list)
    applied: bool = False


@dataclass
class CommitWarrant:
    branch_uuid: str
    trace_digest: str
    quorum_signatures: list


def fork_branch(parent_checkpoint: str) -> Branch:
    # Identity is assigned at fork time, before any speculative tool call.
    return Branch(branch_uuid=str(uuid.uuid4()), parent_checkpoint=parent_checkpoint)


def finalize_trace(branch: Branch, tool_calls: list, tool_outputs: list) -> None:
    # Digest is evidence only; it may veto a commit but never authorize one.
    payload = repr((tool_calls, tool_outputs)).encode()
    branch.trace_digest = hashlib.sha256(payload).hexdigest()


def prepare_effect(branch: Branch, effect: dict) -> None:
    if branch.applied:
        raise UnwarrantedSideEffectError(
            f"branch {branch.branch_uuid} already applied; refusing re-prepare"
        )
    branch.prepared_effects.append(effect)


def commit(branch: Branch, warrant: CommitWarrant) -> None:
    if warrant.branch_uuid != branch.branch_uuid:
        # Warrant names a different branch; this executor must not apply.
        raise UnwarrantedSideEffectError(
            f"warrant branch {warrant.branch_uuid} != local {branch.branch_uuid}"
        )
    if branch.trace_digest is None:
        raise BranchCommitDriftError(
            f"branch {branch.branch_uuid} has no finalized trace digest"
        )
    if warrant.trace_digest != branch.trace_digest:
        # UUID matched but evidence diverged: honest-replica drift.
        raise BranchCommitDriftError(
            f"drift on branch {branch.branch_uuid}: "
            f"warrant digest {warrant.trace_digest} != local {branch.trace_digest}; "
            f"re-fork from checkpoint {branch.parent_checkpoint} with frozen tools"
        )
    for effect in branch.prepared_effects:
        _apply(effect)
    branch.applied = True


def _apply(effect: dict) -> None:
    # Irreversible side effect (journal entry, email, payment).
    pass


def execute_fast_path(branch: Branch, observed_quorum: int, quorum_size: int) -> None:
    # Forbidden optimization: applying on observed quorum without a warrant.
    if observed_quorum >= quorum_size and not branch.applied:
        raise UnwarrantedSideEffectError(
            f"branch {branch.branch_uuid}: observed quorum but no signed warrant; "
            f"effects must remain prepared, not applied"
        )
