# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-commit-to-a-prefetched-tool-result-that-its-own-uncertainty-budget-has-already-invalidated.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-commit-to-a-prefetched-tool-result-that-its-own-uncertainty-budget-has-already-invalidated.warrant.json
# Markdown SHA-256:   2efc58b7ed340b50dc02a444dbd8282c433a45f99e86359f18c2e4b890fc2afa
# Code AST SHA-256:   5c21fe8970eb7f7b99b9f6cb065c32d626507259bdacdf52dd058d118cb331d9
# Verified Classes:   PrefetchWarrantError, Warrant, PrefetchedResult
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class PrefetchWarrantError(RuntimeError):
    """Raised when a prefetched result is admitted under a contaminated or
    stale uncertainty budget — i.e. the admission check was performed against
    a context that already contained the prefetched payload."""


@dataclass(frozen=True)
class Warrant:
    u_dispatch: float          # entropy at dispatch, stamped by dispatcher
    c_tool: float              # tool's own confidence in the returned row
    p_branch: float            # probability of the branch this was prefetched for
    branch_id: str
    quarantined: bool          # was the payload hidden from the reasoning ctx?


@dataclass
class PrefetchedResult:
    payload: dict
    warrant: Warrant
    admitted: bool = False


def admit_prefetch(
    result: PrefetchedResult,
    tau: float,
    tool_floor: float,
    p_commit: float,
    committed_branch: str,
    live_entropy: float,
) -> PrefetchedResult:
    w = result.warrant

    # Invariant 1: the payload must not have influenced the entropy it is
    # being judged against. If not quarantined, live_entropy is contaminated.
    if not w.quarantined:
        raise PrefetchWarrantError(
            f"payload was in-context at admission; live_entropy={live_entropy:.2f} "
            f"is contaminated by the payload itself (u_dispatch={w.u_dispatch:.2f})"
        )

    # Invariant 2: budget at admission must be at least as strict as at dispatch.
    if w.u_dispatch > tau:
        raise PrefetchWarrantError(
            f"dispatch-time uncertainty {w.u_dispatch:.2f} exceeded budget {tau:.2f}; "
            f"result has no valid warrant regardless of current entropy"
        )

    # Invariant 3: tool's own confidence must clear its floor.
    if w.c_tool < tool_floor:
        raise PrefetchWarrantError(
            f"tool confidence {w.c_tool:.2f} below floor {tool_floor:.2f}; "
            f"prefetch was speculative and the row is not admissible"
        )

    # Invariant 4: the branch the result was fetched for must be the branch
    # that won. A prefetch for a lost branch is a category error to admit.
    if w.branch_id != committed_branch:
        raise PrefetchWarrantError(
            f"prefetched for branch {w.branch_id!r} but committed to "
            f"{committed_branch!r}; re-fetch under the committed branch"
        )

    if w.p_branch < p_commit:
        raise PrefetchWarrantError(
            f"branch probability {w.p_branch:.2f} below commit threshold "
            f"{p_commit:.2f}; result was fetched while genuinely undecided"
        )

    result.admitted = True
    return result
