# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-multi-agent-rollback-from-resurrecting-a-poisoned-sibling-checkpoint.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-multi-agent-rollback-from-resurrecting-a-poisoned-sibling-checkpoint.warrant.json
# Markdown SHA-256:   eec5485a377b94173ccf6d336ee5ede52f67e22ca7c333c56127e33715887777
# Code AST SHA-256:   43574c4e0d28f558466d54decc111c826f57b6bfcd841e03bee4537c592c3cce
# Verified Classes:   RollbackInvariantError, BranchState, Branch, Coordinator
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class RollbackInvariantError(RuntimeError):
    """Raised when a speculative branch is killed or committed in violation of
    the epoch-fencing / terminality invariant."""
    pass


class BranchState(Enum):
    RUNNING = "running"
    TERMINAL = "terminal"      # producer asserts done, but not yet validated
    VALIDATED = "validated"    # independently re-read by coordinator
    RETRACTED = "retracted"    # producer withdrew its own terminal claim
    KILLED = "killed"


@dataclass
class Branch:
    worker_id: str
    epoch: int
    state: BranchState = BranchState.RUNNING
    context_retained: bool = True
    scratch_writes: list = field(default_factory=list)


@dataclass
class Coordinator:
    committed_epoch: Optional[int] = None
    scratch: dict = field(default_factory=dict)  # epoch -> list of writes

    def select(self, branches: list[Branch], claim_epoch: int) -> Branch:
        target = next((b for b in branches if b.epoch == claim_epoch), None)
        if target is None:
            raise RollbackInvariantError(
                f"no branch with epoch {claim_epoch} to select"
            )
        if target.state is not BranchState.TERMINAL:
            raise RollbackInvariantError(
                f"epoch {claim_epoch} selected in state {target.state.value}; "
                "selection requires TERMINAL, not RUNNING"
            )
        # Invariant: cannot commit a branch whose terminality is producer-asserted
        # only. Must be independently validated through a fresh read path.
        if not self._independently_validate(target):
            raise RollbackInvariantError(
                f"epoch {claim_epoch} terminality is producer-asserted but not "
                "independently re-readable; committing would freeze a claim the "
                "producer may still retract"
            )
        target.state = BranchState.VALIDATED
        self.committed_epoch = claim_epoch
        return target

    def kill(self, branches: list[Branch], keep_epoch: int) -> None:
        for b in branches:
            if b.epoch == keep_epoch:
                continue
            # Invariant: a branch may only be killed (and its context freed) if
            # its scratch writes are epoch-fenced out of the committed branch's
            # evidence set, OR the committed branch has been independently
            # validated without needing those writes.
            if b.scratch_writes and self.committed_epoch is None:
                raise RollbackInvariantError(
                    f"cannot kill epoch {b.epoch}: it has unfenced scratch "
                    "writes and no validated commit exists to re-derive from"
                )
            b.state = BranchState.KILLED
            b.context_retained = False

    def _independently_validate(self, branch: Branch) -> bool:
        # Stub: real implementation re-reads through a fresh, epoch-fenced path
        # that does not consult the producing branch's context.
        return branch.state is BranchState.TERMINAL and not any(
            w.get("retracted") for w in branch.scratch_writes
        )
