# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-a-speculative-branch-when-an-optimistic-tool-invocation-has-already-produced-irreversible-side-effects-before-the-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-a-speculative-branch-when-an-optimistic-tool-invocation-has-already-produced-irreversible-side-effects-before-the-rollback.warrant.json
# Markdown SHA-256:   f57e61c89c665b06545e43bce55d88d5d9efba8414b05917744e076cbbf6252b
# Code AST SHA-256:   040bfee0ded6447776be2234c536fb0cf4385bbfa241a6eaa88629e97b176c80
# Verified Classes:   UnrollbackableEffectError, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnrollbackableEffectError(RuntimeError):
    """Raised when a losing speculative branch has emitted an effect outside
    the checkpoint undo set, or has an in-flight call at barrier time."""
    pass


class Branch:
    def __init__(self, branch_id, emitted_effects, in_flight_calls):
        self.branch_id = branch_id
        self.emitted_effects = emitted_effects   # list of effect_class strings
        self.in_flight_calls = in_flight_calls   # list of call_state strings


def rollback_branch(branch: Branch, checkpoint_undo_set: set[str]) -> str:
    # Drain check: any in-flight call means terminal state is unknown.
    if branch.in_flight_calls:
        raise UnrollbackableEffectError(
            f"branch {branch.branch_id} has in-flight calls "
            f"{branch.in_flight_calls}; barrier fired before quiescence"
        )

    # Undo-set membership: every emitted effect must be invertible.
    out_of_set = [e for e in branch.emitted_effects if e not in checkpoint_undo_set]
    if out_of_set:
        raise UnrollbackableEffectError(
            f"branch {branch.branch_id} emitted non-invertible effects "
            f"{out_of_set} outside undo_set {sorted(checkpoint_undo_set)}; "
            f"taint checkpoint and escalate, do not revert"
        )

    # Legal: all effects terminal and invertible.
    for effect in branch.emitted_effects:
        invert(effect)
    return f"branch {branch.branch_id} rolled_back effects={len(branch.emitted_effects)}"


def invert(effect: str) -> None:
    # Delta inversion against the checkpoint model.
    pass
