# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-verifier-drift-when-a-speculative-agent-planner-s-commit-gate-silently-accepts-stale-rollouts-under-cost-aware-speculation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-verifier-drift-when-a-speculative-agent-planner-s-commit-gate-silently-accepts-stale-rollouts-under-cost-aware-speculation.warrant.json
# Markdown SHA-256:   fbd89673920946865542fb0f911d1371b0c9099e41f78a88f1bef99e02c2271b
# Code AST SHA-256:   aff19b0206343f6039e5b7216393f3310c411edebb273b62c74e5200e0d8ea8d
# Verified Classes:   VerifierDriftError, DriftMonitor
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass, field
from typing import Callable, Sequence


class VerifierDriftError(RuntimeError):
    """Raised when the sampled verifier's acceptance diverges from the
    budget-invariant reference verifier beyond the operational boundary."""


@dataclass
class DriftMonitor:
    audit_rate: float = 0.02
    window: int = 50
    rejection_boundary: float = 0.15
    min_audit_samples: int = 10
    _rejections: list[int] = field(default_factory=list)
    _samples: list[int] = field(default_factory=list)

    def record(self, audited: bool, reference_rejected: bool) -> None:
        if not audited:
            return
        self._samples.append(1)
        self._rejections.append(1 if reference_rejected else 0)
        if len(self._samples) > self.window:
            self._samples.pop(0)
            self._rejections.pop(0)

    def rejection_rate(self) -> float:
        n = len(self._samples)
        if n == 0:
            return 0.0
        return sum(self._rejections) / n

    def check(self) -> None:
        n = len(self._samples)
        if n < self.min_audit_samples:
            # Drift metric is statistically meaningless; verifier is unverified.
            raise VerifierDriftError(
                f"insufficient audit samples ({n} < {self.min_audit_samples}); "
                "speculation budget floor violated, verifier unverified"
            )
        rate = self.rejection_rate()
        if rate > self.rejection_boundary:
            raise VerifierDriftError(
                f"reference-verifier rejection rate {rate:.3f} exceeds "
                f"boundary {self.rejection_boundary:.3f} over {n} audited steps; "
                "halt speculative commit and fall back to full-budget verification"
            )


def commit_step(
    rollout_score: float,
    sampled_verifier_accepts: bool,
    audit_due: bool,
    reference_verifier: Callable[[], bool],
    monitor: DriftMonitor,
    commit_threshold: float = 0.5,
) -> bool:
    if audit_due:
        monitor.record(audited=True, reference_rejected=not reference_verifier())
        monitor.check()  # may raise VerifierDriftError before any commit
    if sampled_verifier_accepts and rollout_score >= commit_threshold:
        return True
    return False
