# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abandon-speculative-rollback-and-escalate-to-branch-reconciliation-when-concurrent-agents-commit-side-effecting.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abandon-speculative-rollback-and-escalate-to-branch-reconciliation-when-concurrent-agents-commit-side-effecting.warrant.json
# Markdown SHA-256:   f00192478fa07684c638f909fc8932801025767956c5d549a28dd7b35801c35a
# Code AST SHA-256:   5311429bf2daa3ca9a2396d5f8ef1277d569b5c80534a17d362ec83023af3128
# Verified Classes:   UnmergeableState, EffectClass, Effect, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class UnmergeableState(RuntimeError):
    """Raised when a losing branch has committed non-invertible effects and
    the effect ledger is incomplete, so neither rollback nor reconciliation
    can produce a coherent successor state. Terminal: requires human escalation."""


class EffectClass(Enum):
    INVERTIBLE = "invertible"        # has a registered, authorized inverse
    COMPENSABLE = "compensable"      # no inverse, but a compensating effect exists
    COMMITTED = "committed"          # no inverse, no compensation: irreversible


@dataclass
class Effect:
    branch_id: str
    tool: str
    effect_class: EffectClass
    inverse_ref: Optional[str] = None
    inverse_confirmed: bool = False
    observable: bool = True          # False = fire-and-forget, ledger may be incomplete


@dataclass
class Branch:
    branch_id: str
    ledger: list[Effect] = field(default_factory=list)

    def record(self, effect: Effect) -> None:
        # Ledger write is synchronous and precedes the branch seeing the result.
        self.ledger.append(effect)


def classify_disposition(branch: Branch) -> str:
    """Decide whether a losing branch may be rolled back, must be reconciled,
    or is unmergeable. Evaluated per-effect at selection time."""
    if any(not e.observable for e in branch.ledger):
        # Cannot enumerate effects -> cannot reconcile -> cannot safely collapse.
        raise UnmergeableState(
            f"branch {branch.branch_id} has unobservable effects; "
            f"ledger incomplete, rollback and reconciliation both unsafe"
        )
    if all(e.effect_class is EffectClass.INVERTIBLE and e.inverse_confirmed
           for e in branch.ledger):
        return "rollback"
    if any(e.effect_class is EffectClass.COMMITTED for e in branch.ledger):
        # Irreversible committed effect: reconcile via compensating delta,
        # never via inverse.
        return "reconcile"
    return "reconcile"


def collapse_fanout(branches: list[Branch], winner_id: str) -> dict[str, str]:
    dispositions: dict[str, str] = {}
    for b in branches:
        if b.branch_id == winner_id:
            dispositions[b.branch_id] = "commit"
            continue
        try:
            dispositions[b.branch_id] = classify_disposition(b)
        except UnmergeableState:
            # Terminal: halt fan-out, surface ledger, do not swallow.
            raise
    return dispositions
