#!/usr/bin/env python3 """Auditable comparison gate and resource ledger from Chapter 9. All externally supplied numbers must be integers, decimal/rational strings, or fractions.Fraction values. Float inputs are deliberately rejected. The statistical radius uses a rational upper bound for log followed by an upward rational-grid square root, so rounding cannot make it smaller than the manuscript's Hoeffding radius. This module does not establish that an evaluation data source is fresh, that its conditional mean is the declared risk difference, or that a claimed numerical-error bound is true. Those are the explicit modeling obligations in the manuscript. It also does not generate candidates or claim an empirical RSI speedup. """ from __future__ import annotations import argparse import json from dataclasses import dataclass from fractions import Fraction from math import isqrt from pathlib import Path from typing import Iterable, Optional F = Fraction def exact(value) -> F: if isinstance(value, float): raise TypeError("Use an exact decimal string or Fraction, not a float.") if isinstance(value, (int, str, F)): return F(value) raise TypeError("Expected int, str, or fractions.Fraction.") def log_series_interval(w: F, terms: int = 24): """Bounds for log((1+w)/(1-w)), for 0<=w<=1/3. log((1+w)/(1-w)) = 2 sum_{j>=0} w^(2j+1)/(2j+1). Its positive omitted tail is at most 2*w^(2N+1)/((2N+1)*(1-w*w)). """ w = exact(w) if not 0 <= w <= F(1, 3) or terms < 1: raise ValueError("Require 0<=w<=1/3 and terms>=1.") total = F(0) power = w for j in range(terms): total += 2 * power / (2 * j + 1) power *= w * w tail = 2 * power / ((2 * terms + 1) * (1 - w * w)) return total, total + tail def rational_log_upper(x, terms: int = 24) -> F: """A rigorous rational upper bound for log(x), x>=1.""" x = exact(x) if x < 1: raise ValueError("This function is defined here only for x>=1.") k = 0 y = x while y >= 2: y /= 2 k += 1 _, log_two_upper = log_series_interval(F(1, 3), terms) _, log_y_upper = log_series_interval((y - 1) / (y + 1), terms) return k * log_two_upper + log_y_upper def rational_sqrt_upper(x, scale: int = 10**12) -> F: """Least multiple of 1/scale whose square is at least exact x.""" x = exact(x) if x < 0 or scale < 1: raise ValueError("Require x>=0 and a positive integer grid scale.") squared_grid = x * scale * scale root = isqrt(squared_grid.numerator // squared_grid.denominator) if root * root * squared_grid.denominator < squared_grid.numerator: root += 1 result = F(root, scale) assert result * result >= x if root: assert F(root - 1, scale) ** 2 < x return result def anytime_radius(trial: int, n: int, delta, *, terms: int = 24, scale: int = 10**12) -> F: """Rational upper bound for sqrt(2/n log(2t(t+1)n(n+1)/delta)).""" delta = exact(delta) if trial < 1 or n < 1 or not 0 < delta < 1: raise ValueError("Require trial,n>=1 and 0 ComparisonCertificate: """Certify a single frozen paired comparison at any collected sample size. values[j] is the recorded incumbent-minus-candidate loss on paired task j. measurement_errors[j], if supplied, is a true bound on its recording error. Repeated calls may use longer prefixes of the same frozen comparison. Use the same whole-run delta and a unique positive trial index per proposal. """ values = [exact(x) for x in values] if not values: raise ValueError("At least one paired observation is required.") if measurement_errors is None: errors = [F(0)] * len(values) else: errors = [exact(x) for x in measurement_errors] if len(errors) != len(values): raise ValueError("Each observation needs its own error bound.") for value, error in zip(values, errors): if error < 0 or abs(value) > 1 + error: raise ValueError("Error interval must be compatible with a true value in [-1,1].") n = len(values) return ComparisonCertificate(trial, n, sum(values, F(0)) / n, anytime_radius(trial, n, delta), sum(errors, F(0)) / n, exact(delta)) def should_accept(certificate: ComparisonCertificate, margin=0) -> bool: margin = exact(margin) if margin < 0: raise ValueError("The required improvement must be nonnegative.") return certificate.lower >= margin def comparison_action(certificate: ComparisonCertificate, margin=0, *, force_decision: bool = False) -> str: """Return accept, reject, or continue for one frozen comparison. A resource cap can force a rejection when acceptance is not certified. This still obeys the manuscript's finite oracle inequality, with the confidence radius at the actual stopping sample size. """ margin = exact(margin) if margin < 0: raise ValueError("The required improvement must be nonnegative.") if certificate.lower >= margin: return "accept" if certificate.upper < margin or force_decision: return "reject" return "continue" class CreditLedger: """Exact cost reservation and settlement; rejected trials are charged. Credit is in risk-improvement units, cost_weight converts cost units. A caller must reserve before undertaking a trial and honor the cap. An accepted gain must be a valid nonnegative lower certificate. The ledger verifies arithmetic and caps, not the certificate's provenance. """ def __init__(self, initial_credit, cost_weight): self.initial_credit = exact(initial_credit) self.cost_weight = exact(cost_weight) if self.initial_credit < 0 or self.cost_weight <= 0: raise ValueError("Require nonnegative credit and positive cost weight.") self.credit = self.initial_credit self.total_cost = F(0) self.total_certified_gain = F(0) self.completed_trials = 0 self._reserved_cap = None def _check_accounting(self): escrow_cost = self._reserved_cap if self._reserved_cap is not None else F(0) assert self.credit >= 0 assert self.credit + self.cost_weight * escrow_cost == ( self.initial_credit - self.cost_weight * self.total_cost + self.total_certified_gain) def reserve(self, cost_cap): cap = exact(cost_cap) if self._reserved_cap is not None: raise RuntimeError("Settle the active reservation before starting another.") if cap < 0 or self.cost_weight * cap > self.credit: raise ValueError("The full cost cap must fit the available credit.") self.credit -= self.cost_weight * cap self._reserved_cap = cap self._check_accounting() def settle(self, actual_cost, *, accepted=False, certified_lower_gain=0): cost = exact(actual_cost) gain = exact(certified_lower_gain) if accepted else F(0) if self._reserved_cap is None: raise RuntimeError("Reserve a cost cap before settling a trial.") if cost < 0 or cost > self._reserved_cap: raise ValueError("Actual cost must stay within the reserved cap.") if accepted and not 0 <= gain <= 1: raise ValueError("Accepted risk-improvement certificate must lie in [0,1].") self.credit += self.cost_weight * (self._reserved_cap - cost) + gain self.total_cost += cost self.total_certified_gain += gain self.completed_trials += 1 self._reserved_cap = None self._check_accounting() def to_dict(self): return {"initial_credit": str(self.initial_credit), "cost_weight": str(self.cost_weight), "available_credit": str(self.credit), "reserved_cost_cap": (str(self._reserved_cap) if self._reserved_cap is not None else None), "total_cost": str(self.total_cost), "total_certified_gain": str(self.total_certified_gain), "completed_trials": self.completed_trials} def self_test(): assertions = 0 for w in [F(0), F(1, 10), F(1, 3)]: lo, hi = log_series_interval(w, 24) lo_more, hi_more = log_series_interval(w, 25) assert lo <= lo_more <= hi_more <= hi assertions += 1 lo2, hi2 = log_series_interval(F(1, 3), 24) assert F(2, 3) < lo2 < hi2 < F(7, 10) assert rational_log_upper(F(1)) == 0 assert rational_log_upper(F(8)) == 3 * hi2 assertions += 3 for x in [F(0), F(1), F(2), F(7, 9), F(137, 17)]: b = rational_sqrt_upper(x, scale=10**6) assert b * b >= x if b: assert (b - F(1, 10**6)) ** 2 < x assertions += 1 for T in [1, 2, 7, 50]: total = sum((F(1, t * (t + 1)) for t in range(1, T + 1)), F(0)) assert total == F(T, T + 1) < 1 assertions += 1 cert = compare(["3/4"] * 1000, trial=1, delta="1/20") assert should_accept(cert, "1/2") cert_error = compare(["3/4"] * 1000, trial=1, delta="1/20", measurement_errors=["1/100"] * 1000) assert cert_error.lower == cert.lower - F(1, 100) assert cert_error.upper == cert.upper + F(1, 100) negative = compare(["-1/2"] * 1000, trial=2, delta="1/20") assert not should_accept(negative) assertions += 4 ambiguous = compare([0] * 1000, trial=3, delta="1/20") assert comparison_action(cert, "1/2") == "accept" assert comparison_action(negative) == "reject" assert comparison_action(ambiguous) == "continue" assert comparison_action(ambiguous, force_decision=True) == "reject" assertions += 4 ledger = CreditLedger("1/10", "1/1000") ledger.reserve(50) ledger.settle(40, accepted=False) assert ledger.credit == F(3, 50) ledger.reserve(50) ledger.settle(50, accepted=True, certified_lower_gain=cert.lower) assert ledger.credit == F(1, 100) + cert.lower ledger.reserve(60) ledger.settle(30, accepted=False) assert ledger.total_cost == 120 assert ledger.cost_weight * ledger.total_cost <= ( ledger.initial_credit + ledger.total_certified_gain) assertions += 4 # Pathwise oracle inequality under declared valid intervals. incumbent = F(9, 10) initial = incumbent candidates = [F(7, 10), F(4, 5), F(1, 5), F(1, 4)] radius, margin = F(1, 20), F(1, 50) offsets = [-radius / 2, radius / 2, -radius / 2, radius / 2] accepted_margins = F(0) for candidate, offset in zip(candidates, offsets): delta = incumbent - candidate lower = delta + offset - radius upper = delta + offset + radius assert lower <= delta <= upper if lower >= margin: incumbent = candidate accepted_margins += margin assert incumbent <= initial - accepted_margins assertions += 2 assert incumbent == F(1, 5) assert incumbent <= min(candidates) + margin + 2 * radius assertions += 2 # API guard checks must fail before any incorrect ledger mutation. try: exact(0.1) raise AssertionError("Float guard did not trigger") except TypeError: assertions += 1 before = ledger.to_dict() try: ledger.reserve(10**10) raise AssertionError("Unaffordable reservation was accepted") except ValueError: assert ledger.to_dict() == before assertions += 1 return {"all_checks_passed": True, "reported_assertion_groups": assertions, "arithmetic": "exact rational log-series bound and upward square-root grid", "acceptance_example": cert.to_dict(), "ledger_example": ledger.to_dict(), "scope": "Arithmetic and accounting audits; probability and data contracts are proved/stated in Chapter 9."} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--self-test", action="store_true") parser.add_argument("--output", type=Path) args = parser.parse_args() if not args.self_test: parser.print_help() return report = self_test() if args.output: args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") print(json.dumps(report, indent=2)) if __name__ == "__main__": main()