# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-litmus-guardrail-signal-invert-under-checkpoint-replay-and-how-do-we-bound-the-observability-gate-before-it-admits-a-poisoned-r.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-litmus-guardrail-signal-invert-under-checkpoint-replay-and-how-do-we-bound-the-observability-gate-before-it-admits-a-poisoned-r.warrant.json
# Markdown SHA-256:   edb1e23980f2e6f5700d628850eadec43cad37f051a1fd2c9e44e2c8fe8fa9fe
# Code AST SHA-256:   8b9b8eaf4b11cfcef491943dc11e4923c3b00e9413c9890e7a723d59eb95fc50
# Verified Classes:   GuardrailSignalInvalid, SignalRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class GuardrailSignalInvalid(RuntimeError):
    """Raised when a cached LITMUS signal cannot be trusted for the gated action."""
    pass


@dataclass(frozen=True)
class SignalRecord:
    value: float
    context_fingerprint: str  # hash over tokens + probe positions + eviction offsets
    probe_positions: tuple[int, ...]
    eviction_offset: int


def fingerprint(tokens: list[str], probe_positions: tuple[int, ...], eviction_offset: int) -> str:
    h = hashlib.sha256()
    h.update("\x1f".join(tokens).encode())
    h.update(b"|probes:" + ",".join(map(str, probe_positions)).encode())
    h.update(b"|evict:" + str(eviction_offset).encode())
    return h.hexdigest()


def gate_action(
    cached: SignalRecord,
    live_tokens: list[str],
    live_probe_positions: tuple[int, ...],
    live_eviction_offset: int,
    tau: float,
    reprobe_fn,  # callable() -> float, synchronous fresh LITMUS measurement
) -> float:
    live_fp = fingerprint(live_tokens, live_probe_positions, live_eviction_offset)

    if cached.context_fingerprint == live_fp:
        signal = cached.value
    else:
        # Fingerprint mismatch: cached value is a different measurement.
        # Do NOT average, do NOT prefer last-known-good. Re-probe.
        signal = reprobe_fn()
        if signal != signal:  # NaN guard on the fresh probe
            raise GuardrailSignalInvalid(
                "fresh LITMUS probe returned NaN; refusing to gate on undefined signal"
            )

    if signal < tau:
        raise GuardrailSignalInvalid(
            f"guardrail signal {signal:.3f} below tau {tau:.3f} "
            f"(cached_fp={cached.context_fingerprint[:12]} live_fp={live_fp[:12]})"
        )
    return signal
