# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-litmus-derived-runtime-safety-monitor-as-a-liveness-hazard-rather-than-a-pure-safety-gate-when-the-monitor-s-own-probe.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-litmus-derived-runtime-safety-monitor-as-a-liveness-hazard-rather-than-a-pure-safety-gate-when-the-monitor-s-own-probe.warrant.json
# Markdown SHA-256:   035a46aa1fde089b1e2bb7caac81fdbf188ce9aa68c79d1ea1f5c5055e86c8ce
# Code AST SHA-256:   450d50486cea14487d4bd8a76f94fc542d44347b40bedec7f36a763ec0c99fd3
# Verified Classes:   MonitorBudgetViolation, MonitorProfile
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class MonitorBudgetViolation(RuntimeError):
    """Raised when a LITMUS-derived monitor cannot complete a probe
    within the action's remaining decision budget minus dispatch reserve.
    This is a liveness failure, not a safety verdict: the predicate was
    never consulted. Callers must NOT retry; they must route to the
    degraded-verdict path."""


@dataclass(frozen=True)
class MonitorProfile:
    action_class: str
    probe_latency_p99_s: float
    dispatch_reserve_s: float
    decision_deadline_s: float


def admit_monitor(profile: MonitorProfile, retry_attempts: int = 1) -> None:
    """Configuration admission check. Rejects monitor/action-class
    pairings that violate the probe-budget separation invariant:
        L_probe_p99 * retry_attempts + R < D_remaining
    Must run at config-load time, not at request time."""
    cumulative_probe = profile.probe_latency_p99_s * retry_attempts
    required = cumulative_probe + profile.dispatch_reserve_s
    if required >= profile.decision_deadline_s:
        raise MonitorBudgetViolation(
            f"action_class={profile.action_class!r} "
            f"L_probe_p99={profile.probe_latency_p99_s:.3f}s "
            f"x{retry_attempts} retries + R={profile.dispatch_reserve_s:.3f}s "
            f"= {required:.3f}s >= D_remaining={profile.decision_deadline_s:.3f}s; "
            f"monitor would time out before grading, converting a safety "
            f"gate into a liveness hazard. Reject this pairing or reduce "
            f"probe latency."
        )


def run_inline_probe(
    profile: MonitorProfile,
    probe_fn,
    started_at: float,
) -> object:
    """Run the probe only if the invariant holds at runtime. If the
    grader has drifted slow (e.g. load spike), fail with an explicit
    bypass record rather than silently failing open or closed."""
    elapsed = time.monotonic() - started_at
    remaining = profile.decision_deadline_s - elapsed
    required = profile.probe_latency_p99_s + profile.dispatch_reserve_s
    if required >= remaining:
        # Degraded-verdict bypass: do NOT run the probe, do NOT retry.
        raise MonitorBudgetViolation(
            f"action_class={profile.action_class!r} "
            f"remaining={remaining:.3f}s < required={required:.3f}s; "
            f"emitting verdict=bypassed_budget_exhausted and routing to "
            f"fallback policy (static rule / human approval / hard deny)."
        )
    return probe_fn()
