# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-invalidate-a-speculatively-prefetched-tool-result-before-commit-when-a-concurrent-memory-write-has-mutated-the.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-invalidate-a-speculatively-prefetched-tool-result-before-commit-when-a-concurrent-memory-write-has-mutated-the.warrant.json
# Markdown SHA-256:   691803640cc08b7298379346cee77585de29e6f3e1e94710a84b13d6e399c115
# Code AST SHA-256:   cad28007953571ed2f995bc5eb7ecffa0340b77d0b247fb599802276ad849060
# Verified Classes:   ReadSetDriftError, Prefetch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any, Hashable


class ReadSetDriftError(RuntimeError):
    """Raised when a speculatively prefetched result's read-set changed between
    argument materialization and commit. The result MUST NOT be committed."""


@dataclass(frozen=True)
class Prefetch:
    tool: str
    args: dict[str, Any]
    read_set: dict[Hashable, Any]      # cell -> value observed at materialization
    result: Any
    materialized_at: int               # logical clock at argument materialization


def commit_prefetch(prefetch: Prefetch, store, commit_clock: int) -> Any:
    """Validate the read-set at commit time; raise on any drift.

    The window is [materialized_at, commit_clock]. A write landing in this
    window that intersects the read-set invalidates the prefetch even if the
    tool returned a schema-valid result.
    """
    if not prefetch.read_set:
        # Empty read-set is only legal for constant args; otherwise the
        # materializer failed to record dependencies and we must fail closed.
        if not all(_is_constant(v) for v in prefetch.args.values()):
            raise ReadSetDriftError(
                f"tool={prefetch.tool!r} has non-constant args but empty read-set; "
                "cannot verify at commit, refusing speculative commit"
            )
        return prefetch.result

    # Atomic read-at-commit: snapshot all cells at a single consistent point.
    snapshot = store.snapshot(prefetch.read_set.keys(), at=commit_clock)

    for cell, expected in prefetch.read_set.items():
        if cell not in snapshot:
            raise ReadSetDriftError(
                f"tool={prefetch.tool!r} read-set cell {cell!r} no longer exists "
                f"at commit_clock={commit_clock}; prefetch is uncommittable"
            )
        observed = snapshot[cell]
        if observed != expected:
            raise ReadSetDriftError(
                f"tool={prefetch.tool!r} read-set drift on cell {cell!r}: "
                f"materialized={expected!r} (t={prefetch.materialized_at}) "
                f"commit={observed!r} (t={commit_clock}); "
                "invalidate and re-execute, do not commit"
            )

    return prefetch.result


def _is_constant(value: Any) -> bool:
    return isinstance(value, (str, int, float, bool, type(None)))
