check_repair.py

back to table · edit · history · where entries came from · files · download

6393 bytes, as of the version from 2026-12-02 03:41 (current). Recorded here, not run.

"""Read-only T856 repair checks; run with agents/sage.sh and mounted inputs.

Mount generate.py, stored-results.json, verification-document.json and
repair-skill-manifest.json beside this script. Supply the bot key on stdin.
All 22 unchanged production enclosures are reused, not recomputed. Three
fresh mpmath calculations test the event interpretation and a square control;
they are heuristic checks, not new certification of the stored precision.
"""
import hashlib
import json
import re
import sys
from decimal import Decimal
from fractions import Fraction
from pathlib import Path

import numberdb.sage as numberdb
from sage.env import SAGE_VERSION
from sage.rings.rational_field import QQ
from sage.rings.real_mpfi import RealIntervalField
import mpmath as mp
from generate import WattsCrossing

work = Path(__file__).resolve().parent
document = json.loads((work / 'verification-document.json').read_text())
checkpoint = json.loads((work / 'stored-results.json').read_text())
manifest = work / 'repair-skill-manifest.json'
generator_hash = hashlib.sha256((work / 'generate.py').read_bytes()).hexdigest()
assert generator_hash == checkpoint['generator_sha256']
key = sys.stdin.read().strip()
if re.match(r'^[A-Z_][A-Z0-9_]*\s*=', key):
    key = key.split('=', 1)[1].strip().strip('"\'')
assert key and not any(c.isspace() for c in key)
numberdb.configure(api_key=key)


def stored_interval(text):
    d = Decimal(text)
    if not d.is_finite():
        raise ValueError('Nonfinite stored value')
    unit = Fraction(10) ** d.as_tuple().exponent
    mid = Fraction(d)
    return mid - unit, mid + unit


def enclosed(entry, text):
    lo, hi = Fraction(entry['lower']), Fraction(entry['upper'])
    a, b = stored_interval(text)
    assert lo < hi and hi - lo < (b - a) / 1000000
    return a <= lo <= hi <= b


cached = {e['params']['r']: e for e in checkpoint['entries']}
assert list(cached) == list(document['Numbers'])
checkpoint_checks = []
for r, entry in cached.items():
    text = document['Numbers'][r]['number']
    assert text == entry['number'], (r, 'Changed checkpoint input')
    assert enclosed(entry, text), r
    checkpoint_checks.append({'r': r, 'stored_interval_contains_saved_ball': True})

bad_text = str(Decimal(document['Numbers']['2']['number']) + Decimal('0.001'))
assert not enclosed(cached['2'], bad_text)
try:
    stored_interval('NaN')
except ValueError:
    nonfinite_rejected = True
else:
    raise AssertionError('Nonfinite control accepted')


class CachedWatts(WattsCrossing):
    """Verify all live values against unchanged saved rigorous bounds."""
    def value(self, params, digits):
        e = cached[params['r']]
        return RealIntervalField(640)(QQ(e['lower']), QQ(e['upper']))


verification = CachedWatts().verify(sample=None)
assert verification.ok
verify_result = {name: getattr(verification, name) for name in
                 ['table', 'checked', 'matched', 'differing', 'missing',
                  'extra', 'coarser', 'refined']}
verify_result['ok'] = bool(verification.ok)
verify_result['mode'] = 'Saved production enclosures; no full-table recomputation'

mp.mp.dps = 150


def probabilities(r):
    r = Fraction(r)
    rr = mp.mpf(r.numerator) / r.denominator
    q = mp.exp(-mp.pi * rr)
    x = (mp.jtheta(2, 0, q) / mp.jtheta(3, 0, q)) ** 4
    third = mp.mpf(1) / 3
    # Normalized beta formula independently supplies C, without hyp2f1.
    cardy = mp.betainc(third, third, 0, x, regularized=True)
    difference = mp.sqrt(3) / (2 * mp.pi) * x * mp.hyper(
        [1, 1, 4 * third], [2, 5 * third], x)
    watts = cardy - difference
    assert all(mp.isfinite(t) for t in [x, cardy, difference, watts])
    return cardy, watts, difference


c2, w2, d2 = probabilities(Fraction(2))
chalf, whalf, dhalf = probabilities(Fraction(1, 2))
c1, w1, d1 = probabilities(Fraction(1))
square = mp.mpf(1) / 4 + mp.sqrt(3) / (4 * mp.pi) * (
    3 * mp.log(3) - 4 * mp.log(2))
tol = mp.mpf('1e-130')
assert abs(w1 - square) < tol and abs(c1 - mp.mpf('0.5')) < tol
assert abs(c2 + chalf - 1) < tol
assert abs(w2 - whalf) < tol
assert abs((dhalf - d2) - (1 - 2 * c2)) < tol
assert abs(dhalf - d2) > mp.mpf('0.6')  # reject the ambiguous false reading
for r, value in [('1', w1), ('2', w2)]:
    lo, hi = stored_interval(document['Numbers'][r]['number'])
    assert mp.mpf(lo.numerator) / lo.denominator < value
    assert value < mp.mpf(hi.numerator) / hi.denominator

results = {
    'table': 'T856',
    'skill_manifest': 'agents/runs/20261128T134310Z-repair-skills/manifest.json',
    'skill_manifest_sha256': hashlib.sha256(manifest.read_bytes()).hexdigest(),
    'skill_bundle_sha256': 'f20b09e3db5fd443660c0c6b29391ee369b7c710a43e22d8abb971ec3f54dd14',
    'generator_sha256': generator_hash,
    'checkpoint_sha256': hashlib.sha256((work / 'stored-results.json').read_bytes()).hexdigest(),
    'versions': {'sage': SAGE_VERSION, 'mpmath': mp.__version__},
    'checked_entries': len(cached), 'total_entries': len(cached), 'failures': [],
    'checkpoint_checks': checkpoint_checks, 'package_verify': verify_result,
    'fresh_evaluations': ['1', '2', '1/2'], 'mpmath_dps': mp.mp.dps,
    'fresh_method': 'Normalized incomplete beta for C; explicit theta and 3F2 for D; W=C-D at each orientation independently',
    'C2': mp.nstr(c2, 45), 'W2': mp.nstr(w2, 45),
    'D2': mp.nstr(d2, 45), 'D_one_half': mp.nstr(dhalf, 45),
    'W_rotation_residual': mp.nstr(w2 - whalf, 12),
    'C_duality_residual': mp.nstr(c2 + chalf - 1, 12),
    'D_rotation_difference': mp.nstr(dhalf - d2, 45),
    'D_rotation_identity_residual': mp.nstr((dhalf - d2) - (1 - 2 * c2), 12),
    'square_control_residual': mp.nstr(w1 - square, 12),
    'known_answer_control': True, 'negative_control_rejected': True,
    'nonfinite_control_rejected': nonfinite_rejected,
    'limitations': 'Fresh mpmath values are heuristic, not rigorous error bounds. Stored 100-digit values retain original certified production bounds and original provenance; no numerical entries are edited.',
    'proof': 'For D=C-W, C(1/r)=1-C(r) and W(1/r)=W(r) give D(1/r)-D(r)=1-2*C(r). The four-side event is fixed by rotation, but horizontal-without-vertical becomes vertical-without-horizontal.',
    'sources': [
        'Kleban-Zagier (2003), section 2, equations (1),(2),(7),(8)',
        'Sheffield-Wilson (2011), section 1 and Figure 1',
    ],
}
print(json.dumps(results, indent=2))