# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-commits-a-branch-whose-rollback-witness-was-evicted-before-reconciliation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-commits-a-branch-whose-rollback-witness-was-evicted-before-reconciliation.warrant.json
# Markdown SHA-256:   a44a8f2df9da86036a78ab6233381c6e2f1b29703cdeae868e3e29466e4e2d00
# Code AST SHA-256:   17a2b9c544de8a78ed5325ffb81e283f1068d121b6b4742aced9217a67d3ca5f
# Verified Classes:   WitnessMissingError, UnreconciledCommitError, BranchState, Witness, Branch, WitnessStore, Coordinator
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum


class WitnessMissingError(RuntimeError):
    """Raised when a rollback is attempted for a branch whose witness
    pre-image is no longer material. Must trigger quarantine, never discard."""


class UnreconciledCommitError(RuntimeError):
    """Raised when a coordinator attempts to commit a winner over a region
    still affected by an un-rollbackable losing branch."""


class BranchState(Enum):
    LIVE = "live"
    EXTERNALIZED = "externalized"
    TERMINAL = "terminal"
    QUARANTINED = "quarantined"


@dataclass
class Witness:
    branch_id: str
    pre_image_hash: str
    pre_image: bytes
    refcount: int = 1
    ttl_s: int = 90


@dataclass
class Branch:
    branch_id: str
    state: BranchState = BranchState.LIVE
    externalized: bool = False


class WitnessStore:
    def __init__(self):
        self._witnesses: dict[str, Witness] = {}

    def register(self, w: Witness) -> None:
        self._witnesses[w.branch_id] = w

    def reap(self, branch_id: str, wallclock_s: int) -> None:
        w = self._witnesses.get(branch_id)
        if w is None:
            return
        # Guardrail 1+2: never evict a pinned or externalized witness.
        if w.refcount > 0:
            return
        if wallclock_s > w.ttl_s:
            del self._witnesses[branch_id]

    def materialize(self, branch_id: str) -> bytes:
        w = self._witnesses.get(branch_id)
        if w is None:
            raise WitnessMissingError(
                f"no material pre-image for branch {branch_id}; "
                f"cannot roll back, must quarantine"
            )
        return w.pre_image


class Coordinator:
    def __init__(self, store: WitnessStore):
        self.store = store
        self.branches: dict[str, Branch] = {}
        self.quarantine: set[str] = set()

    def spawn(self, branch_id: str, pre_image: bytes) -> None:
        self.branches[branch_id] = Branch(branch_id)
        self.store.register(
            Witness(
                branch_id=branch_id,
                pre_image_hash=hashlib.sha256(pre_image).hexdigest(),
                pre_image=pre_image,
            )
        )

    def externalize(self, branch_id: str) -> None:
        b = self.branches[branch_id]
        b.externalized = True
        b.state = BranchState.EXTERNALIZED
        # Guardrail 2: pin the witness the moment effects escape.
        w = self.store._witnesses.get(branch_id)
        if w is not None:
            w.refcount = max(w.refcount, 1)

    def rollback(self, branch_id: str) -> None:
        b = self.branches[branch_id]
        try:
            self.store.materialize(branch_id)
        except WitnessMissingError:
            # Guardrail 3: missing witness on an externalized branch is a
            # hard stop. Never silently discard.
            if b.externalized:
                b.state = BranchState.QUARANTINED
                self.quarantine.add(branch_id)
                raise
            b.state = BranchState.TERMINAL
            return
        b.state = BranchState.TERMINAL

    def commit_winner(self, winner_id: str) -> None:
        if self.quarantine:
            raise UnreconciledCommitError(
                f"refusing to commit {winner_id}; un-rollbackable branches "
                f"still affect region: {sorted(self.quarantine)}"
            )
        self.branches[winner_id].state = BranchState.TERMINAL
