# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-and-verify-rollback-from-resurrecting-committed-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-and-verify-rollback-from-resurrecting-committed-side-effects.warrant.json
# Markdown SHA-256:   c3cd5924ac87ef6d26bda1ea70cf737b2b9e13c869f213eb15457d8a43c8be4f
# Code AST SHA-256:   36aa630072152c98a10a0fa5e529321f2da7f2a0ee596fadeb5596420e70923f
# Verified Classes:   UncompensableDiscardError, EffectReceipt, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UncompensableDiscardError(RuntimeError):
    """Raised when a speculative branch is discarded while holding effects
    that cannot be reversed or attributed. Halts the plan; never downgraded
    to a warning, because an uncompensated discard is a world-state leak."""


@dataclass
class EffectReceipt:
    tool: str
    handle: str                 # tool-returned identity, not just success
    idempotency_key: str        # must include branch_warrant_id
    compensable: bool
    compensated: bool = False


@dataclass
class Branch:
    warrant_id: str
    receipts: list[EffectReceipt] = field(default_factory=list)
    committed: bool = False
    discarded: bool = False


def discard_branch(branch: Branch, compensate) -> None:
    if branch.committed:
        raise UncompensableDiscardError(
            f"branch {branch.warrant_id} already committed; cannot discard"
        )
    for r in branch.receipts:
        if r.compensated:
            continue
        if not r.compensable:
            raise UncompensableDiscardError(
                f"branch {branch.warrant_id} holds non-compensable effect "
                f"{r.tool}:{r.handle} (key={r.idempotency_key}); "
                f"serialize this tool behind commit instead of speculating"
            )
        # Inverse must succeed before we mark the branch discarded.
        compensate(r)
        r.compensated = True
    branch.discarded = True


def commit_branch(chosen: Branch, siblings: list[Branch]) -> None:
    # Cross-branch collision check: no sibling may hold an unreleased
    # receipt on a resource the chosen branch will touch.
    chosen_handles = {r.handle for r in chosen.receipts}
    for sib in siblings:
        if sib is chosen:
            continue
        for r in sib.receipts:
            if r.handle in chosen_handles and not r.compensated:
                raise UncompensableDiscardError(
                    f"commit of {chosen.warrant_id} aliases live effect "
                    f"{r.handle} held by sibling {sib.warrant_id}; "
                    f"discard the sibling first"
                )
    chosen.committed = True
