# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-call-pre-execution-from-corrupting-shared-multi-agent-state.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-call-pre-execution-from-corrupting-shared-multi-agent-state.warrant.json
# Markdown SHA-256:   9d1bd4730d96d27ac510a76224f0919ef825b59e1a3d15dabecad98ec5448b9a
# Code AST SHA-256:   bad225b3a62be533b2c56962d9f560f51f2fbf89b98dae8ca5eb6d63915152fb
# Verified Classes:   WriteIntentConflict, LeaseExpired, WriteIntent, IntentRegistry
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class WriteIntentConflict(RuntimeError):
    """Raised when a speculative tool call's write-set intersects an uncommitted intent."""


class LeaseExpired(RuntimeError):
    """Raised when a write-intent lease was reaped before the tool committed."""


@dataclass(frozen=True)
class WriteIntent:
    table: str
    key: str
    op: str  # 'reserve', 'transfer', 'append', ...
    agent_id: str
    plan_id: str
    acquired_at: float = field(default_factory=time.monotonic)
    ttl_s: float = 30.0

    def conflicts_with(self, other: "WriteIntent") -> bool:
        return (self.table, self.key) == (other.table, other.key)


class IntentRegistry:
    """Atomic compare-and-insert registry of in-flight write-intents across a cohort."""

    def __init__(self) -> None:
        self._held: dict[tuple[str, str], WriteIntent] = {}

    def _reap(self, now: float) -> None:
        for k, v in list(self._held.items()):
            if now - v.acquired_at > v.ttl_s:
                del self._held[k]

    def acquire(self, intent: WriteIntent) -> None:
        # Atomic in real deployments (single-row INSERT ... ON CONFLICT DO NOTHING
        # or a compare-and-swap on a versioned registry row). Here: single critical section.
        self._reap(time.monotonic())
        slot = (intent.table, intent.key)
        existing = self._held.get(slot)
        if existing is not None and existing.plan_id != intent.plan_id:
            raise WriteIntentConflict(
                f"speculative write-set {slot} already held by plan "
                f"{existing.plan_id} (agent {existing.agent_id}); "
                f"refusing pre-execution for plan {intent.plan_id}"
            )
        self._held[slot] = intent

    def release(self, intent: WriteIntent) -> None:
        slot = (intent.table, intent.key)
        if self._held.get(slot) == intent:
            del self._held[slot]

    def assert_held(self, intent: WriteIntent) -> None:
        slot = (intent.table, intent.key)
        if self._held.get(slot) != intent:
            raise LeaseExpired(
                f"write-intent lease for {slot} (plan {intent.plan_id}) "
                f"was reaped or stolen before commit; effect must not execute"
            )


def speculative_execute(
    registry: IntentRegistry,
    intent: WriteIntent,
    tool_body,
    *args,
    **kwargs,
):
    """Reserve-then-execute: the only sound path for non-commutative effects."""
    registry.acquire(intent)
    try:
        # Re-validate atomically at the moment of execution, not just at registration.
        registry.assert_held(intent)
        return tool_body(*args, **kwargs)
    finally:
        # Abort and success both release; commit is the caller's responsibility
        # to make durable before this finally runs.
        registry.release(intent)
