# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-orphaned-speculative-tool-calls-from-corrupting-the-commit-frontier-during-branch-and-verify-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-orphaned-speculative-tool-calls-from-corrupting-the-commit-frontier-during-branch-and-verify-rollback.warrant.json
# Markdown SHA-256:   b3dc68206e2c3b8cdbda97549e9ac5e3ade6f2696f3ec045f052b866181bd1d7
# Code AST SHA-256:   46e1ebd7740fcb26f6b489021cf5217d997fdd8e4a39c97fcd18cf31aa94fe21
# Verified Classes:   ToolClass, SpeculativeDispatchRefused, StaleEpochWrite, ToolSpec, Branch, EffectStore, SpeculativeDispatcher
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List


class ToolClass(Enum):
    SPECULABLE = "speculable"
    SERIALIZED = "serialized"


class SpeculativeDispatchRefused(RuntimeError):
    """Raised when a mutating or uncancellable tool is dispatched on a speculative branch."""


class StaleEpochWrite(RuntimeError):
    """Raised when an effect write arrives from a branch epoch below the committed epoch."""


@dataclass
class ToolSpec:
    name: str
    classification: ToolClass
    exec_latency_p99_ms: float
    cancel_propagation_p99_ms: float

    def is_safely_cancellable(self) -> bool:
        # A call is cancellable only if cancellation can outrun execution.
        return self.cancel_propagation_p99_ms < self.exec_latency_p99_ms


@dataclass
class Branch:
    branch_id: str
    epoch: int


@dataclass
class EffectStore:
    committed_epoch: int = 0
    applied: List[tuple] = field(default_factory=list)

    def apply(self, branch: Branch, tool: ToolSpec, payload: dict) -> None:
        if branch.epoch < self.committed_epoch:
            raise StaleEpochWrite(
                f"branch {branch.branch_id} epoch {branch.epoch} < "
                f"committed {self.committed_epoch}; write suppressed"
            )
        self.applied.append((branch.epoch, tool.name, payload))


@dataclass
class SpeculativeDispatcher:
    tools: Dict[str, ToolSpec]
    store: EffectStore

    def dispatch(self, branch: Branch, tool_name: str, payload: dict) -> None:
        tool = self.tools[tool_name]
        if tool.classification is not ToolClass.SPECULABLE:
            raise SpeculativeDispatchRefused(
                f"tool {tool_name} is {tool.classification.value}; "
                f"cannot be dispatched speculatively on branch {branch.branch_id}"
            )
        if not tool.is_safely_cancellable():
            # Nominal speculable, but its tail outlives the verifier horizon.
            raise SpeculativeDispatchRefused(
                f"tool {tool_name} cancel-propagation "
                f"{tool.cancel_propagation_p99_ms}ms >= exec "
                f"{tool.exec_latency_p99_ms}ms; treat as serialized"
            )
        self.store.apply(branch, tool, payload)


def commit_winner(store: EffectStore, winner: Branch) -> None:
    if winner.epoch <= store.committed_epoch:
        raise StaleEpochWrite(
            f"winner epoch {winner.epoch} not above committed {store.committed_epoch}"
        )
    store.committed_epoch = winner.epoch


def run_incident_replay() -> None:
    store = EffectStore()
    tools = {
        "read_snapshot": ToolSpec("read_snapshot", ToolClass.SPECULABLE, 200, 50),
        "write_reconciliation": ToolSpec(
            "write_reconciliation", ToolClass.SERIALIZED, 1100, 2000
        ),
    }
    dispatcher = SpeculativeDispatcher(tools, store)

    branches = [Branch(f"b{i}", epoch=i) for i in range(1, 5)]

    # Losing branches attempt speculative writes: must be refused.
    for b in (branches[0], branches[1], branches[3]):
        try:
            dispatcher.dispatch(b, "write_reconciliation", {"offset": b.epoch})
        except SpeculativeDispatchRefused:
            pass  # suppressed, as designed

    # Winning branch commits, then applies its effect.
    commit_winner(store, branches[2])
    dispatcher.dispatch(branches[2], "write_reconciliation", {"offset": 3})

    # A straggler branch-4 write landing after commit is caught at the store.
    try:
        store.apply(branches[3], tools["write_reconciliation"], {"offset": 4})
    except StaleEpochWrite:
        pass  # late write suppressed; ledger reflects branch 3 only

    assert [e[0] for e in store.applied] == [3], store.applied


if __name__ == "__main__":
    run_incident_replay()
