# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-branch-before-its-tool-effects-are-observable-speculative-plan-execution-and-rollback-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-branch-before-its-tool-effects-are-observable-speculative-plan-execution-and-rollback-boundary.warrant.json
# Markdown SHA-256:   52b74fbdaad289d9f5f222febaded000f940725f5aea7b44fc506a8d4a082f08
# Code AST SHA-256:   e86ba8072fc8c8683c2864900519a4dff2149222627e1f37634e6f6b0e878c29
# Verified Classes:   HorizonCrossedError, ToolCall, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class HorizonCrossedError(RuntimeError):
    """Raised when a speculative branch attempts a call past its observability horizon."""
    pass


@dataclass(frozen=True)
class ToolCall:
    name: str
    deferred_commit: bool          # adapter supports prepare/commit/abort
    reversible_until: Optional[float]  # epoch seconds; None = never reversible


@dataclass(frozen=True)
class Branch:
    branch_id: str
    tools: tuple[ToolCall, ...]


def speculatable(branch: Branch, now: float, expected_decision_latency: float) -> bool:
    for call in branch.tools:
        if not call.deferred_commit:
            return False
        if call.reversible_until is not None:
            if now + expected_decision_latency >= call.reversible_until:
                return False
    return True


def admit_branch(branch: Branch, now: float, expected_decision_latency: float) -> None:
    if not speculatable(branch, now, expected_decision_latency):
        raise HorizonCrossedError(
            f"branch {branch.branch_id} is not speculatable at t={now:.3f}: "
            f"a tool is commit-on-call or will cross its reversible_until "
            f"before the expected verifier decision. Serialize this branch; "
            f"do not speculate it."
        )


def dispatch(branch: Branch, call: ToolCall, now: float,
             expected_decision_latency: float) -> None:
    # Re-evaluate per dispatch: horizon can be crossed mid-flight.
    if call.reversible_until is not None and now >= call.reversible_until:
        raise HorizonCrossedError(
            f"branch {branch.branch_id} call {call.name} dispatched at t={now:.3f} "
            f"past reversible_until={call.reversible_until:.3f}; freeze branch and "
            f"escalate to incident path, do not attempt compensation."
        )
    if not speculatable(branch, now, expected_decision_latency):
        raise HorizonCrossedError(
            f"branch {branch.branch_id} lost speculative status mid-flight at "
            f"call {call.name}; freeze, do not abort."
        )
