# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-a-speculative-branch-from-a-committed-effect-when-rolling-back-a-divergent-agent-plan.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-a-speculative-branch-from-a-committed-effect-when-rolling-back-a-divergent-agent-plan.warrant.json
# Markdown SHA-256:   db16b2f65496b2ab721077a37ed5b44a9fff64adfc11ac4235a3ae1c0295dedd
# Code AST SHA-256:   096f82fdad4119176eecbf2d689890e40e43cdf4dda54eed986750a5b1eac64a
# Verified Classes:   EffectLeakageError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class EffectLeakageError(RuntimeError):
    """Raised when a diverged speculative branch has emitted an effect
    that cannot be rolled back, invalidating the commit record."""
    pass


IRREVERSIBLE = "irreversible"
SHARED_NO_READ_ISOLATION = "shared_no_read_isolation"


def verify_branch_rollback(branch, effect_log):
    """
    Called when a speculative branch diverges and the orchestrator intends
    to roll back. Returns only if every emitted effect is safely reversible
    and isolated. Raises EffectLeakageError otherwise.
    """
    for effect in effect_log:
        if effect.branch_id != branch.id:
            continue
        if effect.effect_class == IRREVERSIBLE:
            raise EffectLeakageError(
                f"branch {branch.id} emitted irreversible effect "
                f"{effect.tool}@{effect.target}; commit record invalid"
            )
        if effect.effect_class == SHARED_NO_READ_ISOLATION:
            raise EffectLeakageError(
                f"branch {branch.id} mutated shared target {effect.target} "
                f"without read isolation; downstream may have observed it"
            )
    # All effects reversible and isolated: safe to discard plan state.
    branch.rollback_plan_state()
    return True


def commit_winner(winner, diverged_branches, effect_logs):
    for branch in diverged_branches:
        verify_branch_rollback(branch, effect_logs[branch.id])
    winner.commit()
    return winner.id
