# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-call-prefetching-from-committing-against-a-concurrently-mutated-resource.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-call-prefetching-from-committing-against-a-concurrently-mutated-resource.warrant.json
# Markdown SHA-256:   dc7ead39b17ff7a79dd71e64799763161cbcb88d407872c14b2922577b8b2449
# Code AST SHA-256:   9d8279acc2f5caeefa677875b7c2bcc521c8c89cbcc38fa1cd25f08f039dedaf
# Verified Classes:   StalePrefetchCommit, PrefetchResult
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StalePrefetchCommit(RuntimeError):
    """Raised when a commit consumes a speculatively-prefetched value whose
    version no longer matches the authoritative store at commit time."""
    pass


@dataclass(frozen=True)
class PrefetchResult:
    source: str
    value: str
    version: Optional[str]       # None => store cannot supply a version token
    fetched_at: float
    cache_bypass_token: str


def revalidate(source: str, expected_version: str, bypass_token: str) -> str:
    """Hit the authoritative store directly, bypassing the prefetch cache.
    Returns the current version. Stub for the real transport."""
    return _authoritative_version(source, bypass=bypass_token)


def commit_using_prefetch(prefetch: PrefetchResult, action: str) -> None:
    if prefetch.version is None:
        # Unverifiable speculation: must not be used as a commit premise.
        raise StalePrefetchCommit(
            f"prefetch of {prefetch.source!r} carries no version token; "
            f"refusing to commit action {action!r} against unverifiable state"
        )

    current = revalidate(
        prefetch.source,
        expected_version=prefetch.version,
        bypass_token=prefetch.cache_bypass_token,
    )

    if current != prefetch.version:
        raise StalePrefetchCommit(
            f"resource {prefetch.source!r} moved from version "
            f"{prefetch.version!r} (prefetched at {prefetch.fetched_at}) to "
            f"{current!r} before commit of {action!r}; re-plan required"
        )

    _apply(action)


def _authoritative_version(source: str, bypass: str) -> str:
    raise NotImplementedError


def _apply(action: str) -> None:
    raise NotImplementedError
