# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-speculative-multi-agent-execution-diverge-from-its-rollback-checkpoint-under-concurrent-branch-arbitration.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-speculative-multi-agent-execution-diverge-from-its-rollback-checkpoint-under-concurrent-branch-arbitration.warrant.json
# Markdown SHA-256:   490624a35c9187d8d19081a681e98af382cb6d279efc775dc6fd719d1c9989b3
# Code AST SHA-256:   3f36d45f31c797d4b973146aa30ad741fa141ba49e81900ce45f9f1765be6697
# Verified Classes:   SpeculativeRollbackDivergence
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class SpeculativeRollbackDivergence(RuntimeError):
    """Raised when a losing branch left uncompensated side effects observable to the winner."""
    pass


EFFECT_CLASSES = {"PURE", "IDEMPOTENT_WRITE", "EFFECTFUL"}


def assert_rollback_fidelity(branches, winner_id, undo_log):
    """
    branches: list of dicts with keys 'id', 'tool_effects' (list of effect-class strings)
    winner_id: id of the arbitrated branch
    undo_log: dict mapping loser branch id -> list of compensation records applied
    """
    for br in branches:
        if br["id"] == winner_id:
            continue
        effectful = [e for e in br["tool_effects"] if e == "EFFECTFUL"]
        if not effectful:
            continue
        applied = undo_log.get(br["id"], [])
        if len(applied) < len(effectful):
            raise SpeculativeRollbackDivergence(
                f"branch {br['id']} reached {len(effectful)} EFFECTFUL tool(s) "
                f"but only {len(applied)} compensation(s) were applied before "
                f"commit of winner {winner_id}; checkpoint rollback is not a "
                f"sufficient boundary and the winner may observe contaminated state"
            )
    return True
