# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-call-pre-execution-from-leaking-side-effects-before-commit-gating.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-call-pre-execution-from-leaking-side-effects-before-commit-gating.warrant.json
# Markdown SHA-256:   a0ba74b0e958bd1ec457867fbc5193fd4aac758272742cb559b09611ddf51e40
# Code AST SHA-256:   f3af5c1d99a433652690f110620d2ad7092c5ffd6709003d06e83f430d6e11d4
# Verified Classes:   SpeculationEgressViolation, EffectManifest, SpeculativeAttempt, CommitGate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class SpeculationEgressViolation(RuntimeError):
    """Raised when a speculative call leaked an effect outside the isolation boundary."""
    pass


@dataclass
class EffectManifest:
    modeled_effects: frozenset[str]
    eager_client_effects: frozenset[str] = field(default_factory=frozenset)

    def is_speculation_safe(self) -> bool:
        # Speculation is safe only if every eager client effect is modeled
        # by the isolation boundary. Any unmodeled eager effect leaks.
        return self.eager_client_effects <= self.modeled_effects


@dataclass
class SpeculativeAttempt:
    tool: str
    nonce: str
    manifest: EffectManifest


class CommitGate:
    def __init__(self) -> None:
        self._pending: dict[str, SpeculativeAttempt] = {}

    def speculate(self, attempt: SpeculativeAttempt) -> None:
        if not attempt.manifest.is_speculation_safe():
            unmodeled = attempt.manifest.eager_client_effects - attempt.manifest.modeled_effects
            raise SpeculationEgressViolation(
                f"tool {attempt.tool!r} has unmodeled eager effects {sorted(unmodeled)}; "
                f"speculation would leak past the commit gate"
            )
        self._pending[attempt.nonce] = attempt

    def commit(self, nonce: str, regenerate: Callable[[str], str]) -> str:
        attempt = self._pending.pop(nonce, None)
        if attempt is None:
            raise SpeculationEgressViolation(f"no speculative attempt for nonce {nonce!r}")
        # Invariant: committed calls MUST NOT inherit the speculative nonce.
        # Regenerate so a leaked reservation cannot alias this committed call.
        committed_nonce = regenerate(nonce)
        if committed_nonce == nonce:
            raise SpeculationEgressViolation(
                "commit nonce equals speculative nonce; leaked reservations may alias"
            )
        return committed_nonce

    def discard(self, nonce: str) -> None:
        # Discard removes the attempt but does NOT un-leak effects; callers
        # must still regenerate identifiers on any subsequent committed call.
        self._pending.pop(nonce, None)
