# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-commit-a-speculative-branch-whose-rollback-cost-exceeds-its-expected-value-the-orphaned-effect-debt-invariant-in-parallel-agent-s.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-commit-a-speculative-branch-whose-rollback-cost-exceeds-its-expected-value-the-orphaned-effect-debt-invariant-in-parallel-agent-s.warrant.json
# Markdown SHA-256:   96a255165925a39642a223a7c418dd6d908577615ae7823437860c916a9d0396
# Code AST SHA-256:   50bedb63ddf0b118b0db1a577740bc3cf5e5bee65e5342e0f1a750cdcd76944e
# Verified Classes:   SpeculationCommitError, Effect, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

EffectClass = Literal["reversible_free", "reversible_costly", "irreversible"]


class SpeculationCommitError(RuntimeError):
    """Raised when a speculative commit decision violates the orphaned-effect debt invariant."""


@dataclass
class Effect:
    class_: EffectClass
    reversal_cost: float = 0.0
    unbufferable: bool = False


@dataclass
class Branch:
    id: str
    score: float
    completed: bool
    effects: list[Effect] = field(default_factory=list)

    def rollback_cost(self) -> float:
        # Only unbufferable effects are actually paid on rollback.
        # Buffered effects are discarded for free by the proxy.
        return sum(e.reversal_cost for e in self.effects if e.unbufferable)


def commit_decision(
    branches: list[Branch],
    *,
    require_completed_runner_up: bool = True,
) -> Branch:
    if len(branches) < 2:
        raise SpeculationCommitError("arbitration requires at least two branches")

    ranked = sorted(branches, key=lambda b: b.score, reverse=True)
    leader, runner_up = ranked[0], ranked[1]

    if require_completed_runner_up and not runner_up.completed:
        raise SpeculationCommitError(
            f"runner-up {runner_up.id} is partial; its value distribution is "
            f"unbounded and cannot be compared to leader {leader.id}"
        )

    score_delta = leader.score - runner_up.score
    debt = sum(b.rollback_cost() for b in branches if b is not leader)

    if score_delta <= debt:
        raise SpeculationCommitError(
            f"commit of {leader.id} would incur debt {debt:.2f} exceeding "
            f"score delta {score_delta:.2f}; orphaned-effect debt invariant violated"
        )

    return leader


def guarded_commit(branches: list[Branch]) -> Branch:
    try:
        return commit_decision(branches)
    except SpeculationCommitError:
        # Fallback: serialize the unbufferable effects and re-arbitrate,
        # or abort the task and surface the debt to the operator.
        raise
