# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-checkpoint-before-speculative-branch-and-verify-execution-to-prevent-irreversible-side-effect-leakage-on-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-checkpoint-before-speculative-branch-and-verify-execution-to-prevent-irreversible-side-effect-leakage-on-rollback.warrant.json
# Markdown SHA-256:   20ef078d3b71aea50431cec6f74f1d087472c74382314d02a7d4520c73c06021
# Code AST SHA-256:   7c9b1b8b8a55c7d609d5d4d1e36bd352ea5375e6a6def409f62da5bbff478236
# Verified Classes:   UnrollbackableEffectError, Branch, Effect
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnrollbackableEffectError(RuntimeError):
    """Raised when rollback is attempted over a branch holding a non-stageable,
    non-quiescent external effect. Rollback would revert belief, not world."""
    pass


class Branch:
    def __init__(self, branch_id, effects):
        self.branch_id = branch_id
        self.effects = effects  # list of Effect


class Effect:
    def __init__(self, tool, stageable, in_flight, committed):
        self.tool = tool
        self.stageable = stageable
        self.in_flight = in_flight
        self.committed = committed


def rollback_branch(branch: Branch) -> None:
    for eff in branch.effects:
        # A stageable effect that never flushed is genuinely reversible.
        if eff.stageable and not eff.committed:
            continue
        # A non-stageable effect already committed or still in flight
        # cannot be reverted by dropping branch context.
        if not eff.stageable and (eff.committed or eff.in_flight):
            raise UnrollbackableEffectError(
                f"branch {branch.branch_id} tool={eff.tool} "
                f"committed={eff.committed} in_flight={eff.in_flight}: "
                f"rollback would leak external state; "
                f"await quiescence and re-verify before commit"
            )


def commit_winner(winner: Branch, losers: list[Branch]) -> None:
    # Quiescence gate: no branch may hold an in-flight effect at commit time.
    for b in [winner, *losers]:
        for eff in b.effects:
            if eff.in_flight:
                raise UnrollbackableEffectError(
                    f"branch {b.branch_id} has in-flight effect {eff.tool}; "
                    f"scoring is premature"
                )
    for loser in losers:
        rollback_branch(loser)  # raises if any loser leaked a non-stageable effect
    flush_pending(winner)       # only now do winner's staged effects reach the world
