# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-a-speculative-branch-before-rollback-commits-side-effects-it-cannot-retract.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-a-speculative-branch-before-rollback-commits-side-effects-it-cannot-retract.warrant.json
# Markdown SHA-256:   3c30733b55448421ddbf0745edd3027ba2477e6c10e6c50f19f02f7d3b8e7ca9
# Code AST SHA-256:   2d1b4a8900717f3b14b3badf498eb321b295b7c0756e6a4f5e07d4ccaab23abb
# Verified Classes:   IrreversibleBranchRollbackError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class IrreversibleBranchRollbackError(RuntimeError):
    """Raised when a speculative branch is rolled back after committing non-retractable effects."""
    pass


IRREVERSIBLE_TOOLS = {"payments.transfer", "payments.void", "email.send", "records.delete"}


def assert_speculation_eligible(branch_tools: set[str]) -> None:
    crossing = branch_tools & IRREVERSIBLE_TOOLS
    if crossing:
        raise IrreversibleBranchRollbackError(
            f"branch not speculation-eligible: irreversible tools {sorted(crossing)} "
            f"would commit before divergence resolution; run serially or stage effects"
        )


def resolve_divergence(branch, canonical, external_state: dict) -> str:
    effects = external_state.get(branch.id, "unknown")
    if effects == "unknown":
        raise IrreversibleBranchRollbackError(
            f"branch {branch.id} effect state unknown; cannot roll back on unknown, must query"
        )
    if effects and branch.id != canonical.id:
        # effects landed on a losing branch: rollback is a fiction
        raise IrreversibleBranchRollbackError(
            f"branch {branch.id} committed irreversible effects before divergence; "
            f"compensating transaction required, not logical rollback"
        )
    branch.mark_rolled_back()
    return "clean"
