# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-speculative-agent-branch-rollback-as-unsafe-the-side-effect-ordering-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-speculative-agent-branch-rollback-as-unsafe-the-side-effect-ordering-invariant.warrant.json
# Markdown SHA-256:   9903208eeef5f08cd16c5649fbade59ba51a33a6c45e9497367811c687e69727
# Code AST SHA-256:   af88f034cb4f93d23bbde285aed01da76d15d8c4ed30468fd0afdda0e29b6eea
# Verified Classes:   RollbackPastIrreversibleEffectError, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class RollbackPastIrreversibleEffectError(RuntimeError):
    """Raised when a speculative branch is asked to roll back after it has
    emitted an externally visible, non-idempotent effect. State rollback
    cannot neutralize the effect; reconciliation is required."""


class Branch:
    def __init__(self, branch_id: str):
        self.branch_id = branch_id
        self.first_irreversible_effect = None
        self.committed = False

    def emit_irreversible(self, effect_id: str) -> None:
        # Called when a tool performs a non-idempotent external action.
        if self.first_irreversible_effect is None:
            self.first_irreversible_effect = effect_id

    def rollback(self) -> None:
        if self.first_irreversible_effect is not None and not self.committed:
            raise RollbackPastIrreversibleEffectError(
                f"branch {self.branch_id} emitted irreversible effect "
                f"{self.first_irreversible_effect!r}; cannot roll back, "
                f"route to reconciliation"
            )
        # Safe: only private state existed, discard it.
        self.committed = False


def resolve_divergence(branches: list[Branch], winner_id: str) -> None:
    for b in branches:
        if b.branch_id == winner_id:
            b.committed = True
        else:
            b.rollback()
