# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-speculative-tool-call-pre-execution-that-has-already-crossed-a-side-effect-boundary-before-consensus-commit.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-speculative-tool-call-pre-execution-that-has-already-crossed-a-side-effect-boundary-before-consensus-commit.warrant.json
# Markdown SHA-256:   6fdd92a4378b657488f35e22ac7e63a2abc72e5810a74f039d792a999f390e9b
# Code AST SHA-256:   60147b2b7dc2fc7c2f6f59e83f39034fb78c66d66e4e4cac55510dece450bae2
# Verified Classes:   DurabilityState, SpeculativeCommitViolation, DurabilityProbe
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from enum import Enum


class DurabilityState(Enum):
    BUFFERED = "buffered"
    DURABLE = "durable"
    INDETERMINATE = "indeterminate"


class SpeculativeCommitViolation(RuntimeError):
    """Raised when an instance attempts to abort or retry a speculative
    tool call whose durability boundary may already have been crossed."""

    pass


@dataclass
class DurabilityProbe:
    monotonic: bool          # True only if BUFFERED can never follow DURABLE
    state: DurabilityState
    observed_at: float


def assert_safe_to_abort(probe: DurabilityProbe, token: str) -> None:
    """
    Called at abort time, before the instance reports rollback or retries.
    Enforces the Durability Monotonicity Invariant.
    """
    if not probe.monotonic:
        # Cannot distinguish buffered-before-flush from durable-after-flush.
        raise SpeculativeCommitViolation(
            f"token={token}: durability probe is non-monotonic "
            f"(state={probe.state.value}); cannot prove effect never became "
            f"durable. Halt swarm, mark INDETERMINATE, reconcile against outbox."
        )

    if probe.state is DurabilityState.DURABLE:
        # The effect crossed the boundary before the commit decision.
        raise SpeculativeCommitViolation(
            f"token={token}: effect already DURABLE at abort time "
            f"(observed_at={probe.observed_at}); abort is not a rollback. "
            f"Re-enter commit gate as compensation transaction."
        )

    if probe.state is DurabilityState.INDETERMINATE:
        raise SpeculativeCommitViolation(
            f"token={token}: durability INDETERMINATE; retry with a fresh "
            f"token is forbidden (residue will be misread as duplicate)."
        )

    # Only BUFFERED + monotonic reaches here: abort is a pure buffer discard.
    return


def abort_speculative_call(probe: DurabilityProbe, token: str) -> str:
    try:
        assert_safe_to_abort(probe, token)
    except SpeculativeCommitViolation as exc:
        # Do not swallow: the caller must route to reconciliation, not retry.
        raise SpeculativeCommitViolation(str(exc)) from exc
    return f"token={token}: aborted cleanly (buffer discarded, no durability crossing)"
