# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-commit-a-prefetched-tool-call-whose-litmus-risk-score-was-gated-at-prefetch-time-but-whose-risk-silently-re-scored-below-threshol.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-commit-a-prefetched-tool-call-whose-litmus-risk-score-was-gated-at-prefetch-time-but-whose-risk-silently-re-scored-below-threshol.warrant.json
# Markdown SHA-256:   d9e31df13418af1c6ba214287686061e4079598edf5bbfbbd8a5e7eac335d1e6
# Code AST SHA-256:   a9944f1c274dca4f2fbebc089552bdb54cdf2572492502ac0ffbf347675408ba
# Verified Classes:   ObservationSealViolation, PrefetchSeal, SpeculativeHandle
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ObservationSealViolation(RuntimeError):
    """Raised when a commit-time risk score is computed against observations
    that were not part of the prefetch-time observation seal."""


@dataclass(frozen=True)
class PrefetchSeal:
    call_id: str
    observation_ids: FrozenSet[str]
    prefetch_risk: float
    side_effecting: bool


@dataclass
class SpeculativeHandle:
    seal: PrefetchSeal
    result: object
    committed: bool = False
    rolled_back: bool = False


def commit_prefetch(
    handle: SpeculativeHandle,
    commit_risk: float,
    commit_observation_ids: FrozenSet[str],
    tau_commit: float,
) -> object:
    if handle.committed or handle.rolled_back:
        raise ObservationSealViolation(
            f"handle {handle.seal.call_id} already terminal"
        )

    # Invariant 1: commit-time score must be computed under the prefetch seal.
    extra = commit_observation_ids - handle.seal.observation_ids
    if extra:
        raise ObservationSealViolation(
            f"commit for {handle.seal.call_id} used {len(extra)} observations "
            f"outside the prefetch seal: {sorted(extra)}"
        )

    # Invariant 2: for side-effecting prefetch, a prefetch score above
    # threshold can never be admitted by a later, lower re-score.
    if handle.seal.side_effecting and handle.seal.prefetch_risk >= tau_commit:
        handle.rolled_back = True
        raise ObservationSealViolation(
            f"side-effecting prefetch {handle.seal.call_id} scored "
            f"{handle.seal.prefetch_risk:.3f} >= tau {tau_commit:.3f} at "
            f"prefetch; commit re-score {commit_risk:.3f} cannot admit it. "
            f"Roll back and re-prefetch under current observations."
        )

    # Invariant 3: within the seal, risk may not decrease below the
    # prefetch score (non-monotone features are a world-change signal).
    if commit_risk < handle.seal.prefetch_risk - 1e-9:
        raise ObservationSealViolation(
            f"risk decreased under a pinned observation set for "
            f"{handle.seal.call_id}: {handle.seal.prefetch_risk:.3f} -> "
            f"{commit_risk:.3f}; this indicates evidence leaked past the seal"
        )

    if commit_risk >= tau_commit:
        handle.rolled_back = True
        return None

    handle.committed = True
    return handle.result
