# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-speculative-tool-call-prefetching-when-a-conflicted-write-is-only-detectable-after-the-read-that-justifies-it.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-speculative-tool-call-prefetching-when-a-conflicted-write-is-only-detectable-after-the-read-that-justifies-it.warrant.json
# Markdown SHA-256:   b5c97f29769834a467f298d7339bb8d525c1ca34738fe5ab773ddb32ec281d5b
# Code AST SHA-256:   f811e6e7d29d6a13d8f759dcb61273e2ee46673b4e690e4d1132803bf0a0d1b5
# Verified Classes:   PrefetchDependencyConflict, PrefetchedRead, GatedWrite
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class PrefetchDependencyConflict(RuntimeError):
    """Raised when a write gated on a prefetched read commits after that read's key advanced."""
    pass


class PrefetchedRead:
    def __init__(self, key: str, version: int, value):
        self.key = key
        self.version = version
        self.value = value


class GatedWrite:
    """A write whose validity depends on a prefetched read. Must re-validate at commit."""

    def __init__(self, store, read: PrefetchedRead, target_key: str, delta: int):
        self.store = store
        self.read = read
        self.target_key = target_key
        self.delta = delta

    def commit(self):
        # Re-validate the gating read against the CURRENT stamp, not the prefetch stamp.
        current_version = self.store.version(self.read.key)
        if current_version != self.read.version:
            raise PrefetchDependencyConflict(
                f"gating read {self.read.key} advanced {self.read.version}->{current_version} "
                f"between validation and commit of {self.target_key}; refusing to commit"
            )
        # Re-read the target under the same stamp to close the read-to-write window.
        current_target = self.store.get(self.target_key)
        if current_target + self.delta > self.store.get(self.read.key):
            raise PrefetchDependencyConflict(
                f"commit of {self.target_key}+={self.delta} would exceed stock "
                f"{self.store.get(self.read.key)}; peer reservation won the race"
            )
        self.store.set(self.target_key, current_target + self.delta)
        return True
