# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-rollback-state-when-speculative-agent-branches-commit-side-effects-to-a-shared-external-substrate-before-divergence-i.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-rollback-state-when-speculative-agent-branches-commit-side-effects-to-a-shared-external-substrate-before-divergence-i.warrant.json
# Markdown SHA-256:   70211367e11fe5f01c15650d3d59401dc8328ab89d418efd1126ccbbc71b2e66
# Code AST SHA-256:   9e0da966c4d9deb2855d96d3d2d1b1864c2ef0d1ff1f5b3bc26ea4cfbe5be950
# Verified Classes:   SpeculationRollbackError, InvertibilityClass, Effect, SpeculationLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class SpeculationRollbackError(RuntimeError):
    """Raised when a loser branch's effect cannot be inverted or quarantined
    before the winning branch is released to execute."""


class InvertibilityClass(Enum):
    COMPENSABLE = "compensable"      # has a tested inverse; may commit early
    NON_COMPENSABLE = "non_compensable"  # must be staged, applied only on selection


@dataclass
class Effect:
    branch_id: str
    tool: str
    inverse: Callable[[], None] | None
    quarantined: bool = False
    applied: bool = False


@dataclass
class SpeculationLedger:
    effects: list[Effect] = field(default_factory=list)

    def record(self, effect: Effect) -> None:
        self.effects.append(effect)

    def unresolved_for(self, branch_id: str) -> list[Effect]:
        return [
            e for e in self.effects
            if e.branch_id == branch_id
            and not e.quarantined
            and not (e.applied and e.inverse is not None)
        ]


def resolve_barrier(ledger: SpeculationLedger, selected: str, all_branches: list[str]) -> None:
    """Enforce: every loser effect is inverted or quarantined before the winner runs."""
    for branch in all_branches:
        if branch == selected:
            continue
        for effect in ledger.unresolved_for(branch):
            if effect.inverse is None:
                # No inverse registered: must be quarantined, never silently ignored.
                raise SpeculationRollbackError(
                    f"branch {branch} committed non-invertible effect via "
                    f"{effect.tool!r} with no compensating action and no quarantine; "
                    f"winner {selected!r} would observe a phantom commit"
                )
            try:
                effect.inverse()
                effect.applied = True
            except Exception as exc:  # inverse itself failed
                raise SpeculationRollbackError(
                    f"inverse for {effect.tool!r} on branch {branch} raised {exc!r}; "
                    f"substrate is in an indeterminate state"
                ) from exc
    # Barrier: reaching here means the winner may safely execute.
