# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-speculative-tool-call-divergence-under-optimistic-concurrency-in-agent-execution-loops.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-speculative-tool-call-divergence-under-optimistic-concurrency-in-agent-execution-loops.warrant.json
# Markdown SHA-256:   965f0838ec9699b3f57b939a7c4d60ccc8905a4afc759b80d85edbebfd652b54
# Code AST SHA-256:   b2269e868cd42f7b3bc35969a08d064a8b3963db2a224b3bdd59a33713ebcdfa
# Verified Classes:   SpeculativeDivergenceError, SpeculativeCall, StagedTurn, SpeculativeOrchestrator
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class SpeculativeDivergenceError(RuntimeError):
    """Raised when a version conflict occurs after a dependent emission was committed."""


@dataclass
class SpeculativeCall:
    call_id: str
    version: int
    output: Any
    committed: bool = False


@dataclass
class StagedTurn:
    call_id: str
    depends_on: set[str] = field(default_factory=set)
    committed: bool = False


class SpeculativeOrchestrator:
    def __init__(self) -> None:
        self.calls: dict[str, SpeculativeCall] = {}
        self.staged: list[StagedTurn] = []
        self.durable_transcript: list[StagedTurn] = []

    def dispatch(self, call_id: str, version: int, output: Any) -> None:
        self.calls[call_id] = SpeculativeCall(call_id, version, output)

    def emit_dependent(self, turn: StagedTurn) -> None:
        # Stage, do not commit. The model's output is buffered until preconditions pass.
        self.staged.append(turn)

    def commit(self, current_versions: dict[str, int]) -> None:
        for turn in self.staged:
            for dep in turn.depends_on:
                call = self.calls.get(dep)
                if call is None:
                    raise SpeculativeDivergenceError(
                        f"turn {turn.call_id} depends on unknown call {dep}"
                    )
                if current_versions.get(dep) != call.version:
                    # Conflict detected. If the turn is already durable, we cannot retry.
                    if turn.committed:
                        raise SpeculativeDivergenceError(
                            f"dependent emission {turn.call_id} committed before "
                            f"version check on {dep} (spec {call.version}, "
                            f"current {current_versions.get(dep)}); "
                            f"transcript is contaminated, quarantine required"
                        )
                    # Safe path: discard staged turn, force re-derivation.
                    self.staged.remove(turn)
                    return
            turn.committed = True
            self.durable_transcript.append(turn)
        self.staged.clear()
