# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-speculative-tool-call-prefetching-against-read-after-write-divergence-on-shared-mutable-state.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-speculative-tool-call-prefetching-against-read-after-write-divergence-on-shared-mutable-state.warrant.json
# Markdown SHA-256:   62e22894418f0ec18f855d9a26499c43d5143d417b4609adddcbe2036d1be4ab
# Code AST SHA-256:   2971a9a6ce21ef8274b3d5bb0ea12c8ac4844451b120eb8858cd497e365d2433
# Verified Classes:   SupersededPrefetchError, PrefetchResult, TurnFrontier
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SupersededPrefetchError(RuntimeError):
    """Raised when a prefetched read is consumed after its state version
    has been superseded by a write committed within the same turn frontier."""
    pass


@dataclass
class PrefetchResult:
    resource_id: str
    observed_version: int
    payload: dict


@dataclass
class TurnFrontier:
    # highest committed version seen per resource this turn
    committed: dict = field(default_factory=dict)
    # resources with an in-flight, unconfirmed write
    pending_writes: set = field(default_factory=set)
    # resources the agent has authorized a write against this turn
    write_set: set = field(default_factory=set)

    def record_write_authorized(self, resource_id: str) -> None:
        self.write_set.add(resource_id)
        self.pending_writes.add(resource_id)

    def record_write_committed(self, resource_id: str, version: int) -> None:
        self.pending_writes.discard(resource_id)
        prev = self.committed.get(resource_id, -1)
        if version > prev:
            self.committed[resource_id] = version


def verify_prefetch(result: PrefetchResult, frontier: TurnFrontier) -> bool:
    """Return True only if the prefetch is safe to inject into context.
    Raises SupersededPrefetchError on a hard RAWD violation so the caller
    cannot silently consume a causally invalidated snapshot."""
    rid = result.resource_id

    # Hard boundary: never consume a prefetch against an identity in the write-set.
    if rid in frontier.write_set:
        raise SupersededPrefetchError(
            f"prefetch for {rid} targets an identity in this turn's write-set; "
            f"snapshot v{result.observed_version} is not consumable regardless of version match"
        )

    # Pending write => snapshot may be pre- or post-commit; assume superseded.
    if rid in frontier.pending_writes:
        raise SupersededPrefetchError(
            f"prefetch for {rid} races an unconfirmed in-flight write; "
            f"v{result.observed_version} cannot be ordered against commit"
        )

    max_committed = frontier.committed.get(rid, -1)
    if result.observed_version < max_committed:
        raise SupersededPrefetchError(
            f"prefetch for {rid} observed v{result.observed_version} "
            f"but v{max_committed} already committed this turn"
        )

    return True


def inject_or_revalidate(result: PrefetchResult, frontier: TurnFrontier) -> str:
    try:
        verify_prefetch(result, frontier)
        return "consume"
    except SupersededPrefetchError:
        # Downgrade to re-validation rather than injecting a stale snapshot.
        return "revalidate"
