# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-abort-a-speculative-tool-call-prefetch-when-a-federated-peer-revokes-a-dependency-warrant-mid-flight.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-abort-a-speculative-tool-call-prefetch-when-a-federated-peer-revokes-a-dependency-warrant-mid-flight.warrant.json
# Markdown SHA-256:   0705cfdd1cd7ac8ab2ef028ec9146dad7c9834714ba98c9d5543d054384ce1aa
# Code AST SHA-256:   cef06363bd96efa0359eb4b0ff936643aa96fa5ea205827022393657e870fa90
# Verified Classes:   StaleWarrantEpochError, WarrantRef, SpeculativeResult, CommitGate
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleWarrantEpochError(RuntimeError):
    """Raised when a speculative result is committed under a superseded warrant epoch."""
    pass


@dataclass(frozen=True)
class WarrantRef:
    warrant_id: str
    epoch: int
    scope_binding: str


@dataclass
class SpeculativeResult:
    payload: dict
    warrant: WarrantRef
    epoch_suspect: bool = False


class CommitGate:
    """Enforces the epoch fence at commit time for speculative prefetches."""

    def __init__(self, current_epoch_lookup, proof_fetch, commit_deadline_ms: int):
        self._current_epoch = current_epoch_lookup  # warrant_id -> int
        self._proof_fetch = proof_fetch            # (warrant_id, binding) -> Optional[int]
        self._deadline = commit_deadline_ms

    def on_epoch_advance(self, warrant_id: str, new_epoch: int) -> None:
        # Global fence: any advance marks all results under this warrant suspect,
        # regardless of which scope member triggered the revocation.
        self._suspect_warrant(warrant_id, new_epoch)

    def _suspect_warrant(self, warrant_id: str, new_epoch: int) -> None:
        for r in self._registry.get(warrant_id, []):
            if r.warrant.epoch < new_epoch:
                r.epoch_suspect = True

    _registry: dict = {}

    def commit(self, result: SpeculativeResult) -> dict:
        current = self._current_epoch(result.warrant.warrant_id)
        if current <= result.warrant.epoch and not result.epoch_suspect:
            return result.payload
        # Epoch advanced (or result flagged suspect): require a fresh proof.
        proof_epoch = self._proof_fetch(
            result.warrant.warrant_id, result.warrant.scope_binding
        )
        if proof_epoch is None or proof_epoch < current:
            raise StaleWarrantEpochError(
                f"refusing to commit prefetch under warrant "
                f"{result.warrant.warrant_id} binding={result.warrant.scope_binding} "
                f"issued_epoch={result.warrant.epoch} current_epoch={current} "
                f"proof_epoch={proof_epoch}; discard and re-issue under fresh warrant"
            )
        return result.payload
