#!/usr/bin/env python3 """Unit tests for the restartable Ritz wrapper (research/0024). Run: ../../../../.venv/bin/python3 tests/test_ritz_ckpt.py """ from __future__ import annotations import os import sys import tempfile import time from fractions import Fraction as Fr HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(HERE, "..", "src")) import ritz_ckpt as R # noqa: E402 fails = 0 def check(name, cond, detail=""): global fails if not cond: fails += 1 print(f"[{'PASS' if cond else 'FAIL'}] {name} {detail}") tmp = tempfile.mkdtemp(prefix="ritzckpt_") cdir = os.path.join(tmp, "ckpt") # ---- checkpoint creation and heartbeat ------------------------------------ ck = R.Ckpt(cdir, 50, Fr(1, 25), 25, 1024) check("meta.json written", os.path.exists(os.path.join(cdir, "meta.json"))) time.sleep(0.3) check("heartbeat.json written", os.path.exists(os.path.join(cdir, "heartbeat.json"))) check("heartbeat fingerprint", R._read_json(os.path.join(cdir, "meta.json"))["d"] == 25) # ---- fingerprint mismatch is rejected ------------------------------------- try: R.Ckpt(cdir, 51, Fr(1, 25), 25, 1024) check("fingerprint mismatch rejected", False) except ValueError: check("fingerprint mismatch rejected", True) # ---- exact-rational vector round trip ------------------------------------- c = [Fr(i + 1, 7) for i in range(5)] ck.save_vec([float(x) for x in c], c, 1.2345) cf, cr, lam = ck.load_vec() check("vec round trip (rationals)", cr == c, str(cr)) check("vec round trip (lambda)", abs(lam - 1.2345) < 1e-12) # ---- STOP sentinel --------------------------------------------------------- check("no stop initially", not ck.stop_requested()) open(os.path.join(cdir, "STOP"), "w").close() check("stop detected", ck.stop_requested()) try: ck.check_stop() check("check_stop raises StopRequested", False) except R.StopRequested: check("check_stop raises StopRequested", True) # ---- resumable short-circuit: banked vector returns without an engine ------ t0 = time.time() ef, cf2, lam2, cr2 = R.ritz_vector_resumable(50, Fr(1, 25), 25, prec=1024, ckpt_dir=cdir) dt = time.time() - t0 check("short-circuit returns no engine", ef is None) check("short-circuit returns the banked vector", cr2 == c) check("short-circuit is fast (< 2 s)", dt < 2.0, f"{dt:.3f}s") ck.hb.close() print("\nALL TESTS PASSED" if not fails else f"\n{fails} TEST(S) FAILED") raise SystemExit(1 if fails else 0)