# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-call-pre-execution-from-committing-effects-out-of-causal-order.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-call-pre-execution-from-committing-effects-out-of-causal-order.warrant.json
# Markdown SHA-256:   6a5ba8bab10410e14b206cf9753bc6a667a1753388891f3ece921247c2a872df
# Code AST SHA-256:   819c392a37bbb35fdc0c2f62e81d70c3df8c47f9431c11f5e0673e1dcfa8f6a0
# Verified Classes:   CommitOrderViolation, SpeculativeCall, TopologicalCommitDrain
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class CommitOrderViolation(RuntimeError):
    """Raised when a speculative call is drained before its dependency frontier is committed."""


@dataclass
class SpeculativeCall:
    call_id: str
    deps: Set[str]
    speculated_args: tuple
    resolved_args: tuple
    resolved_at: float
    committed: bool = False


class TopologicalCommitDrain:
    def __init__(self) -> None:
        self.calls: Dict[str, SpeculativeCall] = {}

    def register(self, call: SpeculativeCall) -> None:
        self.calls[call.call_id] = call

    def _frontier_committed(self, call: SpeculativeCall) -> bool:
        return all(
            self.calls.get(dep) is not None and self.calls[dep].committed
            for dep in call.deps
        )

    def drain(self) -> list:
        # Drain in dependency order, never in resolved_at order.
        committed_order = []
        progress = True
        while progress:
            progress = False
            for call in sorted(self.calls.values(), key=lambda c: c.resolved_at):
                if call.committed:
                    continue
                if not self._frontier_committed(call):
                    continue
                if call.speculated_args != call.resolved_args:
                    # Argument rebound after speculation: abort and respeculate.
                    raise CommitOrderViolation(
                        f"stale speculation for {call.call_id}: "
                        f"{call.speculated_args!r} != {call.resolved_args!r}"
                    )
                call.committed = True
                committed_order.append(call.call_id)
                progress = True
        # Any remaining uncommitted call is causally blocked, not merely slow.
        blocked = [c.call_id for c in self.calls.values() if not c.committed]
        if blocked:
            raise CommitOrderViolation(
                f"causally blocked at commit TTL: {blocked}"
            )
        return committed_order
