# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branch-divergence-when-rollback-cost-exceeds-forward-hedge-cost-mid-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branch-divergence-when-rollback-cost-exceeds-forward-hedge-cost-mid-execution.warrant.json
# Markdown SHA-256:   aea64fb784e02353832b8f7ea2e9553a75f5b997b79ba1e1a055274419a986de
# Code AST SHA-256:   0d83422d8feb93b0f9bd8343db9f752ec3f71f6e18a5298c2d48973ecfacf1be
# Verified Classes:   RollbackLedgerError, BranchState, Branch, SpeculativeOrchestrator
# Defensive Guards:   9 fail-closed invariants (zero external deps)

from __future__ import annotations

import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Callable, Dict, Optional


class RollbackLedgerError(RuntimeError):
    """Raised when a branch lifecycle transition violates the reconciliation invariant."""


class BranchState(Enum):
    LIVE = "live"
    ROLLBACK_PENDING = "rollback_pending"
    REVERTED_VERIFIED = "reverted_verified"
    HEDGED = "hedged"
    ABORTED = "aborted"


@dataclass
class Branch:
    branch_id: str
    score: float
    rollback_cost: float          # R_i: tokens + latency + risk-adjusted damage
    forward_cost: float           # H_i: remaining marginal cost of keeping alive
    compensation_verifiable: bool # True iff completion predicate is synchronous
    state: BranchState = BranchState.LIVE
    completion_predicate: Optional[Callable[[], bool]] = None
    effects: set = field(default_factory=set)


class SpeculativeOrchestrator:
    def __init__(self, barrier_timeout_s: float = 5.0) -> None:
        self.branches: Dict[str, Branch] = {}
        self.barrier_timeout_s = barrier_timeout_s

    def register(self, b: Branch) -> None:
        self.branches[b.branch_id] = b

    def decide(self, branch_id: str) -> BranchState:
        """Apply the cost-aware boundary at a checkpoint."""
        b = self.branches[branch_id]
        if b.state is not BranchState.LIVE:
            return b.state

        # Boundary: roll back only if cheaper AND verifiable; else hedge.
        if b.rollback_cost < b.forward_cost and b.compensation_verifiable:
            b.state = BranchState.ROLLBACK_PENDING
        else:
            b.state = BranchState.HEDGED
        return b.state

    def reconcile_barrier(self, winner_id: str) -> None:
        """
        Gate the winner's commit on completion predicates of all
        ROLLBACK_PENDING branches. On timeout, escalate to HEDGED rather
        than proceed (a pending branch is still a writer).
        """
        winner = self.branches.get(winner_id)
        if winner is None or winner.state is not BranchState.LIVE:
            raise RollbackLedgerError(
                f"winner {winner_id} not live; cannot commit"
            )

        deadline = time.monotonic() + self.barrier_timeout_s
        for b in self.branches.values():
            if b.state is not BranchState.ROLLBACK_PENDING:
                continue
            if b.completion_predicate is None:
                raise RollbackLedgerError(
                    f"branch {b.branch_id} is ROLLBACK_PENDING with no "
                    f"completion predicate; cannot establish silence"
                )
            while time.monotonic() < deadline:
                if b.completion_predicate():
                    b.state = BranchState.REVERTED_VERIFIED
                    break
                time.sleep(0.05)
            else:
                # Timeout: advisory ack was never terminal. Escalate to hedge.
                b.state = BranchState.HEDGED

    def attribute_write(self, writer_branch_id: str) -> str:
        """
        Classify a write observed during the winner's commit.
        Expected writers: HEDGED and ROLLBACK_PENDING branches (attributed).
        Foreign writers: anything else -> StateConflict.
        """
        b = self.branches.get(writer_branch_id)
        if b is None:
            raise RollbackLedgerError(
                f"foreign writer {writer_branch_id!r} not in ledger; "
                f"reconciliation invariant violated"
            )
        if b.state in (BranchState.HEDGED, BranchState.ROLLBACK_PENDING):
            return "expected"
        if b.state is BranchState.REVERTED_VERIFIED:
            raise RollbackLedgerError(
                f"branch {writer_branch_id} is REVERTED_VERIFIED but emitted "
                f"a write; completion predicate was unsound"
            )
        raise RollbackLedgerError(
            f"branch {writer_branch_id} in state {b.state.value} emitted an "
            f"unattributed write; aborting reconciliation"
        )


def _demo() -> None:
    orch = SpeculativeOrchestrator(barrier_timeout_s=0.2)
    # B: advisory compensation, expensive to retract -> must hedge, not roll back.
    orch.register(Branch("B", score=0.22, rollback_cost=9.0, forward_cost=1.5,
                         compensation_verifiable=False))
    # C: synchronous, cheap -> roll back.
    orch.register(Branch("C", score=0.09, rollback_cost=0.5, forward_cost=2.0,
                         compensation_verifiable=True,
                         completion_predicate=lambda: True))
    orch.register(Branch("A", score=0.71, rollback_cost=0.0, forward_cost=0.0,
                         compensation_verifiable=True))

    assert orch.decide("B") is BranchState.HEDGED
    assert orch.decide("C") is BranchState.ROLLBACK_PENDING

    orch.reconcile_barrier("A")
    assert orch.branches["C"].state is BranchState.REVERTED_VERIFIED
    assert orch.attribute_write("B") == "expected"

    # A REVERTED_VERIFIED branch emitting a write is the unsound-predicate case.
    try:
        orch.attribute_write("C")
    except RollbackLedgerError:
        pass  # expected: surfaces the unsound completion predicate


if __name__ == "__main__":
    _demo()
