# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-precomputed-tool-call-invalidation-when-speculative-execution-races-a-concurrent-peer-s-write.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-precomputed-tool-call-invalidation-when-speculative-execution-races-a-concurrent-peer-s-write.warrant.json
# Markdown SHA-256:   25cddfb36d398a3175490dea44bb8cd9c6b12039c89ef518eb748d1f2c85f60c
# Code AST SHA-256:   7cd12b997ff762a8882c31086c09c2d791fd726c5923d4d295a29dfb6ddbf720
# Verified Classes:   SpeculativeInvalidationError, ReadWitness, SpeculativeCall
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class SpeculativeInvalidationError(RuntimeError):
    """Raised when a speculative call's read-set witness no longer matches at dispatch."""


@dataclass
class ReadWitness:
    field: str
    value: Any
    read_at_version: int


@dataclass
class SpeculativeCall:
    tool: str
    args: dict
    read_set: list[ReadWitness] = field(default_factory=list)
    registered_version: int = 0


def register_speculative(
    tool: str,
    args: dict,
    read_set: list[ReadWitness],
    current_version: int,
) -> SpeculativeCall:
    if not read_set:
        raise SpeculativeInvalidationError(
            f"cannot speculate {tool!r} without a read-set witness; "
            "version-only registration launders stale reads"
        )
    # The witness is captured at read time, not registration time. We do NOT
    # re-probe fields here — that would launder the stale read.
    return SpeculativeCall(
        tool=tool,
        args=args,
        read_set=read_set,
        registered_version=current_version,
    )


def dispatch(
    call: SpeculativeCall,
    resource: dict[str, Any],
    current_version: int,
) -> dict:
    """Re-validate the read-set witness before committing the speculative call."""
    for witness in call.read_set:
        live = resource.get(witness.field)
        if live != witness.value:
            raise SpeculativeInvalidationError(
                f"speculative {call.tool!r} invalidated: field {witness.field!r} "
                f"was {witness.value!r} at read (v{witness.read_at_version}), "
                f"is {live!r} at dispatch (v{current_version}); "
                "discard and re-derive, do not retry against new version"
            )
    # Cross-field invariant check: field-level disjointness does not imply
    # semantic compatibility. This must be declared per-resource.
    if call.tool == "patch_config":
        policy = resource.get("retry_policy")
        timeout = call.args.get("timeout")
        if policy == "conservative" and timeout is not None and timeout < 30:
            raise SpeculativeInvalidationError(
                f"cross-field invariant violated: timeout={timeout} "
                f"incompatible with retry_policy={policy!r}"
            )
    return call.args
