# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-tool-call-whose-optimistic-concurrency-check-passed-but-whose-read-set-was-already-stale-at-commit-time.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-tool-call-whose-optimistic-concurrency-check-passed-but-whose-read-set-was-already-stale-at-commit-time.warrant.json
# Markdown SHA-256:   33cae01d4177c6859f508b5471bfca328c609be6f2255285d86645341b3f1f54
# Code AST SHA-256:   ee313bb3302c9c3e47be511c81364da6e0a97e6af114d85d85425e72e85d918e
# Verified Classes:   StaleReadSetError, SpeculativeCall
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class StaleReadSetError(RuntimeError):
    """Raised when an optimistic commit's version token validates but the
    read-set content witness no longer matches the premise actually reasoned over."""


@dataclass
class SpeculativeCall:
    resource: str
    args: dict[str, Any]
    read_set: dict[str, Any]          # resource -> value consumed to form args
    version_token: int                # sampled at speculation launch
    witness_at_premise: str | None = None  # captured when premise materialized


def _witness(read_set: dict[str, Any]) -> str:
    h = hashlib.sha256()
    for k in sorted(read_set):
        h.update(f"{k}={read_set[k]!r};".encode())
    return h.hexdigest()


def commit_speculative(
    call: SpeculativeCall,
    store: Any,                       # exposes current_version / value_at / is_monotonic
) -> None:
    # 1. Classic OCC token check.
    if store.current_version(call.resource) != call.version_token:
        raise StaleReadSetError(
            f"token mismatch on {call.resource}: "
            f"have {store.current_version(call.resource)} want {call.version_token}"
        )

    # 2. Content witness: recompute the read-set as it exists at the
    #    validated token and compare to the premise-time witness.
    if call.witness_at_premise is None:
        raise StaleReadSetError(
            f"no premise witness for {call.resource}; cannot distinguish "
            f"rebased token from valid token"
        )
    live = {k: store.value_at(k, call.version_token) for k in call.read_set}
    if _witness(live) != call.witness_at_premise:
        # Token passed, content is stale (e.g. delta compaction reused the token).
        raise StaleReadSetError(
            f"read-set stale at token {call.version_token} on {call.resource}: "
            f"witness {_witness(live)[:12]} != premise {call.witness_at_premise[:12]}"
        )

    # 3. Non-monotonic store: force witness invalidation across compactions.
    if not store.is_monotonic(call.resource) and store.compacted_since(call.version_token):
        raise StaleReadSetError(
            f"compaction/rebase occurred on {call.resource} since token "
            f"{call.version_token}; speculative premise cannot be trusted"
        )

    store.apply(call.resource, call.args, expected_version=call.version_token)
