# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-speculative-tool-call-pre-execution-when-byzantine-quorum-validation-cannot-reach-agreement-before-the-commit-deadline.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-speculative-tool-call-pre-execution-when-byzantine-quorum-validation-cannot-reach-agreement-before-the-commit-deadline.warrant.json
# Markdown SHA-256:   048e142939018b281b175e6a18354c7c98ac529b2168dceaa859a3b33774ced0
# Code AST SHA-256:   047d64bae1e2d65ed52dceb8ebecb1609cc02b02811be280c198e029fc3c980f
# Verified Classes:   SpeculationHorizonViolation, ToolSpec, QuorumConfig
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class SpeculationHorizonViolation(RuntimeError):
    """Raised when a speculative tool call is dispatched or rolled back
    outside the window in which its effects are provably reversible."""
    pass


@dataclass(frozen=True)
class ToolSpec:
    name: str
    reversible: bool
    rollback_horizon_ms: float | None  # H_r; None means undisclosed


@dataclass(frozen=True)
class QuorumConfig:
    threshold: int
    total: int
    deadline_ms: float          # D_q, must be a pinned upper bound
    equivocation_single_round: bool


CLOCK_SKEW_EPS_MS = 15.0


def may_speculate(tool: ToolSpec, quorum: QuorumConfig) -> bool:
    if not tool.reversible:
        return False
    if tool.rollback_horizon_ms is None:
        return False
    if not quorum.equivocation_single_round:
        return False
    # Invariant: H_r > D_q + eps, with D_q pinned (no per-call extension).
    return tool.rollback_horizon_ms > quorum.deadline_ms + CLOCK_SKEW_EPS_MS


def dispatch_speculative(
    tool: ToolSpec,
    quorum: QuorumConfig,
    dispatch_ts_ms: float,
) -> None:
    if not may_speculate(tool, quorum):
        raise SpeculationHorizonViolation(
            f"refusing speculative dispatch of {tool.name!r}: "
            f"H_r={tool.rollback_horizon_ms} D_q={quorum.deadline_ms} "
            f"reversible={tool.reversible} "
            f"single_round_equiv={quorum.equivocation_single_round}"
        )
    # ... dispatch tool and collect intent votes in parallel ...


def rollback_speculative(
    tool: ToolSpec,
    dispatch_ts_ms: float,
    now_ms: float,
) -> None:
    if tool.rollback_horizon_ms is None:
        raise SpeculationHorizonViolation(
            f"cannot roll back {tool.name!r}: rollback horizon undisclosed"
        )
    elapsed = now_ms - dispatch_ts_ms
    if elapsed >= tool.rollback_horizon_ms:
        raise SpeculationHorizonViolation(
            f"rollback of {tool.name!r} attempted at {elapsed:.1f}ms, "
            f"past horizon {tool.rollback_horizon_ms}ms; "
            f"escalate to reconciliation quorum and mark memory UNCOMMITTED"
        )
    # ... issue compensating call within the horizon ...
