# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-rollback-from-resurrecting-a-cancelled-tool-call-s-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-rollback-from-resurrecting-a-cancelled-tool-call-s-side-effects.warrant.json
# Markdown SHA-256:   90a5c866942200107c7a4191b4c8aea34c038bba631ae78cf8b1dc5b871e5f73
# Code AST SHA-256:   3a8ea7352f6cef85d60f1ced3eadc02ef6101c450169e26badaae07be8370087
# Verified Classes:   RollbackInvariantViolation, BranchState, CallDisposition, ToolCall, Branch, SpeculativeOrchestrator
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, Set


class RollbackInvariantViolation(RuntimeError):
    """Raised when a branch is rolled back while an emitted tool call is not provably terminal."""


class BranchState(Enum):
    SPECULATING = "speculating"
    LOSER_CANCELLING = "loser_cancelling"
    DRAINING = "draining"
    ROLLED_BACK = "rolled_back"
    ORPHANED = "orphaned"


class CallDisposition(Enum):
    PENDING = "pending"
    CANCELLATION_ACKED = "cancellation_acked"   # NOT terminal
    COMMITTED = "committed"
    COMPENSATED = "compensated"
    NOT_STARTED = "not_started"                 # terminal, fenced
    FENCE_EXPIRED = "fence_expired"             # terminal, provable


TERMINAL = {CallDisposition.COMPENSATED, CallDisposition.NOT_STARTED, CallDisposition.FENCE_EXPIRED}


@dataclass
class ToolCall:
    idem_key: str
    disposition: CallDisposition = CallDisposition.PENDING
    epoch: int = 0


@dataclass
class Branch:
    branch_id: str
    state: BranchState = BranchState.SPECULATING
    calls: Dict[str, ToolCall] = field(default_factory=dict)


class SpeculativeOrchestrator:
    def __init__(self) -> None:
        # Tombstones survive branch rollback; they are the only handle for reconciliation.
        self.tombstones: Set[str] = set()

    def emit(self, branch: Branch, idem_key: str, epoch: int) -> None:
        branch.calls[idem_key] = ToolCall(idem_key=idem_key, epoch=epoch)
        self.tombstones.add(idem_key)

    def request_cancel(self, branch: Branch) -> None:
        if branch.state is not BranchState.SPECULATING:
            raise RollbackInvariantViolation(f"cannot cancel branch {branch.branch_id} in {branch.state}")
        branch.state = BranchState.LOSER_CANCELLING
        for call in branch.calls.values():
            if call.disposition is CallDisposition.PENDING:
                # Async cancel acknowledged; still NOT terminal.
                call.disposition = CallDisposition.CANCELLATION_ACKED
        branch.state = BranchState.DRAINING

    def try_rollback(self, branch: Branch) -> None:
        if branch.state is not BranchState.DRAINING:
            raise RollbackInvariantViolation(
                f"branch {branch.branch_id} not draining; state={branch.state}"
            )
        nonterminal = [
            c.idem_key for c in branch.calls.values() if c.disposition not in TERMINAL
        ]
        if nonterminal:
            # This is the exact bug: acknowledging cancel is not proof of non-execution.
            raise RollbackInvariantViolation(
                f"branch {branch.branch_id} has non-terminal calls {nonterminal}; "
                f"rollback would discard reconciliation handles"
            )
        branch.state = BranchState.ROLLED_BACK
        # Tombstones are retained deliberately; only a fenced sweeper may clear them.

    def winner_commit_guard(self, winner_idem_key: str, effect_class: str) -> None:
        # Any live tombstone in the same effect class blocks the winning commit.
        live = [k for k in self.tombstones if k.startswith(effect_class)]
        if live and winner_idem_key not in live:
            raise RollbackInvariantViolation(
                f"winner {winner_idem_key} blocked by live loser tombstones {live}"
            )


def demo() -> None:
    orch = SpeculativeOrchestrator()
    loser = Branch(branch_id="credit")
    orch.emit(loser, "task7:credit", epoch=3)
    orch.request_cancel(loser)
    # Cancellation was merely ACKed; rollback must refuse.
    orch.try_rollback(loser)  # raises


if __name__ == "__main__":
    demo()
