# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-reconciliation-from-committing-a-tool-call-whose-side-effects-escaped-the-rollback-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-reconciliation-from-committing-a-tool-call-whose-side-effects-escaped-the-rollback-boundary.warrant.json
# Markdown SHA-256:   1d637872de1cd33f5d949c01f536890e066775b0f5815b5d88322bd7502d69a9
# Code AST SHA-256:   a503a624ffbc2406130f5faf523c32a00a31b8460690a513b16efc0ac71ff49d
# Verified Classes:   SpeculativeCommitViolation, Reversibility, ToolSpec, Receipt, SideEffectLedger, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class SpeculativeCommitViolation(RuntimeError):
    """Raised when a speculative branch attempts an action that cannot be
    rolled back, or when reconciliation would commit over an escaped effect."""
    pass


class Reversibility(Enum):
    REVERSIBLE = "reversible"
    IDEMPOTENT = "idempotent"
    IRREVERSIBLE = "irreversible"


@dataclass(frozen=True)
class ToolSpec:
    name: str
    reversibility: Reversibility
    key_fn: Optional[Callable[[dict], str]] = None


@dataclass
class Receipt:
    branch_id: str
    tool: str
    idem_key: Optional[str]
    txn: str


@dataclass
class SideEffectLedger:
    # Append-only; survives branch rollback. This is the testimony log.
    receipts: list[Receipt] = field(default_factory=list)

    def record(self, r: Receipt) -> None:
        self.receipts.append(r)

    def keys_for(self, tool: str) -> set[str]:
        return {r.idem_key for r in self.receipts
                if r.tool == tool and r.idem_key is not None}


@dataclass
class Branch:
    branch_id: str
    speculative: bool = True


def dispatch_tool(branch: Branch, spec: ToolSpec, args: dict,
                  ledger: SideEffectLedger, txn: str) -> Receipt:
    """Dispatch a tool call from a branch, enforcing the rollback invariant.

    Invariant: a speculative branch may only dispatch calls that are
    reversible or idempotent under a *stable* key. Irreversible calls must
    be committed (branch promoted) before dispatch.
    """
    if branch.speculative and spec.reversibility is Reversibility.IRREVERSIBLE:
        raise SpeculativeCommitViolation(
            f"branch {branch.branch_id} is speculative but tool "
            f"{spec.name!r} is irreversible; promote branch to committed "
            f"before dispatch or serialize behind consensus"
        )

    idem_key = None
    if spec.reversibility is Reversibility.IDEMPOTENT:
        if spec.key_fn is None:
            raise SpeculativeCommitViolation(
                f"tool {spec.name!r} is idempotent but has no key_fn; "
                f"branch-local keys defeat idempotency across branches"
            )
        idem_key = spec.key_fn(args)
        if idem_key in ledger.keys_for(spec.name):
            # Collision with a sibling branch's receipt: dedupe, do not re-execute.
            existing = next(r for r in ledger.receipts
                            if r.tool == spec.name and r.idem_key == idem_key)
            return existing

    receipt = Receipt(branch_id=branch.branch_id, tool=spec.name,
                      idem_key=idem_key, txn=txn)
    ledger.record(receipt)
    return receipt


def reconcile(surviving: Branch, ledger: SideEffectLedger,
              planned_effects: list[tuple[str, Optional[str]]]) -> None:
    """Commit the surviving plan only if no escaped effect collides with it."""
    for tool, key in planned_effects:
        if key is not None and key in ledger.keys_for(tool):
            raise SpeculativeCommitViolation(
                f"reconciliation blocked: planned {tool!r} with key {key!r} "
                f"already exists in ledger from a prior (possibly rolled-back) "
                f"branch; duplicate side effect would commit silently"
            )
    surviving.speculative = False


# --- demonstration of the observed incident ---
if __name__ == "__main__":
    ledger = SideEffectLedger()
    refund = ToolSpec("issue_refund", Reversibility.IRREVERSIBLE)

    b = Branch("B")
    try:
        # Correct behavior: refuse speculative dispatch of an irreversible call.
        dispatch_tool(b, refund, {"amount": 4200}, ledger, txn="r_8891")
    except SpeculativeCommitViolation as e:
        print("blocked at dispatch:", e)

    # If B had been (wrongly) promoted and committed, the ledger retains the
    # receipt even when B loses consensus; reconciliation then detects the dup.
    b.speculative = False
    receipt = dispatch_tool(b, refund, {"amount": 4200}, ledger, txn="r_8891")
    ledger.record(receipt)

    a = Branch("A")
    a.speculative = False
    try:
        reconcile(a, ledger, planned_effects=[("issue_refund", None)])
        # key is None here: no idempotency key, so the ledger check must be
        # backed by a write-set intersection; this demo surfaces the gap.
        print("committed A (no key: relies on write-set check upstream)")
    except SpeculativeCommitViolation as e:
        print("reconciliation blocked:", e)
