# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-speculative-multi-agent-execution-deadlock-at-the-verify-barrier-when-a-speculative-tool-call-s-side-effect-outlives-its-rollb.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-speculative-multi-agent-execution-deadlock-at-the-verify-barrier-when-a-speculative-tool-call-s-side-effect-outlives-its-rollb.warrant.json
# Markdown SHA-256:   f2bcccb0c66506575ea1e37a078e4711298b3996399fd6b531eb30221777f576
# Code AST SHA-256:   78c44ec20c6942b430df56c3c2c11293031a58797dea31d5e8132fe257212d71
# Verified Classes:   SpeculationBarrierError, BranchState, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class SpeculationBarrierError(RuntimeError):
    """Raised when the verify barrier is declared complete over a branch
    whose external effects have not been physically compensated."""


class BranchState(Enum):
    SPECULATING = "speculating"
    ROLLBACK_REQUESTED = "rollback_requested"
    ROLLBACK_COMPLETE = "rollback_complete"
    COMMITTED = "committed"


@dataclass
class Branch:
    name: str
    state: BranchState = BranchState.SPECULATING
    held_resources: set = field(default_factory=set)
    compensation_pending: bool = False


def assert_barrier_safe(branches, contended_resource):
    """The verify barrier may only pass when every branch is either committed
    or fully compensated. A branch in ROLLBACK_REQUESTED still physically holds
    whatever its in-flight tool calls acquired, even though it is logically dead.
    """
    for b in branches:
        if b.state is BranchState.ROLLBACK_REQUESTED or b.compensation_pending:
            raise SpeculationBarrierError(
                f"branch {b.name!r} is logically rolled back but physically live "
                f"(state={b.state.value}, compensation_pending={b.compensation_pending}, "
                f"held={sorted(b.held_resources)}); verify barrier would deadlock on "
                f"contended resource {contended_resource!r}"
            )
        if b.state is BranchState.ROLLBACK_COMPLETE and b.held_resources:
            raise SpeculationBarrierError(
                f"branch {b.name!r} marked rollback_complete but still holds "
                f"{sorted(b.held_resources)}; budget was released while the effect was live"
            )
    return True


def release_budget(branch, budget_ledger):
    """Budget is reclaimed only on compensation completion, never on rollback issuance."""
    if branch.state is not BranchState.ROLLBACK_COMPLETE or branch.compensation_pending:
        raise SpeculationBarrierError(
            f"refusing to release budget for {branch.name!r}: rollback not physically complete"
        )
    budget_ledger.reclaim(branch.name)
