# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-roll-back-a-speculative-branch-committed-side-effect-divergence-in-cost-aware-speculative-multi-agent-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-roll-back-a-speculative-branch-committed-side-effect-divergence-in-cost-aware-speculative-multi-agent-execution.warrant.json
# Markdown SHA-256:   9f0569c8fc74b96bebfa373305000dc1415a5835645f94d77f52df024e50028b
# Code AST SHA-256:   c6824b283c133fc5272d7e65d096e8cecd49087ea791ca9428d509cce81eaf7d
# Verified Classes:   IrreversibleEffectError, RollbackDivergenceError, EffectKind, Effect, Branch, SpeculativeOrchestrator
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class IrreversibleEffectError(RuntimeError):
    """Raised when a branch crosses the commit horizon without a speculation token."""
    pass


class RollbackDivergenceError(RuntimeError):
    """Raised when a local effect log claims voided but the remote ledger shows applied."""
    pass


class EffectKind(Enum):
    REVERSIBLE = "reversible"
    IRREVERSIBLE = "irreversible"


@dataclass
class Effect:
    branch_id: str
    kind: EffectKind
    op: str
    spec_token: Optional[str]
    committed_remote: bool = False
    voided_local: bool = False


@dataclass
class Branch:
    branch_id: str
    steps_taken: int = 0
    tokens_spent: int = 0
    crossed_horizon: bool = False
    effects: list = field(default_factory=list)


class SpeculativeOrchestrator:
    def __init__(self, fork_width: int, token_budget_per_branch: int):
        self.fork_width = fork_width
        self.token_budget = token_budget_per_branch
        self.branches: dict[str, Branch] = {}
        self.remote_ledger: list[Effect] = []
        self._min_steps_to_irreversible: Optional[int] = None

    def register_branch(self, branch_id: str) -> Branch:
        b = Branch(branch_id)
        self.branches[branch_id] = b
        return b

    def record_step(self, branch_id: str, tokens: int, effect: Optional[Effect] = None) -> None:
        b = self.branches[branch_id]
        b.steps_taken += 1
        b.tokens_spent += tokens

        if effect is not None and effect.kind is EffectKind.IRREVERSIBLE:
            if effect.spec_token is None:
                # Branch crossed the commit horizon un-fenced: it is now committed-by-side-effect.
                b.crossed_horizon = True
                self._min_steps_to_irreversible = min(
                    self._min_steps_to_irreversible or b.steps_taken,
                    b.steps_taken,
                )
                self._apply_irreversible(b, effect)
            else:
                # Fenced: safe to hold until winner selection.
                self.remote_ledger.append(effect)
                b.effects.append(effect)

        if b.tokens_spent > self.token_budget and not b.crossed_horizon:
            # Pruning a branch that has NOT crossed the horizon is safe.
            self._discard(b)
        elif b.tokens_spent > self.token_budget and b.crossed_horizon:
            raise IrreversibleEffectError(
                f"branch {branch_id} exceeded budget after crossing commit horizon; "
                f"cannot discard committed-by-side-effect branch"
            )

    def _apply_irreversible(self, branch: Branch, effect: Effect) -> None:
        effect.committed_remote = True
        self.remote_ledger.append(effect)
        branch.effects.append(effect)

    def _discard(self, branch: Branch) -> None:
        for e in branch.effects:
            if e.committed_remote:
                raise RollbackDivergenceError(
                    f"attempted to void committed effect {e.op} on branch {branch.branch_id}"
                )
            e.voided_local = True

    def select_winner(self, scores: dict[str, float]) -> Branch:
        committed = [b for b in self.branches.values() if b.crossed_horizon]
        if committed:
            # Rollback is forbidden for committed branches; re-score among them only.
            winner = max(committed, key=lambda b: scores.get(b.branch_id, float("-inf")))
            return winner
        return max(self.branches.values(), key=lambda b: scores.get(b.branch_id, float("-inf")))

    def finalize(self) -> None:
        # Reconcile local effect log against remote ledger before declaring round complete.
        for b in self.branches.values():
            for e in b.effects:
                if e.voided_local and e.committed_remote:
                    raise RollbackDivergenceError(
                        f"effect {e.op} voided locally but committed remotely on {b.branch_id}"
                    )
        if self._min_steps_to_irreversible is not None and self._min_steps_to_irreversible == 0:
            raise IrreversibleEffectError(
                "irreversible effect occurred at step 0; speculation depth is unsound"
            )
