# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-branch-the-irreversible-external-side-effect-invariant-in-multi-agent-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-branch-the-irreversible-external-side-effect-invariant-in-multi-agent-rollback.warrant.json
# Markdown SHA-256:   87bf14d2c18b2148c0bdfddeed4327cafff133d412f8eb7e2b19b773bd870e39
# Code AST SHA-256:   d3caf32714d6e12a8822429162299ba1ee3030bfeb04686e1c36ba51dbd2b77d
# Verified Classes:   IrreversibleSideEffectError, BranchState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class IrreversibleSideEffectError(RuntimeError):
    """Raised when a speculative branch attempts rollback after externalizing
    an effect that cannot be revoked or compensated within the transaction."""
    pass


class BranchState:
    STAGED = "staged"
    EXTERNALIZED = "externalized"
    FENCED = "fenced"
    COMMITTED = "committed"
    ROLLED_BACK = "rolled_back"


def rollback_branch(branch, compensation_registry):
    """Attempt to discard a speculative branch.

    A branch is only discardable while every effect it produced remains
    inside the transaction boundary (staged, or externalized under a
    revocable branch-scoped key with a registered compensation).
    """
    if branch.state == BranchState.STAGED:
        branch.state = BranchState.ROLLED_BACK
        return

    if branch.state == BranchState.EXTERNALIZED:
        compensation = compensation_registry.get(branch.id)
        if compensation is None or not compensation.is_idempotent:
            # Effect crossed the boundary with no revocable path.
            branch.state = BranchState.FENCED
            raise IrreversibleSideEffectError(
                f"branch {branch.id!r} externalized an effect without a "
                f"revocable idempotency key or registered compensation; "
                f"it cannot be rolled back, only compensated"
            )
        compensation.invoke()
        branch.state = BranchState.ROLLED_BACK
        return

    if branch.state == BranchState.FENCED:
        raise IrreversibleSideEffectError(
            f"branch {branch.id!r} is already fenced; rollback is not a "
            f"valid transition, invoke compensation instead"
        )

    raise IrreversibleSideEffectError(
        f"branch {branch.id!r} in state {branch.state!r} is not rollback-eligible"
    )
