# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-divergent-speculative-branches-when-rollback-of-a-committed-side-effect-is-not-idempotent.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-divergent-speculative-branches-when-rollback-of-a-committed-side-effect-is-not-idempotent.warrant.json
# Markdown SHA-256:   58488960004345adde412dbbc9aaee540dfd17fe302ecfa8921bfb5f731bf397
# Code AST SHA-256:   9e4d6e7d13e2c3c7ff54210542f92c6c9b4803def62ce2d1bac6908d219e4b92
# Verified Classes:   NonIdempotentRollbackError, Effect, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class NonIdempotentRollbackError(RuntimeError):
    """Raised when reconciliation attempts to roll back a branch whose
    committed effects cannot be undone idempotently."""
    pass


@dataclass
class Effect:
    tool: str
    args_hash: str
    idempotency_key: Optional[str]  # None => not replay-safe
    committed: bool = False


@dataclass
class Branch:
    name: str
    effects: list = field(default_factory=list)
    state_rolled_back: bool = False


def reconcile(winner: Branch, losers: list) -> list:
    """Return the residual effects that must be compensated.
    Refuses to declare a clean rollback if a losing branch committed
    a non-idempotent effect that was never enumerated."""
    residuals = []
    for b in losers:
        for eff in b.effects:
            if not eff.committed:
                continue
            if eff.idempotency_key is None:
                # Cannot be safely undone; must surface, not drop.
                raise NonIdempotentRollbackError(
                    f"branch {b.name!r} committed non-idempotent effect "
                    f"{eff.tool}({eff.args_hash}); rollback is not sound. "
                    f"Compensate explicitly and log as RESIDUAL_EFFECT."
                )
            if eff.tool not in {w.tool for w in winner.effects}:
                residuals.append((b.name, eff))
        b.state_rolled_back = True
    return residuals


# Trace of the incident: branch_B merged without an idempotency key.
branch_b = Branch("branch_B", [Effect("merge_records", "123,124", None, committed=True)])
try:
    reconcile(Branch("branch_A"), [branch_b])
except NonIdempotentRollbackError as e:
    print(f"BLOCKED: {e}")
