# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-reconciliation-from-silently-committing-orphaned-side-effects-in-multi-agent-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-reconciliation-from-silently-committing-orphaned-side-effects-in-multi-agent-rollback.warrant.json
# Markdown SHA-256:   83e011c1e7373257b7037868b0ae1e2e8c05aed30791108b4ad1c257128abea2
# Code AST SHA-256:   f000b1e8d2f6c174abf983e0fe9621976cd233911ea6eb6a558baf9892118f36
# Verified Classes:   UnreconcilableRollbackError, EffectRecord, Branch, ReconciliationLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnreconcilableRollbackError(RuntimeError):
    """Raised when a branch cannot be safely rolled back: its effects are live
    and either unattributable or uncompensable. The branch must be quarantined."""


@dataclass
class EffectRecord:
    effect_id: str
    branch_id: str
    compensation_handle: Optional[str]  # None => no inverse reachable
    idempotency_key: str


@dataclass
class Branch:
    branch_id: str
    terminal: bool
    score: float
    ledger: list[EffectRecord] = field(default_factory=list)


class ReconciliationLedger:
    def __init__(self) -> None:
        self._records: dict[str, EffectRecord] = {}

    def record(self, rec: EffectRecord) -> None:
        # Append-only; written BEFORE the effect is emitted.
        self._records[rec.effect_id] = rec

    def effects_for(self, branch_id: str) -> list[EffectRecord]:
        return [r for r in self._records.values() if r.branch_id == branch_id]


def reconcile(
    ledger: ReconciliationLedger,
    winner: Branch,
    losers: list[Branch],
) -> list[str]:
    """Commit winner, roll back losers only where compensation is reachable.
    Returns list of quarantined branch ids. Raises if winner aliases a held effect."""

    quarantined: list[str] = []
    held_effect_ids: set[str] = set()

    for loser in losers:
        effects = ledger.effects_for(loser.branch_id)
        # A non-terminal branch may be mid-effect: presume live, uncompensated.
        if not loser.terminal:
            quarantined.append(loser.branch_id)
            held_effect_ids.update(e.effect_id for e in effects)
            continue
        uncompensable = [e for e in effects if e.compensation_handle is None]
        if uncompensable:
            quarantined.append(loser.branch_id)
            held_effect_ids.update(e.effect_id for e in uncompensable)
            continue
        # Safe: every effect has a reachable inverse. Execute compensation.
        for e in effects:
            _compensate(e)

    # Gate the winner's commit on held effects it might alias.
    for e in ledger.effects_for(winner.branch_id):
        if e.effect_id in held_effect_ids:
            raise UnreconcilableRollbackError(
                f"winner {winner.branch_id} aliases held effect {e.effect_id} "
                f"from a quarantined branch; commit blocked pending resolution"
            )

    _commit(winner)
    return quarantined


def _compensate(effect: EffectRecord) -> None:
    if effect.compensation_handle is None:
        raise UnreconcilableRollbackError(
            f"effect {effect.effect_id} has no compensation handle"
        )
    # invoke inverse tool by handle; idempotent via idempotency_key


def _commit(branch: Branch) -> None:
    # apply winning branch's effects atomically
    ...
