# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-invalidate-a-speculative-prefetch-that-its-own-dependency-graph-has-already-proven-safe.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-invalidate-a-speculative-prefetch-that-its-own-dependency-graph-has-already-proven-safe.warrant.json
# Markdown SHA-256:   92bbcce3e82c120edd2ca06ca8aefc8c4a8578908bfb72bec95f673d9a61ac3c
# Code AST SHA-256:   d8fcce65c1ebb48c7b18906973fab73231bb42f02d6dd79facda36d9c0e2eba7
# Verified Classes:   SpeculativeKeyMismatch, Prefetch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class SpeculativeKeyMismatch(RuntimeError):
    """Raised when a prefetched entry's fingerprint is prediction-derived and
    cannot be reconciled with the resolver-issued fingerprint without re-fetch."""
    pass


@dataclass(frozen=True)
class Prefetch:
    doc_id: str
    body: bytes
    predicted_rev: str          # model-guessed label, NOT trustworthy as a key
    resolver_rev: str | None    # None until a confirming call returns


def content_fingerprint(body: bytes) -> str:
    return "sha256:" + hashlib.sha256(body).hexdigest()


def resolve_key(pf: Prefetch) -> str:
    """Compute the cache key under which a prefetch may be *promoted*.

    Invariant: the key must be content-derived or resolver-minted. A predicted
    revision label may never be the sole key component, because the resolver
    can issue a different label for byte-identical content (false invalidation)
    or a colliding label for changed content (false retention).
    """
    if pf.resolver_rev is None:
        # No confirming call yet: provisional namespace only, never promoted.
        raise SpeculativeKeyMismatch(
            f"prefetch {pf.doc_id} has no resolver-issued revision; "
            f"predicted_rev={pf.predicted_rev!r} is not a valid promotion key"
        )
    # Content hash is authoritative; resolver_rev is included only as a
    # secondary, resolver-minted component. predicted_rev is discarded.
    return f"{pf.doc_id}|{content_fingerprint(pf.body)}|{pf.resolver_rev}"


def promote(pf: Prefetch, cache: dict[str, bytes]) -> str:
    key = resolve_key(pf)  # raises if unconfirmed
    cache[key] = pf.body
    return key
