# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branch-merges-when-a-rolled-back-branch-has-already-emitted-irreversible-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branch-merges-when-a-rolled-back-branch-has-already-emitted-irreversible-side-effects.warrant.json
# Markdown SHA-256:   9dc5bd4531dc1ccdc9e46e976cac831f1e41ef6c6750b7f5f67d971c482a5aab
# Code AST SHA-256:   51f4ca79d689356e52731fe541a5a4f46c25bc3a44813550cdd28338e6c556f7
# Verified Classes:   EffectClass, CorruptMergeError, Effect, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Callable


class EffectClass(Enum):
    READ = "read"
    COMPENSABLE = "compensable"
    IRREVERSIBLE = "irreversible"


class CorruptMergeError(RuntimeError):
    """Raised when a merge would install canonical state while an
    irreversible effect from a losing branch remains unaccounted for."""


@dataclass
class Effect:
    branch_id: str
    tool: str
    effect_class: EffectClass
    inverse: Callable[[], None] | None = None
    reversed: bool = False


@dataclass
class Branch:
    branch_id: str
    is_winner: bool = False
    effects: list[Effect] = field(default_factory=list)
    # reasoning state is discarded on loss; effect log is NOT


def merge(branches: list[Branch]) -> None:
    winners = [b for b in branches if b.is_winner]
    if len(winners) != 1:
        raise CorruptMergeError(f"expected exactly one winner, got {len(winners)}")

    losers = [b for b in branches if not b.is_winner]
    unresolved: list[Effect] = []

    for loser in losers:
        for eff in loser.effects:
            if eff.effect_class is EffectClass.READ:
                continue
            if eff.effect_class is EffectClass.COMPENSABLE and eff.inverse is not None:
                try:
                    eff.inverse()
                    eff.reversed = True
                except Exception:
                    unresolved.append(eff)
                continue
            # IRREVERSIBLE and not commit-gated to winner: cannot roll back the world
            if not eff.reversed:
                unresolved.append(eff)

    if unresolved:
        # Do NOT install canonical state. Mark tainted and escalate.
        raise CorruptMergeError(
            "merge blocked: losing-branch irreversible effects unaccounted for: "
            + ", ".join(f"{e.branch_id}:{e.tool}" for e in unresolved)
            + " -- state must be installed as TAINTED, not canonical"
        )
    # only now is it safe to discard loser reasoning state and install winner
