# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-speculatively-execute-tool-calls-before-authorization-and-how-does-the-side-effect-buffer-leak.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-speculatively-execute-tool-calls-before-authorization-and-how-does-the-side-effect-buffer-leak.warrant.json
# Markdown SHA-256:   5a0258b3f302c6cdd451ba3309e874a806fdab4e4e300b35da2aa4621b6475fd
# Code AST SHA-256:   2a9dd3238581678b7fa5411d4f4990966b73862b1c68edff26fad98a9ceaaeda
# Verified Classes:   SpeculationWarrantError, SpeculationWarrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class SpeculationWarrantError(RuntimeError):
    """Raised when a tool is speculatively dispatched without a closure-complete warrant."""


@dataclass(frozen=True)
class SpeculationWarrant:
    tool: str
    closure_buffered: bool
    key_attempt_scoped: bool
    dependency_hash: str


def dispatch_speculative(tool: str, args: dict, warrant: SpeculationWarrant,
                         current_dep_hash: str, attempt_key: str) -> dict:
    # Invariant 1: the tool's full effect closure must be buffered.
    if not warrant.closure_buffered:
        raise SpeculationWarrantError(
            f"tool {tool!r} has unbuffered effects in its closure; "
            "speculative dispatch would leak past abort"
        )
    # Invariant 2: idempotency keys must be attempt-scoped, never logical-op-scoped,
    # or an aborted speculation poisons the dedup window for the committed retry.
    if not warrant.key_attempt_scoped:
        raise SpeculationWarrantError(
            f"tool {tool!r} uses a logical-operation idempotency key; "
            "aborted speculation would masquerade as prior success"
        )
    # Invariant 3: warrants are invalidated when the tool's dependency graph changes.
    if warrant.dependency_hash != current_dep_hash:
        raise SpeculationWarrantError(
            f"warrant for {tool!r} is stale: dependency graph changed "
            f"({warrant.dependency_hash} -> {current_dep_hash})"
        )
    return {"tool": tool, "args": args, "attempt_key": attempt_key,
            "status": "buffered_pending_commit"}


def commit_or_abort(dispatched: dict, authorized: bool) -> str:
    if not authorized:
        # Memory plane must record "deferred", never "not attempted",
        # so the planner's next premise stays sound.
        return "aborted_recorded_as_deferred"
    return "committed"
