# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abandon-optimistic-speculative-tool-call-pre-execution-and-fall-back-to-pessimistic-reservation-under-cross-agent-w.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abandon-optimistic-speculative-tool-call-pre-execution-and-fall-back-to-pessimistic-reservation-under-cross-agent-w.warrant.json
# Markdown SHA-256:   4b4fb0df4de84191c5ef022b4001b90101a79dbc5ee8c1ec18e9e862474aa567
# Code AST SHA-256:   b2ef8236380bfaeba0a0447c5d09c2fd3f68b342b93bc766262e48838ba83bbd
# Verified Classes:   SpeculationBoundaryError, Isolation, ToolProfile
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class SpeculationBoundaryError(RuntimeError):
    """Raised when optimistic speculative pre-execution crosses the shared-limit /
    non-commutative-compensation / long-flip-horizon boundary and must be refused."""


class Isolation(str, Enum):
    OPTIMISTIC = "optimistic"
    PESSIMISTIC_LEASE = "pessimistic_lease"


@dataclass(frozen=True)
class ToolProfile:
    name: str
    constraint_scope: str | None      # non-None => shared-limit resource
    compensation_commutes: bool        # compensate(op) commutes with peer ops?
    commit_latency_ms: int
    flip_probability: float            # planner branch entropy at this step
    reconciliation_window_ms: int


def choose_isolation(profile: ToolProfile, peer_writers: int) -> Isolation:
    if profile.constraint_scope is None:
        return Isolation.OPTIMISTIC  # no shared limit, speculation is free

    shared_limit = profile.constraint_scope is not None and peer_writers >= 1
    non_commutative = not profile.compensation_commutes
    flip_horizon_long = (
        profile.flip_probability * profile.commit_latency_ms
        > profile.reconciliation_window_ms
    )

    if shared_limit and non_commutative and flip_horizon_long:
        raise SpeculationBoundaryError(
            f"tool={profile.name!r} scope={profile.constraint_scope!r} "
            f"peers={peer_writers} flip_p={profile.flip_probability:.2f} "
            f"commit_ms={profile.commit_latency_ms} "
            f"recon_window_ms={profile.reconciliation_window_ms}: "
            "speculative pre-execution would produce ambiguous-ownership "
            "double-commit; require pessimistic lease on the constraint scope "
            "and intent-tag the call with a branch_id"
        )
    return Isolation.OPTIMISTIC


def dispatch_speculative(profile: ToolProfile, peer_writers: int) -> Isolation:
    # Caller must handle SpeculationBoundaryError by acquiring a lease
    # (or serializing) before pre-executing; never swallow it.
    return choose_isolation(profile, peer_writers)


if __name__ == "__main__":
    reserve = ToolProfile(
        name="reserve_funds",
        constraint_scope="order-7741-budget",
        compensation_commutes=False,
        commit_latency_ms=180,
        flip_probability=0.35,
        reconciliation_window_ms=40,
    )
    dispatch_speculative(reserve, peer_writers=1)  # raises SpeculationBoundaryError
