# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-prove-rollback-completeness-before-speculatively-committing-a-tool-call-in-a-multi-agent-branch.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-prove-rollback-completeness-before-speculatively-committing-a-tool-call-in-a-multi-agent-branch.warrant.json
# Markdown SHA-256:   0651cd55d1c96c26d0b22c995e6b107fe1a6849f8b62ea5a37f0061f0be68070
# Code AST SHA-256:   a2b3e57d85ca9a7e91eff5c0015cc6f836f6800264f71b4692bea97eef281f9b
# Verified Classes:   SpeculativeRollbackError, BranchState, EffectLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict


class SpeculativeRollbackError(RuntimeError):
    """Raised when a branch claims rollback-complete without sink-confirmed no-effect."""


class BranchState(Enum):
    UNRESOLVED = "unresolved"
    DISPATCHING = "dispatching"
    COMMITTED = "committed"
    CANCELLED = "cancelled"
    ORPHANED = "orphaned"


@dataclass
class EffectLedger:
    # intent_key -> branch_id that holds the claim, or None if free
    claims: Dict[str, str] = field(default_factory=dict)
    committed: Dict[str, str] = field(default_factory=dict)

    def claim(self, intent_key: str, branch_id: str) -> bool:
        if intent_key in self.committed:
            return False  # already applied by a sibling; dedupe
        if intent_key in self.claims:
            return False  # another branch is mid-dispatch; block
        self.claims[intent_key] = branch_id
        return True

    def commit(self, intent_key: str, branch_id: str) -> None:
        if self.claims.get(intent_key) != branch_id:
            raise SpeculativeRollbackError(
                f"branch {branch_id} committed {intent_key} without holding the claim"
            )
        self.committed[intent_key] = branch_id
        self.claims.pop(intent_key, None)

    def release(self, intent_key: str, branch_id: str) -> None:
        if self.claims.get(intent_key) == branch_id:
            self.claims.pop(intent_key)


def cancel_branch(
    branch_id: str,
    intent_key: str,
    state: BranchState,
    ledger: EffectLedger,
    sink_confirms_no_effect: bool,
) -> BranchState:
    """Transition a branch to CANCELLED only if rollback is effect-complete."""
    if intent_key in ledger.committed:
        # Effect already durable; cancellation cannot un-apply it.
        raise SpeculativeRollbackError(
            f"cannot cancel branch {branch_id}: intent {intent_key} already "
            f"committed by {ledger.committed[intent_key]}; requires compensation"
        )
    if state == BranchState.DISPATCHING and not sink_confirms_no_effect:
        # Ambiguous ack window: dispatcher may have acked while sink committed.
        return BranchState.ORPHANED
    ledger.release(intent_key, branch_id)
    return BranchState.CANCELLED
