# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-multi-agent-forks-from-committing-divergent-state-on-rollback-reconciliation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-multi-agent-forks-from-committing-divergent-state-on-rollback-reconciliation.warrant.json
# Markdown SHA-256:   289191345f3d206fb3fe503e301df08b4f9efd6a1916e39974d0fb8ac6ee419f
# Code AST SHA-256:   b385ad467895c0dbf8e4d29a1c94413f3f953c2640b7814329f8dcd564c37f4a
# Verified Classes:   RollbackReconciliationError, SinkClass, ToolCall, Fork, CapabilityRegistry, Reconciler
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class RollbackReconciliationError(RuntimeError):
    """Raised when a losing fork's effects cannot be attested as fully suppressed."""


class SinkClass(Enum):
    SPECULATABLE = "speculatable"        # addressable + gated + attestable
    SERIAL_ONLY = "serial_only"          # side-effect-free on rollback (pure reads)
    FORBIDDEN_IN_FORK = "forbidden"      # non-addressable, non-idempotent


@dataclass
class ToolCall:
    tool: str
    fork_id: str
    sink: str
    idempotency_key: str | None = None


@dataclass
class Fork:
    fork_id: str
    trace: list[ToolCall] = field(default_factory=list)


class CapabilityRegistry:
    def __init__(self, classify: dict[str, SinkClass]):
        self._classify = classify

    def classify(self, tool: str) -> SinkClass:
        return self._classify.get(tool, SinkClass.FORBIDDEN_IN_FORK)


class Reconciler:
    def __init__(
        self,
        registry: CapabilityRegistry,
        attest: Callable[[str, str], bool],   # (fork_id, sink) -> suppressed?
    ):
        self.registry = registry
        self.attest = attest

    def commit(self, winner: Fork, losers: list[Fork]) -> None:
        # 1. Re-derive each loser's effect surface from its TRACE, not its plan.
        for loser in losers:
            for call in loser.trace:
                cls = self.registry.classify(call.tool)
                if cls is SinkClass.FORBIDDEN_IN_FORK:
                    raise RollbackReconciliationError(
                        f"fork {loser.fork_id} emitted forbidden call {call.tool} "
                        f"against sink {call.sink}; cannot roll back, quarantine required"
                    )
                # 2. Attest suppression against the snapshot; never trust tool return.
                if not self.attest(loser.fork_id, call.sink):
                    raise RollbackReconciliationError(
                        f"fork {loser.fork_id} effects on {call.sink} not attested "
                        f"as suppressed; commit of {winner.fork_id} blocked"
                    )
        # 3. Only now is the winner's commit safe to run against the snapshot view.
        self._apply(winner)

    def _apply(self, fork: Fork) -> None:
        for call in fork.trace:
            if self.registry.classify(call.tool) is SinkClass.FORBIDDEN_IN_FORK:
                raise RollbackReconciliationError(
                    f"winner {fork.fork_id} contains forbidden call {call.tool}; "
                    f"plan must be restructured to run this serially post-commit"
                )
        # ... apply winner effects against snapshot view ...


def reconcile_or_quarantine(winner, losers, reconciler):
    try:
        reconciler.commit(winner, losers)
    except RollbackReconciliationError:
        # Quarantine: do not commit, do not pretend rollback succeeded.
        raise
