# 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-stale-read-snapshot-under-concurrent-agent-writes.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-call-prefetching-from-committing-against-a-stale-read-snapshot-under-concurrent-agent-writes.warrant.json
# Markdown SHA-256:   e6fc7926b0418f8596cd32a35be405bf6beeb84169e8f6a99e0c126981eea53e
# Code AST SHA-256:   7f331175d2bdd070c6beebc5b17cd5633bc297b0b5d3296370a71d5e3517e6bb
# Verified Classes:   StalePrefetchCommitError, PrefetchAbortedError, Version, Prefetch
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StalePrefetchCommitError(RuntimeError):
    """Raised when a speculative prefetch is about to commit against a stale snapshot."""
    pass


class PrefetchAbortedError(RuntimeError):
    """Raised when a prefetch cycle must be abandoned and re-dispatched."""
    pass


@dataclass(frozen=True)
class Version:
    seq: int
    epoch: str


@dataclass
class Prefetch:
    resource_id: str
    tool_name: str
    payload: dict
    dispatch_version: Version
    foreign_lease_open: bool
    dispatch_seq: int


def commit_prefetch(
    prefetch: Prefetch,
    commit_version: Optional[Version],
    latest_dispatch_seq_for_resource: int,
    dependent_fields: set,
    intervening_write_fields: set,
) -> dict:
    if commit_version is None:
        raise StalePrefetchCommitError(
            f"no version witness for resource {prefetch.resource_id}; "
            "cannot commit prefetch without causal read"
        )

    if prefetch.dispatch_version.epoch != commit_version.epoch:
        raise PrefetchAbortedError(
            f"incomparable epochs for {prefetch.resource_id}: "
            f"dispatch={prefetch.dispatch_version.epoch} commit={commit_version.epoch}"
        )

    if prefetch.dispatch_seq != latest_dispatch_seq_for_resource:
        raise PrefetchAbortedError(
            f"out-of-order commit for {prefetch.resource_id}: "
            f"dispatch_seq={prefetch.dispatch_seq} latest={latest_dispatch_seq_for_resource}"
        )

    if prefetch.foreign_lease_open:
        raise StalePrefetchCommitError(
            f"foreign write lease was open at dispatch for {prefetch.resource_id}; "
            "provisional prefetch requires post-lease re-read"
        )

    if prefetch.dispatch_version.seq == commit_version.seq:
        return prefetch.payload

    if prefetch.dispatch_version.seq < commit_version.seq:
        if dependent_fields & intervening_write_fields:
            raise PrefetchAbortedError(
                f"intervening write to {prefetch.resource_id} touched dependent fields "
                f"{dependent_fields & intervening_write_fields}; re-dispatch required"
            )
        raise StalePrefetchCommitError(
            f"prefetch for {prefetch.resource_id} advanced "
            f"{prefetch.dispatch_version.seq}->{commit_version.seq}; "
            "re-validate against fresh payload before commit"
        )

    raise StalePrefetchCommitError(
        f"commit_version {commit_version.seq} precedes dispatch_version "
        f"{prefetch.dispatch_version.seq} for {prefetch.resource_id}; "
        "version regression indicates replica fork"
    )
