# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-a-speculative-branch-reconciling-divergent-side-effect-logs-after-rollback-in-multi-agent-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-a-speculative-branch-reconciling-divergent-side-effect-logs-after-rollback-in-multi-agent-execution.warrant.json
# Markdown SHA-256:   f06fde8e3d1de95a5cfc116d5c7cf3302236a2d68c0e99aa5aedac22b6713f0f
# Code AST SHA-256:   2157ea86ce7412c34996c9cc1da65aaaf17468c90d531b20607d6ba7274fbba1
# Verified Classes:   SpeculativeContaminationError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class SpeculativeContaminationError(RuntimeError):
    """Raised when a discarded branch left an irreversible side effect
    that a surviving branch's auditor can observe, invalidating reconciliation."""


def reconcile_branches(branches, effect_ledger, live_state_snapshot):
    # effect_ledger: {branch_id: [{"kind": "reversible"|"irreversible", "reversed": bool}]}
    winners = select_winners(branches)
    discarded = [b for b in branches if b.id not in {w.id for w in winners}]

    for b in discarded:
        effects = effect_ledger.get(b.id, [])
        for eff in effects:
            if eff["kind"] == "irreversible" and not eff.get("reversed", False):
                # Cannot cleanly discard: the world is already changed.
                raise SpeculativeContaminationError(
                    f"branch {b.id} committed irreversible effect "
                    f"{eff.get('desc', '<unnamed>')} and was discarded; "
                    f"surviving branches will observe contaminated state. "
                    f"Abort speculative set or promote {b.id}."
                )

    # Only after all discarded branches are proven clean may auditors read live state.
    for w in winners:
        auditor_replay(w, live_state_snapshot)
    return [w.id for w in winners]
