"""Tests for the screening-ceiling dataset. The important tests here are not "does the file parse" -- they are "is the published claim true of the published data". A dataset whose ground truth is wrong is worse than no dataset, because every result scored against it inherits the error. """ from __future__ import annotations import json import math import pathlib import random import sys import pytest HERE = pathlib.Path(__file__).resolve().parents[1] sys.path.insert(0, str(HERE)) import verify # noqa: E402 from loader import ( # noqa: E402 family_layout, load_counterexamples, load_regions, load_theorem, ) DATA = HERE / "data" # --------------------------------------------------------------------- presence def test_data_files_exist_and_are_nonempty(): for name in ("certified_regions.jsonl", "counterexamples.jsonl", "theorem.json"): p = DATA / name assert p.exists(), f"missing {name}" assert p.stat().st_size > 0, f"empty {name}" def test_every_line_is_valid_json(): for name in ("certified_regions.jsonl", "counterexamples.jsonl"): for i, line in enumerate((DATA / name).read_text(encoding="utf-8").splitlines()): if line.strip(): json.loads(line) # raises on malformed # ---------------------------------------------------------------------- schema def test_region_schema_is_complete(): required = {"region_id", "bounds", "status", "certified_leaves", "processed_leaves", "sup_certified_k_hi", "volume_fraction_of_region", "unresolved_leaves"} for r in load_regions(): assert required <= set(r), f"{r.get('region_id')} missing {required - set(r)}" assert set(r["bounds"]) == {"d0_um", "pt_mult", "sep_mult", "jog_mult"} for b in r["bounds"].values(): assert b["lo"] < b["hi"], "degenerate interval" def test_counterexample_schema_is_complete(): required = {"case_id", "model", "n_conductors", "worst_pair", "k_predicted", "violates_ceiling", "xy_um", "radius_um", "eps_r"} for c in load_counterexamples(): assert required <= set(c), f"{c.get('case_id')} missing {required - set(c)}" assert len(c["xy_um"]) == c["n_conductors"] assert len(c["radius_um"]) == c["n_conductors"] def test_case_ids_are_unique(): ids = [c["case_id"] for c in load_counterexamples()] assert len(ids) == len(set(ids)) def test_region_ids_are_unique(): ids = [r["region_id"] for r in load_regions()] assert len(ids) == len(set(ids)) # ------------------------------------------------------------------ the claims def test_every_region_is_certified_with_no_unresolved_leaves(): for r in load_regions(): assert r["status"] == "CERTIFIED", f"{r['region_id']} is {r['status']}" assert r["unresolved_leaves"] == 0 def test_no_region_admits_a_k_above_the_bound(): """The published per-region supremum must respect the published bound.""" k_bar = load_theorem()["k_bar"] for r in load_regions(): assert r["sup_certified_k_hi"] <= k_bar, \ f"{r['region_id']} admits {r['sup_certified_k_hi']} > {k_bar}" def test_leaf_total_matches_the_sum_over_regions(): t = load_theorem() assert sum(r["certified_leaves"] for r in load_regions()) \ == t["certified_leaves_total"] def test_regions_tile_the_family_box(): """Union of region bounds must span the declared family box on every axis.""" t = load_theorem() regions = load_regions() for name, b in t["family_box"].items(): assert min(r["bounds"][name]["lo"] for r in regions) == b["lo"] assert max(r["bounds"][name]["hi"] for r in regions) == b["hi"] @pytest.mark.parametrize("seed", [0, 1, 2]) def test_sampling_inside_certified_regions_never_exceeds_the_bound(seed): """Independent re-derivation: sampling must fail to refute the claim.""" k_bar = load_theorem()["k_bar"] rng = random.Random(seed) worst, violations = verify.check_regions(load_regions(), k_bar, samples=3, rng=rng, verbose=False) assert violations == [], f"claim refuted at {violations[:2]}" assert worst <= k_bar def test_every_counterexample_really_violates_the_ceiling(): """Existential claim, re-derived from stored coordinates rather than trusted.""" confirmed, failed = verify.check_counterexamples(load_counterexamples(), verbose=False) assert failed == [], f"counterexamples did not re-derive: {failed[:2]}" assert confirmed == len(load_counterexamples()) def test_published_k_matches_recomputation_to_tight_tolerance(): for c in load_counterexamples(): xy = [[x * 1e-6, y * 1e-6] for x, y in c["xy_um"]] radius = [r * 1e-6 for r in c["radius_um"]] k = verify.born_second_order_k(xy, radius) n = len(xy) kmax = max(k[i][j] for i in range(n) for j in range(n) if i != j) assert kmax == pytest.approx(c["k_predicted"], rel=1e-9) assert kmax > 1.0 # ------------------------------------------------------------------- physics def test_isolated_pair_has_no_screening(): """Two conductors alone: k must be exactly 1, since there is nothing to screen.""" k = verify.screening_factors([[0.0, 0.0], [1e-4, 0.0]], [2e-5, 2e-5]) assert k[0][1] == pytest.approx(1.0, abs=1e-12) assert k[1][0] == pytest.approx(1.0, abs=1e-12) def test_adding_a_conductor_reduces_coupling(): """The physical content of the ceiling: screening only ever removes coupling.""" pair = verify.screening_factors([[0.0, 0.0], [2e-4, 0.0]], [2e-5] * 2)[0][1] with_third = verify.screening_factors( [[0.0, 0.0], [2e-4, 0.0], [1e-4, 0.0]], [2e-5] * 3)[0][1] assert with_third < pair def test_family_layout_matches_the_documented_geometry(): xy, radius = family_layout(40.0, 1.0, 3.0, 0.0) pt = 1.6 * 40.0 * 1e-6 assert xy[1][0] == pytest.approx(pt) assert xy[2][0] == pytest.approx(pt * 3.0) assert xy[3][0] == pytest.approx(pt * 3.0 + pt) assert all(r == pytest.approx(20e-6) for r in radius) def test_loader_and_verify_agree_on_geometry(): """Two implementations of the family layout must not drift apart.""" a_xy, a_r = family_layout(37.5, 1.1, 3.3, -0.2) b_xy, b_r = verify.family_layout(37.5, 1.1, 3.3, -0.2) assert [c for pt in a_xy for c in pt] == pytest.approx( [c for pt in b_xy for c in pt]) assert a_r == pytest.approx(b_r) def test_inverse_is_correct(): m = [[4.0, 7.0], [2.0, 6.0]] inv = verify.inverse(m) prod = [[sum(m[i][k] * inv[k][j] for k in range(2)) for j in range(2)] for i in range(2)] assert prod[0][0] == pytest.approx(1.0) assert prod[1][1] == pytest.approx(1.0) assert prod[0][1] == pytest.approx(0.0, abs=1e-12) def test_singular_matrix_raises_rather_than_returning_garbage(): with pytest.raises(ZeroDivisionError): verify.inverse([[1.0, 2.0], [2.0, 4.0]]) # ------------------------------------------------------------ negative control def test_the_checker_rejects_a_fabricated_bound(): """A checker that cannot fail is not a checker.""" rng = random.Random(0) _, violations = verify.check_regions(load_regions()[:4], k_bar=0.5, samples=5, rng=rng, verbose=False) assert violations, "an impossible bound was not refuted" def test_the_checker_rejects_a_tampered_counterexample(): cases = load_counterexamples() bad = dict(cases[0], k_predicted=cases[0]["k_predicted"] * 1.5) _, failed = verify.check_counterexamples([bad], verbose=False) assert failed, "a tampered value was accepted" def test_self_test_entrypoint_passes(): assert verify.self_test() == 0 # ---------------------------------------------------------------- provenance def test_theorem_records_provenance_and_scope(): t = load_theorem() p = t["provenance"] assert len(p["source_sha256"]) == 64 assert len(p["witness_content_sha256"]) == 64 assert p["partition_regions"] == len(load_regions()) assert "MONOPOLE-CLOSURE" in t["honest_scope"] assert "not establish" in t["honest_scope"] def test_stated_overprediction_follows_from_the_certified_supremum(): """The headline percentage must be derivable, not asserted. It derives from the supremum the proof actually certified rather than from the target bound, so it is marginally STRONGER than 100/k_bar - 100. Both relationships are checked, because that last digit is exactly the kind of thing a careful reader will try to reproduce and then query. """ t = load_theorem() assert t["forced_pairwise_overprediction_basis"] == "sup_certified_k_hi" assert t["forced_pairwise_overprediction_pct"] == \ pytest.approx(100.0 / t["sup_certified_k_hi"] - 100.0, rel=1e-12) assert t["forced_pairwise_overprediction_pct"] >= 100.0 / t["k_bar"] - 100.0 def test_scope_is_not_overclaimed_anywhere_in_the_card(): """The card must not say the theorem is about Maxwell or measured silicon.""" card = (HERE / "README.md").read_text(encoding="utf-8").lower() assert "monopole-closure" in card or "monopole closure" in card for forbidden in ("proves maxwell", "measured silicon shows", "validated against measurement"): assert forbidden not in card def test_verify_is_importable_with_no_third_party_modules(): """The zero-dependency promise, enforced rather than documented.""" src = (HERE / "verify.py").read_text(encoding="utf-8") banned = ("import numpy", "import pandas", "import scipy", "import torch", "from numpy", "from pandas", "import datasets") for b in banned: assert b not in src, f"verify.py must stay stdlib-only, found {b!r}" def test_math_import_is_actually_used(): assert math.hypot(3, 4) == 5.0 # guards the import above from bit-rot def test_readme_figures_match_the_data(): """Headline numbers in the card are re-derived from the files, not typed once.""" readme = (HERE / "README.md").read_text(encoding="utf-8") cs, t = load_counterexamples(), load_theorem() assert f"{sum(c['n_pairs_violating'] for c in cs):,}" in readme assert f"{max(c['k_predicted'] for c in cs):.4f}" in readme assert f"{t['certified_leaves_total']:,}" in readme assert f"{t['processed_leaves_total']:,}" in readme assert f"{t['forced_pairwise_overprediction_pct']:.6f}"[:9] in readme @pytest.mark.parametrize("samples,expected", [ (25, "0.902144353337"), (100, "0.903775408593"), ]) def test_readme_sampling_ladder_reproduces(samples, expected): """The card quotes a sampling ladder; a reader will run it, so it must hold. 400 samples is quoted too but takes ~6 s, so it is exercised by the quoted-string check below rather than re-run on every commit. """ worst, violations = verify.check_regions( load_regions(), load_theorem()["k_bar"], samples, random.Random(7), verbose=False) assert f"{worst:.12f}" == expected assert violations == [] assert expected in (HERE / "README.md").read_text(encoding="utf-8") def test_readme_marks_the_two_figures_it_cannot_reproduce(): """0.081% and 0.9053 come from tooling that is not in this release. Every other number on the card re-derives from the published files. These two do not, and a reader has no way to tell them apart unless we say so. """ readme = (HERE / "README.md").read_text(encoding="utf-8") for figure in ("0.081%", "0.9053"): assert figure in readme, f"{figure} vanished; drop this guard with it" assert "not part of this release" in readme assert "cannot re-derive it from what is published here" in readme