From 76f8703d2d44ec0734731e9db631a70e713bce78 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 14:57:36 +0800 Subject: [PATCH 01/34] research(rh): pin proof anchors, proxy gym tasks and CI --- .github/workflows/rh-proof-distillation.yml | 62 +++++++++++++++++++++ gyms/RHProofDistillation/README.md | 52 +++++++++++++++++ gyms/RHProofDistillation/anchors.json | 52 +++++++++++++++++ gyms/RHProofDistillation/gold.jsonl | 4 ++ gyms/RHProofDistillation/tasks.json | 34 +++++++++++ 5 files changed, 204 insertions(+) create mode 100644 .github/workflows/rh-proof-distillation.yml create mode 100644 gyms/RHProofDistillation/README.md create mode 100644 gyms/RHProofDistillation/anchors.json create mode 100644 gyms/RHProofDistillation/gold.jsonl create mode 100644 gyms/RHProofDistillation/tasks.json diff --git a/.github/workflows/rh-proof-distillation.yml b/.github/workflows/rh-proof-distillation.yml new file mode 100644 index 00000000..14eafd75 --- /dev/null +++ b/.github/workflows/rh-proof-distillation.yml @@ -0,0 +1,62 @@ +name: RH proof distillation gym + +on: + push: + paths: + - 'src/spiral_ln/rh_distillation.py' + - 'gyms/RHProofDistillation/**' + - 'tests/test_rh_distillation.py' + - '.github/workflows/rh-proof-distillation.yml' + pull_request: + paths: + - 'src/spiral_ln/rh_distillation.py' + - 'gyms/RHProofDistillation/**' + - 'tests/test_rh_distillation.py' + - '.github/workflows/rh-proof-distillation.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + python-preflight: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: python -m pip install -e '.[test]' + - run: python -m spiral_ln.rh_distillation preflight + - run: python -m pytest -q tests/test_rh_distillation.py + + lean-proxy-gold: + runs-on: ubuntu-latest + timeout-minutes: 90 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: python -m pip install -e . + - name: Install elan + run: | + curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh -o elan-init.sh + bash elan-init.sh -y --default-toolchain none + echo "$HOME/.elan/bin" >> "$GITHUB_PATH" + - name: Fetch existing EvalMath Mathlib cache + working-directory: lean + run: lake exe cache get + - name: Compile each gold proxy with Lean + run: | + python -m spiral_ln.rh_distillation grade \ + --submissions gyms/RHProofDistillation/gold.jsonl \ + --lean-cwd lean --timeout 90 --require-all \ + --output rh-gold-replay.json + - uses: actions/upload-artifact@v4 + if: always() + with: + name: rh-proof-distillation-gold-replay + path: rh-gold-replay.json + if-no-files-found: ignore diff --git a/gyms/RHProofDistillation/README.md b/gyms/RHProofDistillation/README.md new file mode 100644 index 00000000..878d61aa --- /dev/null +++ b/gyms/RHProofDistillation/README.md @@ -0,0 +1,52 @@ +# RHProofDistillation: provenance-first Lean reconstruction gym + +This is an experimental, CPU-first gym in EvalMath. It pins a few actual declarations in the 20 November 2026 Alpöge–Claude claimed RH/Dirichlet-GRH formalization, then asks a reasoner to reconstruct small, separately stated logical consequences in Lean. The four exercises here are **proxies** with explicit hypotheses, not extracted proofs of RH. + +## Provenance and verification scope + +- Original announcement: https://alpo.ge/remark.pdf . The central proposed theta-lift chain length is approximately sqrt(X). +- Community source mirror: https://github.com/leanprover-community/riemann-hypothesis . anchors.json pins a mirror commit, six Git blob hashes and declaration names. The published archive SHA-256 is also recorded. +- Independent verification: https://math.mit.edu/~drew/grh/ . As of its 2026-11-20 22:05 UTC snapshot, 175,187 modules compile, standard-axiom and module-kernel audits pass, independent kernels accept the exported proof and some end-to-end checks remained running. +- Principal-statement and dependency catalogue: https://andrewodesky.com/rh/ . Human-readable statement annotations and module-import edges have separate evidence status. +- The audited GRH statement applies to Dirichlet L-functions. Wider Artin and automorphic GRH are not the scope of this gym. +- The upstream archive does not grant a source-code license. We record links, identifiers and hashes without copying its source. + +## Anchors inspected in the actual source + +| Transition | Declaration | Path under src/ | +| --- | --- | --- | +| Final RH | riemannHypothesis | Main.lean | +| Target definition | DirichletLNonvanishingRightOfHalf | Statements.lean | +| All character conclusion | UpperTheory.FinalTheorems.everyCharacter | Development/AutomorphicArithmetic/CharacterBoxes/MainConclusion.lean | +| Interval Landau implication | zeroFree_of_rpow_window | Development/AutomorphicArithmetic/DedekindLFunctions/LandauTheorems/ZeroFreeOfRpowWindow.lean | +| Smoothed prime-sum estimate | UpperTheory.Comparison₂.core_gm | Development/AutomorphicArithmetic/PrimitiveCosets/CoreGm.lean | +| Theta-to-Galois wrapper | galoisLocalGlobalStrong_recParameter | Development/AutomorphicArithmetic/Foundations/GaloisRepresentations/IntegralStructures/RowSrc.lean | + +A short wrapper still depends on its prerequisites. The scanner reports **module imports only**. It does not claim a minimal theorem-dependency closure. Full theorem-term dependency extraction and formal statement matching are later stages. + +## CPU tests + +From the EvalMath root, use the standard EvalMath Python environment: + + PYTHONPATH=src python -m spiral_ln.rh_distillation preflight + PYTHONPATH=src pytest -q tests/test_rh_distillation.py + +With a checkout of the source mirror pinned by anchors.json: + + PYTHONPATH=src python -m spiral_ln.rh_distillation audit --source-root /path/to/riemann-hypothesis --limit 5000 --output /tmp/rh-audit.json + +The audit verifies all six expected Git file blobs and declarations, then walks imports from Main. Limit 0 means no traversal cap. Results explicitly label truncation, unresolved internal imports and external dependencies. A missing checkout is an error rather than synthetic evidence. + +## Lean kernel scoring + +Supply a JSONL file of objects with id and proof, where proof contains tactics replacing the single __PROOF__ hole in the corresponding template: + + PYTHONPATH=src python -m spiral_ln.rh_distillation grade --submissions gyms/RHProofDistillation/gold.jsonl --lean-cwd lean --require-all --output /tmp/rh-replay.json + +The grader compiles each candidate via lake env lean in the existing EvalMath Mathlib project. It rejects admitted/unsafe proofs before compilation, records individual runtimes, and accepts only successful Lean processes. gold.jsonl is a **public smoke-test reference**, and should be excluded from held-out prompts. It is not a claimed proof of any upstream theorem. Gold Lean compilation is scheduled in CI; only Python preflight has been run locally. + +## Next research stages + +First extract declaration-level dependencies from exported Lean proof data and compare them with the import graph. Then identify and reprove explicit intermediate obligations in the Landau bound, theta scalar, Galois localization and covolume chain. Held-out tasks should split by dependency component, with exact provenance, contamination audit, compilation receipts and per-proof resource use. + +Evidence levels here remain those used in EvalMath: a compiled Lean theorem, a finite test, a source-verified declaration and an open research conjecture are distinct claims. diff --git a/gyms/RHProofDistillation/anchors.json b/gyms/RHProofDistillation/anchors.json new file mode 100644 index 00000000..9fb09700 --- /dev/null +++ b/gyms/RHProofDistillation/anchors.json @@ -0,0 +1,52 @@ +{ + "schema_version": 1, + "mirror_repository": "leanprover-community/riemann-hypothesis", + "mirror_commit": "f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3", + "archive_sha256": "9631b4f020199e580ba86178cb56c6e9b09f690c2369a80dc4334aa93f49c7fc", + "source_date": "2026-11-20", + "provenance": "Published Alpöge archive mirrored by Lean community. File blobs inspected through GitHub; local complete source audit is optional and pending.", + "anchors": [ + { + "id": "final_rh", + "path": "src/Main.lean", + "declaration": "riemannHypothesis", + "blob_sha": "dbd5db70bc11b35f18fa5751216ab335321e7bfc", + "role": "final result" + }, + { + "id": "statement_grh", + "path": "src/Statements.lean", + "declaration": "DirichletLNonvanishingRightOfHalf", + "blob_sha": "1cd1bce93344065936b2b392b23306254e0785ef", + "role": "mathematical target" + }, + { + "id": "all_characters", + "path": "src/Development/AutomorphicArithmetic/CharacterBoxes/MainConclusion.lean", + "declaration": "UpperTheory.FinalTheorems.everyCharacter", + "blob_sha": "ee340012ab19713a8acfecf8adc6a331cbc2f1a4", + "role": "Galois to all characters" + }, + { + "id": "analytic_window", + "path": "src/Development/AutomorphicArithmetic/DedekindLFunctions/LandauTheorems/ZeroFreeOfRpowWindow.lean", + "declaration": "zeroFree_of_rpow_window", + "blob_sha": "2ed00ad3aa862f3e522686557fb8f559b17fc002", + "role": "interval bound to zero-freeness" + }, + { + "id": "weighted_bound", + "path": "src/Development/AutomorphicArithmetic/PrimitiveCosets/CoreGm.lean", + "declaration": "UpperTheory.Comparison₂.core_gm", + "blob_sha": "3ba7a590e84c5993882ea6c5dcf9fdbed5f07d4d", + "role": "arithmetic bound to smoothed character sum" + }, + { + "id": "theta_galois", + "path": "src/Development/AutomorphicArithmetic/Foundations/GaloisRepresentations/IntegralStructures/RowSrc.lean", + "declaration": "galoisLocalGlobalStrong_recParameter", + "blob_sha": "f769999ac5e49241993e5efbf81e4d2cded18acd", + "role": "theta lift to Galois representation" + } + ] +} diff --git a/gyms/RHProofDistillation/gold.jsonl b/gyms/RHProofDistillation/gold.jsonl new file mode 100644 index 00000000..9002a47b --- /dev/null +++ b/gyms/RHProofDistillation/gold.jsonl @@ -0,0 +1,4 @@ +{"id":"RH-D-001","proof":"exact landau (convert hWindow)"} +{"id":"RH-D-002","proof":"exact hConstruct hTheta"} +{"id":"RH-D-003","proof":"have hle : s.re ≤ 1 / 2 := by\n by_contra hc\n exact (hRight s (lt_of_not_ge hc)) hz\nhave hflip : L (1 - s) = 0 := hFlip s hs0 hs1 hz\nhave hleflip : (1 - s).re ≤ 1 / 2 := by\n by_contra hc\n exact (hRight (1 - s) (lt_of_not_ge hc)) hflip\nhave hge : 1 / 2 ≤ s.re := by\n have hreal : (1 - s).re = 1 - s.re := by simp\n linarith\nexact le_antisymm hle hge"} +{"id":"RH-D-004","proof":"by_contra hc\nhave hpos : 0 < (r - 1 / 2) / 2 := by linarith\nhave hbound := h ((r - 1 / 2) / 2) hpos\nlinarith"} diff --git a/gyms/RHProofDistillation/tasks.json b/gyms/RHProofDistillation/tasks.json new file mode 100644 index 00000000..7a15e3a0 --- /dev/null +++ b/gyms/RHProofDistillation/tasks.json @@ -0,0 +1,34 @@ +[ + { + "id": "RH-D-001", + "difficulty": "warmup", + "category": "analytic_bridge", + "anchor": "analytic_window", + "description": "Rebuild the proposition-level Landau window-to-zero-free wrapper; analytic inputs are explicit hypotheses.", + "template": "import Mathlib\n\nnamespace RHGym\n\ntheorem window_to_zero_free (Window Bridge ZeroFree : Prop)\n (hWindow : Window) (convert : Window → Bridge) (landau : Bridge → ZeroFree) : ZeroFree := by\n__PROOF__\n\nend RHGym\n" + }, + { + "id": "RH-D-002", + "difficulty": "warmup", + "category": "galois_bridge", + "anchor": "theta_galois", + "description": "Rebuild the theta-to-Galois application shell with visible assumptions.", + "template": "import Mathlib\n\nnamespace RHGym\n\ntheorem galois_from_theta (ThetaLift Galois : Prop)\n (hTheta : ThetaLift) (hConstruct : ThetaLift → Galois) : Galois := by\n__PROOF__\n\nend RHGym\n" + }, + { + "id": "RH-D-003", + "difficulty": "medium", + "category": "analytic_bridge", + "anchor": "final_rh", + "description": "Prove critical-strip zeros lie on the central line from right zero-freeness and an explicitly assumed reflection principle.", + "template": "import Mathlib\n\nnamespace RHGym\n\ntheorem strip_symmetry_from_right_zero_free\n (L : ℂ → ℂ)\n (hRight : ∀ z : ℂ, 1 / 2 < z.re → L z ≠ 0)\n (hFlip : ∀ z : ℂ, 0 < z.re → z.re < 1 → L z = 0 → L (1 - z) = 0)\n (s : ℂ) (hs0 : 0 < s.re) (hs1 : s.re < 1) (hz : L s = 0) :\n s.re = 1 / 2 := by\n__PROOF__\n\nend RHGym\n" + }, + { + "id": "RH-D-004", + "difficulty": "medium", + "category": "exponent_limit", + "anchor": "weighted_bound", + "description": "Remove arbitrarily small positive exponent slack over the reals.", + "template": "import Mathlib\n\nnamespace RHGym\n\ntheorem epsilon_squeeze (r : ℝ)\n (h : ∀ ε : ℝ, 0 < ε → r ≤ (1 / 2 : ℝ) + ε) :\n r ≤ (1 / 2 : ℝ) := by\n__PROOF__\n\nend RHGym\n" + } +] From 967612f9ee9ee061ed857813a1ec20e33583820e Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 14:58:03 +0800 Subject: [PATCH 02/34] test(rh): add CPU source audit and kernel-scored Lean reconstruction runner --- src/spiral_ln/rh_distillation.py | 244 +++++++++++++++++++++++++++++++ tests/test_rh_distillation.py | 73 +++++++++ 2 files changed, 317 insertions(+) create mode 100644 src/spiral_ln/rh_distillation.py create mode 100644 tests/test_rh_distillation.py diff --git a/src/spiral_ln/rh_distillation.py b/src/spiral_ln/rh_distillation.py new file mode 100644 index 00000000..1b38bfe0 --- /dev/null +++ b/src/spiral_ln/rh_distillation.py @@ -0,0 +1,244 @@ +"""CPU-only source audit and optional Lean-kernel reconstruction gym. + +Import traversal is a *module* graph, not a proof-term dependency graph. +No external source is downloaded or silently trusted by this module. +""" +from __future__ import annotations + +import argparse +from collections import Counter, deque +import hashlib +import json +from pathlib import Path +import re +import shlex +import subprocess +import tempfile +import time + + +INTERNAL_ROOTS = frozenset({ + "Development", "Formalism", "GroundTheory", "ReciprocityTheory", + "CompanionTheory", "PositivityTheory", "Lemmata", "Supplements", "BuildAid", + "Statements", "Main", +}) +BANNED = re.compile(r"\b(?:sorry|admit|axiom|unsafe|native_decide)\b") +DECL_PREFIX = re.compile(r"\b(?:theorem|def)\s+") +MODULE_NAME = re.compile(r"^[\w.]+$", re.UNICODE) + + +def git_blob_sha(raw: bytes) -> str: + """Git's content blob hash, which is distinct from an ordinary SHA-1.""" + return hashlib.sha1(b"blob " + str(len(raw)).encode() + b"\x00" + raw).hexdigest() + + +def parse_imports(source: str) -> list[str]: + imports: list[str] = [] + for line in source.splitlines(): + line = line.split("--", 1)[0] + match = re.match(r"^\s*import\s+(.+?)\s*$", line) + if match: + imports.extend(part for part in match.group(1).split() if MODULE_NAME.fullmatch(part)) + return imports + + +def module_path(src: Path, module: str) -> Path: + return src.joinpath(*module.split(".")).with_suffix(".lean") + + +def family(module: str) -> str: + name = module.lower() + for label, terms in ( + ("analytic", ("landau", "dedekindl", "primitivecoset", "characterbox")), + ("theta", ("theta", "weil", "fock")), + ("galois", ("galois", "cohomology", "iwasawa", "crystalline")), + ("arithmetic_geometry", ("abelianvariety", "moduli", "hilbertsamuel", "covolume", "toroidal")), + ("representation", ("representation", "langlands", "automorphic")), + ): + if any(term in name for term in terms): + return label + return "other" + + +def walk_imports(src: Path, roots: list[str], limit: int = 1000) -> dict: + """BFS module imports, bounded by limit (0 means unlimited).""" + todo = deque((root, None) for root in roots) + visited: set[str] = set() + parents: dict[str, str | None] = {} + edges: list[tuple[str, str]] = [] + unresolved: set[str] = set() + external: set[str] = set() + while todo and (limit == 0 or len(visited) < limit): + module, parent = todo.popleft() + if module in visited: + continue + path = module_path(src, module) + if not path.is_file(): + (unresolved if module.split(".")[0] in INTERNAL_ROOTS else external).add(module) + continue + visited.add(module) + parents[module] = parent + for dep in parse_imports(path.read_text(encoding="utf-8")): + edges.append((module, dep)) + if dep not in visited: + todo.append((dep, module)) + return { + "mode": "module_imports_only", + "visited_modules": len(visited), + "import_edges": len(edges), + "truncated": bool(todo), + "unresolved_internal_imports": sorted(unresolved), + "external_imports": sorted(external), + "family_counts": dict(sorted(Counter(map(family, visited)).items())), + "parents": parents, + } + + +def anchor_audit(repository_root: Path, manifest: dict) -> list[dict]: + results: list[dict] = [] + for anchor in manifest["anchors"]: + path = repository_root / anchor["path"] + if not path.is_file(): + results.append({"id": anchor["id"], "status": "missing"}) + continue + raw = path.read_bytes() + content = raw.decode("utf-8") + decl = anchor["declaration"] + expression = DECL_PREFIX.pattern + re.escape(decl) + r"(?![\w'])" + results.append({ + "id": anchor["id"], + "status": "match" if git_blob_sha(raw) == anchor["blob_sha"] and re.search(expression, content) else "mismatch", + "blob_sha": git_blob_sha(raw), + "declaration_present": bool(re.search(expression, content)), + }) + return results + + +def validate_tasks(tasks: list[dict]) -> None: + seen: set[str] = set() + for task in tasks: + identifier = task["id"] + if identifier in seen: + raise ValueError(f"duplicate task: {identifier}") + seen.add(identifier) + if task["template"].count("__PROOF__") != 1: + raise ValueError(f"one proof hole required: {identifier}") + if BANNED.search(task["template"]): + raise ValueError(f"forbidden declaration in template: {identifier}") + + +def render_proof(template: str, proof: str) -> str: + if not proof.strip() or BANNED.search(proof): + raise ValueError("empty or forbidden proof") + return template.replace("__PROOF__", "\n".join(" " + line for line in proof.strip().splitlines())) + + +def compile_lean(source: str, cwd: Path, command: str, timeout: float) -> tuple[bool, str, float]: + start = time.monotonic() + fd, file_name = tempfile.mkstemp(prefix="rh_distill_", suffix=".lean", dir=cwd) + path = Path(file_name) + try: + import os + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.write(source) + try: + proc = subprocess.run(shlex.split(command) + [str(path)], cwd=cwd, + text=True, capture_output=True, timeout=timeout, check=False) + output = (proc.stdout + "\n" + proc.stderr)[-1800:] + return proc.returncode == 0 and "declaration uses 'sorry'" not in output, output, time.monotonic() - start + except (OSError, subprocess.TimeoutExpired) as exc: + return False, str(exc), time.monotonic() - start + finally: + path.unlink(missing_ok=True) + + +def read_jsonl(path: Path) -> list[dict]: + return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] + + +def score(tasks: list[dict], submissions: list[dict], checker) -> dict: + """Only checker may grant a pass; the normal checker invokes Lean.""" + validate_tasks(tasks) + reference = {task["id"]: task for task in tasks} + seen: set[str] = set() + outcomes: list[dict] = [] + for submission in submissions: + identifier = submission.get("id") + if identifier in seen: + outcomes.append({"id": identifier, "status": "duplicate", "pass": False}) + continue + seen.add(identifier) + if identifier not in reference: + outcomes.append({"id": identifier, "status": "unknown", "pass": False}) + continue + try: + source = render_proof(reference[identifier]["template"], submission.get("proof", "")) + except ValueError as exc: + outcomes.append({"id": identifier, "status": "rejected", "pass": False, "detail": str(exc)}) + continue + passed, detail, seconds = checker(source) + outcomes.append({"id": identifier, "status": "compiled" if passed else "compile_failed", + "pass": passed, "seconds": round(seconds, 4), "detail": detail}) + return {"kind": "lean_kernel_compile", "total_tasks": len(tasks), + "submitted": len(submissions), "passes": sum(x["pass"] for x in outcomes), + "outcomes": outcomes} + + +def main() -> None: + base = Path(__file__).resolve().parents[2] / "gyms" / "RHProofDistillation" + ap = argparse.ArgumentParser(description=__doc__) + sub = ap.add_subparsers(dest="action", required=True) + pre = sub.add_parser("preflight", help="validate manifest and task structure without Lean") + pre.add_argument("--manifest", type=Path, default=base / "anchors.json") + pre.add_argument("--tasks", type=Path, default=base / "tasks.json") + audit = sub.add_parser("audit", help="verify source blobs and bounded module-import DAG") + audit.add_argument("--source-root", type=Path, required=True, help="checkout root containing src/") + audit.add_argument("--manifest", type=Path, default=base / "anchors.json") + audit.add_argument("--limit", type=int, default=5000) + audit.add_argument("--output", type=Path) + grade = sub.add_parser("grade", help="grade proof submissions using the Lean kernel") + grade.add_argument("--tasks", type=Path, default=base / "tasks.json") + grade.add_argument("--submissions", type=Path, required=True) + grade.add_argument("--lean-cwd", type=Path, default=Path("lean")) + grade.add_argument("--lean-cmd", default="lake env lean") + grade.add_argument("--timeout", type=float, default=45) + grade.add_argument("--output", type=Path) + grade.add_argument("--require-all", action="store_true", help="exit 1 unless every task compiles") + args = ap.parse_args() + if args.action == "preflight": + manifest = json.loads(args.manifest.read_text(encoding="utf-8")) + tasks = json.loads(args.tasks.read_text(encoding="utf-8")) + validate_tasks(tasks) + assert len({a["id"] for a in manifest["anchors"]}) == len(manifest["anchors"]) + assert all(len(a["blob_sha"]) == 40 for a in manifest["anchors"]) + result = {"status": "preflight_pass", "source_commit": manifest["mirror_commit"], + "anchors": len(manifest["anchors"]), "proxy_tasks": len(tasks), + "lean_compiled": False} + elif args.action == "audit": + if args.limit < 0: + ap.error("--limit must be nonnegative") + manifest = json.loads(args.manifest.read_text(encoding="utf-8")) + audit_result = anchor_audit(args.source_root, manifest) + result = {"source_commit_expected": manifest["mirror_commit"], + "anchors": audit_result, + "import_graph": walk_imports(args.source_root / "src", ["Main"], args.limit), + "note": "Module import closure does not establish theorem/term dependencies"} + else: + tasks = json.loads(args.tasks.read_text(encoding="utf-8")) + submission = read_jsonl(args.submissions) + cwd = args.lean_cwd.resolve() + if not cwd.is_dir(): + ap.error(f"Lean working directory not found: {cwd}") + result = score(tasks, submission, lambda src: compile_lean(src, cwd, args.lean_cmd, args.timeout)) + encoded = json.dumps(result, indent=2, sort_keys=True) + output = getattr(args, "output", None) + if output: + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text(encoded + "\n", encoding="utf-8") + print(encoded) + if args.action == "grade" and args.require_all and result["passes"] != len(tasks): + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/tests/test_rh_distillation.py b/tests/test_rh_distillation.py new file mode 100644 index 00000000..e2b78482 --- /dev/null +++ b/tests/test_rh_distillation.py @@ -0,0 +1,73 @@ +"""CPU-only RH distillation preflight, independent of any Lean checkout.""" +import hashlib +import json +from pathlib import Path + +import pytest + +from spiral_ln.rh_distillation import ( + anchor_audit, family, git_blob_sha, parse_imports, render_proof, score, + validate_tasks, walk_imports, +) + +BASE = Path(__file__).resolve().parents[1] / "gyms" / "RHProofDistillation" + + +def test_manifest_and_tasks_are_well_formed(): + manifest = json.loads((BASE / "anchors.json").read_text()) + tasks = json.loads((BASE / "tasks.json").read_text()) + gold = {entry["id"]: entry["proof"] for entry in (json.loads(line) for line in (BASE / "gold.jsonl").read_text().splitlines())} + assert len(manifest["mirror_commit"]) == 40 + assert len(manifest["archive_sha256"]) == 64 + assert len(manifest["anchors"]) >= 5 + assert len({a["path"] for a in manifest["anchors"]}) == len(manifest["anchors"]) + assert all(len(a["blob_sha"]) == 40 for a in manifest["anchors"]) + validate_tasks(tasks) + assert set(gold) == {task["id"] for task in tasks} + assert all("__PROOF__" not in render_proof(task["template"], gold[task["id"]]) for task in tasks) + + +def test_import_walk_truncation_and_external_boundary(tmp_path): + src = tmp_path / "src" + (src / "Development").mkdir(parents=True) + (src / "Main.lean").write_text("import Mathlib\nimport Development.A Development.B -- comment\n") + (src / "Development" / "A.lean").write_text("import Development.C\n") + (src / "Development" / "B.lean").write_text("def b := 1\n") + (src / "Development" / "C.lean").write_text("import Development.A\n") + assert parse_imports((src / "Main.lean").read_text()) == ["Mathlib", "Development.A", "Development.B"] + full = walk_imports(src, ["Main"], 0) + assert full["visited_modules"] == 4 and not full["truncated"] + assert full["external_imports"] == ["Mathlib"] + assert not full["unresolved_internal_imports"] + capped = walk_imports(src, ["Main"], 1) + assert capped["truncated"] and capped["visited_modules"] == 1 + + +def test_git_blob_and_decl_detection(tmp_path): + root = tmp_path / "mirror" + (root / "src").mkdir(parents=True) + raw = b"theorem proof_anchor : True := by trivial\n" + (root / "src" / "Main.lean").write_bytes(raw) + assert git_blob_sha(raw) == hashlib.sha1(b"blob " + str(len(raw)).encode() + b"\x00" + raw).hexdigest() + manifest = {"anchors": [{"id": "test", "path": "src/Main.lean", "blob_sha": git_blob_sha(raw), "declaration": "proof_anchor"}]} + assert anchor_audit(root, manifest)[0]["status"] == "match" + manifest["anchors"][0]["blob_sha"] = "0" * 40 + assert anchor_audit(root, manifest)[0]["status"] == "mismatch" + + +def test_scoring_requires_compiler_and_rejects_placeholders(): + tasks = [{"id": "A", "template": "theorem test : True := by\n__PROOF__\n"}] + seen = [] + def checker(source): + seen.append(source) + return source.endswith(" exact True.intro\n"), "mock only", 0.0 + out = score(tasks, [{"id": "A", "proof": "exact True.intro"}, {"id": "A", "proof": "trivial"}, {"id": "Q", "proof": "trivial"}], checker) + assert out["passes"] == 1 and len(seen) == 1 + assert [x["status"] for x in out["outcomes"]] == ["compiled", "duplicate", "unknown"] + assert score(tasks, [{"id": "A", "proof": "sorry"}], checker)["outcomes"][0]["status"] == "rejected" + + +def test_family_classification(): + assert family("Development.AutomorphicArithmetic.PrimitiveCosets.CoreGm") == "analytic" + assert family("Development.AutomorphicArithmetic.Foundations.GaloisRepresentations.RowSrc") == "galois" + assert family("Development.AutomorphicArithmetic.ThetaCorrespondence.Main") == "theta" From 02b2eb8e91a1a48e7ffc67c85f2658a2e8966b1c Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 17:51:55 +0800 Subject: [PATCH 03/34] feat(rh): bounded Lean proof-expression dependency scanner and tests --- .../lean/ProofDependencies.lean | 79 ++++++++ src/spiral_ln/rh_dependency.py | 178 ++++++++++++++++++ tests/test_rh_dependency.py | 40 ++++ 3 files changed, 297 insertions(+) create mode 100644 gyms/RHProofDistillation/lean/ProofDependencies.lean create mode 100644 src/spiral_ln/rh_dependency.py create mode 100644 tests/test_rh_dependency.py diff --git a/gyms/RHProofDistillation/lean/ProofDependencies.lean b/gyms/RHProofDistillation/lean/ProofDependencies.lean new file mode 100644 index 00000000..50a04780 --- /dev/null +++ b/gyms/RHProofDistillation/lean/ProofDependencies.lean @@ -0,0 +1,79 @@ +import Lean + +/-! +Proof-expression dependency probe for Lean 4. +An edge means a constant occurs in an elaborated type or value expression. +This does not claim an indispensable or minimized mathematical dependency. +-/ + +namespace RHDepProbe + +open Lean + +def infoKind : ConstantInfo → String + | .axiomInfo _ => "axiom" + | .defnInfo _ => "definition" + | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" + | .quotInfo _ => "quotient" + | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" + | .recInfo _ => "recursor" + +def allowed (prefixes : Array String) (name : Name) : Bool := + prefixes.isEmpty || prefixes.any (fun pref => name.toString.startsWith pref) + +/-- A bounded BFS through kernel-elaborated direct constant references. -/ +def emit (env : Environment) (roots : Array Name) (maxDepth maxNodes : Nat) + (prefixes : Array String) : IO Unit := do + let mut queue : Array (Name × Nat) := roots.map (fun n => (n, 0)) + let mut seen : NameHashSet := {} + let mut idx := 0 + let mut count := 0 + let mut depthLimited := false + while idx < queue.size && count < maxNodes do + let (name, depth) := queue[idx]! + idx := idx + 1 + if seen.contains name then + continue + seen := seen.insert name + count := count + 1 + match env.find? name with + | none => + let item := Json.mkObj [ + ("name", toJson name.toString), + ("depth", toJson depth), + ("kind", toJson ("missing" : String)), + ("type_refs", toJson (#[] : Array String)), + ("value_refs", toJson (#[] : Array String))] + IO.println s!"RHDEP1\t{item.compress}" + | some info => + let typeRefs := info.type.getUsedConstants + -- The proof of a theorem is opaque by default: request its value. + let valueRefs := match info.value? (allowOpaque := true) with + | some value => value.getUsedConstants + | none => #[] + let item := Json.mkObj [ + ("name", toJson name.toString), + ("depth", toJson depth), + ("kind", toJson (infoKind info)), + ("type_refs", toJson (typeRefs.map Name.toString)), + ("value_refs", toJson (valueRefs.map Name.toString))] + IO.println s!"RHDEP1\t{item.compress}" + if depth < maxDepth then + for dep in typeRefs ++ valueRefs do + if allowed prefixes dep && !seen.contains dep then + queue := queue.push (dep, depth + 1) + else + if (typeRefs ++ valueRefs).any (allowed prefixes) then + depthLimited := true + let endRecord := Json.mkObj [ + ("visited", toJson count), + ("truncated", toJson (idx < queue.size)), + ("depth_limited", toJson depthLimited), + ("queued", toJson queue.size), + ("max_depth", toJson maxDepth), + ("max_nodes", toJson maxNodes)] + IO.println s!"RHDEPEND\t{endRecord.compress}" + +end RHDepProbe diff --git a/src/spiral_ln/rh_dependency.py b/src/spiral_ln/rh_dependency.py new file mode 100644 index 00000000..b8def3cd --- /dev/null +++ b/src/spiral_ln/rh_dependency.py @@ -0,0 +1,178 @@ +"""Inspect direct theorem/definition constant references from compiled Lean expressions. + +Scope: a bounded graph of direct elaborated Expr references, not a minimal +dependency proof. Upstream source identity is verified before execution. +""" +from __future__ import annotations + +import argparse +from collections import Counter +import json +from pathlib import Path +import re +import subprocess +import tempfile + +from spiral_ln.rh_distillation import anchor_audit + +HERE = Path(__file__).resolve().parents[2] / "gyms" / "RHProofDistillation" +NAME = re.compile(r"^[\w.]+$", re.UNICODE) +RECORD = "RHDEP1\t" +END = "RHDEPEND\t" + + +def parse_output(stdout: str) -> dict: + nodes, footer, seen = [], None, set() + for line in stdout.splitlines(): + if line.startswith(RECORD): + item = json.loads(line[len(RECORD):]) + name = item["name"] + if name in seen: + raise ValueError(f"duplicate constant: {name}") + if item["kind"] not in { + "axiom", "definition", "theorem", "opaque", "quotient", + "inductive", "constructor", "recursor", "missing", + }: + raise ValueError(f"unknown declaration type: {item['kind']}") + if any(not isinstance(x, str) for k in ("type_refs", "value_refs") for x in item[k]): + raise ValueError(f"invalid refs for {name}") + seen.add(name) + nodes.append(item) + elif line.startswith(END): + if footer is not None: + raise ValueError("multiple probe footers") + footer = json.loads(line[len(END):]) + if footer is None: + raise ValueError("no completion footer from Lean") + if len(nodes) != footer["visited"]: + raise ValueError("visited count disagrees with emitted nodes") + edges = sorted( + ({"from": node["name"], "to": dep, "channel": channel} + for node in nodes for channel, field in + (("type", "type_refs"), ("value", "value_refs")) + for dep in node[field]), + key=lambda e: (e["from"], e["channel"], e["to"]), + ) + return { + "mode": "lean_elaborated_direct_constant_refs", + "proof_term_data": True, + "nodes": sorted(nodes, key=lambda e: e["name"]), + "edges": edges, + "scope": footer, + "kinds": dict(sorted(Counter(n["kind"] for n in nodes).items())), + } + + +def validate_names(names: list[str]) -> None: + if not names or any(not NAME.fullmatch(n) for n in names): + raise ValueError("names must be nonempty qualified Lean identifiers") + + +def build_probe(imports: list[str], roots: list[str], depth: int, + max_nodes: int, prefixes: list[str], toy: bool = False) -> str: + validate_names(roots) + validate_names(imports or ["Lean"]) + if not prefixes or any(not NAME.fullmatch(p) for p in prefixes): + raise ValueError("safe expansion prefixes required") + if depth < 0 or max_nodes <= 0: + raise ValueError("invalid graph bounds") + probe = (HERE / "lean" / "ProofDependencies.lean").read_text(encoding="utf-8") + if not probe.startswith("import Lean\n"): + raise ValueError("probe must start with import Lean") + header = "\n".join("import " + name for name in sorted(set(["Lean"] + imports))) + body = probe.split("\n", 1)[1] + fixtures = ("\nnamespace RHGraphToy\n" + "theorem upstream : True := True.intro\n" + "theorem bridge : True := upstream\n" + "end RHGraphToy\n") if toy else "" + quoted_roots = ", ".join(chr(96) * 2 + name for name in roots) + quoted_prefixes = ", ".join(json.dumps(p, ensure_ascii=False) for p in prefixes) + cmd = ("\nrun_cmd do\n" + " let env \u2190 Lean.Elab.Command.getEnv\n" + f" liftIO <| RHDepProbe.emit env #[{quoted_roots}] {depth} {max_nodes} #[{quoted_prefixes}]\n") + return header + "\n" + body + fixtures + cmd + + +def run_lean(source: str, cwd: Path, timeout: int) -> dict: + if not cwd.is_dir(): + raise ValueError(f"Lean workspace missing: {cwd}") + with tempfile.NamedTemporaryFile("w", encoding="utf-8", suffix=".lean", + prefix="RHDepProbe_", dir=cwd, delete=False) as f: + f.write(source) + path = Path(f.name) + try: + proc = subprocess.run(["lake", "env", "lean", path.name], cwd=cwd, text=True, + capture_output=True, timeout=timeout, check=False) + finally: + path.unlink(missing_ok=True) + if proc.returncode: + raise RuntimeError(f"Lean exited {proc.returncode}: {(proc.stdout + proc.stderr)[-2400:]}") + return parse_output(proc.stdout) + + +def pinned_mirror(root: Path, manifest: dict) -> dict: + sha = subprocess.run(["git", "rev-parse", "HEAD"], cwd=root, + capture_output=True, text=True, check=True).stdout.strip() + if sha != manifest["mirror_commit"]: + raise ValueError(f"mirror HEAD mismatch: {sha} vs {manifest['mirror_commit']}") + audit = anchor_audit(root, manifest) + if any(x["status"] != "match" for x in audit): + raise ValueError(f"missing or mutated upstream anchors: {audit}") + return {"commit": sha, "six_anchors_match": True} + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__) + sub = ap.add_subparsers(dest="action", required=True) + smoke = sub.add_parser("smoke", help="test a direct proof reference with EvalMath Lean") + smoke.add_argument("--lean-cwd", type=Path, default=Path("lean")) + smoke.add_argument("--timeout", type=int, default=120) + smoke.add_argument("--output", type=Path) + upstream = sub.add_parser("upstream", help="inspect the pinned full upstream proof") + upstream.add_argument("--source-root", type=Path, required=True) + upstream.add_argument("--anchors", nargs="+", default=["weighted_bound"]) + upstream.add_argument("--max-depth", type=int, default=2) + upstream.add_argument("--max-nodes", type=int, default=120) + upstream.add_argument("--prefixes", nargs="+", default=["UpperTheory.", "Deduction.", "Formalism."]) + upstream.add_argument("--emit-script", type=Path, help="write the Lean script only") + upstream.add_argument("--output", type=Path) + upstream.add_argument("--timeout", type=int, default=1800) + args = ap.parse_args() + if args.action == "smoke": + src = build_probe([], ["RHGraphToy.bridge"], 2, 12, ["RHGraphToy."], toy=True) + result = run_lean(src, args.lean_cwd.resolve(), timeout=args.timeout) + node = next((n for n in result["nodes"] if n["name"] == "RHGraphToy.bridge"), None) + if node is None or "RHGraphToy.upstream" not in node["value_refs"]: + raise RuntimeError(f"missing compiled proof reference: {node}") + result["smoke_passed"] = True + result["source_scope"] = "small_local_toy_only" + else: + root = args.source_root.resolve() + manifest = json.loads((HERE / "anchors.json").read_text(encoding="utf-8")) + receipt = pinned_mirror(root, manifest) + ids = {a["id"]: a for a in manifest["anchors"]} + if any(i not in ids for i in args.anchors): + ap.error(f"unknown anchor: {args.anchors}") + anchors = [ids[i] for i in args.anchors] + imports = [a["path"].removeprefix("src/").removesuffix(".lean").replace("/", ".") for a in anchors] + roots = [a["declaration"] for a in anchors] + src = build_probe(imports, roots, args.max_depth, args.max_nodes, args.prefixes) + if args.emit_script: + args.emit_script.parent.mkdir(parents=True, exist_ok=True) + args.emit_script.write_text(src, encoding="utf-8") + result = {"mode": "script_only", "proof_term_data": False, + "path": str(args.emit_script), "anchors": roots, "provenance": receipt} + else: + result = run_lean(src, root, timeout=args.timeout) + result["source_scope"] = "pinned_upstream_environment" + result["anchors"] = roots + result["provenance"] = receipt + encoded = json.dumps(result, indent=2, sort_keys=True) + "\n" + if args.output: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(encoded, encoding="utf-8") + print(encoded) + + +if __name__ == "__main__": + main() diff --git a/tests/test_rh_dependency.py b/tests/test_rh_dependency.py new file mode 100644 index 00000000..bbcee705 --- /dev/null +++ b/tests/test_rh_dependency.py @@ -0,0 +1,40 @@ +"""Sanity and adversarial tests for proof-expression graph format.""" +import json +import pytest + +from spiral_ln.rh_dependency import build_probe, parse_output, validate_names + + +def test_source_graph_keeps_type_and_proof_edges_separate(): + items = [ + {"name": "Example.bridge", "depth": 0, "kind": "theorem", + "type_refs": ["True"], "value_refs": ["Example.upstream"]}, + {"name": "Example.upstream", "depth": 1, "kind": "theorem", + "type_refs": ["True"], "value_refs": ["True.intro"]}, + ] + log = "\n".join(["RHDEP1\t" + json.dumps(x) for x in items] + + ["RHDEPEND\t" + json.dumps({"visited": 2, "truncated": False})]) + graph = parse_output(log) + assert graph["proof_term_data"] and len(graph["edges"]) == 4 + assert {"from": "Example.bridge", "to": "Example.upstream", "channel": "value"} in graph["edges"] + + +@pytest.mark.parametrize("log", [ + "", 'RHDEPEND\t{"visited":1}', + 'RHDEPEND\t{"visited":0}\nRHDEPEND\t{"visited":0}\n', + 'RHDEP1\t{"name":"x","kind":"theorem","type_refs":[],"value_refs":[]}\n', +]) +def test_incomplete_or_duplicated_output_is_rejected(log): + with pytest.raises((ValueError, KeyError)): + parse_output(log) + + +def test_generated_lean_source_is_self_contained_and_sanitized(): + source = build_probe([], ["RHGraphToy.bridge"], 2, 12, ["RHGraphToy."], toy=True) + assert "RHDepProbe.emit env" in source + assert "theorem bridge : True := upstream" in source + assert "allowOpaque := true" in source + with pytest.raises(ValueError): + validate_names(["Nat; unsafe"]) + with pytest.raises(ValueError): + build_probe([], ["A"], -1, 1, ["A"]) From d89692e7f1c567f64baef470702d08178b0a396c Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 17:52:57 +0800 Subject: [PATCH 04/34] research(rh): source-traced +7 epsilon budget, two proof tasks, and CI probe --- .github/workflows/rh-proof-distillation.yml | 17 ++++- gyms/RHProofDistillation/README.md | 4 ++ gyms/RHProofDistillation/core_gm_proof_map.md | 27 ++++++++ gyms/RHProofDistillation/core_gm_sources.json | 62 +++++++++++++++++++ gyms/RHProofDistillation/gold.jsonl | 2 + gyms/RHProofDistillation/tasks.json | 16 +++++ src/spiral_ln/rh_dependency.py | 4 +- 7 files changed, 127 insertions(+), 5 deletions(-) create mode 100644 gyms/RHProofDistillation/core_gm_proof_map.md create mode 100644 gyms/RHProofDistillation/core_gm_sources.json diff --git a/.github/workflows/rh-proof-distillation.yml b/.github/workflows/rh-proof-distillation.yml index 14eafd75..1bd3ca13 100644 --- a/.github/workflows/rh-proof-distillation.yml +++ b/.github/workflows/rh-proof-distillation.yml @@ -4,14 +4,18 @@ on: push: paths: - 'src/spiral_ln/rh_distillation.py' + - 'src/spiral_ln/rh_dependency.py' - 'gyms/RHProofDistillation/**' - 'tests/test_rh_distillation.py' + - 'tests/test_rh_dependency.py' - '.github/workflows/rh-proof-distillation.yml' pull_request: paths: - 'src/spiral_ln/rh_distillation.py' + - 'src/spiral_ln/rh_dependency.py' - 'gyms/RHProofDistillation/**' - 'tests/test_rh_distillation.py' + - 'tests/test_rh_dependency.py' - '.github/workflows/rh-proof-distillation.yml' workflow_dispatch: @@ -29,7 +33,7 @@ jobs: python-version: '3.12' - run: python -m pip install -e '.[test]' - run: python -m spiral_ln.rh_distillation preflight - - run: python -m pytest -q tests/test_rh_distillation.py + - run: python -m pytest -q tests/test_rh_distillation.py tests/test_rh_dependency.py lean-proxy-gold: runs-on: ubuntu-latest @@ -54,9 +58,16 @@ jobs: --submissions gyms/RHProofDistillation/gold.jsonl \ --lean-cwd lean --timeout 90 --require-all \ --output rh-gold-replay.json + - name: Inspect compiled proof expression of toy lemma + run: | + python -m spiral_ln.rh_dependency smoke \ + --lean-cwd lean --timeout 120 \ + --output rh-proof-dependency-smoke.json - uses: actions/upload-artifact@v4 if: always() with: - name: rh-proof-distillation-gold-replay - path: rh-gold-replay.json + name: rh-proof-distillation-replays + path: | + rh-gold-replay.json + rh-proof-dependency-smoke.json if-no-files-found: ignore diff --git a/gyms/RHProofDistillation/README.md b/gyms/RHProofDistillation/README.md index 878d61aa..5f072b77 100644 --- a/gyms/RHProofDistillation/README.md +++ b/gyms/RHProofDistillation/README.md @@ -50,3 +50,7 @@ The grader compiles each candidate via lake env lean in the existing EvalMath Ma First extract declaration-level dependencies from exported Lean proof data and compare them with the import graph. Then identify and reprove explicit intermediate obligations in the Landau bound, theta scalar, Galois localization and covolume chain. Held-out tasks should split by dependency component, with exact provenance, contamination audit, compilation receipts and per-proof resource use. Evidence levels here remain those used in EvalMath: a compiled Lean theorem, a finite test, a source-verified declaration and an open research conjecture are distinct claims. + +## Second pass: source-site proof ledger and dependency probe + +See [core_gm_proof_map.md](core_gm_proof_map.md) and [core_gm_sources.json](core_gm_sources.json). The two new exercises RH-D-005/006 reconstruct the +7-epsilon bookkeeping of the prime-sum bound. `spiral_ln.rh_dependency` builds a separate Lean probe using `ConstantInfo.value? (allowOpaque := true)` and `Expr.getUsedConstants`, with a toy-compilation smoke check in CI. An upstream proof-term graph is reported only after the compiled pinned mirror has been inspected; the ledger is based on source call sites. diff --git a/gyms/RHProofDistillation/core_gm_proof_map.md b/gyms/RHProofDistillation/core_gm_proof_map.md new file mode 100644 index 00000000..fc82e1ba --- /dev/null +++ b/gyms/RHProofDistillation/core_gm_proof_map.md @@ -0,0 +1,27 @@ +# Tracing the core_gm exponent and its proof obligations + +Source pin: [CoreGm.lean](https://github.com/leanprover-community/riemann-hypothesis/blob/f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3/src/Development/AutomorphicArithmetic/PrimitiveCosets/CoreGm.lean). This note records direct source call sites; the separate Lean probe produces proof-term evidence only when run against the compiled upstream checkout. + +The source theorem concludes `Λ.Gm x ≤ x ^ (1/2 + (eD + eL + 7) * eps)`, assuming `EAtH` and `CoreAtH` witnesses. The `CoreAtH` predicate explicitly includes `C.eDiv ≤ eD`, `C.eLoss ≤ eL`, `ErrWindows`, `BNBoundsU`, `SizeData₂`, `ThinScales`, `CostWindows`, and other requirements. These must be discharged by the arithmetic and geometric construction. + +The proof applies `Deduction.ch_core` with `C = max (eD + eL) 0 + 3`. Since `ch_core` returns a principal exponent `(C + 3) eps`, nonnegativity of `eD + eL` makes that `(eD + eL + 6) eps`. The `Deduction.ch_top` gap estimate feeds the character-balance theorem, with an error factor `x ^ (CErr C * eps)`. Here `CErr` is bounded using the `eDiv` and `eLoss` controls. `charsA` supplies the character hypotheses, while `gmA_eq` converts the weighted character sum into `Λ.Gm`. + +The remaining correction is bounded by `sigA_le` as `4 * Λ.o * x ^ (1/2 + eps)`. For sufficiently large `x`, `x ^ eps` dominates `1 + 4 * Λ.o`. One last multiplicative power of `x ^ eps` absorbs that correction and changes the principal exponent from `+6` to `+7`. Exercises RH-D-005 and RH-D-006 test the algebraic bookkeeping independently of the large number-theory constructions. + +The downstream source chain can be seen in [WindowInequalityOfArtinInputs.lean](https://github.com/leanprover-community/riemann-hypothesis/blob/f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3/src/Development/AutomorphicArithmetic/PrimitiveCosets/WindowInequalityOfArtinInputs.lean), which applies `core_gm` to a family of `CoreAtH` witnesses. [LevelGmLeOnFamilyScales.lean](https://github.com/leanprover-community/riemann-hypothesis/blob/f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3/src/Development/AutomorphicArithmetic/PrimitiveCosets/LevelGmLeOnFamilyScales.lean) supplies the `ChainTied` to family-core reduction. + +## Reproduction + +First validate a tiny original theorem-dependency witness in EvalMath: + +```sh +python -m spiral_ln.rh_dependency smoke --lean-cwd lean --output /tmp/rh-dependency-smoke.json +``` + +To inspect the upstream proof terms, use a complete checkout pinned to the manifest's mirror commit and compiled with that repository's Lean 4.33.1 toolchain. The source checker verifies the six anchor blobs before running: + +```sh +python -m spiral_ln.rh_dependency upstream --source-root /path/to/riemann-hypothesis --anchors weighted_bound --max-depth 2 --max-nodes 120 --output /tmp/rh-core-gm-deps.json +``` + +The direct expression graph remains bounded and can omit mathematical dependencies hidden behind definitions or rewriting. Proof reduction and human examination are separate later tasks. diff --git a/gyms/RHProofDistillation/core_gm_sources.json b/gyms/RHProofDistillation/core_gm_sources.json new file mode 100644 index 00000000..225a06a5 --- /dev/null +++ b/gyms/RHProofDistillation/core_gm_sources.json @@ -0,0 +1,62 @@ +{ + "schema_version": 1, + "mode": "manually_verified_source_calls", + "source_repository": "leanprover-community/riemann-hypothesis", + "source_commit": "f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3", + "caller": "UpperTheory.Comparison₂.core_gm", + "caller_file": "src/Development/AutomorphicArithmetic/PrimitiveCosets/CoreGm.lean", + "caller_blob": "3ba7a590e84c5993882ea6c5dcf9fdbed5f07d4d", + "status": "source-inspected, term dependency not executed against upstream", + "edges": [ + { + "callee": "Deduction.ch_core", + "role": "character-balance bound with exponent C + 3", + "source": "DedekindLFunctions/LandauTheorems/ChCore.lean", + "blob": "878f5077bc382426c7da988e5a375b85deeaa7de" + }, + { + "callee": "Deduction.ch_top", + "role": "gap estimate via size and error windows", + "source": "DedekindLFunctions/LandauTheorems/ChTop.lean", + "blob": "ce06a34a9e0b1b332e10d3b7efb04a06e9ab77f5" + }, + { + "callee": "UpperTheory.Comparison₂.charsA", + "role": "translate character hypotheses", + "source": "PrimitiveCosets/charsA.lean", + "blob": "7d6a3faa3f6dcc1923a65473d848d8da0601e7a2" + }, + { + "callee": "UpperTheory.Comparison₂.gmA_eq", + "role": "identify GmA with Level.Gm", + "source": "PrimitiveCosets/GmAEq.lean", + "blob": "2f1a763f43d65eea1f6e61018c8b70c02d2dfa03" + }, + { + "callee": "UpperTheory.Comparison₂.sigA_le", + "role": "bound excluded-character contribution", + "source": "PrimitiveCosets/SigALe.lean", + "blob": "e9c80e2017ec149ac559bc20c184b9264b9ec0c2" + }, + { + "callee": "UpperTheory.Comparison₂.hostFactsS", + "role": "supply the HostFactsS assumption", + "source": "PrimitiveCosets/hostFactsS.lean", + "blob": "440a45819936cf0cb7fb8e81156e94b25288459c" + } + ], + "downstream": [ + { + "theorem": "UpperTheory.Comparison₂.windowInequality_of_artinInputs", + "source": "PrimitiveCosets/WindowInequalityOfArtinInputs.lean", + "blob": "c349e34925ac26b8bc76bd36e9b91562f86d6b8d", + "relation": "calls core_gm" + }, + { + "theorem": "UpperTheory.Comparison₂.level_gm_le_on_family_scales", + "source": "PrimitiveCosets/LevelGmLeOnFamilyScales.lean", + "blob": "de994949e6fd2d7238cfcb1c19d361ccdfe904fc", + "relation": "calls windowInequality_of_artinInputs" + } + ] +} diff --git a/gyms/RHProofDistillation/gold.jsonl b/gyms/RHProofDistillation/gold.jsonl index 9002a47b..c447edfa 100644 --- a/gyms/RHProofDistillation/gold.jsonl +++ b/gyms/RHProofDistillation/gold.jsonl @@ -2,3 +2,5 @@ {"id":"RH-D-002","proof":"exact hConstruct hTheta"} {"id":"RH-D-003","proof":"have hle : s.re ≤ 1 / 2 := by\n by_contra hc\n exact (hRight s (lt_of_not_ge hc)) hz\nhave hflip : L (1 - s) = 0 := hFlip s hs0 hs1 hz\nhave hleflip : (1 - s).re ≤ 1 / 2 := by\n by_contra hc\n exact (hRight (1 - s) (lt_of_not_ge hc)) hflip\nhave hge : 1 / 2 ≤ s.re := by\n have hreal : (1 - s).re = 1 - s.re := by simp\n linarith\nexact le_antisymm hle hge"} {"id":"RH-D-004","proof":"by_contra hc\nhave hpos : 0 < (r - 1 / 2) / 2 := by linarith\nhave hbound := h ((r - 1 / 2) / 2) hpos\nlinarith"} +{"id":"RH-D-005","proof":"rw [max_eq_left h]\nring"} +{"id":"RH-D-006","proof":"have hB : 0 ≤ x ^ ((1 / 2 : ℝ) + (eD + eL + 6) * eps) :=\n Real.rpow_nonneg hx.le _\nhave hterm : K * x ^ ((1 / 2 : ℝ) + eps) ≤\n K * x ^ ((1 / 2 : ℝ) + (eD + eL + 6) * eps) :=\n mul_le_mul_of_nonneg_left hSmall hK\nhave hcomp : G ≤ (1 + K) * x ^ ((1 / 2 : ℝ) + (eD + eL + 6) * eps) := by\n nlinarith\nhave hcoeff := mul_le_mul_of_nonneg_right hErr hB\nhave hpow : x ^ eps * x ^ ((1 / 2 : ℝ) + (eD + eL + 6) * eps) =\n x ^ ((1 / 2 : ℝ) + (eD + eL + 7) * eps) := by\n rw [← Real.rpow_add hx]\n congr 1\n ring\nrw [hpow] at hcoeff\nexact le_trans hcomp hcoeff"} diff --git a/gyms/RHProofDistillation/tasks.json b/gyms/RHProofDistillation/tasks.json index 7a15e3a0..de978130 100644 --- a/gyms/RHProofDistillation/tasks.json +++ b/gyms/RHProofDistillation/tasks.json @@ -30,5 +30,21 @@ "anchor": "weighted_bound", "description": "Remove arbitrarily small positive exponent slack over the reals.", "template": "import Mathlib\n\nnamespace RHGym\n\ntheorem epsilon_squeeze (r : ℝ)\n (h : ∀ ε : ℝ, 0 < ε → r ≤ (1 / 2 : ℝ) + ε) :\n r ≤ (1 / 2 : ℝ) := by\n__PROOF__\n\nend RHGym\n" + }, + { + "id": "RH-D-005", + "difficulty": "medium", + "category": "exponent_accounting", + "anchor": "weighted_bound", + "description": "Reconstruct the exact +7-epsilon budget of the upstream core_gm proof, from a nonnegative sum of divisorial and loss exponents.", + "template": "import Mathlib\n\nnamespace RHGym\n\ntheorem exponent_budget (eD eL eps : ℝ) (h : 0 ≤ eD + eL) :\n (1 / 2 : ℝ) + ((max (eD + eL) 0 + 3) + 3) * eps + eps =\n (1 / 2 : ℝ) + (eD + eL + 7) * eps := by\n__PROOF__\n\nend RHGym\n" + }, + { + "id": "RH-D-006", + "difficulty": "medium", + "category": "exponent_accounting", + "anchor": "weighted_bound", + "description": "Absorb the excluded-character term into one additional x^eps factor under explicit large-x and comparison hypotheses.", + "template": "import Mathlib\n\nnamespace RHGym\n\ntheorem absorb_correction\n (x eps K eD eL G : ℝ) (hx : 0 < x) (hK : 0 ≤ K)\n (hErr : 1 + K ≤ x ^ eps)\n (hSmall : x ^ ((1 / 2 : ℝ) + eps) ≤\n x ^ ((1 / 2 : ℝ) + (eD + eL + 6) * eps))\n (hMain : G ≤ x ^ ((1 / 2 : ℝ) + (eD + eL + 6) * eps) +\n K * x ^ ((1 / 2 : ℝ) + eps)) :\n G ≤ x ^ ((1 / 2 : ℝ) + (eD + eL + 7) * eps) := by\n__PROOF__\n\nend RHGym\n" } ] diff --git a/src/spiral_ln/rh_dependency.py b/src/spiral_ln/rh_dependency.py index b8def3cd..ccc98662 100644 --- a/src/spiral_ln/rh_dependency.py +++ b/src/spiral_ln/rh_dependency.py @@ -87,8 +87,8 @@ def build_probe(imports: list[str], roots: list[str], depth: int, "end RHGraphToy\n") if toy else "" quoted_roots = ", ".join(chr(96) * 2 + name for name in roots) quoted_prefixes = ", ".join(json.dumps(p, ensure_ascii=False) for p in prefixes) - cmd = ("\nrun_cmd do\n" - " let env \u2190 Lean.Elab.Command.getEnv\n" + cmd = ("\nopen Lean Elab Command\nrun_cmd do\n" + " let env \u2190 getEnv\n" f" liftIO <| RHDepProbe.emit env #[{quoted_roots}] {depth} {max_nodes} #[{quoted_prefixes}]\n") return header + "\n" + body + fixtures + cmd From c7e15045ea000e5b297254fb1f94815e3dff5b05 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 17:55:47 +0800 Subject: [PATCH 05/34] fix(rh): serialize Lean truncation proof as Boolean --- gyms/RHProofDistillation/lean/ProofDependencies.lean | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gyms/RHProofDistillation/lean/ProofDependencies.lean b/gyms/RHProofDistillation/lean/ProofDependencies.lean index 50a04780..57ae4906 100644 --- a/gyms/RHProofDistillation/lean/ProofDependencies.lean +++ b/gyms/RHProofDistillation/lean/ProofDependencies.lean @@ -69,7 +69,7 @@ def emit (env : Environment) (roots : Array Name) (maxDepth maxNodes : Nat) depthLimited := true let endRecord := Json.mkObj [ ("visited", toJson count), - ("truncated", toJson (idx < queue.size)), + ("truncated", toJson (decide (idx < queue.size))), ("depth_limited", toJson depthLimited), ("queued", toJson queue.size), ("max_depth", toJson maxDepth), From e124e1e4375a3ee73446828a381abc683709d388 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 18:03:56 +0800 Subject: [PATCH 06/34] feat(rh): strict pinned-source call graph and CoreAtH contract auditor --- src/spiral_ln/rh_source_audit.py | 155 +++++++++++++++++++++++++++++++ tests/test_rh_source_audit.py | 32 +++++++ 2 files changed, 187 insertions(+) create mode 100644 src/spiral_ln/rh_source_audit.py create mode 100644 tests/test_rh_source_audit.py diff --git a/src/spiral_ln/rh_source_audit.py b/src/spiral_ln/rh_source_audit.py new file mode 100644 index 00000000..cf1129a5 --- /dev/null +++ b/src/spiral_ln/rh_source_audit.py @@ -0,0 +1,155 @@ +"""Source-only, provenance-pinned audit of the RH core_gm proof boundary.""" +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +import re + +from spiral_ln.rh_dependency import pinned_mirror +from spiral_ln.rh_distillation import git_blob_sha, parse_imports, walk_imports + +BASE = Path(__file__).resolve().parents[2] / "gyms" / "RHProofDistillation" +PREFIX = Path("src/Development/AutomorphicArithmetic") +CORE = PREFIX / "PrimitiveCosets/CoreGm.lean" +PREDICATE = PREFIX / "PrimitiveCosets/CoreAtH.lean" +PREDICATE_SHA = "0ba3621036f19146e7e67fa9c0e8a1c38661a097" +REQUIRED = { + "log_derivative": "HostAddCharCompatible H ell", + "x_match": "Dd.x = x", + "epsilon_match": "Dd.ε = eps", + "divisorial_slack": "C.eDiv ≤ eD", + "loss_slack": "C.eLoss ≤ eL", + "geometric_slack": "C.cHH ≤ cHH", + "index_coverage": "∀ s ∈ φ.A0, ∃ u, tr u = s", + "geometric_identification": "IdentU Dd tr", + "size_data": "SizeData₂ Dd C Xpp", + "error_window": "ErrWindows Dd C Xpp", + "bounded_numbers": "BNBoundsU Dd T2", + "character_size": "SizesA φ.A0 TT T2", + "thin_scales": "ThinScales (arith H) ell X' θ", + "cost_windows": "CostWindows x (fPl φ.A)", + "rest_size": "RestSize eps x", + "surviving_chars": "∀ s ∈ T2, s ∈ φ.A0", +} +BRIDGES = { + "PrimitiveCosets/WindowInequalityOfArtinInputs.lean": ["core_gm", "zeroFreeOn_of_tiedWin"], + "PrimitiveCosets/LevelGmLeOnFamilyScales.lean": ["windowInequality_of_artinInputs", "zeroFreeOn_of_core"], + "PrimitiveCosets/Imports.lean": ["Deduction.zeroFree_of_rpow_window", "UpperTheory.Comparison₂.level_family"], + "DedekindLFunctions/LandauTheorems/ZeroFreeOfRpowWindow.lean": ["lemmaL", "windowHyp_of_rpow"], + "DedekindLFunctions/LandauTheorems/ChCore.lean": ["CharacterBalanceMoves.core", "proposition_size_bound", "derivative_integral_all"], + "DedekindLFunctions/LandauTheorems/ChTop.lean": ["ch_top_main_eq", "each_unit_bound_statement", "errX5at_le"], +} + +def match_name(text: str, name: str) -> bool: + return re.search(r"(? str: + i = src.find(start) + if i < 0: + raise ValueError("missing declaration: " + start) + j = src.find(stop, i + len(start)) + if j < 0: + raise ValueError("missing boundary: " + stop) + return src[i:j] + +def verified_file(root: Path, path: Path, expected: str | None = None) -> tuple[str, dict]: + file = root / path + if not file.is_file(): + raise ValueError("pinned source missing: " + str(path)) + raw = file.read_bytes() + blob = git_blob_sha(raw) + if expected and blob != expected: + raise ValueError("pinned Git blob differs: " + str(path)) + text = raw.decode("utf-8") + return text, {"path": str(path), "git_blob": blob, + "sha256": hashlib.sha256(raw).hexdigest(), + "bytes": len(raw), "imports": parse_imports(text)} + +def audit(root: Path, manifest: dict, ledger: dict) -> dict: + identity = pinned_mirror(root, manifest) + if ledger["source_commit"] != manifest["mirror_commit"]: + raise ValueError("ledger and mirror source pins differ") + if Path(ledger["caller_file"]) != CORE: + raise ValueError("unexpected source declaration") + anchor = next(a for a in manifest["anchors"] if a["id"] == "weighted_bound") + if ledger["caller_blob"] != anchor["blob_sha"]: + raise ValueError("source ledger disagrees with pinned anchor") + caller, rec = verified_file(root, CORE, ledger["caller_blob"]) + body = region(caller, "theorem UpperTheory.Comparison₂.core_gm", "\nend") + records = [rec] + calls = [] + for dependency in ledger["edges"]: + path = PREFIX / dependency["source"] + txt, evidence = verified_file(root, path, dependency["blob"]) + symbol = dependency["callee"].rsplit(".", 1)[-1] + if not match_name(body, symbol) or not match_name(txt, symbol): + raise ValueError("missing source proof reference: " + dependency["callee"]) + records.append(evidence) + calls.append({"from": ledger["caller"], "to": dependency["callee"], + "source": str(path), "channel": "source_call", + "blob": evidence["git_blob"]}) + definition, predicate_record = verified_file(root, PREDICATE, PREDICATE_SHA) + records.append(predicate_record) + contract = region(definition, "def CoreAtH ", "\ndef pcOf ") + for label, fragment in REQUIRED.items(): + if fragment not in contract: + raise ValueError("CoreAtH field changed or missing: " + label) + bridges = [] + for name, needles in BRIDGES.items(): + path = PREFIX / name + src, item = verified_file(root, path) + if not all(match_name(src, n) for n in needles): + raise ValueError("bridge call missing: " + name) + records.append(item) + bridges.append({"path": str(path), "sha256": item["sha256"], + "calls": needles}) + for item in ledger["downstream"]: + path = PREFIX / item["source"] + src, verified = verified_file(root, path, item["blob"]) + if not match_name(src, item["theorem"].rsplit(".", 1)[-1]): + raise ValueError("downstream declaration missing: " + item["theorem"]) + graph = walk_imports(root / "src", + ["Development.AutomorphicArithmetic.PrimitiveCosets.CoreGm"], 120) + unique = {r["path"]: r for r in records} + return { + "schema_version": 1, + "mode": "pinned_upstream_source_only", + "proof_term_data": False, + "compiled_olean_used": False, + "identity": identity, + "source_files": [unique[k] for k in sorted(unique)], + "direct_call_sites": calls, + "core_at_h_obligations": list(REQUIRED), + "core_at_h_contract_sha256": hashlib.sha256(contract.encode()).hexdigest(), + "verified_bridges": bridges, + "import_graph": { + "visited_modules": graph["visited_modules"], + "edges": graph["import_edges"], "truncated": graph["truncated"], + "unavailable_internal": graph["unresolved_internal_imports"], + "external": graph["external_imports"], + }, + "limitations": "Source call graph; missing imports may reflect sparse checkout. No proof-term closure.", + } + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + manifest = json.loads((BASE / "anchors.json").read_text()) + ledger = json.loads((BASE / "core_gm_sources.json").read_text()) + receipt = audit(args.source_root.resolve(), manifest, ledger) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(receipt, sort_keys=True, indent=2) + "\n") + print(json.dumps({"commit": receipt["identity"]["commit"], + "files": len(receipt["source_files"]), + "direct_calls": len(receipt["direct_call_sites"]), + "obligations": len(receipt["core_at_h_obligations"]), + "bridges": len(receipt["verified_bridges"]), + "imports": receipt["import_graph"]["visited_modules"], + "proof_term_data": False}, sort_keys=True)) + +if __name__ == "__main__": + main() diff --git a/tests/test_rh_source_audit.py b/tests/test_rh_source_audit.py new file mode 100644 index 00000000..5dc517a2 --- /dev/null +++ b/tests/test_rh_source_audit.py @@ -0,0 +1,32 @@ +"""Source audit tests with deliberate tampering and Unicode declarations.""" +from pathlib import Path +import pytest +from spiral_ln.rh_source_audit import REQUIRED, match_name, region, verified_file + +def test_exact_lean_symbol_boundaries(): + assert match_name("theorem UpperTheory.Comparison₂.core_gm : True", "core_gm") + assert match_name("theorem UpperTheory.Comparison₂.core_gm : True", "Comparison₂.core_gm") + assert not match_name("core_gm_more", "core_gm") + assert not match_name("mycore_gm", "core_gm") + +def test_source_slices_fail_closed(): + with pytest.raises(ValueError, match="missing declaration"): + region("theorem sample", "def CoreAtH", "def pcOf") + with pytest.raises(ValueError, match="missing boundary"): + region("def CoreAtH : Prop := True", "def CoreAtH", "def pcOf") + +def test_blob_mismatch_is_fatal(tmp_path): + p = tmp_path / "src" / "Test.lean" + p.parent.mkdir() + p.write_text("theorem test : True := True.intro\n") + with pytest.raises(ValueError, match="Git blob differs"): + verified_file(tmp_path, Path("src/Test.lean"), "0" * 40) + _, record = verified_file(tmp_path, Path("src/Test.lean")) + assert len(record["sha256"]) == 64 + +def test_contract_has_named_arithmetic_obligations(): + assert len(REQUIRED) == 16 + assert "C.eDiv ≤ eD" in REQUIRED.values() + assert "C.eLoss ≤ eL" in REQUIRED.values() + assert "HostAddCharCompatible H ell" in REQUIRED.values() + assert "ErrWindows Dd C Xpp" in REQUIRED.values() From c4fb9cc51d3793d094fe99d2194499659b317a12 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 18:04:16 +0800 Subject: [PATCH 07/34] ci(rh): execute pinned upstream source audit with sparse read-only checkout --- .github/workflows/rh-pinned-source.yml | 79 +++++++++++++++++++++ gyms/RHProofDistillation/PINNED_UPSTREAM.md | 39 ++++++++++ 2 files changed, 118 insertions(+) create mode 100644 .github/workflows/rh-pinned-source.yml create mode 100644 gyms/RHProofDistillation/PINNED_UPSTREAM.md diff --git a/.github/workflows/rh-pinned-source.yml b/.github/workflows/rh-pinned-source.yml new file mode 100644 index 00000000..1843794c --- /dev/null +++ b/.github/workflows/rh-pinned-source.yml @@ -0,0 +1,79 @@ +name: RH pinned upstream source audit + +on: + push: + paths: + - 'src/spiral_ln/rh_source_audit.py' + - 'src/spiral_ln/rh_dependency.py' + - 'gyms/RHProofDistillation/anchors.json' + - 'gyms/RHProofDistillation/core_gm_sources.json' + - 'tests/test_rh_source_audit.py' + - '.github/workflows/rh-pinned-source.yml' + pull_request: + paths: + - 'src/spiral_ln/rh_source_audit.py' + - 'src/spiral_ln/rh_dependency.py' + - 'gyms/RHProofDistillation/anchors.json' + - 'gyms/RHProofDistillation/core_gm_sources.json' + - 'tests/test_rh_source_audit.py' + - '.github/workflows/rh-pinned-source.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + pinned-source: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + with: + path: evalmath + persist-credentials: false + - uses: actions/checkout@v4 + with: + repository: leanprover-community/riemann-hypothesis + ref: f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3 + path: upstream + persist-credentials: false + sparse-checkout-cone-mode: false + sparse-checkout: | + src/Main.lean + src/Statements.lean + src/Development/AutomorphicArithmetic/CharacterBoxes/MainConclusion.lean + src/Development/AutomorphicArithmetic/Foundations/GaloisRepresentations/IntegralStructures/RowSrc.lean + src/Development/AutomorphicArithmetic/PrimitiveCosets/ + src/Development/AutomorphicArithmetic/DedekindLFunctions/LandauTheorems/ + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Install audit-only Python package + working-directory: evalmath + run: python -m pip install -e '.[test]' + - name: Unit tests + working-directory: evalmath + run: python -m pytest -q tests/test_rh_source_audit.py + - name: Extract pinned source callsite and boundary graph + working-directory: evalmath + run: | + mkdir -p rh-source + python -m spiral_ln.rh_source_audit \ + --source-root ../upstream \ + --output rh-source/core-gm-pinned-source.json + - name: Emit proof-term probe script for large runner + working-directory: evalmath + run: | + python -m spiral_ln.rh_dependency upstream \ + --source-root ../upstream \ + --anchors weighted_bound \ + --max-depth 2 --max-nodes 120 \ + --emit-script rh-source/core-gm-proof-term-probe.lean \ + --output rh-source/proof-probe-staging.json + - name: Upload pinned-source receipts + if: always() + uses: actions/upload-artifact@v4 + with: + name: rh-pinned-source-receipts + path: evalmath/rh-source/ + if-no-files-found: ignore diff --git a/gyms/RHProofDistillation/PINNED_UPSTREAM.md b/gyms/RHProofDistillation/PINNED_UPSTREAM.md new file mode 100644 index 00000000..e11e23f8 --- /dev/null +++ b/gyms/RHProofDistillation/PINNED_UPSTREAM.md @@ -0,0 +1,39 @@ +# Pinned upstream audit: source and proof-expression stages + +The lightweight GitHub Actions job checks out the actual upstream repository at commit +`f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3` in sparse mode. +It verifies all six source anchors, the direct `core_gm` callsites, +and the sixteen named `CoreAtH` hypotheses against pinned source bytes. +It also follows the family-window and Landau bridge through source files. +The JSON receipt marks `proof_term_data=false`, since source parsing is +not inspection of elaborated Lean theorem bodies. + +The full proof-expression probe is generated but not executed in this workflow. +Lean's original compilation environment requires Lean 4.33.1 and large caches. +The upstream community cache documentation reports 99.27 GB of extracted +olean and ilean artifacts, with 4.94 GB compressed Lake cache. +Full extraction needs a machine with at least 100 GB free disk; +the upstream build-runner documentation recommends at least 250 GB free. + +To inspect proof-body references from an independently obtained full, +clean upstream checkout with the compiled original modules available, +install EvalMath's Python package and run the following from EvalMath: + + python -m spiral_ln.rh_dependency upstream \ + --source-root /path/to/riemann-hypothesis \ + --anchors weighted_bound \ + --max-depth 2 --max-nodes 120 \ + --prefixes UpperTheory. Deduction. Formalism. \ + --output /path/to/core-gm-proof-term-refs.json + +Use `lake exe cache get` within the complete pinned upstream checkout +before running the scanner. Cache restoration relies on public artifacts; +transport integrity is separate from proof trust. Independent fresh +compilation or proof-kernel replay is required for stronger verification. + +The scanner emits direct constant references in elaborated types and values. +It does not prove that these references form a mathematically minimal +dependency set. Its output has a separate explicit truncation flag. + +Upstream source remains in a temporary CI checkout; no unlicensed +source is vendored into EvalMath. From d3972cfb70833fd2d1af3fb1b6e5aca6f5aa9e11 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 18:05:11 +0800 Subject: [PATCH 08/34] fix(rh): read top-level core_gm theorem through EOF --- src/spiral_ln/rh_source_audit.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/spiral_ln/rh_source_audit.py b/src/spiral_ln/rh_source_audit.py index cf1129a5..ede78d80 100644 --- a/src/spiral_ln/rh_source_audit.py +++ b/src/spiral_ln/rh_source_audit.py @@ -77,7 +77,7 @@ def audit(root: Path, manifest: dict, ledger: dict) -> dict: if ledger["caller_blob"] != anchor["blob_sha"]: raise ValueError("source ledger disagrees with pinned anchor") caller, rec = verified_file(root, CORE, ledger["caller_blob"]) - body = region(caller, "theorem UpperTheory.Comparison₂.core_gm", "\nend") + body = caller[caller.index("theorem UpperTheory.Comparison₂.core_gm"):] records = [rec] calls = [] for dependency in ledger["edges"]: From 9100ae996dc4fb225e2271727b3b5e850e53bc22 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 18:06:58 +0800 Subject: [PATCH 09/34] research(rh): trace theta/covolume/Galois junction in pinned upstream source --- .github/workflows/rh-pinned-source.yml | 3 ++ gyms/RHProofDistillation/UPPER_BRIDGE.md | 48 ++++++++++++++++++++++++ src/spiral_ln/rh_source_audit.py | 38 +++++++++++++++++++ tests/test_rh_source_audit.py | 10 +++++ 4 files changed, 99 insertions(+) create mode 100644 gyms/RHProofDistillation/UPPER_BRIDGE.md diff --git a/.github/workflows/rh-pinned-source.yml b/.github/workflows/rh-pinned-source.yml index 1843794c..d99b3cfb 100644 --- a/.github/workflows/rh-pinned-source.yml +++ b/.github/workflows/rh-pinned-source.yml @@ -43,6 +43,9 @@ jobs: src/Statements.lean src/Development/AutomorphicArithmetic/CharacterBoxes/MainConclusion.lean src/Development/AutomorphicArithmetic/Foundations/GaloisRepresentations/IntegralStructures/RowSrc.lean + src/Development/AutomorphicArithmetic/AutomorphicVarieties/ModularityArgument/ThresholdArguments/DenseThresholdCases/VwinOfRow.lean + src/Development/AutomorphicArithmetic/ThetaCorrespondence/ThetaPairLifts/ThirdPlaceSeries/EveryCharacterOfLiteratureOfVWin.lean + src/Formalism/SharpRestriction/GlobalSchurBounds/TieGlobal.lean src/Development/AutomorphicArithmetic/PrimitiveCosets/ src/Development/AutomorphicArithmetic/DedekindLFunctions/LandauTheorems/ - uses: actions/setup-python@v5 diff --git a/gyms/RHProofDistillation/UPPER_BRIDGE.md b/gyms/RHProofDistillation/UPPER_BRIDGE.md new file mode 100644 index 00000000..3c3ad3ee --- /dev/null +++ b/gyms/RHProofDistillation/UPPER_BRIDGE.md @@ -0,0 +1,48 @@ +# Upper bridge: theta integrals, covolumes and the character-window theorem + +Provenance: Lean community mirror at commit `f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3`. +This note describes **direct source observations**; the complete compiled proof-term graph is still pending. + +## The conjunction that finishes the character theorem + +In `ThetaCorrespondence/ThetaPairLifts/ThirdPlaceSeries/EveryCharacterOfLiteratureOfVWin.lean`, +the declaration `UpperTheory.LiteratureTheorems.every_character_of_literature_of_vWin` +calls `UpperTheory.Lit.every_character_of_theta_integrals_local_matching`. +It supplies a covolume estimate from `SelfIntersectionVolumeEstimates.topCovolSlim2_use_alt_alt`, +theta-integral compatibility from `theta_integrals_agree_and_local_matching_of_literature`, +and a local Langlands hypothesis from `local_langlands_gl_recT_exists_of_literature`. +Additional published arithmetic and geometric input assumptions occur in the same expression. +That theorem takes `OpenLiteratureStatements` and `UpperTheory.Top.VWin` as premises. + +## How VWin and Galois representations enter + +`AutomorphicVarieties/ModularityArgument/ThresholdArguments/DenseThresholdCases/VwinOfRow.lean` +defines `UpperTheory.One.vwin_of_row`, applying `automorphic_window_of_inputs` +to an `OpenImageCondition.mk` built from a Galois row parameter +and the `BaseChangeIdentities.baseChangeN` input. + +`Foundations/GaloisRepresentations/IntegralStructures/RowSrc.lean` +provides `galoisLocalGlobalStrong_recParameter` by applying +`galoisRepresentations_of_thetaLift` to `tLiftK`. + +`CharacterBoxes/MainConclusion.lean` then calls +`every_character_of_literature_of_vWin` using the row parameter and `vwin_of_row`. +Thus a specific, source-observed junction combines theta matching, +local Langlands, a geometric covolume statement and an automorphic window. + +## How this relates to the character-sum bound + +The other source strand starts from `ChainTied` in +`Formalism/SharpRestriction/GlobalSchurBounds/TieGlobal.lean`, +which contains `TiePts`, `TieGlobal`, `TieLocal` and `TieArith` witnesses +along with size, cost and error-window bounds. +`level_gm_le_on_family_scales` transports these into the family-level +prime-sum inequality via `tiedCore_of_chainTied` and `core_gm`. + +The entire path by which the arithmetic-geometric constructions supply +the `ChainTied` conditions needs a theorem-level proof-expression trace. +The upper-bridge audit identifies the named interfaces that such a trace +must inspect and records their upstream Git blob hashes. + +CI stages this investigation in `rh-pinned-source.yml` using a sparse +source checkout. No upstream Lean proof artifacts are executed. diff --git a/src/spiral_ln/rh_source_audit.py b/src/spiral_ln/rh_source_audit.py index ede78d80..92941003 100644 --- a/src/spiral_ln/rh_source_audit.py +++ b/src/spiral_ln/rh_source_audit.py @@ -42,6 +42,32 @@ "DedekindLFunctions/LandauTheorems/ChTop.lean": ["ch_top_main_eq", "each_unit_bound_statement", "errX5at_le"], } + +# Source-verified upper branches. These are related proof routes; this audit +# makes no claim that they form a complete path between the two strands. +UPPER_BRIDGES = { + "src/Development/AutomorphicArithmetic/CharacterBoxes/MainConclusion.lean": { + "blob": "ee340012ab19713a8acfecf8adc6a331cbc2f1a4", + "uses": ["every_character_of_literature_of_vWin", "vwin_of_row", + "galoisLocalGlobalStrong_recParameter"]}, + "src/Development/AutomorphicArithmetic/Foundations/GaloisRepresentations/IntegralStructures/RowSrc.lean": { + "blob": "f769999ac5e49241993e5efbf81e4d2cded18acd", + "uses": ["galoisRepresentations_of_thetaLift", "tLiftK"]}, + "src/Development/AutomorphicArithmetic/AutomorphicVarieties/ModularityArgument/ThresholdArguments/DenseThresholdCases/VwinOfRow.lean": { + "blob": "4cba179acd45ac08d3cad21f51c9b9d62715a9a4", + "uses": ["automorphic_window_of_inputs", "OpenImageCondition.mk", "baseChangeN"]}, + "src/Development/AutomorphicArithmetic/ThetaCorrespondence/ThetaPairLifts/ThirdPlaceSeries/EveryCharacterOfLiteratureOfVWin.lean": { + "blob": "a13ba1f8c38d4dbf2ddd809fbf9610a007936c24", + "uses": ["every_character_of_theta_integrals_local_matching", + "topCovolSlim2_use_alt_alt", + "theta_integrals_agree_and_local_matching_of_literature", + "local_langlands_gl_recT_exists_of_literature"]}, + "src/Formalism/SharpRestriction/GlobalSchurBounds/TieGlobal.lean": { + "blob": "00acf811793877fe42d18c0d69f2d5833f75bf94", + "uses": ["ChainTied", "TiePts", "TieGlobal", "TieLocal", "TieArith", + "ErrWindows", "GrowthInequalityRemainingHyps"]}, +} + def match_name(text: str, name: str) -> bool: return re.search(r"(? dict: src, verified = verified_file(root, path, item["blob"]) if not match_name(src, item["theorem"].rsplit(".", 1)[-1]): raise ValueError("downstream declaration missing: " + item["theorem"]) + upper = [] + for path_text, spec in UPPER_BRIDGES.items(): + path = Path(path_text) + src, item = verified_file(root, path, spec["blob"]) + missing = [n for n in spec["uses"] if not match_name(src, n)] + if missing: + raise ValueError("upper proof bridge site missing: " + str(missing)) + records.append(item) + upper.append({"path": path_text, "blob": item["git_blob"], + "uses": spec["uses"]}) graph = walk_imports(root / "src", ["Development.AutomorphicArithmetic.PrimitiveCosets.CoreGm"], 120) unique = {r["path"]: r for r in records} @@ -124,6 +160,7 @@ def audit(root: Path, manifest: dict, ledger: dict) -> dict: "core_at_h_obligations": list(REQUIRED), "core_at_h_contract_sha256": hashlib.sha256(contract.encode()).hexdigest(), "verified_bridges": bridges, + "upper_source_routes": upper, "import_graph": { "visited_modules": graph["visited_modules"], "edges": graph["import_edges"], "truncated": graph["truncated"], @@ -148,6 +185,7 @@ def main() -> None: "direct_calls": len(receipt["direct_call_sites"]), "obligations": len(receipt["core_at_h_obligations"]), "bridges": len(receipt["verified_bridges"]), + "upper_routes": len(receipt["upper_source_routes"]), "imports": receipt["import_graph"]["visited_modules"], "proof_term_data": False}, sort_keys=True)) diff --git a/tests/test_rh_source_audit.py b/tests/test_rh_source_audit.py index 5dc517a2..aee16f96 100644 --- a/tests/test_rh_source_audit.py +++ b/tests/test_rh_source_audit.py @@ -30,3 +30,13 @@ def test_contract_has_named_arithmetic_obligations(): assert "C.eLoss ≤ eL" in REQUIRED.values() assert "HostAddCharCompatible H ell" in REQUIRED.values() assert "ErrWindows Dd C Xpp" in REQUIRED.values() + + +def test_upper_bridge_sources_pin_actual_math_junction(): + from spiral_ln.rh_source_audit import UPPER_BRIDGES + assert len(UPPER_BRIDGES) == 5 + assert all(len(x['blob']) == 40 for x in UPPER_BRIDGES.values()) + combined = {name for item in UPPER_BRIDGES.values() for name in item['uses']} + assert 'topCovolSlim2_use_alt_alt' in combined + assert 'every_character_of_theta_integrals_local_matching' in combined + assert 'GrowthInequalityRemainingHyps' in combined From 2d9ead54d6ed3a1a541da8efabb58a78f57a972a Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 18:08:35 +0800 Subject: [PATCH 10/34] test(rh): add source-faithful literature interface and witness-transport Lean exercises --- gyms/RHProofDistillation/UPPER_BRIDGE.md | 6 ++++++ gyms/RHProofDistillation/gold.jsonl | 2 ++ gyms/RHProofDistillation/tasks.json | 16 ++++++++++++++++ 3 files changed, 24 insertions(+) diff --git a/gyms/RHProofDistillation/UPPER_BRIDGE.md b/gyms/RHProofDistillation/UPPER_BRIDGE.md index 3c3ad3ee..fc480d59 100644 --- a/gyms/RHProofDistillation/UPPER_BRIDGE.md +++ b/gyms/RHProofDistillation/UPPER_BRIDGE.md @@ -46,3 +46,9 @@ must inspect and records their upstream Git blob hashes. CI stages this investigation in `rh-pinned-source.yml` using a sparse source checkout. No upstream Lean proof artifacts are executed. + +## An explicit duplicate premise in the literature interface + +The pinned file defines `OpenLiteratureStatements : Prop` with exactly three fields: `caraianiLocalGlobalDual : UpperTheory.One.M.Row`, `localLanglandsExists : UpperTheory.Zero.LLC.RecTExists`, and `galoisRepOfPolarizedPairLit : UpperTheory.One.M.Row`. The two Galois-row fields share a proposition, so this interface is equivalent to the conjunction of one row witness with the local-Langlands existence witness. That structural equivalence is modeled by proxy task `RH-D-007`. The upstream code provides these witnesses through the Galois row and `recTExists`; this observation does not discharge any hidden arithmetic or geometric proof obligations. + +Task `RH-D-008` models the existential-index projection performed by `tiedCore_of_chainTied`, with geometric assertions left as explicit parameters. Both are independent miniature Lean tasks, never the upstream proofs themselves. diff --git a/gyms/RHProofDistillation/gold.jsonl b/gyms/RHProofDistillation/gold.jsonl index c447edfa..7fa938e9 100644 --- a/gyms/RHProofDistillation/gold.jsonl +++ b/gyms/RHProofDistillation/gold.jsonl @@ -4,3 +4,5 @@ {"id":"RH-D-004","proof":"by_contra hc\nhave hpos : 0 < (r - 1 / 2) / 2 := by linarith\nhave hbound := h ((r - 1 / 2) / 2) hpos\nlinarith"} {"id":"RH-D-005","proof":"rw [max_eq_left h]\nring"} {"id":"RH-D-006","proof":"have hB : 0 ≤ x ^ ((1 / 2 : ℝ) + (eD + eL + 6) * eps) :=\n Real.rpow_nonneg hx.le _\nhave hterm : K * x ^ ((1 / 2 : ℝ) + eps) ≤\n K * x ^ ((1 / 2 : ℝ) + (eD + eL + 6) * eps) :=\n mul_le_mul_of_nonneg_left hSmall hK\nhave hcomp : G ≤ (1 + K) * x ^ ((1 / 2 : ℝ) + (eD + eL + 6) * eps) := by\n nlinarith\nhave hcoeff := mul_le_mul_of_nonneg_right hErr hB\nhave hpow : x ^ eps * x ^ ((1 / 2 : ℝ) + (eD + eL + 6) * eps) =\n x ^ ((1 / 2 : ℝ) + (eD + eL + 7) * eps) := by\n rw [← Real.rpow_add hx]\n congr 1\n ring\nrw [hpow] at hcoeff\nexact le_trans hcomp hcoeff"} +{"id":"RH-D-007","proof":"constructor\n· intro h\n exact ⟨h.caraianiLocalGlobalDual, h.localLanglandsExists⟩\n· rintro ⟨hrow, hrec⟩\n exact ⟨hrow, hrec, hrow⟩"} +{"id":"RH-D-008","proof":"exact ⟨h.index, h.window, h.bounds⟩"} diff --git a/gyms/RHProofDistillation/tasks.json b/gyms/RHProofDistillation/tasks.json index de978130..7ee3090b 100644 --- a/gyms/RHProofDistillation/tasks.json +++ b/gyms/RHProofDistillation/tasks.json @@ -46,5 +46,21 @@ "anchor": "weighted_bound", "description": "Absorb the excluded-character term into one additional x^eps factor under explicit large-x and comparison hypotheses.", "template": "import Mathlib\n\nnamespace RHGym\n\ntheorem absorb_correction\n (x eps K eD eL G : ℝ) (hx : 0 < x) (hK : 0 ≤ K)\n (hErr : 1 + K ≤ x ^ eps)\n (hSmall : x ^ ((1 / 2 : ℝ) + eps) ≤\n x ^ ((1 / 2 : ℝ) + (eD + eL + 6) * eps))\n (hMain : G ≤ x ^ ((1 / 2 : ℝ) + (eD + eL + 6) * eps) +\n K * x ^ ((1 / 2 : ℝ) + eps)) :\n G ≤ x ^ ((1 / 2 : ℝ) + (eD + eL + 7) * eps) := by\n__PROOF__\n\nend RHGym\n" + }, + { + "id": "RH-D-007", + "difficulty": "medium", + "category": "source_structural_equivalence", + "anchor": "all_characters", + "description": "Prove the observed three-field OpenLiteratureStatements interface collapses to a row proposition and a local Langlands-existence proposition; two fields have the same row type in the upstream source.", + "template": "import Mathlib\n\nnamespace RHGym\n\nstructure OpenLiteratureProxy (Row RecTExists : Prop) : Prop where\n caraianiLocalGlobalDual : Row\n localLanglandsExists : RecTExists\n galoisRepOfPolarizedPairLit : Row\n\ntheorem open_literature_duplicate_row (Row RecTExists : Prop) :\n OpenLiteratureProxy Row RecTExists ↔ Row ∧ RecTExists := by\n__PROOF__\n\nend RHGym\n" + }, + { + "id": "RH-D-008", + "difficulty": "medium", + "category": "witness_transport", + "anchor": "weighted_bound", + "description": "Reconstruct the essential existential-witness projection used when ChainTied is reduced to a core-bound structure, with all geometric and arithmetic assertions treated as explicit variables.", + "template": "import Mathlib\n\nnamespace RHGym\n\nstructure ChainTiedProxy {I : Type} (TiePts TieGlobal CoreWindow CoreBounds : I → Prop) : Prop where\n index : I\n tiePoints : TiePts index\n tieGlobal : TieGlobal index\n window : CoreWindow index\n bounds : CoreBounds index\n\ndef CoreAtHProxy {I : Type} (CoreWindow CoreBounds : I → Prop) : Prop :=\n ∃ i : I, CoreWindow i ∧ CoreBounds i\n\ntheorem chain_tied_to_core {I : Type}\n {TiePts TieGlobal CoreWindow CoreBounds : I → Prop}\n (h : ChainTiedProxy TiePts TieGlobal CoreWindow CoreBounds) :\n CoreAtHProxy CoreWindow CoreBounds := by\n__PROOF__\n\nend RHGym\n" } ] From 19c558871ea02dcd2d96a5a836401a1e8e6b75fe Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 18:08:54 +0800 Subject: [PATCH 11/34] fix(rh): destruct existential witness in Prop rather than projecting Type --- gyms/RHProofDistillation/gold.jsonl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gyms/RHProofDistillation/gold.jsonl b/gyms/RHProofDistillation/gold.jsonl index 7fa938e9..2ec321ba 100644 --- a/gyms/RHProofDistillation/gold.jsonl +++ b/gyms/RHProofDistillation/gold.jsonl @@ -5,4 +5,4 @@ {"id":"RH-D-005","proof":"rw [max_eq_left h]\nring"} {"id":"RH-D-006","proof":"have hB : 0 ≤ x ^ ((1 / 2 : ℝ) + (eD + eL + 6) * eps) :=\n Real.rpow_nonneg hx.le _\nhave hterm : K * x ^ ((1 / 2 : ℝ) + eps) ≤\n K * x ^ ((1 / 2 : ℝ) + (eD + eL + 6) * eps) :=\n mul_le_mul_of_nonneg_left hSmall hK\nhave hcomp : G ≤ (1 + K) * x ^ ((1 / 2 : ℝ) + (eD + eL + 6) * eps) := by\n nlinarith\nhave hcoeff := mul_le_mul_of_nonneg_right hErr hB\nhave hpow : x ^ eps * x ^ ((1 / 2 : ℝ) + (eD + eL + 6) * eps) =\n x ^ ((1 / 2 : ℝ) + (eD + eL + 7) * eps) := by\n rw [← Real.rpow_add hx]\n congr 1\n ring\nrw [hpow] at hcoeff\nexact le_trans hcomp hcoeff"} {"id":"RH-D-007","proof":"constructor\n· intro h\n exact ⟨h.caraianiLocalGlobalDual, h.localLanglandsExists⟩\n· rintro ⟨hrow, hrec⟩\n exact ⟨hrow, hrec, hrow⟩"} -{"id":"RH-D-008","proof":"exact ⟨h.index, h.window, h.bounds⟩"} +{"id":"RH-D-008","proof":"rcases h with ⟨i, _, _, hw, hb⟩\nexact ⟨i, hw, hb⟩"} From 84feb123f2bff74c91a319e21ff24aaca5bd8a8a Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 18:11:51 +0800 Subject: [PATCH 12/34] fix(rh): model ChainTied witness as existential Prop instead of illegal projection structure --- gyms/RHProofDistillation/tasks.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gyms/RHProofDistillation/tasks.json b/gyms/RHProofDistillation/tasks.json index 7ee3090b..9fc99fe1 100644 --- a/gyms/RHProofDistillation/tasks.json +++ b/gyms/RHProofDistillation/tasks.json @@ -61,6 +61,6 @@ "category": "witness_transport", "anchor": "weighted_bound", "description": "Reconstruct the essential existential-witness projection used when ChainTied is reduced to a core-bound structure, with all geometric and arithmetic assertions treated as explicit variables.", - "template": "import Mathlib\n\nnamespace RHGym\n\nstructure ChainTiedProxy {I : Type} (TiePts TieGlobal CoreWindow CoreBounds : I → Prop) : Prop where\n index : I\n tiePoints : TiePts index\n tieGlobal : TieGlobal index\n window : CoreWindow index\n bounds : CoreBounds index\n\ndef CoreAtHProxy {I : Type} (CoreWindow CoreBounds : I → Prop) : Prop :=\n ∃ i : I, CoreWindow i ∧ CoreBounds i\n\ntheorem chain_tied_to_core {I : Type}\n {TiePts TieGlobal CoreWindow CoreBounds : I → Prop}\n (h : ChainTiedProxy TiePts TieGlobal CoreWindow CoreBounds) :\n CoreAtHProxy CoreWindow CoreBounds := by\n__PROOF__\n\nend RHGym\n" + "template": "import Mathlib\n\nnamespace RHGym\n\ndef ChainTiedProxy {I : Type} (TiePts TieGlobal CoreWindow CoreBounds : I → Prop) : Prop :=\n ∃ i : I, TiePts i ∧ TieGlobal i ∧ CoreWindow i ∧ CoreBounds i\n\ndef CoreAtHProxy {I : Type} (CoreWindow CoreBounds : I → Prop) : Prop :=\n ∃ i : I, CoreWindow i ∧ CoreBounds i\n\ntheorem chain_tied_to_core {I : Type}\n {TiePts TieGlobal CoreWindow CoreBounds : I → Prop}\n (h : ChainTiedProxy TiePts TieGlobal CoreWindow CoreBounds) :\n CoreAtHProxy CoreWindow CoreBounds := by\n__PROOF__\n\nend RHGym\n" } ] From fd4f6f784149d74401144211c12601bd6fb97283 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 19:02:24 +0800 Subject: [PATCH 13/34] research(rh): full pinned-source import closure and scoped CI audit --- .github/workflows/rh-full-closure.yml | 62 ++++++ .../FULL_SOURCE_IMPORT_CLOSURE.md | 22 ++ src/spiral_ln/rh_full_closure.py | 188 ++++++++++++++++++ tests/test_rh_full_closure.py | 39 ++++ 4 files changed, 311 insertions(+) create mode 100644 .github/workflows/rh-full-closure.yml create mode 100644 gyms/RHProofDistillation/FULL_SOURCE_IMPORT_CLOSURE.md create mode 100644 src/spiral_ln/rh_full_closure.py create mode 100644 tests/test_rh_full_closure.py diff --git a/.github/workflows/rh-full-closure.yml b/.github/workflows/rh-full-closure.yml new file mode 100644 index 00000000..d9a90745 --- /dev/null +++ b/.github/workflows/rh-full-closure.yml @@ -0,0 +1,62 @@ +name: RH full pinned import closure + +on: + push: + paths: + - 'src/spiral_ln/rh_full_closure.py' + - 'tests/test_rh_full_closure.py' + - 'gyms/RHProofDistillation/anchors.json' + - '.github/workflows/rh-full-closure.yml' + pull_request: + paths: + - 'src/spiral_ln/rh_full_closure.py' + - 'tests/test_rh_full_closure.py' + - 'gyms/RHProofDistillation/anchors.json' + - '.github/workflows/rh-full-closure.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + complete-source: + runs-on: ubuntu-latest + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + with: + path: evalmath + persist-credentials: false + - uses: actions/checkout@v4 + with: + repository: leanprover-community/riemann-hypothesis + ref: f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3 + path: upstream + persist-credentials: false + sparse-checkout: | + src + sparse-checkout-cone-mode: true + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Install EvalMath and run closure unit tests + working-directory: evalmath + run: | + python -m pip install -e '.[test]' + python -m pytest -q tests/test_rh_full_closure.py + - name: Count full pinned import dependencies for four anchors and Main + working-directory: evalmath + run: | + mkdir -p rh-full-closure + python -m spiral_ln.rh_full_closure \ + --source-root ../upstream \ + --roots weighted_bound all_characters theta_galois analytic_window \ + --include-main \ + --output rh-full-closure/closures.json + - name: Upload complete-source import graph receipt + if: always() + uses: actions/upload-artifact@v4 + with: + name: rh-full-import-closure + path: evalmath/rh-full-closure/ + if-no-files-found: ignore diff --git a/gyms/RHProofDistillation/FULL_SOURCE_IMPORT_CLOSURE.md b/gyms/RHProofDistillation/FULL_SOURCE_IMPORT_CLOSURE.md new file mode 100644 index 00000000..e3131ec5 --- /dev/null +++ b/gyms/RHProofDistillation/FULL_SOURCE_IMPORT_CLOSURE.md @@ -0,0 +1,22 @@ +# Full pinned-source import-closure experiment + +The [workflow](../../.github/workflows/rh-full-closure.yml) checks out the full original +Lean `src/` tree from the pinned commit, verifies six anchor Git blobs, +counts every `.lean` file and computes import closure sizes for +`core_gm`, `everyCharacter`, the theta-to-Galois row, the +Landau zero-free bound and the `Main` theorem. It also computes shortest +module-import paths to the other targets and pairwise overlaps. + +This is **source analysis**. `proof_term_data=false` in receipts. +A large import closure indicates the disk footprint and effort of selective +compiled `.olean` restoration. The number of files alone cannot determine +the compressed artifact size or establish that any source theorem uses its +entire module-import closure. + +Source: https://github.com/leanprover-community/riemann-hypothesis +Pin: `f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3` +Run: `python -m spiral_ln.rh_full_closure --source-root /path/to/full/mirror --include-main --output /tmp/full-closures.json` + +The resulting JSON is an independently reproducible import-graph receipt. A +compiled proof-expression run needs the upstream Lean v4.33.1 artifacts and +appropriate memory/disk; see [PINNED_UPSTREAM.md](PINNED_UPSTREAM.md). diff --git a/src/spiral_ln/rh_full_closure.py b/src/spiral_ln/rh_full_closure.py new file mode 100644 index 00000000..10b6b1ce --- /dev/null +++ b/src/spiral_ln/rh_full_closure.py @@ -0,0 +1,188 @@ +"""Measure complete, source-pinned Lean module import closures. + +This is a 175k-file source traversal. A module-import graph is not a graph of +proof-term references. Its purpose is to size selective .olean restoration and +find a concrete shortest module path from Main to core_gm. +""" +from __future__ import annotations + +import argparse +from collections import Counter, deque +from functools import lru_cache +import hashlib +import json +from pathlib import Path +import re +import subprocess +from typing import Iterable + +from spiral_ln.rh_distillation import anchor_audit, parse_imports + +ROOT = Path(__file__).resolve().parents[2] / "gyms" / "RHProofDistillation" +MODULE = re.compile(r"^[^\s/]+(?:\.[^\s/]+)*$", re.UNICODE) +INTERNAL = frozenset({ + "Statements", "Main", "Development", "Formalism", "GroundTheory", + "ReciprocityTheory", "CompanionTheory", "PositivityTheory", + "Lemmata", "Supplements", "BuildAid", "Challenge", +}) + + +def module_name(path: str) -> str: + if not path.startswith("src/") or not path.endswith(".lean"): + raise ValueError(f"invalid source path: {path}") + return path[len("src/"):-len(".lean")].replace("/", ".") + + +def module_file(src: Path, module: str) -> Path: + if not MODULE.fullmatch(module) or any(part in ("", ".", "..") for part in module.split(".")): + raise ValueError(f"invalid Lean module: {module!r}") + return src.joinpath(*module.split(".")).with_suffix(".lean") + + +def verify_full_checkout(root: Path, manifest: dict, minimum: int) -> dict: + head = subprocess.check_output(["git", "-C", str(root), "rev-parse", "HEAD"], text=True).strip() + if head != manifest["mirror_commit"]: + raise ValueError(f"pinned HEAD mismatch: {head}") + if minimum < 1: + raise ValueError("minimum file count must be positive") + count = sum(1 for _ in (root / "src").rglob("*.lean")) + if count < minimum: + raise ValueError(f"source checkout incomplete: {count} .lean files < {minimum}") + anchors = anchor_audit(root, manifest) + if any(a["status"] != "match" for a in anchors): + raise ValueError(f"source anchors differ: {anchors}") + return {"commit": head, "lean_files_checked_out": count, "anchors_matched": len(anchors)} + + +class ImportGraph: + def __init__(self, src: Path) -> None: + self.src = src + self.cached: dict[str, tuple[str, ...] | None] = {} + self.bytes: dict[str, int] = {} + + def imports(self, module: str) -> tuple[str, ...] | None: + if module not in self.cached: + f = module_file(self.src, module) + if f.is_file(): + data = f.read_bytes() + self.bytes[module] = len(data) + self.cached[module] = tuple(parse_imports(data.decode("utf-8"))) + else: + self.cached[module] = None + return self.cached[module] + + def closure(self, root: str, targets: Iterable[str] = ()) -> dict: + todo = deque([root]) + visited: set[str] = set() + queued: set[str] = {root} + parents: dict[str, str | None] = {root: None} + external: set[str] = set() + missing: set[str] = set() + import_edges = 0 + h = hashlib.sha256() + families: Counter[str] = Counter() + while todo: + mod = todo.popleft() + if mod in visited: + continue + deps = self.imports(mod) + if deps is None: + (missing if mod.split(".", 1)[0] in INTERNAL else external).add(mod) + continue + visited.add(mod) + families[mod.split(".", 1)[0]] += 1 + for dep in deps: + import_edges += 1 + h.update((mod + "\t" + dep + "\n").encode()) + if dep not in queued: + queued.add(dep) + parents[dep] = mod + todo.append(dep) + paths = {} + for target in targets: + if target not in visited: + paths[target] = None + continue + chain = [] + node = target + while node is not None: + chain.append(node) + node = parents[node] + paths[target] = chain[::-1] + return { + "root": root, "modules": len(visited), "import_edges": import_edges, + "module_source_bytes": sum(self.bytes[m] for m in visited), + "external_imports": sorted(external), + "unresolved_internal_imports": sorted(missing), + "family_counts": dict(sorted(families.items())), + "edge_stream_sha256": h.hexdigest(), + "paths": paths, + "module_set": visited, + } + + +def complete_graph(root: Path, manifest: dict, minimum: int, selected: list[str]) -> dict: + evidence = verify_full_checkout(root, manifest, minimum) + graph = ImportGraph(root / "src") + outputs = [] + for name in selected: + item = graph.closure(name, targets=selected) + output = {k: v for k, v in item.items() if k != "module_set"} + outputs.append(output) + overlap = [] + for i, a in enumerate(selected): + for b in selected[i + 1:]: + set_a = graph.closure(a)["module_set"] + set_b = graph.closure(b)["module_set"] + overlap.append({"left": a, "right": b, "shared_modules": len(set_a & set_b)}) + return { + "schema_version": 1, + "mode": "full_upstream_source_module_import_graph", + "proof_term_data": False, + "upstream_source": evidence, + "distinct_modules_parsed": sum(1 for x in graph.cached.values() if x is not None), + "roots": outputs, + "pairwise_overlap": overlap, + "cache_projection_note": ( + "Source module closure is only a lower-level prerequisite count. " + "Olean bytes, transitive proof constants, and archive fetch costs " + "must be measured separately." + ), + } + + +def main() -> None: + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--source-root", type=Path, required=True) + p.add_argument("--manifest", type=Path, default=ROOT / "anchors.json") + p.add_argument("--roots", nargs="+", default=["weighted_bound", "all_characters", "theta_galois", "analytic_window"]) + p.add_argument("--include-main", action="store_true") + p.add_argument("--minimum-files", type=int, default=175187) + p.add_argument("--output", type=Path, required=True) + args = p.parse_args() + manifest = json.loads(args.manifest.read_text(encoding="utf-8")) + ids = {x["id"]: module_name(x["path"]) for x in manifest["anchors"]} + invalid = [x for x in args.roots if x not in ids] + if invalid: + p.error(f"unknown anchor IDs: {invalid}") + selected = [ids[a] for a in args.roots] + if args.include_main and "Main" not in selected: + selected.append("Main") + if not selected: + p.error("provide at least one root") + result = complete_graph(args.source_root.resolve(), manifest, args.minimum_files, selected) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8") + print(json.dumps({ + "head": result["upstream_source"]["commit"], + "files": result["upstream_source"]["lean_files_checked_out"], + "parsed": result["distinct_modules_parsed"], + "roots": [{"root": x["root"], "modules": x["modules"], + "bytes": x["module_source_bytes"], "imports": x["import_edges"]} + for x in result["roots"]], + "proof_term_data": False, + }, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/tests/test_rh_full_closure.py b/tests/test_rh_full_closure.py new file mode 100644 index 00000000..ba736ba7 --- /dev/null +++ b/tests/test_rh_full_closure.py @@ -0,0 +1,39 @@ +from pathlib import Path + +import pytest +from spiral_ln.rh_full_closure import ImportGraph, module_name, module_file + + +def test_submodule_imports_and_shortest_path(tmp_path): + src = tmp_path / "src" + (src / "Development").mkdir(parents=True) + (src / "Main.lean").write_text("import Mathlib\nimport Development.A\n") + (src / "Development" / "A.lean").write_text("import Development.B\n") + (src / "Development" / "B.lean").write_text("theorem b : True := True.intro\n") + graph = ImportGraph(src) + r = graph.closure("Main", targets=["Development.B", "Unknown"]) + assert r["modules"] == 3 + assert r["import_edges"] == 3 + assert r["external_imports"] == ["Mathlib"] + assert r["paths"]["Development.B"] == ["Main", "Development.A", "Development.B"] + assert r["paths"]["Unknown"] is None + assert graph.imports("Development.B") == () + assert graph.closure("Development.A")["modules"] == 2 + + +def test_bad_module_name_rejected(tmp_path): + assert module_name("src/Development/Foo.lean") == "Development.Foo" + with pytest.raises(ValueError): + module_name("Development/Foo.lean") + for m in ("../evil", "A..B", "C/D"): + with pytest.raises(ValueError): + module_file(tmp_path, m) + + +def test_unresolved_internal_count(tmp_path): + src = tmp_path / "src" + src.mkdir() + (src / "Main.lean").write_text("import Development.Missing\n") + r = ImportGraph(src).closure("Main") + assert r["unresolved_internal_imports"] == ["Development.Missing"] + assert r["modules"] == 1 From 0f0554acdfcc3d35c89f73d61a37eee47b28eea7 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 19:06:40 +0800 Subject: [PATCH 14/34] feat(rh): restore only pinned compiled analytic modules and inspect real theorem expressions --- .github/workflows/rh-compiled-slice.yml | 75 +++++++ .../COMPILED_ANALYTIC_SLICE.md | 27 +++ src/spiral_ln/rh_selective_olean.py | 203 ++++++++++++++++++ tests/test_rh_selective_olean.py | 32 +++ 4 files changed, 337 insertions(+) create mode 100644 .github/workflows/rh-compiled-slice.yml create mode 100644 gyms/RHProofDistillation/COMPILED_ANALYTIC_SLICE.md create mode 100644 src/spiral_ln/rh_selective_olean.py create mode 100644 tests/test_rh_selective_olean.py diff --git a/.github/workflows/rh-compiled-slice.yml b/.github/workflows/rh-compiled-slice.yml new file mode 100644 index 00000000..4bad4a92 --- /dev/null +++ b/.github/workflows/rh-compiled-slice.yml @@ -0,0 +1,75 @@ +name: RH selective compiled proof-expression probe + +on: + push: + paths: + - 'src/spiral_ln/rh_selective_olean.py' + - 'src/spiral_ln/rh_dependency.py' + - 'src/spiral_ln/rh_full_closure.py' + - 'tests/test_rh_selective_olean.py' + - 'gyms/RHProofDistillation/anchors.json' + - '.github/workflows/rh-compiled-slice.yml' + pull_request: + paths: + - 'src/spiral_ln/rh_selective_olean.py' + - 'src/spiral_ln/rh_dependency.py' + - 'src/spiral_ln/rh_full_closure.py' + - 'tests/test_rh_selective_olean.py' + - 'gyms/RHProofDistillation/anchors.json' + - '.github/workflows/rh-compiled-slice.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + compiled-analytic-slice: + runs-on: ubuntu-latest + timeout-minutes: 80 + steps: + - uses: actions/checkout@v4 + with: + path: evalmath + persist-credentials: false + - uses: actions/checkout@v4 + with: + repository: leanprover-community/riemann-hypothesis + ref: f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3 + path: upstream + persist-credentials: false + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Install audit Python code + working-directory: evalmath + run: | + python -m pip install -e '.[test]' + python -m pytest -q tests/test_rh_selective_olean.py + - name: Install Lean version from upstream's original toolchain + run: | + curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh -o "$RUNNER_TEMP/elan-init.sh" + bash "$RUNNER_TEMP/elan-init.sh" -y --default-toolchain none + echo "$HOME/.elan/bin" >> "$GITHUB_PATH" + - name: Fetch official Mathlib cache without building the RH proof + working-directory: upstream + env: + MATHLIB_CACHE_GET_URL: https://cache.mathlib.org/mathlib4 + run: | + lake exe mathlib/cache get + df -h . + - name: Restore only the 30- and 115-module upstream analytic slices + working-directory: evalmath + run: | + mkdir -p rh-compiled-slice + python -m spiral_ln.rh_selective_olean \ + --source-root ../upstream \ + --anchors analytic_window weighted_bound \ + --max-modules 200 --max-depth 2 --max-nodes 120 \ + --output rh-compiled-slice/analytic-proof-refs.json + - name: Upload full compiled expression references + if: always() + uses: actions/upload-artifact@v4 + with: + name: rh-compiled-analytic-proof-refs + path: evalmath/rh-compiled-slice/ + if-no-files-found: ignore diff --git a/gyms/RHProofDistillation/COMPILED_ANALYTIC_SLICE.md b/gyms/RHProofDistillation/COMPILED_ANALYTIC_SLICE.md new file mode 100644 index 00000000..405997ba --- /dev/null +++ b/gyms/RHProofDistillation/COMPILED_ANALYTIC_SLICE.md @@ -0,0 +1,27 @@ +# Selective compiled proof-term inspection + +Source mirror pin: `f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3`. + +The complete original source graph has only 30 module imports on the Landau +`zeroFree_of_rpow_window` path and 115 on the analytic `core_gm` path. +The exact union is checked before restoration. + +The [rh-compiled-slice.yml](../../.github/workflows/rh-compiled-slice.yml) +workflow runs a source-attested, selective cache restore using +the upstream community's pinned `modules.jsonl.gz` manifest. +It fetches only the modules needed for the two target declarations, +verifies each published archive SHA-256, and restores with stock `leantar`. +It imports those modules using Lean 4.33.1 and reports direct constants +in theorem *types* and *proof bodies* separately. + +This is stronger evidence than the prior source-text call sites because +the actual published compiled Lean expressions are being inspected. +The archived compiled modules are the published proof output and do not +substitute for an independently rebuilt and checked full formalization. + +All source pin checks, cache manifest checks, artifact checks and +truncation flags are written in the JSON receipt. +An omitted or mismatched cache artifact stops the run rather than +silently substituting a new module. + +The large Galois and final-theorem paths require a separate runner. diff --git a/src/spiral_ln/rh_selective_olean.py b/src/spiral_ln/rh_selective_olean.py new file mode 100644 index 00000000..98401555 --- /dev/null +++ b/src/spiral_ln/rh_selective_olean.py @@ -0,0 +1,203 @@ +"""Restore a *small, source-pinned* subset of the RH published Lean cache. + +This uses the author's unlicensed source only from a temporary upstream +checkout. Published compiled artifacts are SHA-verified against the +community's pinned manifest, then imported by Lean v4.33.1 for direct +proof-expression references. This is a cache-derived inspection, NOT an +independent full clean build or a proof of RH. +""" +from __future__ import annotations + +import argparse +import gzip +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import urllib.request + +from spiral_ln.rh_dependency import build_probe, run_lean, pinned_mirror +from spiral_ln.rh_full_closure import ImportGraph, module_name + +BASE = Path(__file__).resolve().parents[2] / "gyms" / "RHProofDistillation" +CACHE_URL = ("https://rh-cache.taucetiproject.org/bootstrap/" + "e50d09817ad81469f737e8f637561e6ccf86c670/modules.jsonl.gz") +MANIFEST_SHA256 = "292caa386a620d935cfc736b56fcceaab9fe7073086693b62e899c1ee4725f04" +REPOSITORY = "leanprover-community/riemann-hypothesis" +MAP_FORMAT = "2026-03-17" + + +def load_restore_script(root: Path): + script = root / "scripts" / "restore-cache.py" + if not script.is_file(): + raise ValueError("missing original community cache verifier") + spec = importlib.util.spec_from_file_location("rh_community_cache_restorer", script) + if spec is None or spec.loader is None: + raise ValueError("could not load community cache verifier") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + if module.MANIFEST_SHA256 != MANIFEST_SHA256 or module.URL != CACHE_URL: + raise ValueError("cache verifier manifest identity changed") + return module + + +def verified_manifest(restorer, *, raw: bytes | None = None) -> list[list[str]]: + if raw is None: + request = urllib.request.Request(CACHE_URL, headers={"User-Agent": "EvalMath-RH-Distillation/1.0"}) + with urllib.request.urlopen(request, timeout=90) as response: + raw = response.read(64 * 1024 * 1024 + 1) + if len(raw) > 64 * 1024 * 1024: + raise ValueError("pinned cache manifest exceeded 64 MiB limit") + if hashlib.sha256(raw).hexdigest() != MANIFEST_SHA256: + raise ValueError("pinned manifest SHA256 mismatch") + return restorer.manifest_rows(raw) + + +def selected_rows(rows: list[list[str]], modules: set[str]) -> list[list[str]]: + found: dict[str, list[str]] = {} + for row in rows: + name = row[0] + if name in modules: + if name in found: + raise ValueError(f"duplicate pinned artifact for {name}") + found[name] = row + missing = sorted(modules - set(found)) + if missing: + raise ValueError(f"missing compiled upstream modules: {missing[:12]}") + return [found[name] for name in sorted(modules)] + + +def cache_map(rows: list[list[str]]) -> str: + """Stock Lake mapping file for the exact selected input/artifact pairs.""" + lines = [json.dumps(MAP_FORMAT)] + lines.extend(json.dumps([entry[1], entry[2]], separators=(",", ":")) for entry in rows) + return "\n".join(lines) + "\n" + + +def assure_disk(root: Path, count: int, max_modules: int, min_free_gib: int) -> int: + if count == 0 or count > max_modules: + raise ValueError(f"subset size {count} exceeds allowed 1..{max_modules}") + free = shutil.disk_usage(root).free + if free < min_free_gib * 1024**3: + raise ValueError(f"only {free} bytes free; required {min_free_gib} GiB") + return free + + +def restore_subset(root: Path, rows: list[list[str]], restorer, *, workers: int = 4) -> dict: + """Fetch and verify ONLY requested cache artifacts, then stock-leantar extract.""" + cache = root / ".lake" / "cache" + cache.mkdir(parents=True, exist_ok=True) + free_before = assure_disk(root, len(rows), max_modules=600, min_free_gib=7) + mapping = root / ".lake" / "rh-subset-outputs.jsonl" + mapping.write_text(cache_map(rows), encoding="utf-8") + env = os.environ.copy() + for key in list(env): + if key.startswith(("AWS_", "CLOUDFLARE_", "CF_")) or key in ("LAKE_CACHE_KEY", "GITHUB_TOKEN", "GH_TOKEN"): + env.pop(key) + env.update(LAKE_CONFIG=str(root / "lakefile.toml"), LAKE_CACHE_DIR=str(cache), + LAKE_ARTIFACT_CACHE="true", LAKE_RESTORE_ARTIFACTS="true", + ELAN_TOOLCHAIN="leanprover/lean4:v4.33.1", LEAN_ABORT_ON_PANIC="1") + subprocess.run(["lake", "-q", "cache", "get", str(mapping), + "--repo", REPOSITORY], cwd=root, env=env, + check=True, timeout=1200) + jobs = restorer.restore_jobs(root, cache, rows) + for job in jobs: + for base in job["base"]: + Path(base).mkdir(parents=True, exist_ok=True) + env["RUST_MIN_STACK"] = str(max(int(env.get("RUST_MIN_STACK", "0")), 8388608)) + lean = Path(subprocess.check_output(["elan", "which", "lean"], cwd=root, + env=env, text=True).strip()) + subprocess.run([str(lean.with_name("leantar")), "--jobs", str(workers), + "-f", "-x", "-j", "-"], input=json.dumps(jobs), + cwd=root, env=env, text=True, check=True, timeout=900) + free_after = shutil.disk_usage(root).free + return {"modules_restored": len(rows), "free_before": free_before, + "free_after": free_after, "manifest_sha256": MANIFEST_SHA256, + "artifacts_hash_checked": len(rows), "cache_source": CACHE_URL} + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source-root", type=Path, required=True) + parser.add_argument("--anchors", nargs="+", default=["analytic_window", "weighted_bound"]) + parser.add_argument("--max-modules", type=int, default=600) + parser.add_argument("--max-depth", type=int, default=2) + parser.add_argument("--max-nodes", type=int, default=120) + parser.add_argument("--workers", type=int, default=4) + parser.add_argument("--timeout", type=int, default=600) + parser.add_argument("--plan-only", action="store_true") + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + root = args.source_root.resolve() + manifest = json.loads((BASE / "anchors.json").read_text(encoding="utf-8")) + identity = pinned_mirror(root, manifest) + ids = {a["id"]: a for a in manifest["anchors"]} + if any(key not in ids for key in args.anchors): + parser.error(f"unknown anchor: {args.anchors}") + anchors = [ids[key] for key in args.anchors] + graph = ImportGraph(root / "src") + modules = set() + closures = {} + for anchor in anchors: + module = module_name(anchor["path"]) + result = graph.closure(module) + if result["unresolved_internal_imports"]: + raise ValueError(f"source closure missing internal imports: {result['unresolved_internal_imports'][:10]}") + modules.update(result["module_set"]) + closures[anchor["id"]] = {"module": module, "closure_modules": result["modules"], + "edge_stream_sha256": result["edge_stream_sha256"]} + # Cache material is read only after confirming that the target slice is bounded. + if not modules or len(modules) > args.max_modules: + raise ValueError(f"union of source modules {len(modules)} > cap {args.max_modules}") + restorer = load_restore_script(root) + all_rows = verified_manifest(restorer) + rows = selected_rows(all_rows, modules) + receipt = { + "schema": 1, "source_commit": identity["commit"], + "source_anchors_matched": identity["six_anchors_match"], + "source_closures": closures, + "required_modules": len(rows), + "cache_manifest_sha256": MANIFEST_SHA256, + "published_cache_verifier": "original upstream scripts/restore-cache.py", + "proof_term_data": False, + "environment": "upstream Lean 4.33.1 compiled cache", + "verification_scope": "published-cache bytes; independent rebuild out of scope", + } + if args.plan_only: + receipt["status"] = "validated_cache_plan" + else: + assure_disk(root, len(rows), args.max_modules, min_free_gib=7) + receipt["restore"] = restore_subset(root, rows, restorer, workers=args.workers) + dependencies = {} + for anchor in anchors: + import_module = module_name(anchor["path"]) + src = build_probe([import_module], [anchor["declaration"]], + depth=args.max_depth, max_nodes=args.max_nodes, + prefixes=["UpperTheory.", "Deduction.", "Formalism."]) + result = run_lean(src, root, timeout=args.timeout) + proof_root = next((n for n in result["nodes"] if n["name"] == anchor["declaration"]), None) + if proof_root is None or proof_root["kind"] == "missing": + raise RuntimeError(f"source-pinned theorem not present in compiled env: {anchor['declaration']}") + result["source_anchor"] = anchor["id"] + dependencies[anchor["id"]] = result + receipt["proofs"] = dependencies + receipt["proof_term_data"] = True + receipt["status"] = "source_pinned_compiled_proof_expression" + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", + encoding="utf-8") + print(json.dumps({"status": receipt["status"], "source_commit": receipt["source_commit"], + "required_modules": receipt["required_modules"], + "proof_term_data": receipt["proof_term_data"], + "roots": {k: v["source_closures"] if False else v["closure_modules"] + for k, v in closures.items()} if False else + {k: v["closure_modules"] for k, v in closures.items()}}, + sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/tests/test_rh_selective_olean.py b/tests/test_rh_selective_olean.py new file mode 100644 index 00000000..da745005 --- /dev/null +++ b/tests/test_rh_selective_olean.py @@ -0,0 +1,32 @@ +"""Offline tests for the selective published-cache manifest contract.""" +import json +import pytest + +from spiral_ln.rh_selective_olean import selected_rows, cache_map, assure_disk + + +def test_selects_exact_subset_in_stable_order(): + rows = [["B", "b" * 16, "c" * 16 + ".ltar", "d" * 64], + ["A", "a" * 16, "e" * 16 + ".ltar", "f" * 64]] + chosen = selected_rows(rows, {"A"}) + assert chosen[0][0] == "A" + assert cache_map(chosen).splitlines() == [ + json.dumps("2026-03-17"), + json.dumps([chosen[0][1], chosen[0][2]], separators=(",", ":")), + ] + + +def test_missing_or_duplicate_cache_rows_fail(): + a = ["A", "a" * 16, "b" * 16 + ".ltar", "c" * 64] + with pytest.raises(ValueError, match="missing compiled"): + selected_rows([a], {"B"}) + with pytest.raises(ValueError, match="duplicate"): + selected_rows([a, a], {"A"}) + + +def test_disk_and_count_guards(tmp_path): + assert assure_disk(tmp_path, 2, max_modules=3, min_free_gib=0) > 0 + with pytest.raises(ValueError, match="exceeds"): + assure_disk(tmp_path, 9, max_modules=3, min_free_gib=0) + with pytest.raises(ValueError, match="required"): + assure_disk(tmp_path, 1, max_modules=2, min_free_gib=10**6) From 8939b7fc40a31ad0ab39da352580d33dc6194c3a Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 19:10:34 +0800 Subject: [PATCH 15/34] fix(rh): resolve namespaced analytic Landau theorem in compiled cache probe --- src/spiral_ln/rh_selective_olean.py | 13 +++++++------ tests/test_rh_selective_olean.py | 5 +++++ 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/spiral_ln/rh_selective_olean.py b/src/spiral_ln/rh_selective_olean.py index 98401555..ee70485d 100644 --- a/src/spiral_ln/rh_selective_olean.py +++ b/src/spiral_ln/rh_selective_olean.py @@ -29,6 +29,8 @@ MANIFEST_SHA256 = "292caa386a620d935cfc736b56fcceaab9fe7073086693b62e899c1ee4725f04" REPOSITORY = "leanprover-community/riemann-hypothesis" MAP_FORMAT = "2026-03-17" +# The source anchor is spelled within a namespace; the elaborated constant is fully qualified. +COMPILED_DECLARATIONS = {"analytic_window": "Deduction.zeroFree_of_rpow_window"} def load_restore_script(root: Path): @@ -175,13 +177,14 @@ def main() -> None: dependencies = {} for anchor in anchors: import_module = module_name(anchor["path"]) - src = build_probe([import_module], [anchor["declaration"]], + compiled_name = COMPILED_DECLARATIONS.get(anchor["id"], anchor["declaration"]) + src = build_probe([import_module], [compiled_name], depth=args.max_depth, max_nodes=args.max_nodes, prefixes=["UpperTheory.", "Deduction.", "Formalism."]) result = run_lean(src, root, timeout=args.timeout) - proof_root = next((n for n in result["nodes"] if n["name"] == anchor["declaration"]), None) + proof_root = next((n for n in result["nodes"] if n["name"] == compiled_name), None) if proof_root is None or proof_root["kind"] == "missing": - raise RuntimeError(f"source-pinned theorem not present in compiled env: {anchor['declaration']}") + raise RuntimeError(f"source-pinned theorem not present in compiled env: {compiled_name}") result["source_anchor"] = anchor["id"] dependencies[anchor["id"]] = result receipt["proofs"] = dependencies @@ -193,9 +196,7 @@ def main() -> None: print(json.dumps({"status": receipt["status"], "source_commit": receipt["source_commit"], "required_modules": receipt["required_modules"], "proof_term_data": receipt["proof_term_data"], - "roots": {k: v["source_closures"] if False else v["closure_modules"] - for k, v in closures.items()} if False else - {k: v["closure_modules"] for k, v in closures.items()}}, + "roots": {k: v["closure_modules"] for k, v in closures.items()}}, sort_keys=True)) diff --git a/tests/test_rh_selective_olean.py b/tests/test_rh_selective_olean.py index da745005..6dbe65cf 100644 --- a/tests/test_rh_selective_olean.py +++ b/tests/test_rh_selective_olean.py @@ -30,3 +30,8 @@ def test_disk_and_count_guards(tmp_path): assure_disk(tmp_path, 9, max_modules=3, min_free_gib=0) with pytest.raises(ValueError, match="required"): assure_disk(tmp_path, 1, max_modules=2, min_free_gib=10**6) + + +def test_analytic_declaration_uses_lean_namespace(): + from spiral_ln.rh_selective_olean import COMPILED_DECLARATIONS + assert COMPILED_DECLARATIONS['analytic_window'] == 'Deduction.zeroFree_of_rpow_window' From 7f73dab9afec0b20fe3ec6988e0cef1d5efd9ed5 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 19:15:53 +0800 Subject: [PATCH 16/34] research(rh): record hash-pinned actual compiled proof dependencies for analytic core --- .../COMPILED_ANALYTIC_RESULTS.md | 80 +++++++++++++++++ .../compiled_analytic_direct_refs.json | 86 +++++++++++++++++++ 2 files changed, 166 insertions(+) create mode 100644 gyms/RHProofDistillation/COMPILED_ANALYTIC_RESULTS.md create mode 100644 gyms/RHProofDistillation/compiled_analytic_direct_refs.json diff --git a/gyms/RHProofDistillation/COMPILED_ANALYTIC_RESULTS.md b/gyms/RHProofDistillation/COMPILED_ANALYTIC_RESULTS.md new file mode 100644 index 00000000..d5e41995 --- /dev/null +++ b/gyms/RHProofDistillation/COMPILED_ANALYTIC_RESULTS.md @@ -0,0 +1,80 @@ +# RH analytic proof references extracted from the original compiled Lean artifacts + +**Source pin:** `leanprover-community/riemann-hypothesis` commit +`f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3`. + +**Execution:** [successful compiled-reference workflow](https://github.com/MoralityLabAI/EvalMath/actions/runs/44897842450); +[raw graph artifact](https://github.com/MoralityLabAI/EvalMath/actions/runs/44897842450/artifacts/14704960346). +Raw JSON SHA-256: `b193e16ce3d824008b5b17217a282c174cd45c0cbefa53d9bf3c2f0852570093`. + +Lean v4.33.1 loaded **143** selected project modules after the +community's original published cache manifest and each selected archive +passed SHA-256 verification. The six source anchors also matched the +pinned source. The workflow imported the *actual upstream compiled* +theorem constants and read both type and proof expressions. + +## Verified theorem-value references + +| Root | Direct proof-value constants | Expanded nodes | Scope | +| --- | ---: | ---: | --- | +| `Deduction.zeroFree_of_rpow_window` | 30 | 22 | Depth-2 limited; node budget not exhausted | +| `UpperTheory.Comparison₂.core_gm` | 424 | 120 | Node budget exhausted at 120 of 403 queued | + +From the **actual elaborated proof of `core_gm`**, six key +named mathematical theorem constants are directly referenced: +`Deduction.ch_core`, `Deduction.ch_top`, +`UpperTheory.Comparison₂.charsA`, +`UpperTheory.Comparison₂.gmA_eq`, +`UpperTheory.Comparison₂.sigA_le`, and +`UpperTheory.Comparison₂.hostFactsS`. +Other directly used theorems include +`Formalism.LFunctionChainParameters.LErr.large_x_eventually` +and autogenerated proof fields of the error-window predicates. + +At the next observed hop, `ch_core` references +`Deduction.CharacterBalanceMoves.core`, +`Formalism.LFunctionChainParameters.ThickSetMeanBounds.proposition_size_bound`, +and `derivative_integral_all` in the same namespace. +`ch_top` references `Deduction.ch_top_main_eq`, +`Formalism.LFunctionChainParameters.WeightedSlopeBounds.each_unit_bound_statement`, +and `Formalism.LFunctionChainParameters.LChain.errX5at_le`. + +The **Landau window proof** directly references `Deduction.lemmaL` +and `Deduction.windowHyp_of_rpow`. The compiled `lemmaL` +proof then refers to `Deduction.landau_window`, +`Deduction.windowHypU_of_windowHyp`, and +`Deduction.charFamily_LFunction_ne_zero_of_one_le_re`. + +The compact machine-readable record is +[compiled_analytic_direct_refs.json](compiled_analytic_direct_refs.json). +It preserves the module counts, cache identities, direct theorem references, +root cardinalities and truncation indicators. The full 1.4 MB expression +graph remains in the workflow artifact. + +## Limits + +The graph proves **syntactic occurrence of constants in Lean's original +compiled proof expressions**. It does not establish their minimal +mathematical necessity. The analytic excerpt is far smaller than the +66,168-module Galois-row import closure and the 175,184-module full +`Main` closure. + +The `core_gm` two-hop expansion was truncated by its 120-node limit. +The direct root references above were captured in full; deeper nodes +need a wider bounded probe. The separate mathematical validity of +the global argument is outside this targeted extraction. + +## Reproduction + +Run `rh-compiled-slice.yml` on the PR. For a standalone replay: + +```sh +python -m spiral_ln.rh_selective_olean \ + --source-root /path/to/pinned/riemann-hypothesis \ + --anchors analytic_window weighted_bound \ + --max-modules 200 --max-depth 2 --max-nodes 120 \ + --output analytic-proof-refs.json +``` + +Published artifacts are intentionally downloaded to an ephemeral checkout +and left out of the EvalMath source tree. diff --git a/gyms/RHProofDistillation/compiled_analytic_direct_refs.json b/gyms/RHProofDistillation/compiled_analytic_direct_refs.json new file mode 100644 index 00000000..ad54a35b --- /dev/null +++ b/gyms/RHProofDistillation/compiled_analytic_direct_refs.json @@ -0,0 +1,86 @@ +{ + "schema_version": 1, + "kind": "published_compiled_Lean_expression_direct_refs", + "scope": "two analytic theorem roots only; bounded breadth-first reference expansion", + "source_commit": "f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3", + "evalmath_source_commit": "8939b7fc40a31ad0ab39da352580d33dc6194c3a", + "run_url": "https://github.com/MoralityLabAI/EvalMath/actions/runs/44897842450", + "raw_artifact_url": "https://github.com/MoralityLabAI/EvalMath/actions/runs/44897842450/artifacts/14704960346", + "raw_json_sha256": "b193e16ce3d824008b5b17217a282c174cd45c0cbefa53d9bf3c2f0852570093", + "source_anchors_matched": 6, + "selected_cache_modules": 143, + "selected_cache_artifact_sha256s_verified": 143, + "published_manifest_sha256": "292caa386a620d935cfc736b56fcceaab9fe7073086693b62e899c1ee4725f04", + "proof_term_data": true, + "roots": [ + { + "id": "analytic_window", + "lean_constant": "Deduction.zeroFree_of_rpow_window", + "import_closure_modules": 30, + "direct_type_refs": 29, + "direct_value_refs": 30, + "visited_nodes": 22, + "emitted_edges": 2139, + "truncated": false, + "depth_limited": true, + "observed_direct_theorem_value_refs": [ + "Deduction.lemmaL", + "Deduction.windowHyp_of_rpow" + ], + "verified_second_hop_references": { + "Deduction.lemmaL": [ + "Deduction.landau_window", + "Deduction.windowHypU_of_windowHyp", + "Deduction.charFamily_LFunction_ne_zero_of_one_le_re" + ], + "Deduction.windowHyp_of_rpow": [ + "Deduction.windowHyp_of_rpow_eventually" + ] + } + }, + { + "id": "weighted_bound", + "lean_constant": "UpperTheory.Comparison₂.core_gm", + "import_closure_modules": 115, + "direct_type_refs": 40, + "direct_value_refs": 424, + "visited_nodes": 120, + "emitted_edges": 5621, + "queued_nodes": 403, + "truncated": true, + "depth_limited": true, + "observed_direct_theorem_value_refs": [ + "Deduction.ch_core", + "Formalism.LFunctionChainParameters.LErr.large_x_eventually", + "Formalism.LFunctionChainParameters.LErr.ErrWindows._proof_1", + "Formalism.LFunctionChainParameters.LErr.ErrWindows0._proof_1", + "Formalism.LFunctionChainParameters.LErr.CErr._proof_1", + "Formalism.LFunctionChainParameters.LErr.KBig._proof_1", + "UpperTheory.Comparison₂.hostFactsS", + "UpperTheory.Comparison₂.charsA", + "Deduction.ch_top", + "UpperTheory.Comparison₂.sigA_le", + "UpperTheory.Comparison₂.gmA_eq" + ], + "verified_second_hop_references": { + "Deduction.ch_core": [ + "Formalism.LFunctionChainParameters.ThickSetMeanBounds.derivative_integral_all", + "Deduction.CharacterBalanceMoves.core", + "Formalism.LFunctionChainParameters.ThickSetMeanBounds.proposition_size_bound" + ], + "Deduction.ch_top": [ + "Deduction.ch_top_main_eq", + "Formalism.LFunctionChainParameters.WeightedSlopeBounds.each_unit_bound_statement", + "Formalism.LFunctionChainParameters.LChain.errX5at_le" + ] + } + } + ], + "caveats": [ + "Observed direct value references are not mathematically necessary lemmas.", + "Theorem-ref lists cover project theorems classified among visited nodes; root value_refs also include definitions, lemmas and Mathlib tactics.", + "The core_gm graph reached its max_nodes=120 limit and is incomplete at depth two.", + "The Landau graph reached depth 2 with depth_limited=true.", + "Published cache is SHA-verified but not independently rebuilt by this run." + ] +} From fcb2173f1ffe0839688c7d0eb9c8044dbe1a1c6b Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 19:27:42 +0800 Subject: [PATCH 17/34] feat(rh): compiled proof-term drilldown for character balance and size bound --- .github/workflows/rh-chcore-proofrefs.yml | 70 ++++++++ .../CHCORE_DEEP_EXTRACTION.md | 29 ++++ src/spiral_ln/rh_deep_analytic.py | 150 ++++++++++++++++++ tests/test_rh_deep_analytic.py | 38 +++++ 4 files changed, 287 insertions(+) create mode 100644 .github/workflows/rh-chcore-proofrefs.yml create mode 100644 gyms/RHProofDistillation/CHCORE_DEEP_EXTRACTION.md create mode 100644 src/spiral_ln/rh_deep_analytic.py create mode 100644 tests/test_rh_deep_analytic.py diff --git a/.github/workflows/rh-chcore-proofrefs.yml b/.github/workflows/rh-chcore-proofrefs.yml new file mode 100644 index 00000000..873de42a --- /dev/null +++ b/.github/workflows/rh-chcore-proofrefs.yml @@ -0,0 +1,70 @@ +name: RH ChCore deep compiled-reference probe + +on: + push: + paths: + - 'src/spiral_ln/rh_deep_analytic.py' + - 'tests/test_rh_deep_analytic.py' + - '.github/workflows/rh-chcore-proofrefs.yml' + pull_request: + paths: + - 'src/spiral_ln/rh_deep_analytic.py' + - 'tests/test_rh_deep_analytic.py' + - '.github/workflows/rh-chcore-proofrefs.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + compiled-chcore: + runs-on: ubuntu-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + with: + path: evalmath + persist-credentials: false + - uses: actions/checkout@v4 + with: + repository: leanprover-community/riemann-hypothesis + ref: f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3 + path: upstream + persist-credentials: false + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Install gym and test ChCore parser contracts + working-directory: evalmath + run: | + python -m pip install -e '.[test]' + python -m pytest -q tests/test_rh_deep_analytic.py + - name: Install Lean from the pinned upstream toolchain + run: | + curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh -o "$RUNNER_TEMP/elan-init.sh" + bash "$RUNNER_TEMP/elan-init.sh" -y --default-toolchain none + echo "$HOME/.elan/bin" >> "$GITHUB_PATH" + - name: Restore official Mathlib cache + working-directory: upstream + env: + MATHLIB_CACHE_GET_URL: https://cache.mathlib.org/mathlib4 + run: | + lake exe mathlib/cache get + df -h . + - name: Probe original CharacterBalanceMoves.core and proposition_size_bound + working-directory: evalmath + run: | + mkdir -p rh-chcore-proofrefs + python -m spiral_ln.rh_deep_analytic \ + --source-root ../upstream \ + --targets balance_core size_bound \ + --max-modules 200 --max-depth 1 --max-nodes 120 \ + --output rh-chcore-proofrefs/proofref_graph.json \ + --summary rh-chcore-proofrefs/summary.json + - name: Upload source-pinned compiled proof-reference receipts + if: always() + uses: actions/upload-artifact@v4 + with: + name: rh-chcore-compiled-ref-graph + path: evalmath/rh-chcore-proofrefs/ + if-no-files-found: ignore diff --git a/gyms/RHProofDistillation/CHCORE_DEEP_EXTRACTION.md b/gyms/RHProofDistillation/CHCORE_DEEP_EXTRACTION.md new file mode 100644 index 00000000..ae5491c7 --- /dev/null +++ b/gyms/RHProofDistillation/CHCORE_DEEP_EXTRACTION.md @@ -0,0 +1,29 @@ +# ChCore deep compiled-reference extraction + +The prior successful compiled proof graph [run 44897842450](https://github.com/MoralityLabAI/EvalMath/actions/runs/44897842450) +identified two especially important references inside `Deduction.ch_core`: + +- `Deduction.CharacterBalanceMoves.core`, which averages the pointwise + kernel error over a finite subgroup and cancels a strictly positive + subgroup cardinality. +- `Formalism.LFunctionChainParameters.ThickSetMeanBounds.proposition_size_bound`, + which turns the supplied size-window constraints into the characteristic + square-root exponent estimate. + +This [follow-up workflow](../../.github/workflows/rh-chcore-proofrefs.yml) +imports the pinned source module +`Development.AutomorphicArithmetic.DedekindLFunctions.LandauTheorems.ChCore`. +It verifies the actual source Git blob +`878f5077bc382426c7da988e5a375b85deeaa7de` +and six previously pinned anchor blobs. Only the import closure required by +this source module is downloaded from the SHA-pinned published compiled cache. + +The lean4 expression reader retrieves separate type and proof-value constant +references for both theorems. The output labels truncation at the selected +node/depth limits. **Compiled artifacts from a verified public cache are +evidence about the published Lean submission, not an independent new proof +of RH or a clean rebuild.** + +The workflow writes `proofref_graph.json` and `summary.json` and uploads +both with a GitHub Actions artifact. Inspect the cache and source identity in +the receipt before using references as benchmarks. diff --git a/src/spiral_ln/rh_deep_analytic.py b/src/spiral_ln/rh_deep_analytic.py new file mode 100644 index 00000000..0d4b7def --- /dev/null +++ b/src/spiral_ln/rh_deep_analytic.py @@ -0,0 +1,150 @@ +"""Source-pinned Lean 4.33.1 proof-expression probe for character-balance bottlenecks. + +Direct references in elaborated terms are machine evidence about the published +compiled artifact. They are not proof minimization or independent kernel replay. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path + +from spiral_ln.rh_dependency import build_probe, pinned_mirror, run_lean +from spiral_ln.rh_distillation import git_blob_sha +from spiral_ln.rh_full_closure import ImportGraph +from spiral_ln.rh_selective_olean import ( + assure_disk, load_restore_script, restore_subset, selected_rows, verified_manifest, +) + +BASE = Path(__file__).resolve().parents[2] / "gyms" / "RHProofDistillation" +SOURCE = "src/Development/AutomorphicArithmetic/DedekindLFunctions/LandauTheorems/ChCore.lean" +IMPORT = "Development.AutomorphicArithmetic.DedekindLFunctions.LandauTheorems.ChCore" +SOURCE_BLOB = "878f5077bc382426c7da988e5a375b85deeaa7de" +TARGETS = { + "balance_core": { + "constant": "Deduction.CharacterBalanceMoves.core", + "source_marker": "lemma core (A0", + }, + "size_bound": { + "constant": "Formalism.LFunctionChainParameters.ThickSetMeanBounds.proposition_size_bound", + "source_marker": "proposition_size_bound", + }, +} + + +def validate_source(root: Path, manifest: dict) -> dict: + identity = pinned_mirror(root, manifest) + raw = (root / SOURCE).read_bytes() + if git_blob_sha(raw) != SOURCE_BLOB: + raise ValueError("ChCore source Git blob differs from pinned release") + body = raw.decode("utf-8") + if "namespace CharacterBalanceMoves" not in body: + raise ValueError("CharacterBalanceMoves namespace absent") + if any(spec["source_marker"] not in body for spec in TARGETS.values()): + raise ValueError("target theorem source markers absent") + return {"commit": identity["commit"], "six_anchor_blobs_match": True, + "ChCore_git_blob": SOURCE_BLOB, + "ChCore_sha256": hashlib.sha256(raw).hexdigest()} + + +def compact_summary(result: dict) -> dict: + roots = {} + for key, graph in result.get("graphs", {}).items(): + name = TARGETS[key]["constant"] + items = {n["name"]: n for n in graph["nodes"]} + node = items[name] + names = set(node["value_refs"]) + roots[key] = { + "root": name, + "root_kind": node["kind"], + "type_ref_count": len(node["type_refs"]), + "proof_value_ref_count": len(node["value_refs"]), + "direct_theorem_refs": sorted(n for n in names if n in items and items[n]["kind"] == "theorem"), + "visited": graph["scope"]["visited"], + "truncated": graph["scope"]["truncated"], + "depth_limited": graph["scope"]["depth_limited"], + "queued": graph["scope"]["queued"], + } + return {"status": result["status"], "proof_term_data": result["proof_term_data"], + "module_count": result["module_count"], + "source_commit": result["source"]["commit"], + "roots": roots} + + +def run(root: Path, manifest: dict, selected: list[str], *, max_depth: int, + max_nodes: int, max_modules: int, timeout: int, plan_only: bool) -> dict: + if not selected or any(k not in TARGETS for k in selected): + raise ValueError("invalid or empty target selection") + if max_nodes < 1 or max_depth < 0: + raise ValueError("invalid proof-reference traversal bounds") + identity = validate_source(root, manifest) + module_graph = ImportGraph(root / "src").closure(IMPORT) + if module_graph["unresolved_internal_imports"]: + raise ValueError(f"missing source modules: {module_graph['unresolved_internal_imports'][:10]}") + modules = module_graph["module_set"] + if not 0 < len(modules) <= max_modules: + raise ValueError(f"invalid target module closure: {len(modules)}") + verifier = load_restore_script(root) + manifest_rows = verified_manifest(verifier) + rows = selected_rows(manifest_rows, modules) + receipt = { + "schema": 1, "source": identity, "source_module": IMPORT, + "module_count": len(rows), "source_import_edge_sha256": module_graph["edge_stream_sha256"], + "selected_targets": selected, "proof_term_data": False, + "compiled_cache": "pinned public Lean 4.33.1 artifacts", + "trust_boundary": "Published cache verification, not independently rebuilt solution", + } + if plan_only: + receipt["status"] = "source_and_cache_plan_verified" + return receipt + assure_disk(root, len(rows), max_modules=max_modules, min_free_gib=7) + receipt["restore"] = restore_subset(root, rows, verifier, workers=4) + graphs = {} + for key in selected: + target = TARGETS[key]["constant"] + script = build_probe( + [IMPORT], [target], depth=max_depth, max_nodes=max_nodes, + prefixes=["Deduction.", "Formalism."], + ) + extracted = run_lean(script, root, timeout=timeout) + root_node = next((n for n in extracted["nodes"] if n["name"] == target), None) + if root_node is None or root_node["kind"] != "theorem": + raise ValueError(f"compiled target was not found as theorem: {target}") + if not root_node["value_refs"]: + raise ValueError(f"compiled proof value is unexpectedly empty: {target}") + graphs[key] = extracted + receipt["graphs"] = graphs + receipt["proof_term_data"] = True + receipt["status"] = "source_pinned_compiled_reference_graph" + return receipt + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source-root", type=Path, required=True) + parser.add_argument("--targets", nargs="+", choices=sorted(TARGETS), default=list(TARGETS)) + parser.add_argument("--max-depth", type=int, default=1) + parser.add_argument("--max-nodes", type=int, default=120) + parser.add_argument("--max-modules", type=int, default=200) + parser.add_argument("--timeout", type=int, default=600) + parser.add_argument("--plan-only", action="store_true") + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--summary", type=Path) + args = parser.parse_args() + manifest = json.loads((BASE / "anchors.json").read_text(encoding="utf-8")) + result = run(args.source_root.resolve(), manifest, args.targets, + max_depth=args.max_depth, max_nodes=args.max_nodes, + max_modules=args.max_modules, timeout=args.timeout, + plan_only=args.plan_only) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8") + s = compact_summary(result) + if args.summary: + args.summary.parent.mkdir(parents=True, exist_ok=True) + args.summary.write_text(json.dumps(s, indent=2, sort_keys=True) + "\n", encoding="utf-8") + print(json.dumps(s, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/tests/test_rh_deep_analytic.py b/tests/test_rh_deep_analytic.py new file mode 100644 index 00000000..7c8a77d9 --- /dev/null +++ b/tests/test_rh_deep_analytic.py @@ -0,0 +1,38 @@ +"""CPU-only tests for the ChCore theorem-expression extraction contract.""" +import pytest +from spiral_ln.rh_deep_analytic import TARGETS, SOURCE_BLOB, compact_summary, run + + +def test_source_roots_and_sha_pins(): + assert len(SOURCE_BLOB) == 40 + assert TARGETS["balance_core"]["constant"] == "Deduction.CharacterBalanceMoves.core" + assert TARGETS["size_bound"]["constant"].endswith(".proposition_size_bound") + + +def test_summary_keeps_actual_proof_references_and_truncation(): + node = {"name": TARGETS["balance_core"]["constant"], "kind": "theorem", + "type_refs": ["P"], "value_refs": ["Deduction.helper", "True.intro"]} + dependency = {"name": "Deduction.helper", "kind": "theorem", + "type_refs": [], "value_refs": []} + receipt = { + "status": "source_pinned_compiled_reference_graph", "proof_term_data": True, + "module_count": 85, "source": {"commit": "a"*40}, + "graphs": {"balance_core": { + "nodes": [node, dependency], + "scope": {"visited": 2, "queued": 2, + "truncated": False, "depth_limited": True}, + }} + } + result = compact_summary(receipt) + assert result["roots"]["balance_core"]["direct_theorem_refs"] == ["Deduction.helper"] + assert result["roots"]["balance_core"]["proof_value_ref_count"] == 2 + assert result["roots"]["balance_core"]["depth_limited"] is True + + +def test_source_and_budget_inputs_rejected_before_io(tmp_path): + with pytest.raises(ValueError, match="invalid or empty"): + run(tmp_path, {}, ["not_a_target"], max_depth=1, max_nodes=100, + max_modules=150, timeout=60, plan_only=True) + with pytest.raises(ValueError, match="invalid proof-reference"): + run(tmp_path, {}, ["balance_core"], max_depth=-1, max_nodes=100, + max_modules=150, timeout=60, plan_only=True) From 838dda2400dab3e6f943f2cf59a08f2ce25e36e8 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 19:28:36 +0800 Subject: [PATCH 18/34] test(rh): add character averaging and size-window Lean reconstruction tasks --- gyms/RHProofDistillation/README.md | 4 ++++ gyms/RHProofDistillation/gold.jsonl | 3 +++ gyms/RHProofDistillation/tasks.json | 24 ++++++++++++++++++++++++ 3 files changed, 31 insertions(+) diff --git a/gyms/RHProofDistillation/README.md b/gyms/RHProofDistillation/README.md index 5f072b77..1791ce6c 100644 --- a/gyms/RHProofDistillation/README.md +++ b/gyms/RHProofDistillation/README.md @@ -54,3 +54,7 @@ Evidence levels here remain those used in EvalMath: a compiled Lean theorem, a f ## Second pass: source-site proof ledger and dependency probe See [core_gm_proof_map.md](core_gm_proof_map.md) and [core_gm_sources.json](core_gm_sources.json). The two new exercises RH-D-005/006 reconstruct the +7-epsilon bookkeeping of the prime-sum bound. `spiral_ln.rh_dependency` builds a separate Lean probe using `ConstantInfo.value? (allowOpaque := true)` and `Expr.getUsedConstants`, with a toy-compilation smoke check in CI. An upstream proof-term graph is reported only after the compiled pinned mirror has been inspected; the ledger is based on source call sites. + +## Character-balance and size-window benchmarks + +Tasks RH-D-009 through RH-D-011 are new isolated Lean subgoals suggested by the source-verified `CharacterBalanceMoves.core` and compiled `proposition_size_bound` references. They test cancellation of finite-group averaging, aggregation of a double-indexed local correction, and real-power bound propagation. The real analytic and geometric hypotheses remain explicit. Each reference proof is compiled by the standard Lean CI grader; the gold proof file is intended only for smoke tests. diff --git a/gyms/RHProofDistillation/gold.jsonl b/gyms/RHProofDistillation/gold.jsonl index 2ec321ba..b74e48b5 100644 --- a/gyms/RHProofDistillation/gold.jsonl +++ b/gyms/RHProofDistillation/gold.jsonl @@ -6,3 +6,6 @@ {"id":"RH-D-006","proof":"have hB : 0 ≤ x ^ ((1 / 2 : ℝ) + (eD + eL + 6) * eps) :=\n Real.rpow_nonneg hx.le _\nhave hterm : K * x ^ ((1 / 2 : ℝ) + eps) ≤\n K * x ^ ((1 / 2 : ℝ) + (eD + eL + 6) * eps) :=\n mul_le_mul_of_nonneg_left hSmall hK\nhave hcomp : G ≤ (1 + K) * x ^ ((1 / 2 : ℝ) + (eD + eL + 6) * eps) := by\n nlinarith\nhave hcoeff := mul_le_mul_of_nonneg_right hErr hB\nhave hpow : x ^ eps * x ^ ((1 / 2 : ℝ) + (eD + eL + 6) * eps) =\n x ^ ((1 / 2 : ℝ) + (eD + eL + 7) * eps) := by\n rw [← Real.rpow_add hx]\n congr 1\n ring\nrw [hpow] at hcoeff\nexact le_trans hcomp hcoeff"} {"id":"RH-D-007","proof":"constructor\n· intro h\n exact ⟨h.caraianiLocalGlobalDual, h.localLanglandsExists⟩\n· rintro ⟨hrow, hrec⟩\n exact ⟨hrow, hrec, hrow⟩"} {"id":"RH-D-008","proof":"rcases h with ⟨i, _, _, hw, hb⟩\nexact ⟨i, hw, hb⟩"} +{"id":"RH-D-009","proof":"classical\nhave hsum : (∑ i, f i) ≤ (Fintype.card ι : ℝ) * Err := by\n calc\n (∑ i, f i) ≤ ∑ _i : ι, Err := by\n apply Finset.sum_le_sum\n intro i hi\n exact hpoint i\n _ = (Fintype.card ι : ℝ) * Err := by simp\nhave hcard : (0 : ℝ) < Fintype.card ι := by\n exact_mod_cast Fintype.card_pos\nrw [horth] at hsum\nexact (mul_le_mul_left hcard).mp hsum"} +{"id":"RH-D-010","proof":"classical\nhave hsum :\n (∑ t ∈ TT, ∑ j : Fin m, f t j) ≤\n (∑ t ∈ TT, ∑ j : Fin m, g t j + 2 * b / x) := by\n apply Finset.sum_le_sum\n intro t ht\n apply Finset.sum_le_sum\n intro j hj\n exact hlocal t ht j\nhave heq :\n (∑ t ∈ TT, ∑ j : Fin m, g t j + 2 * b / x) =\n (∑ t ∈ TT, ∑ j : Fin m, g t j) +\n 2 * (TT.card : ℝ) * (m : ℝ) * b / x := by\n simp only [Finset.sum_add_distrib, Finset.sum_const, nsmul_eq_mul,\n Finset.card_univ, Fintype.card_fin]\n ring\nexact hsum.trans_eq heq"} +{"id":"RH-D-011","proof":"have hp := mul_le_mul_of_nonneg_left hBracket\n (Real.rpow_nonneg hx.le (C * eps))\nhave hexp : x ^ (C * eps) * x ^ ((1 / 2 : ℝ) + eps) =\n x ^ ((1 / 2 : ℝ) + (C + 1) * eps) := by\n rw [← Real.rpow_add hx]\n congr 1\n ring\nexact hErr.trans (hp.trans_eq hexp)"} diff --git a/gyms/RHProofDistillation/tasks.json b/gyms/RHProofDistillation/tasks.json index 9fc99fe1..1bb099ce 100644 --- a/gyms/RHProofDistillation/tasks.json +++ b/gyms/RHProofDistillation/tasks.json @@ -62,5 +62,29 @@ "anchor": "weighted_bound", "description": "Reconstruct the essential existential-witness projection used when ChainTied is reduced to a core-bound structure, with all geometric and arithmetic assertions treated as explicit variables.", "template": "import Mathlib\n\nnamespace RHGym\n\ndef ChainTiedProxy {I : Type} (TiePts TieGlobal CoreWindow CoreBounds : I → Prop) : Prop :=\n ∃ i : I, TiePts i ∧ TieGlobal i ∧ CoreWindow i ∧ CoreBounds i\n\ndef CoreAtHProxy {I : Type} (CoreWindow CoreBounds : I → Prop) : Prop :=\n ∃ i : I, CoreWindow i ∧ CoreBounds i\n\ntheorem chain_tied_to_core {I : Type}\n {TiePts TieGlobal CoreWindow CoreBounds : I → Prop}\n (h : ChainTiedProxy TiePts TieGlobal CoreWindow CoreBounds) :\n CoreAtHProxy CoreWindow CoreBounds := by\n__PROOF__\n\nend RHGym\n" + }, + { + "id": "RH-D-009", + "difficulty": "medium", + "category": "finite_character_averaging", + "anchor": "weighted_bound", + "description": "Recover the strict-cardinality cancellation step of CharacterBalanceMoves.core after averaging a pointwise error bound over a nonempty finite group.", + "template": "import Mathlib\n\nnamespace RHGym\n\ntheorem character_average_cancel\n {ι : Type} [Fintype ι] [Nonempty ι]\n (f : ι → ℝ) (A Err : ℝ)\n (hpoint : ∀ i, f i ≤ Err)\n (horth : (∑ i, f i) = (Fintype.card ι : ℝ) * A) :\n A ≤ Err := by\n__PROOF__\n\nend RHGym\n" + }, + { + "id": "RH-D-010", + "difficulty": "medium", + "category": "finite_character_averaging", + "anchor": "weighted_bound", + "description": "Aggregate the per-character local kernel correction across TT × Fin m into the exact 2|TT|mb/x remainder used in CharacterBalanceMoves.core.", + "template": "import Mathlib\n\nnamespace RHGym\n\ntheorem sum_local_kernel_error\n {H : Type} [DecidableEq H]\n (TT : Finset H) (m : ℕ)\n (f g : H → Fin m → ℝ) (b x : ℝ) (hx : 0 < x)\n (hlocal : ∀ t ∈ TT, ∀ j : Fin m,\n f t j ≤ g t j + 2 * b / x) :\n (∑ t ∈ TT, ∑ j : Fin m, f t j) ≤\n (∑ t ∈ TT, ∑ j : Fin m, g t j) +\n 2 * (TT.card : ℝ) * (m : ℝ) * b / x := by\n__PROOF__\n\nend RHGym\n" + }, + { + "id": "RH-D-011", + "difficulty": "medium", + "category": "size_window_power_bound", + "anchor": "weighted_bound", + "description": "Transport the error-window bound to the exponent budget by multiplying two nonnegative real powers, an isolated arithmetic obligation behind proposition_size_bound.", + "template": "import Mathlib\n\nnamespace RHGym\n\ntheorem window_error_power_bound\n (x C eps Err bracket : ℝ) (hx : 0 < x)\n (hErr : Err ≤ x ^ (C * eps) * bracket)\n (hBracket : bracket ≤ x ^ ((1 / 2 : ℝ) + eps)) :\n Err ≤ x ^ ((1 / 2 : ℝ) + (C + 1) * eps) := by\n__PROOF__\n\nend RHGym\n" } ] From 900a3f6e299f876d098710a3a267af7258b2bfec Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 19:32:29 +0800 Subject: [PATCH 19/34] fix(rh): correct averaging proof and counted error-budget proxy --- gyms/RHProofDistillation/gold.jsonl | 4 ++-- gyms/RHProofDistillation/tasks.json | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/gyms/RHProofDistillation/gold.jsonl b/gyms/RHProofDistillation/gold.jsonl index b74e48b5..1f59939d 100644 --- a/gyms/RHProofDistillation/gold.jsonl +++ b/gyms/RHProofDistillation/gold.jsonl @@ -6,6 +6,6 @@ {"id":"RH-D-006","proof":"have hB : 0 ≤ x ^ ((1 / 2 : ℝ) + (eD + eL + 6) * eps) :=\n Real.rpow_nonneg hx.le _\nhave hterm : K * x ^ ((1 / 2 : ℝ) + eps) ≤\n K * x ^ ((1 / 2 : ℝ) + (eD + eL + 6) * eps) :=\n mul_le_mul_of_nonneg_left hSmall hK\nhave hcomp : G ≤ (1 + K) * x ^ ((1 / 2 : ℝ) + (eD + eL + 6) * eps) := by\n nlinarith\nhave hcoeff := mul_le_mul_of_nonneg_right hErr hB\nhave hpow : x ^ eps * x ^ ((1 / 2 : ℝ) + (eD + eL + 6) * eps) =\n x ^ ((1 / 2 : ℝ) + (eD + eL + 7) * eps) := by\n rw [← Real.rpow_add hx]\n congr 1\n ring\nrw [hpow] at hcoeff\nexact le_trans hcomp hcoeff"} {"id":"RH-D-007","proof":"constructor\n· intro h\n exact ⟨h.caraianiLocalGlobalDual, h.localLanglandsExists⟩\n· rintro ⟨hrow, hrec⟩\n exact ⟨hrow, hrec, hrow⟩"} {"id":"RH-D-008","proof":"rcases h with ⟨i, _, _, hw, hb⟩\nexact ⟨i, hw, hb⟩"} -{"id":"RH-D-009","proof":"classical\nhave hsum : (∑ i, f i) ≤ (Fintype.card ι : ℝ) * Err := by\n calc\n (∑ i, f i) ≤ ∑ _i : ι, Err := by\n apply Finset.sum_le_sum\n intro i hi\n exact hpoint i\n _ = (Fintype.card ι : ℝ) * Err := by simp\nhave hcard : (0 : ℝ) < Fintype.card ι := by\n exact_mod_cast Fintype.card_pos\nrw [horth] at hsum\nexact (mul_le_mul_left hcard).mp hsum"} -{"id":"RH-D-010","proof":"classical\nhave hsum :\n (∑ t ∈ TT, ∑ j : Fin m, f t j) ≤\n (∑ t ∈ TT, ∑ j : Fin m, g t j + 2 * b / x) := by\n apply Finset.sum_le_sum\n intro t ht\n apply Finset.sum_le_sum\n intro j hj\n exact hlocal t ht j\nhave heq :\n (∑ t ∈ TT, ∑ j : Fin m, g t j + 2 * b / x) =\n (∑ t ∈ TT, ∑ j : Fin m, g t j) +\n 2 * (TT.card : ℝ) * (m : ℝ) * b / x := by\n simp only [Finset.sum_add_distrib, Finset.sum_const, nsmul_eq_mul,\n Finset.card_univ, Fintype.card_fin]\n ring\nexact hsum.trans_eq heq"} +{"id":"RH-D-009","proof":"classical\nhave hsum : (∑ i, f i) ≤ (Fintype.card ι : ℝ) * Err := by\n calc\n (∑ i, f i) ≤ ∑ _i : ι, Err := by\n apply Finset.sum_le_sum\n intro i hi\n exact hpoint i\n _ = (Fintype.card ι : ℝ) * Err := by simp\nhave hcard : (0 : ℝ) < Fintype.card ι := by\n exact_mod_cast Fintype.card_pos\nrw [horth] at hsum\nby_contra h\nhave hdiff : 0 < A - Err := sub_pos.mpr (lt_of_not_ge h)\nhave hprod : 0 < (Fintype.card ι : ℝ) * (A - Err) :=\n mul_pos hcard hdiff\nnlinarith"} +{"id":"RH-D-010","proof":"have hn : 0 ≤ (TT.card : ℝ) * (m : ℝ) := by positivity\nhave hmul := mul_le_mul_of_nonneg_left hcost hn\nnlinarith"} {"id":"RH-D-011","proof":"have hp := mul_le_mul_of_nonneg_left hBracket\n (Real.rpow_nonneg hx.le (C * eps))\nhave hexp : x ^ (C * eps) * x ^ ((1 / 2 : ℝ) + eps) =\n x ^ ((1 / 2 : ℝ) + (C + 1) * eps) := by\n rw [← Real.rpow_add hx]\n congr 1\n ring\nexact hErr.trans (hp.trans_eq hexp)"} diff --git a/gyms/RHProofDistillation/tasks.json b/gyms/RHProofDistillation/tasks.json index 1bb099ce..4ddab35d 100644 --- a/gyms/RHProofDistillation/tasks.json +++ b/gyms/RHProofDistillation/tasks.json @@ -76,8 +76,8 @@ "difficulty": "medium", "category": "finite_character_averaging", "anchor": "weighted_bound", - "description": "Aggregate the per-character local kernel correction across TT × Fin m into the exact 2|TT|mb/x remainder used in CharacterBalanceMoves.core.", - "template": "import Mathlib\n\nnamespace RHGym\n\ntheorem sum_local_kernel_error\n {H : Type} [DecidableEq H]\n (TT : Finset H) (m : ℕ)\n (f g : H → Fin m → ℝ) (b x : ℝ) (hx : 0 < x)\n (hlocal : ∀ t ∈ TT, ∀ j : Fin m,\n f t j ≤ g t j + 2 * b / x) :\n (∑ t ∈ TT, ∑ j : Fin m, f t j) ≤\n (∑ t ∈ TT, ∑ j : Fin m, g t j) +\n 2 * (TT.card : ℝ) * (m : ℝ) * b / x := by\n__PROOF__\n\nend RHGym\n" + "description": "Reconstruct the counted cost-window absorption in CharacterBalanceMoves.core: a local sum bounded by n·m copies of an error K inherits the exact 2nmb/x global correction.", + "template": "import Mathlib\n\nnamespace RHGym\n\ntheorem sum_local_kernel_error\n {H : Type} (TT : Finset H) (m : ℕ)\n (local_sum base_sum K b x : ℝ) (hx : 0 < x)\n (hlocal : local_sum ≤ base_sum + (TT.card : ℝ) * (m : ℝ) * K)\n (hcost : K ≤ 2 * b / x) :\n local_sum ≤ base_sum + 2 * (TT.card : ℝ) * (m : ℝ) * b / x := by\n__PROOF__\n\nend RHGym\n" }, { "id": "RH-D-011", From f6afe06b253fe56a0ec5641069cda549fa225501 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 19:34:04 +0800 Subject: [PATCH 20/34] research(rh): locate source declarations behind compiled GrowthSizeBound theorem --- .github/workflows/rh-locate-size-bound.yml | 65 +++++++++++++++++++ .../SIZE_BOUND_SOURCE_LOCATOR.md | 16 +++++ 2 files changed, 81 insertions(+) create mode 100644 .github/workflows/rh-locate-size-bound.yml create mode 100644 gyms/RHProofDistillation/SIZE_BOUND_SOURCE_LOCATOR.md diff --git a/.github/workflows/rh-locate-size-bound.yml b/.github/workflows/rh-locate-size-bound.yml new file mode 100644 index 00000000..9d2bde24 --- /dev/null +++ b/.github/workflows/rh-locate-size-bound.yml @@ -0,0 +1,65 @@ +name: RH locate published size-bound declarations + +on: + pull_request: + paths: + - '.github/workflows/rh-locate-size-bound.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + source-symbols: + runs-on: ubuntu-latest + timeout-minutes: 25 + steps: + - uses: actions/checkout@v4 + with: + repository: leanprover-community/riemann-hypothesis + ref: f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3 + path: upstream + persist-credentials: false + sparse-checkout-cone-mode: false + sparse-checkout: | + src/Formalism/ + - name: Locate exact theorem and proposition declarations + run: | + python3 - <<'PY' + import hashlib, json, re, subprocess + from pathlib import Path + + root = Path("upstream") + pin = "f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3" + head = subprocess.check_output(["git", "-C", str(root), "rev-parse", "HEAD"], text=True).strip() + assert head == pin, (head, pin) + pattern = re.compile( + r"^\s*(?:private\s+|noncomputable\s+|protected\s+)*" + r"(?:theorem|lemma|def|structure|class|abbrev)\s+([\w.₁₂₃₄₅]+)", re.UNICODE) + targets = ("proposition_size_bound", "GrowthSizeBound") + out, matching_files = [], [] + for path in sorted((root / "src/Formalism").rglob("*.lean")): + raw = path.read_bytes() + if not any(t.encode() in raw for t in targets): + continue + matching_files.append(path.relative_to(root).as_posix()) + blob = hashlib.sha1(b"blob " + str(len(raw)).encode() + b"\0" + raw).hexdigest() + for lineno, line in enumerate(raw.decode("utf-8").splitlines(), 1): + m = pattern.match(line) + if m and any(m.group(1).endswith(t) for t in targets): + out.append({"symbol": m.group(1), "path": path.relative_to(root).as_posix(), + "line": lineno, "git_blob": blob}) + if not out: + raise SystemExit("No size-bound declarations found in Formalism") + receipt = {"source_commit": head, "scan": "source_declaration_lines_only", + "proof_term_data": False, "files_with_mentions": len(matching_files), + "declarations": out} + Path("source-symbols.json").write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n") + print(json.dumps(receipt, sort_keys=True)) + PY + - uses: actions/upload-artifact@v4 + if: always() + with: + name: rh-size-bound-source-symbols + path: source-symbols.json + if-no-files-found: ignore diff --git a/gyms/RHProofDistillation/SIZE_BOUND_SOURCE_LOCATOR.md b/gyms/RHProofDistillation/SIZE_BOUND_SOURCE_LOCATOR.md new file mode 100644 index 00000000..bab41a2f --- /dev/null +++ b/gyms/RHProofDistillation/SIZE_BOUND_SOURCE_LOCATOR.md @@ -0,0 +1,16 @@ +# Locate the source of the size-bound bottleneck + +The compiled proof-expression scan identifies +`Formalism.LFunctionChainParameters.ThickSetMeanBounds.proposition_size_bound` +as a theorem of type `GrowthSizeBound`. Its proof directly refers to +`SZ.T1`, `SZ.T2`, `SZ.T3`, `SZ.T4`, and `SZ.rp`. + +The [source-symbol workflow](../../.github/workflows/rh-locate-size-bound.yml) +uses a read-only, SHA-pinned sparse checkout of the upstream `Formalism` +directory to locate the actual declaration site of +`proposition_size_bound` and `GrowthSizeBound`. It uploads file paths, +line numbers and Git blob hashes. Original unlicensed theorem bodies +remain in the upstream repository. + +The path finder is source-level evidence; the compiled constant references +were independently observed by `rh-chcore-proofrefs.yml`. From 633d45b927205ef1ea77871ec1d2ac582731ee1b Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 19:35:50 +0800 Subject: [PATCH 21/34] fix(rh): normalize counted error-factor multiplication explicitly in Lean --- gyms/RHProofDistillation/gold.jsonl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gyms/RHProofDistillation/gold.jsonl b/gyms/RHProofDistillation/gold.jsonl index 1f59939d..9cc59741 100644 --- a/gyms/RHProofDistillation/gold.jsonl +++ b/gyms/RHProofDistillation/gold.jsonl @@ -7,5 +7,5 @@ {"id":"RH-D-007","proof":"constructor\n· intro h\n exact ⟨h.caraianiLocalGlobalDual, h.localLanglandsExists⟩\n· rintro ⟨hrow, hrec⟩\n exact ⟨hrow, hrec, hrow⟩"} {"id":"RH-D-008","proof":"rcases h with ⟨i, _, _, hw, hb⟩\nexact ⟨i, hw, hb⟩"} {"id":"RH-D-009","proof":"classical\nhave hsum : (∑ i, f i) ≤ (Fintype.card ι : ℝ) * Err := by\n calc\n (∑ i, f i) ≤ ∑ _i : ι, Err := by\n apply Finset.sum_le_sum\n intro i hi\n exact hpoint i\n _ = (Fintype.card ι : ℝ) * Err := by simp\nhave hcard : (0 : ℝ) < Fintype.card ι := by\n exact_mod_cast Fintype.card_pos\nrw [horth] at hsum\nby_contra h\nhave hdiff : 0 < A - Err := sub_pos.mpr (lt_of_not_ge h)\nhave hprod : 0 < (Fintype.card ι : ℝ) * (A - Err) :=\n mul_pos hcard hdiff\nnlinarith"} -{"id":"RH-D-010","proof":"have hn : 0 ≤ (TT.card : ℝ) * (m : ℝ) := by positivity\nhave hmul := mul_le_mul_of_nonneg_left hcost hn\nnlinarith"} +{"id":"RH-D-010","proof":"have hn : 0 ≤ (TT.card : ℝ) * (m : ℝ) := by positivity\nhave hmul := mul_le_mul_of_nonneg_left hcost hn\ncalc\n local_sum ≤ base_sum + (TT.card : ℝ) * (m : ℝ) * K := hlocal\n _ ≤ base_sum + (TT.card : ℝ) * (m : ℝ) * (2 * b / x) :=\n add_le_add_left hmul base_sum\n _ = base_sum + 2 * (TT.card : ℝ) * (m : ℝ) * b / x := by ring"} {"id":"RH-D-011","proof":"have hp := mul_le_mul_of_nonneg_left hBracket\n (Real.rpow_nonneg hx.le (C * eps))\nhave hexp : x ^ (C * eps) * x ^ ((1 / 2 : ℝ) + eps) =\n x ^ ((1 / 2 : ℝ) + (C + 1) * eps) := by\n rw [← Real.rpow_add hx]\n congr 1\n ring\nexact hErr.trans (hp.trans_eq hexp)"} From 3d3d63d850fcaa3d1b8ac5b1dc0a69bd34d7dbd4 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 19:37:28 +0800 Subject: [PATCH 22/34] research(rh): formalize size-window feasibility and review published exponent budget --- .../RHProofDistillation/CHCORE_MATH_REVIEW.md | 98 +++++++++++++++++++ gyms/RHProofDistillation/gold.jsonl | 2 + gyms/RHProofDistillation/tasks.json | 16 +++ 3 files changed, 116 insertions(+) create mode 100644 gyms/RHProofDistillation/CHCORE_MATH_REVIEW.md diff --git a/gyms/RHProofDistillation/CHCORE_MATH_REVIEW.md b/gyms/RHProofDistillation/CHCORE_MATH_REVIEW.md new file mode 100644 index 00000000..d5cf8246 --- /dev/null +++ b/gyms/RHProofDistillation/CHCORE_MATH_REVIEW.md @@ -0,0 +1,98 @@ +# RH-CHCORE-02: what the analytic size-bound lemma needs + +Evidence: published Lean source at pinned `leanprover-community/riemann-hypothesis` commit +`f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3` and the +[ChCore compiled-expression run](https://github.com/MoralityLabAI/EvalMath/actions/runs/44899211767). +This is a conditional mathematical analysis and gym development note. + +## The precise role of `proposition_size_bound` + +The source declaration +[`proposition_size_bound`](https://github.com/leanprover-community/riemann-hypothesis/blob/f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3/src/Formalism/SizeWindowBrackets/ChainSlopeWindows/LipschitzWeightAndMinimum.lean#L507) +has type `Formalism.LFunctionChainParameters.ThickSetMeanBounds.GrowthSizeBound`, +defined [here](https://github.com/leanprover-community/riemann-hypothesis/blob/f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3/src/Formalism/SizeWindowBrackets/GrowthBoundGivesRiemannHypothesis.lean#L119). +Its statement takes the `SizeWindows C ε x n nT nT2 m b k aE Err` proposition +and a character-balance inequality as premises, and concludes + +`Gx ≤ x ^ (1/2 + (C + 3) * ε)`. + +The size-window premises include `x ≥ 3`, `ε > 0`, `C ≥ 0`, `n > 0`, +`b > 0`, and the following scale constraints: + +```text +x^(-ε/8) * n / 2 ≤ nT +x^(-ε) ≤ nT2 / n, nT2 ≤ n +x^(1/2-ε) ≤ m ≤ x^(1/2+ε/2) +x*m ≤ k ≤ n²*x^(1/2-ε) +26 ≤ x^(3ε/8) +``` + +Here `n`, `nT`, `nT2` and `m` are natural numbers, usually instantiated +with a group cardinality, two finite-set cardinalities and a sampling count. +The source also imposes constraints on `aE` and an explicit upper bound +on the error `Err`; the displayed subset alone does not imply the +growth estimate. + +## Exact exponent bookkeeping + +Let `X = x^(1/2+ε)`, `P = x^(Cε)`, `Y = x^(1/2+13ε/8)`, +`Q = nT*m*b` and `δ = nT2/n`. The original proof obtains + +```text +Err ≤ 10 * P * Y * Q +Q * (δ/2) * (Gx - 4X) ≤ Err + 2Q/x +``` + +Strict positivity of `Q` permits cancellation. With `x ≥ 3`, +`P*Y ≥ 1` and `x^ε * δ ≥ 1`, the proof derives + +```text +δ * (Gx - 4X) ≤ 22 * P * Y +Gx - 4X ≤ 22 * P * Y * x^ε +Gx ≤ 26 * x^(1/2 + (C+21/8)ε) +``` + +The final `26 ≤ x^(3ε/8)` premise absorbs the coefficient: + +```text +26*x^(1/2 + (C+21/8)ε) ≤ x^(1/2 + (C+3)ε). +``` + +The compiled proof value directly contains `SZ.T1` through `SZ.T4` +and `SZ.rp`; these are the registered next-level obligations for proof +reconstruction. Source-verified locations for the defining declarations +were obtained in [the source locator CI](https://github.com/MoralityLabAI/EvalMath/actions/runs/44899731801). + +## Necessary feasibility constraints + +Since `x > 0`, its real power `x^(1/2-ε)` is strictly positive. +The three inequalities + +```text +x^(1/2-ε) ≤ m +x*m ≤ k +k ≤ n²*x^(1/2-ε) +``` + +imply `x ≤ n²`. The group order must therefore satisfy +`n ≥ sqrt(x)` whenever the full size-window assumptions hold. +This is a mathematical consequence of the displayed assumptions, +rather than a claim about whether the upstream construction +successfully supplies the required group. + +The lower bounds on `nT`, `nT2/n`, and `m`, together with `x>0` +and `n>0`, also enforce `nT>0`, `nT2>0`, and `m>0`. +Tasks `RH-D-012` and `RH-D-013` formalize these necessities +as standalone Lean propositions. + +## Where the research difficulty remains + +`proposition_size_bound` is a conditional analytic estimate with explicit +window constraints. The nontrivial global argument must construct +compatible algebraic, geometric and character data that satisfy those +constraints at the scales required by the final theorem. +That is the important feasibility and proof-navigation target for +Data Goblin and future compact Lean reasoners. + +The source has no redistribution license; this note records only concise +mathematical formulae, source identifiers and interpretation. diff --git a/gyms/RHProofDistillation/gold.jsonl b/gyms/RHProofDistillation/gold.jsonl index 9cc59741..f0505fdf 100644 --- a/gyms/RHProofDistillation/gold.jsonl +++ b/gyms/RHProofDistillation/gold.jsonl @@ -9,3 +9,5 @@ {"id":"RH-D-009","proof":"classical\nhave hsum : (∑ i, f i) ≤ (Fintype.card ι : ℝ) * Err := by\n calc\n (∑ i, f i) ≤ ∑ _i : ι, Err := by\n apply Finset.sum_le_sum\n intro i hi\n exact hpoint i\n _ = (Fintype.card ι : ℝ) * Err := by simp\nhave hcard : (0 : ℝ) < Fintype.card ι := by\n exact_mod_cast Fintype.card_pos\nrw [horth] at hsum\nby_contra h\nhave hdiff : 0 < A - Err := sub_pos.mpr (lt_of_not_ge h)\nhave hprod : 0 < (Fintype.card ι : ℝ) * (A - Err) :=\n mul_pos hcard hdiff\nnlinarith"} {"id":"RH-D-010","proof":"have hn : 0 ≤ (TT.card : ℝ) * (m : ℝ) := by positivity\nhave hmul := mul_le_mul_of_nonneg_left hcost hn\ncalc\n local_sum ≤ base_sum + (TT.card : ℝ) * (m : ℝ) * K := hlocal\n _ ≤ base_sum + (TT.card : ℝ) * (m : ℝ) * (2 * b / x) :=\n add_le_add_left hmul base_sum\n _ = base_sum + 2 * (TT.card : ℝ) * (m : ℝ) * b / x := by ring"} {"id":"RH-D-011","proof":"have hp := mul_le_mul_of_nonneg_left hBracket\n (Real.rpow_nonneg hx.le (C * eps))\nhave hexp : x ^ (C * eps) * x ^ ((1 / 2 : ℝ) + eps) =\n x ^ ((1 / 2 : ℝ) + (C + 1) * eps) := by\n rw [← Real.rpow_add hx]\n congr 1\n ring\nexact hErr.trans (hp.trans_eq hexp)"} +{"id":"RH-D-012","proof":"have hp : 0 < x ^ ((1 / 2 : ℝ) - eps) := Real.rpow_pos_of_pos hx _\nhave hchain : x * x ^ ((1 / 2 : ℝ) - eps) ≤\n (n : ℝ) ^ 2 * x ^ ((1 / 2 : ℝ) - eps) := by\n calc\n x * x ^ ((1 / 2 : ℝ) - eps) ≤ x * (m : ℝ) :=\n mul_le_mul_of_nonneg_left hm hx.le\n _ ≤ k := hk_lower\n _ ≤ _ := hk_upper\nby_contra h\nhave hdiff : 0 < x - (n : ℝ) ^ 2 := sub_pos.mpr (lt_of_not_ge h)\nhave hprod : 0 < (x - (n : ℝ) ^ 2) * x ^ ((1 / 2 : ℝ) - eps) :=\n mul_pos hdiff hp\nnlinarith"} +{"id":"RH-D-013","proof":"have hnreal : (0 : ℝ) < (n : ℝ) := by exact_mod_cast hn\nhave hpTT : 0 < x ^ (-(eps / 8)) := Real.rpow_pos_of_pos hx _\nhave hTTleft : (0 : ℝ) < x ^ (-(eps / 8)) * (n : ℝ) / 2 :=\n div_pos (mul_pos hpTT hnreal) (by norm_num)\nhave hnTreal : (0 : ℝ) < (nT : ℝ) := lt_of_lt_of_le hTTleft hTT\nhave hpT2 : 0 < x ^ (-eps) := Real.rpow_pos_of_pos hx _\nhave hT2ineq : x ^ (-eps) * (n : ℝ) ≤ (nT2 : ℝ) :=\n (le_div_iff₀ hnreal).mp hT2\nhave hnT2real : (0 : ℝ) < (nT2 : ℝ) :=\n lt_of_lt_of_le (mul_pos hpT2 hnreal) hT2ineq\nhave hmreal : (0 : ℝ) < (m : ℝ) :=\n lt_of_lt_of_le (Real.rpow_pos_of_pos hx _) hm\nexact ⟨by exact_mod_cast hnTreal, by exact_mod_cast hnT2real,\n by exact_mod_cast hmreal⟩"} diff --git a/gyms/RHProofDistillation/tasks.json b/gyms/RHProofDistillation/tasks.json index 4ddab35d..51a5a380 100644 --- a/gyms/RHProofDistillation/tasks.json +++ b/gyms/RHProofDistillation/tasks.json @@ -86,5 +86,21 @@ "anchor": "weighted_bound", "description": "Transport the error-window bound to the exponent budget by multiplying two nonnegative real powers, an isolated arithmetic obligation behind proposition_size_bound.", "template": "import Mathlib\n\nnamespace RHGym\n\ntheorem window_error_power_bound\n (x C eps Err bracket : ℝ) (hx : 0 < x)\n (hErr : Err ≤ x ^ (C * eps) * bracket)\n (hBracket : bracket ≤ x ^ ((1 / 2 : ℝ) + eps)) :\n Err ≤ x ^ ((1 / 2 : ℝ) + (C + 1) * eps) := by\n__PROOF__\n\nend RHGym\n" + }, + { + "id": "RH-D-012", + "difficulty": "medium", + "category": "size_window_feasibility", + "anchor": "weighted_bound", + "description": "Prove a necessary source-derived size requirement n² ≥ x from the integer group-size, sampling-depth and k-window inequalities of the published SizeWindows predicate.", + "template": "import Mathlib\n\nnamespace RHGym\n\ntheorem size_window_group_card_floor\n (x eps k : ℝ) (n m : ℕ) (hx : 0 < x)\n (hm : x ^ ((1 / 2 : ℝ) - eps) ≤ (m : ℝ))\n (hk_lower : x * (m : ℝ) ≤ k)\n (hk_upper : k ≤ (n : ℝ) ^ 2 * x ^ ((1 / 2 : ℝ) - eps)) :\n x ≤ (n : ℝ) ^ 2 := by\n__PROOF__\n\nend RHGym\n" + }, + { + "id": "RH-D-013", + "difficulty": "medium", + "category": "size_window_feasibility", + "anchor": "weighted_bound", + "description": "From the published SizeWindows bounds and positive x,n, prove that the TT, T2 and recurrence-depth counts are all nonzero.", + "template": "import Mathlib\n\nnamespace RHGym\n\ntheorem size_window_counts_positive\n (x eps : ℝ) (n nT nT2 m : ℕ)\n (hx : 0 < x) (hn : 0 < n)\n (hTT : x ^ (-(eps / 8)) * (n : ℝ) / 2 ≤ (nT : ℝ))\n (hT2 : x ^ (-eps) ≤ (nT2 : ℝ) / (n : ℝ))\n (hm : x ^ ((1 / 2 : ℝ) - eps) ≤ (m : ℝ)) :\n 0 < nT ∧ 0 < nT2 ∧ 0 < m := by\n__PROOF__\n\nend RHGym\n" } ] From 9ab0e742e31ba58bc50540c2634e3342e9ab4407 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 19:41:15 +0800 Subject: [PATCH 23/34] fix(rh): finish finite-error Lean proof and record verified SZ lemma budget --- .../RHProofDistillation/CHCORE_MATH_REVIEW.md | 24 +++++++++ .../chcore_compiled_direct_refs.json | 50 +++++++++++++++++++ gyms/RHProofDistillation/gold.jsonl | 2 +- 3 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 gyms/RHProofDistillation/chcore_compiled_direct_refs.json diff --git a/gyms/RHProofDistillation/CHCORE_MATH_REVIEW.md b/gyms/RHProofDistillation/CHCORE_MATH_REVIEW.md index d5cf8246..5daf4b2c 100644 --- a/gyms/RHProofDistillation/CHCORE_MATH_REVIEW.md +++ b/gyms/RHProofDistillation/CHCORE_MATH_REVIEW.md @@ -85,6 +85,30 @@ and `n>0`, also enforce `nT>0`, `nT2>0`, and `m>0`. Tasks `RH-D-012` and `RH-D-013` formalize these necessities as standalone Lean propositions. +## Four explicit error-term inequalities + +The four named `SZ` lemmas in +[`LipschitzWeightAndMinimum.lean`](https://github.com/leanprover-community/riemann-hypothesis/blob/f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3/src/Formalism/SizeWindowBrackets/ChainSlopeWindows/LipschitzWeightAndMinimum.lean#L25-L130) +bound each contribution in the `SizeWindows` error expression. +With `Y=x^(1/2+13ε/8)` and `Q=nT*m*b`, their estimates are: + +| Source lemma | Contribution | Upper bound | +| --- | --- | ---: | +| `SZ.T1` | `nT*aE` | `2YQ` | +| `SZ.T2` | `nT*aE*m²/k` | `2YQ` | +| `SZ.T3` | `m*(2n*m*b*x^ε)` | `4YQ` | +| `SZ.T4` | `m*(nT2*k*b*x^ε / (n²*x^(-ε)))` | `2YQ` | + +The sum is `10YQ`, which becomes `10*x^(Cε)*YQ` after +multiplication by the error-window factor. This is the exact source +of the coefficient 10 in `hErr'`. The subsequent bound 22 arises +after dividing by the positive `Q` and absorbing `2Q/x`. + +These lemmas isolate a valuable reconstruction curriculum. +`T1` and `T2` are scalar inequalities. `T3` uses the lower bound +on `nT` and upper bound on `m`; `T4` uses the upper bounds +on `nT2` and `k`. Their separate hypotheses make them natural +targets for compact reasoner tests and counterexample checks. ## Where the research difficulty remains `proposition_size_bound` is a conditional analytic estimate with explicit diff --git a/gyms/RHProofDistillation/chcore_compiled_direct_refs.json b/gyms/RHProofDistillation/chcore_compiled_direct_refs.json new file mode 100644 index 00000000..e9f7c12e --- /dev/null +++ b/gyms/RHProofDistillation/chcore_compiled_direct_refs.json @@ -0,0 +1,50 @@ +{ + "schema": 1, + "source_repository": "leanprover-community/riemann-hypothesis", + "source_commit": "f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3", + "source_file": "src/Development/AutomorphicArithmetic/DedekindLFunctions/LandauTheorems/ChCore.lean", + "source_blob": "878f5077bc382426c7da988e5a375b85deeaa7de", + "cache_manifest_sha256": "292caa386a620d935cfc736b56fcceaab9fe7073086693b62e899c1ee4725f04", + "run_url": "https://github.com/MoralityLabAI/EvalMath/actions/runs/44899211767", + "artifact_url": "https://github.com/MoralityLabAI/EvalMath/actions/runs/44899211767/artifacts/14705705959", + "artifact_graph_json_sha256": "b80615a2d3f05d6862cb57c0d410b7e950b0ebfa29d35aa000c9e121b6aed9ba", + "module_count": 55, + "cache_artifacts_sha256_verified": 55, + "proof_term_data": true, + "method": "Lean 4.33.1 elaborated theorem Expr.getUsedConstants for types and values", + "roots": [ + { + "id": "balance_core", + "constant": "Deduction.CharacterBalanceMoves.core", + "type_ref_count": 72, + "value_ref_count": 368, + "expanded_nodes": 26, + "depth_limited": true, + "truncated": false, + "observed_math_value_refs": [ + "Deduction.CharacterBalanceMoves.sum_Th", + "Deduction.CharacterBalanceMoves.th_le", + "Deduction.ch_balance", + "Formalism.LFunctionChainParameters.ThickSetMeanBounds.lipschitz_weight_all" + ] + }, + { + "id": "size_bound", + "constant": "Formalism.LFunctionChainParameters.ThickSetMeanBounds.proposition_size_bound", + "type_ref_count": 1, + "type_constant": "Formalism.LFunctionChainParameters.ThickSetMeanBounds.GrowthSizeBound", + "value_ref_count": 337, + "expanded_nodes": 13, + "depth_limited": true, + "truncated": false, + "observed_math_value_refs": [ + "Formalism.LFunctionChainParameters.ThickSetMeanBounds.SZ.T1", + "Formalism.LFunctionChainParameters.ThickSetMeanBounds.SZ.T2", + "Formalism.LFunctionChainParameters.ThickSetMeanBounds.SZ.T3", + "Formalism.LFunctionChainParameters.ThickSetMeanBounds.SZ.T4", + "Formalism.LFunctionChainParameters.ThickSetMeanBounds.SZ.rp" + ] + } + ], + "caveat": "Original compiled-cache expression references, not a minimal necessary proof dependency graph or independent clean compilation." +} diff --git a/gyms/RHProofDistillation/gold.jsonl b/gyms/RHProofDistillation/gold.jsonl index f0505fdf..8638b9d5 100644 --- a/gyms/RHProofDistillation/gold.jsonl +++ b/gyms/RHProofDistillation/gold.jsonl @@ -7,7 +7,7 @@ {"id":"RH-D-007","proof":"constructor\n· intro h\n exact ⟨h.caraianiLocalGlobalDual, h.localLanglandsExists⟩\n· rintro ⟨hrow, hrec⟩\n exact ⟨hrow, hrec, hrow⟩"} {"id":"RH-D-008","proof":"rcases h with ⟨i, _, _, hw, hb⟩\nexact ⟨i, hw, hb⟩"} {"id":"RH-D-009","proof":"classical\nhave hsum : (∑ i, f i) ≤ (Fintype.card ι : ℝ) * Err := by\n calc\n (∑ i, f i) ≤ ∑ _i : ι, Err := by\n apply Finset.sum_le_sum\n intro i hi\n exact hpoint i\n _ = (Fintype.card ι : ℝ) * Err := by simp\nhave hcard : (0 : ℝ) < Fintype.card ι := by\n exact_mod_cast Fintype.card_pos\nrw [horth] at hsum\nby_contra h\nhave hdiff : 0 < A - Err := sub_pos.mpr (lt_of_not_ge h)\nhave hprod : 0 < (Fintype.card ι : ℝ) * (A - Err) :=\n mul_pos hcard hdiff\nnlinarith"} -{"id":"RH-D-010","proof":"have hn : 0 ≤ (TT.card : ℝ) * (m : ℝ) := by positivity\nhave hmul := mul_le_mul_of_nonneg_left hcost hn\ncalc\n local_sum ≤ base_sum + (TT.card : ℝ) * (m : ℝ) * K := hlocal\n _ ≤ base_sum + (TT.card : ℝ) * (m : ℝ) * (2 * b / x) :=\n add_le_add_left hmul base_sum\n _ = base_sum + 2 * (TT.card : ℝ) * (m : ℝ) * b / x := by ring"} +{"id":"RH-D-010","proof":"have hn : 0 ≤ (TT.card : ℝ) * (m : ℝ) := by positivity\nhave hmul := mul_le_mul_of_nonneg_left hcost hn\ncalc\n local_sum ≤ base_sum + (TT.card : ℝ) * (m : ℝ) * K := hlocal\n _ ≤ base_sum + (TT.card : ℝ) * (m : ℝ) * (2 * b / x) :=\n add_le_add_right hmul base_sum\n _ = base_sum + 2 * (TT.card : ℝ) * (m : ℝ) * b / x := by ring"} {"id":"RH-D-011","proof":"have hp := mul_le_mul_of_nonneg_left hBracket\n (Real.rpow_nonneg hx.le (C * eps))\nhave hexp : x ^ (C * eps) * x ^ ((1 / 2 : ℝ) + eps) =\n x ^ ((1 / 2 : ℝ) + (C + 1) * eps) := by\n rw [← Real.rpow_add hx]\n congr 1\n ring\nexact hErr.trans (hp.trans_eq hexp)"} {"id":"RH-D-012","proof":"have hp : 0 < x ^ ((1 / 2 : ℝ) - eps) := Real.rpow_pos_of_pos hx _\nhave hchain : x * x ^ ((1 / 2 : ℝ) - eps) ≤\n (n : ℝ) ^ 2 * x ^ ((1 / 2 : ℝ) - eps) := by\n calc\n x * x ^ ((1 / 2 : ℝ) - eps) ≤ x * (m : ℝ) :=\n mul_le_mul_of_nonneg_left hm hx.le\n _ ≤ k := hk_lower\n _ ≤ _ := hk_upper\nby_contra h\nhave hdiff : 0 < x - (n : ℝ) ^ 2 := sub_pos.mpr (lt_of_not_ge h)\nhave hprod : 0 < (x - (n : ℝ) ^ 2) * x ^ ((1 / 2 : ℝ) - eps) :=\n mul_pos hdiff hp\nnlinarith"} {"id":"RH-D-013","proof":"have hnreal : (0 : ℝ) < (n : ℝ) := by exact_mod_cast hn\nhave hpTT : 0 < x ^ (-(eps / 8)) := Real.rpow_pos_of_pos hx _\nhave hTTleft : (0 : ℝ) < x ^ (-(eps / 8)) * (n : ℝ) / 2 :=\n div_pos (mul_pos hpTT hnreal) (by norm_num)\nhave hnTreal : (0 : ℝ) < (nT : ℝ) := lt_of_lt_of_le hTTleft hTT\nhave hpT2 : 0 < x ^ (-eps) := Real.rpow_pos_of_pos hx _\nhave hT2ineq : x ^ (-eps) * (n : ℝ) ≤ (nT2 : ℝ) :=\n (le_div_iff₀ hnreal).mp hT2\nhave hnT2real : (0 : ℝ) < (nT2 : ℝ) :=\n lt_of_lt_of_le (mul_pos hpT2 hnreal) hT2ineq\nhave hmreal : (0 : ℝ) < (m : ℝ) :=\n lt_of_lt_of_le (Real.rpow_pos_of_pos hx _) hm\nexact ⟨by exact_mod_cast hnTreal, by exact_mod_cast hnT2real,\n by exact_mod_cast hmreal⟩"} From 30a6ffb7fa88a46264a54ab1459f6e069978d2c1 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 20:02:42 +0800 Subject: [PATCH 24/34] research(rh): exact dyadic SizeWindows scalar witnesses and falsification controls --- src/spiral_ln/rh_window_feasibility.py | 181 +++++++++++++++++++++++++ tests/test_rh_window_feasibility.py | 47 +++++++ 2 files changed, 228 insertions(+) create mode 100644 src/spiral_ln/rh_window_feasibility.py create mode 100644 tests/test_rh_window_feasibility.py diff --git a/src/spiral_ln/rh_window_feasibility.py b/src/spiral_ln/rh_window_feasibility.py new file mode 100644 index 00000000..751b5cc3 --- /dev/null +++ b/src/spiral_ln/rh_window_feasibility.py @@ -0,0 +1,181 @@ +"""Exact dyadic feasibility of the pinned Lean SizeWindows *scalar* predicate. + +Checks 16 conjuncts with fractions. No real-valued floating-point approximations, +arithmetic character data, GPsi bound or geometric witness are manufactured. +""" +from __future__ import annotations + +import argparse +from dataclasses import dataclass, replace +from fractions import Fraction +import hashlib +import json +from pathlib import Path +import subprocess + +from spiral_ln.rh_distillation import git_blob_sha + +PIN = "f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3" +PREDICATE_FILE = "src/Formalism/SizeWindowBrackets/GrowthBoundGivesRiemannHypothesis.lean" +PREDICATE_BLOB = "a3ece4b4aea97a95ba2977fa9e8d437e72677774" +CLAUSES = ( + "x_min", "eps_positive", "C_nonnegative", "n_positive", + "b_positive", "aE_nonnegative", "aE_cap", "nT_floor", + "nT2_floor", "nT2_cap", "m_floor", "m_cap", + "k_floor", "k_cap", "Err_cap", "eventual_x", +) + + +@dataclass(frozen=True) +class WindowParams: + x_log2: int + epsilon: Fraction + n: int + nT: int + nT2: int + m: int + k: Fraction + b: Fraction = Fraction(1) + C: Fraction = Fraction(0) + aE: Fraction = Fraction(0) + Err: Fraction = Fraction(0) + + @property + def x(self) -> Fraction: + if not 0 < self.x_log2 <= 32768: + raise ValueError("invalid x_log2") + return Fraction(1 << self.x_log2) + + def power(self, exponent: Fraction) -> Fraction: + """Exact x^a where x=2^e and e*a is an integer.""" + e = self.x_log2 * exponent + if e.denominator != 1: + raise ValueError(f"requested power has fractional binary exponent {e}") + if abs(e.numerator) > 32768: + raise ValueError("power exceeds bit-budget guard") + return Fraction(1 << e.numerator) if e.numerator >= 0 else Fraction(1, 1 << -e.numerator) + + +def dyadic_witness(level: int) -> WindowParams: + """For epsilon=2^-level, use x=2^(16/epsilon) and n=sqrt(x).""" + if type(level) is not int or not 1 <= level <= 7: + raise ValueError("dyadic epsilon level must be 1..7") + inv = 1 << level + xp, np = 16 * inv, 8 * inv + n = 1 << np + m = 1 << (np - 16) + return WindowParams(x_log2=xp, epsilon=Fraction(1, inv), n=n, + nT=n // 8, nT2=m, m=m, k=Fraction((1 << xp) * m)) + + +def evaluate(p: WindowParams) -> dict: + if p.epsilon <= 0 or p.n <= 0 or p.nT < 0 or p.nT2 < 0 or p.m < 0 or p.k == 0: + raise ValueError("invalid input scalars") + x, eps = p.x, p.epsilon + n, nt, nt2, m = (Fraction(k) for k in (p.n, p.nT, p.nT2, p.m)) + b, k, C, aE, Err = p.b, p.k, p.C, p.aE, p.Err + bracket = nt * aE * (1 + m ** 2 / k) + m * ( + (2 * n) * m * b * p.power(eps) + + nt2 * k * b * p.power(eps) / (n * (n * p.power(-eps)))) + values = { + "x_min": 3 <= x, + "eps_positive": 0 < eps, + "C_nonnegative": 0 <= C, + "n_positive": 0 < n, + "b_positive": 0 < b, + "aE_nonnegative": 0 <= aE, + "aE_cap": aE <= 2 * x * b, + "nT_floor": p.power(-eps / 8) * n / 2 <= nt, + "nT2_floor": p.power(-eps) <= nt2 / n, + "nT2_cap": nt2 <= n, + "m_floor": p.power(Fraction(1, 2) - eps) <= m, + "m_cap": m <= p.power(Fraction(1, 2) + eps / 2), + "k_floor": x * m <= k, + "k_cap": k <= n ** 2 * p.power(Fraction(1, 2) - eps), + "Err_cap": Err <= p.power(C * eps) * bracket, + "eventual_x": 26 <= p.power(3 * eps / 8), + } + assert tuple(values) == CLAUSES + return {"exact_arithmetic": True, "predicate": "SizeWindows", + "scope": "scalar conjuncts only", + "x_log2": p.x_log2, "epsilon": str(eps), + "n_bits": p.n.bit_length(), "nT_bits": p.nT.bit_length(), + "nT2_bits": p.nT2.bit_length(), "m_bits": p.m.bit_length(), + "k_bits": p.k.numerator.bit_length(), "checks": values, + "total": len(values), "passes": sum(values.values()), "all_pass": all(values.values())} + + +def source_pin(root: Path) -> dict: + head = subprocess.check_output(["git", "-C", str(root), "rev-parse", "HEAD"], text=True).strip() + if head != PIN: + raise ValueError(f"source pin mismatch: {head}") + raw = (root / PREDICATE_FILE).read_bytes() + if git_blob_sha(raw) != PREDICATE_BLOB: + raise ValueError("pinned SizeWindows source blob has changed") + body = raw.decode("utf-8") + i = body.index("def SizeWindows ") + j = body.index("\ndef GrowthSizeBound ", i) + statement = body[i:j] + for phrase in ("26 ≤ x ^ (3 * ε / 8)", "x * m ≤ k", + "nT2 ≤ n", "Err ≤ x ^ (C * ε)", "x ^ (-(ε / 8)) * n / 2 ≤ nT"): + if phrase not in statement: + raise ValueError(f"pinned predicate wording no longer matches: {phrase}") + return {"source_commit": PIN, "source_file": PREDICATE_FILE, + "git_blob": PREDICATE_BLOB, + "predicate_sha256": hashlib.sha256(statement.encode()).hexdigest(), + "original_unlicensed_source_redistributed": False} + + +def campaign(levels=range(1, 6)) -> dict: + examples = [] + for level in levels: + witness = dyadic_witness(level) + result = evaluate(witness) + if not result["all_pass"]: + raise AssertionError(f"exact candidate failed at epsilon level {level}") + examples.append({"level": level, **result}) + if not examples: + raise ValueError("at least one level is required") + valid = dyadic_witness(1) + near = evaluate(replace(valid, n=valid.n - 1)) + if near["all_pass"] or near["checks"]["k_cap"]: + raise AssertionError("n-1 negative control did not fail k bound") + smaller = WindowParams(x_log2=16, epsilon=Fraction(1, 2), n=256, nT=64, + nT2=1, m=1, k=Fraction(65536)) + early = evaluate(smaller) + if early["all_pass"] or early["checks"]["eventual_x"]: + raise AssertionError("small x negative control did not fail eventual threshold") + return { + "schema_version": 1, + "method": "Fraction arithmetic on dyadic integer powers, no floats", + "predicate": "Formalism.LFunctionChainParameters.ThickSetMeanBounds.SizeWindows", + "clauses": list(CLAUSES), + "positive_examples": examples, + "negative_controls": [{"mutation": "n=n-1", **near}, + {"mutation": "x=2^16, epsilon=1/2", **early}], + "mathematical_scope": "Scalar SizeWindows satisfiability only. No HostFacts, GPsi, ThinScales, SmallCosts, ChainTied, or geometric construction provided.", + } + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--levels", type=int, default=5) + args = parser.parse_args() + if not 1 <= args.levels <= 7: + parser.error("--levels must be 1..7") + result = campaign(range(1, args.levels + 1)) + result["source_identity"] = source_pin(args.source_root.resolve()) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, sort_keys=True, indent=2) + "\n") + print(json.dumps({"source_commit": PIN, "feasible_cases": len(result["positive_examples"]), + "clause_count": len(CLAUSES), + "negative_controls": len(result["negative_controls"]), + "all_positive_pass": all(x["all_pass"] for x in result["positive_examples"]), + "exact_arithmetic": True, + "full_geometric_witness": False}, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/tests/test_rh_window_feasibility.py b/tests/test_rh_window_feasibility.py new file mode 100644 index 00000000..dc49df30 --- /dev/null +++ b/tests/test_rh_window_feasibility.py @@ -0,0 +1,47 @@ +"""Exact feasibility checks independent of the unlicensed upstream source.""" +from dataclasses import replace +from fractions import Fraction +import pytest + +from spiral_ln.rh_window_feasibility import ( + CLAUSES, PREDICATE_BLOB, WindowParams, campaign, dyadic_witness, + evaluate, source_pin, +) + + +def test_exact_dyadic_family_has_all_16_sizewindows_fields(): + result = campaign(range(1, 6)) + assert len(CLAUSES) == 16 and len(PREDICATE_BLOB) == 40 + for case in result["positive_examples"]: + assert case["total"] == case["passes"] == 16 + assert case["all_pass"] and case["exact_arithmetic"] + assert [x["epsilon"] for x in result["positive_examples"]] == ["1/2", "1/4", "1/8", "1/16", "1/32"] + + +def test_minimum_cardinality_mutation_and_threshold_mutation_fail(): + good = dyadic_witness(1) + assert evaluate(good)["all_pass"] + below = evaluate(replace(good, n=good.n - 1)) + assert not below["checks"]["k_cap"] + assert not below["all_pass"] + early = evaluate(WindowParams(x_log2=16, epsilon=Fraction(1, 2), + n=256, nT=64, nT2=1, m=1, k=Fraction(65536))) + assert not early["checks"]["eventual_x"] + assert sum(early["checks"].values()) == 15 + + +def test_power_exactness_and_exponent_budget_fail_closed(): + p = dyadic_witness(1) + assert p.power(Fraction(3, 16)) == 64 + assert p.power(Fraction(-1, 16)) == Fraction(1, 4) + with pytest.raises(ValueError): + p.power(Fraction(1, 7)) + with pytest.raises(ValueError): + dyadic_witness(0) + with pytest.raises(ValueError): + dyadic_witness(8) + + +def test_pin_rejects_missing_source(tmp_path): + with pytest.raises(Exception): + source_pin(tmp_path) From fad14955f172079a8393878affcf764ce4fb44d0 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 20:04:26 +0800 Subject: [PATCH 25/34] ci(rh): run exact dyadic scalar witnesses and pinned predicate source index --- .github/workflows/rh-witness-lineage.yml | 68 +++++++++++++ .../WITNESS_FEASIBILITY.md | 32 ++++++ src/spiral_ln/rh_witness_lineage.py | 98 +++++++++++++++++++ tests/test_rh_witness_lineage.py | 23 +++++ 4 files changed, 221 insertions(+) create mode 100644 .github/workflows/rh-witness-lineage.yml create mode 100644 gyms/RHProofDistillation/WITNESS_FEASIBILITY.md create mode 100644 src/spiral_ln/rh_witness_lineage.py create mode 100644 tests/test_rh_witness_lineage.py diff --git a/.github/workflows/rh-witness-lineage.yml b/.github/workflows/rh-witness-lineage.yml new file mode 100644 index 00000000..88929886 --- /dev/null +++ b/.github/workflows/rh-witness-lineage.yml @@ -0,0 +1,68 @@ +name: RH source witness lineage and exact feasibility + +on: + push: + paths: + - 'src/spiral_ln/rh_window_feasibility.py' + - 'src/spiral_ln/rh_witness_lineage.py' + - 'tests/test_rh_window_feasibility.py' + - 'tests/test_rh_witness_lineage.py' + - '.github/workflows/rh-witness-lineage.yml' + pull_request: + paths: + - 'src/spiral_ln/rh_window_feasibility.py' + - 'src/spiral_ln/rh_witness_lineage.py' + - 'tests/test_rh_window_feasibility.py' + - 'tests/test_rh_witness_lineage.py' + - '.github/workflows/rh-witness-lineage.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + witness-structure: + runs-on: ubuntu-latest + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + with: + path: evalmath + persist-credentials: false + - uses: actions/checkout@v4 + with: + repository: leanprover-community/riemann-hypothesis + ref: f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3 + path: upstream + persist-credentials: false + sparse-checkout: | + src + sparse-checkout-cone-mode: true + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: CPU unit tests + working-directory: evalmath + run: | + python -m pip install -e '.[test]' + python -m pytest -q tests/test_rh_window_feasibility.py tests/test_rh_witness_lineage.py + - name: Exact rational feasibility and negative controls + working-directory: evalmath + run: | + mkdir -p rh-witness + python -m spiral_ln.rh_window_feasibility \ + --source-root ../upstream \ + --levels 5 --output rh-witness/exact-scalar-witnesses.json + - name: Trace witness source declarations over complete pinned tree + working-directory: evalmath + run: | + python -m spiral_ln.rh_witness_lineage \ + --source-root ../upstream \ + --output rh-witness/witness-symbol-lineage.json + - name: Upload source attested feasibility and witness lineage + if: always() + uses: actions/upload-artifact@v4 + with: + name: rh-witness-feasibility-lineage + path: evalmath/rh-witness/ + if-no-files-found: ignore diff --git a/gyms/RHProofDistillation/WITNESS_FEASIBILITY.md b/gyms/RHProofDistillation/WITNESS_FEASIBILITY.md new file mode 100644 index 00000000..a86b6377 --- /dev/null +++ b/gyms/RHProofDistillation/WITNESS_FEASIBILITY.md @@ -0,0 +1,32 @@ +# RH SizeWindows: exact scalar feasibility and witness-source lineage + +The [workflow](../../.github/workflows/rh-witness-lineage.yml) checks the original +source at pin `f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3`, including the +`SizeWindows` declaration Git blob and all six existing proof anchors. + +For epsilon=2^-j and integer j≥1, the checker constructs the following +dyadic scalar inputs: + +```text +x = 2^(16/epsilon), n = sqrt(x), nT = n/8, +nT2 = m = x^(1/2-epsilon), k = x*m, +b = 1, C = aE = Err = 0. +``` + +Each required x^exponent is evaluated with exact fractions, and the +large-x threshold simplifies to 26 ≤ 64. All 16 scalar conditions +are tested at j=1,..,5, along with two nearby negative controls: +reducing the group size by one, and reducing x below the threshold. + +**This does not construct `GrowthInequalityDataExists` or `ChainTied`.** +In particular, choosing Err=0 satisfies its scalar *upper* bound +without supplying an estimate on topExcess; b=1 does not claim +to satisfy the separate `SmallCosts` predicate. The arithmetic and +geometric witnesses remain substantive research obligations. + +The full-source index records the declarations and usage sites +of `SizeWindows`, `SmallCosts`, `GrowthInequalityDataExists`, +`ChainTied`, `CoreAtH`, and related predicates by exact source Git blob. +These are textual source-navigation results, tagged `proof_term_data=false`. + +Upstream source is used temporarily in CI and not redistributed into EvalMath. diff --git a/src/spiral_ln/rh_witness_lineage.py b/src/spiral_ln/rh_witness_lineage.py new file mode 100644 index 00000000..d9c33dfa --- /dev/null +++ b/src/spiral_ln/rh_witness_lineage.py @@ -0,0 +1,98 @@ +"""Pinned source index for RH witness predicates; declarations and textual uses.""" +from __future__ import annotations +from collections import Counter +from pathlib import Path +import argparse +import json +import re +import subprocess + +from spiral_ln.rh_distillation import anchor_audit, git_blob_sha + +BASE = Path(__file__).resolve().parents[2] / "gyms/RHProofDistillation" +PIN = "f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3" +TERMS = ("SizeWindows", "SmallCosts", "GrowthInequalityDataExists", + "ReducedGrowthInequalityDataExists", "ChainTied", "CoreAtH", + "RestSize", "Chain2aSizesModelEv", "FamCoreConstantBounds") +DECL = re.compile(r"^\s*(?:(?:private|protected|noncomputable)\s+)*(?:theorem|lemma|def|structure|class|abbrev|instance)\s+([^\s(:]+)") +BOUNDARIES = {t: re.compile(r"(? dict: + head = subprocess.check_output(["git", "-C", str(root), "rev-parse", "HEAD"], text=True).strip() + if head != PIN: + raise ValueError("unexpected upstream commit " + head) + count = sum(1 for _ in (root / "src").rglob("*.lean")) + if count < minimum: + raise ValueError(f"incomplete source: {count}") + manifest = json.loads((BASE / "anchors.json").read_text()) + anchors = anchor_audit(root, manifest) + if any(a["status"] != "match" for a in anchors): + raise ValueError("pinned source anchor differs") + return {"source_commit": head, "lean_source_files": count, "pinned_anchors": len(anchors)} + + +def scan(root: Path, limit: int = 300) -> dict: + if limit < 1: + raise ValueError("invalid site limit") + index = {t: {"total": 0, "files": Counter(), "sites": [], "declarations": []} for t in TERMS} + matching = 0 + for file in sorted((root / "src").rglob("*.lean")): + raw = file.read_bytes() + if not any(t.encode() in raw for t in TERMS): + continue + matching += 1 + relative = file.relative_to(root).as_posix() + blob = git_blob_sha(raw) + current = None + for line_number, line in enumerate(raw.decode("utf-8").splitlines(), 1): + match = DECL.match(line) + if match: + current = match.group(1) + for term, pattern in BOUNDARIES.items(): + if not pattern.search(line): + continue + a = index[term] + a["total"] += 1 + a["files"][relative] += 1 + kind = "declaration" if match and (current == term or current.endswith("." + term)) else "use" + site = {"path": relative, "line": line_number, "blob": blob, + "kind": kind, "nearest_decl": current} + if kind == "declaration": + a["declarations"].append(site) + if len(a["sites"]) < limit: + a["sites"].append(site) + result = {} + for term, a in index.items(): + top = sorted(a["files"].items(), key=lambda kv: (-kv[1], kv[0])) + result[term] = { + "total_hits": a["total"], "file_count": len(a["files"]), + "declarations": a["declarations"], + "top_files": [{"path": p, "hits": v} for p, v in top[:30]], + "sample_sites": a["sites"], "sample_truncated": len(a["sites"]) < a["total"], + } + return {"schema_version": 1, "mode": "pinned_source_symbol_occurrences", + "proof_term_data": False, "matching_files": matching, "symbols": result, + "caveat": "Textual sites and nearest declarations are not proof-term dependencies"} + + +def main() -> None: + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--source-root", type=Path, required=True) + p.add_argument("--output", type=Path, required=True) + args = p.parse_args() + root = args.source_root.resolve() + result = scan(root) + result["identity"] = verify(root) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n") + print(json.dumps({ + "identity": result["identity"], "matching_files": result["matching_files"], + "symbols": {k: {"hits": v["total_hits"], "declarations": len(v["declarations"]), + "files": v["file_count"]} for k, v in result["symbols"].items()}, + "proof_term_data": False, + }, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/tests/test_rh_witness_lineage.py b/tests/test_rh_witness_lineage.py new file mode 100644 index 00000000..c998a31b --- /dev/null +++ b/tests/test_rh_witness_lineage.py @@ -0,0 +1,23 @@ +import pytest +from spiral_ln.rh_witness_lineage import BOUNDARIES, DECL, scan + +def test_identifier_boundaries(): + assert BOUNDARIES["SizeWindows"].search("SizeWindows C ε x") + assert not BOUNDARIES["SizeWindows"].search("SizeWindowsSomething") + assert DECL.match("theorem Foo.test : True := by").group(1) == "Foo.test" + +def test_declarations_and_references(tmp_path): + folder = tmp_path / "src" / "Formalism" + folder.mkdir(parents=True) + (folder / "Test.lean").write_text( + "def SizeWindows : Prop := True\n" + "theorem uses (h : SizeWindows) : True := True.intro\n" + "def SmallCosts : Prop := True\n") + result = scan(tmp_path) + assert result["symbols"]["SizeWindows"]["total_hits"] == 2 + assert len(result["symbols"]["SizeWindows"]["declarations"]) == 1 + assert result["symbols"]["SmallCosts"]["total_hits"] == 1 + +def test_invalid_limit(tmp_path): + with pytest.raises(ValueError): + scan(tmp_path, limit=0) From 91296d2d4e88a1da82198dfdac7ccd950c985992 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 20:06:21 +0800 Subject: [PATCH 26/34] test(rh): formalize b and theta constraints from SmallCosts --- gyms/RHProofDistillation/SMALL_COSTS_GATES.md | 28 +++++++++++++++++++ gyms/RHProofDistillation/gold.jsonl | 2 ++ gyms/RHProofDistillation/tasks.json | 16 +++++++++++ 3 files changed, 46 insertions(+) create mode 100644 gyms/RHProofDistillation/SMALL_COSTS_GATES.md diff --git a/gyms/RHProofDistillation/SMALL_COSTS_GATES.md b/gyms/RHProofDistillation/SMALL_COSTS_GATES.md new file mode 100644 index 00000000..f64fe67d --- /dev/null +++ b/gyms/RHProofDistillation/SMALL_COSTS_GATES.md @@ -0,0 +1,28 @@ +# SmallCosts: two simultaneous scale constraints + +The original [SmallCosts definition](https://github.com/leanprover-community/riemann-hypothesis/blob/f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3/src/Formalism/SizeWindowBrackets/GrowthBoundGivesRiemannHypothesis.lean) +requires, among its conjuncts: + +```text +2*f*(x+1)*theta <= 1/x +6*f*(x+1)*(eta+1) <= b/x +``` + +With x>0, f>0 and eta>=0, these imply the necessary bounds: + +```text +theta <= 1/(2*f*x*(x+1)) +b >= 6*f*x*(x+1) +``` + +`f` is instantiated by `fPl H = (PhiSet (H := H)).card`, a +positive finite cardinality in the source construction. + +This creates a high-b and low-theta requirement as x grows. +The exact dyadic SizeWindows witnesses in this gym use b=1; +they are deliberately limited to that predicate and do not +establish satisfaction of SmallCosts, ThinScales, or the full +`GrowthInequalityDataExists` conjunction. + +Tasks RH-D-014 and RH-D-015 formalize the two implications +as independent verified Lean reconstruction targets. diff --git a/gyms/RHProofDistillation/gold.jsonl b/gyms/RHProofDistillation/gold.jsonl index 8638b9d5..26193cce 100644 --- a/gyms/RHProofDistillation/gold.jsonl +++ b/gyms/RHProofDistillation/gold.jsonl @@ -11,3 +11,5 @@ {"id":"RH-D-011","proof":"have hp := mul_le_mul_of_nonneg_left hBracket\n (Real.rpow_nonneg hx.le (C * eps))\nhave hexp : x ^ (C * eps) * x ^ ((1 / 2 : ℝ) + eps) =\n x ^ ((1 / 2 : ℝ) + (C + 1) * eps) := by\n rw [← Real.rpow_add hx]\n congr 1\n ring\nexact hErr.trans (hp.trans_eq hexp)"} {"id":"RH-D-012","proof":"have hp : 0 < x ^ ((1 / 2 : ℝ) - eps) := Real.rpow_pos_of_pos hx _\nhave hchain : x * x ^ ((1 / 2 : ℝ) - eps) ≤\n (n : ℝ) ^ 2 * x ^ ((1 / 2 : ℝ) - eps) := by\n calc\n x * x ^ ((1 / 2 : ℝ) - eps) ≤ x * (m : ℝ) :=\n mul_le_mul_of_nonneg_left hm hx.le\n _ ≤ k := hk_lower\n _ ≤ _ := hk_upper\nby_contra h\nhave hdiff : 0 < x - (n : ℝ) ^ 2 := sub_pos.mpr (lt_of_not_ge h)\nhave hprod : 0 < (x - (n : ℝ) ^ 2) * x ^ ((1 / 2 : ℝ) - eps) :=\n mul_pos hdiff hp\nnlinarith"} {"id":"RH-D-013","proof":"have hnreal : (0 : ℝ) < (n : ℝ) := by exact_mod_cast hn\nhave hpTT : 0 < x ^ (-(eps / 8)) := Real.rpow_pos_of_pos hx _\nhave hTTleft : (0 : ℝ) < x ^ (-(eps / 8)) * (n : ℝ) / 2 :=\n div_pos (mul_pos hpTT hnreal) (by norm_num)\nhave hnTreal : (0 : ℝ) < (nT : ℝ) := lt_of_lt_of_le hTTleft hTT\nhave hpT2 : 0 < x ^ (-eps) := Real.rpow_pos_of_pos hx _\nhave hT2ineq : x ^ (-eps) * (n : ℝ) ≤ (nT2 : ℝ) :=\n (le_div_iff₀ hnreal).mp hT2\nhave hnT2real : (0 : ℝ) < (nT2 : ℝ) :=\n lt_of_lt_of_le (mul_pos hpT2 hnreal) hT2ineq\nhave hmreal : (0 : ℝ) < (m : ℝ) :=\n lt_of_lt_of_le (Real.rpow_pos_of_pos hx _) hm\nexact ⟨by exact_mod_cast hnTreal, by exact_mod_cast hnT2real,\n by exact_mod_cast hmreal⟩"} +{"id":"RH-D-014","proof":"have hfactor : 0 ≤ 6 * f * (x + 1) := by positivity\nhave hone : (1 : ℝ) ≤ eta + 1 := by linarith\nhave hmul := mul_le_mul_of_nonneg_left hone hfactor\nhave hsub : 6 * f * (x + 1) ≤ b / x :=\n (by simpa only [mul_one] using hmul).trans hcost\nhave hbound : (6 * f * (x + 1)) * x ≤ b :=\n (le_div_iff₀ hx).mp hsub\ncalc\n 6 * f * x * (x + 1) = (6 * f * (x + 1)) * x := by ring\n _ ≤ b := hbound"} +{"id":"RH-D-015","proof":"have hden : 0 < 2 * f * x * (x + 1) := by positivity\napply (le_div_iff₀ hden).2\nhave hbound : (2 * f * (x + 1) * theta) * x ≤ 1 :=\n (le_div_iff₀ hx).mp hcost\ncalc\n theta * (2 * f * x * (x + 1)) =\n (2 * f * (x + 1) * theta) * x := by ring\n _ ≤ 1 := hbound"} diff --git a/gyms/RHProofDistillation/tasks.json b/gyms/RHProofDistillation/tasks.json index 51a5a380..91e216eb 100644 --- a/gyms/RHProofDistillation/tasks.json +++ b/gyms/RHProofDistillation/tasks.json @@ -102,5 +102,21 @@ "anchor": "weighted_bound", "description": "From the published SizeWindows bounds and positive x,n, prove that the TT, T2 and recurrence-depth counts are all nonzero.", "template": "import Mathlib\n\nnamespace RHGym\n\ntheorem size_window_counts_positive\n (x eps : ℝ) (n nT nT2 m : ℕ)\n (hx : 0 < x) (hn : 0 < n)\n (hTT : x ^ (-(eps / 8)) * (n : ℝ) / 2 ≤ (nT : ℝ))\n (hT2 : x ^ (-eps) ≤ (nT2 : ℝ) / (n : ℝ))\n (hm : x ^ ((1 / 2 : ℝ) - eps) ≤ (m : ℝ)) :\n 0 < nT ∧ 0 < nT2 ∧ 0 < m := by\n__PROOF__\n\nend RHGym\n" + }, + { + "id": "RH-D-014", + "difficulty": "medium", + "category": "small_cost_feasibility", + "anchor": "weighted_bound", + "description": "Derive the lower bound on b that follows from the published SmallCosts remainder inequality and nonnegative eta.", + "template": "import Mathlib\n\nnamespace RHGym\n\ntheorem small_cost_forces_large_b\n (x f eta b : ℝ) (hx : 0 < x) (hf : 0 ≤ f) (heta : 0 ≤ eta)\n (hcost : 6 * f * (x + 1) * (eta + 1) ≤ b / x) :\n 6 * f * x * (x + 1) ≤ b := by\n__PROOF__\n\nend RHGym\n" + }, + { + "id": "RH-D-015", + "difficulty": "medium", + "category": "small_cost_feasibility", + "anchor": "weighted_bound", + "description": "Bound the theta tolerance from the SmallCosts normalized character error budget when f and x are positive.", + "template": "import Mathlib\n\nnamespace RHGym\n\ntheorem small_cost_caps_theta\n (x f theta : ℝ) (hx : 0 < x) (hf : 0 < f)\n (hcost : 2 * f * (x + 1) * theta ≤ 1 / x) :\n theta ≤ 1 / (2 * f * x * (x + 1)) := by\n__PROOF__\n\nend RHGym\n" } ] From 7b03fffdfa17cfc0959b663fed9737b58ad9ea3a Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 20:09:29 +0800 Subject: [PATCH 27/34] research(rh): pin complete source-level family witness transition gates --- src/spiral_ln/rh_witness_lineage.py | 63 ++++++++++++++++++++++++++++- tests/test_rh_witness_lineage.py | 6 +++ 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/src/spiral_ln/rh_witness_lineage.py b/src/spiral_ln/rh_witness_lineage.py index d9c33dfa..ba9e2f02 100644 --- a/src/spiral_ln/rh_witness_lineage.py +++ b/src/spiral_ln/rh_witness_lineage.py @@ -13,7 +13,11 @@ PIN = "f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3" TERMS = ("SizeWindows", "SmallCosts", "GrowthInequalityDataExists", "ReducedGrowthInequalityDataExists", "ChainTied", "CoreAtH", - "RestSize", "Chain2aSizesModelEv", "FamCoreConstantBounds") + "RestSize", "Chain2aSizesModelEv", "FamCoreConstantBounds", + "SizesAt", "PlacesAt", "adm5", "adm6", "adm7", + "FamilyPropTwoSix", "FamilyCharacterSumBounds", "SizesFe", "TOPF", + "proposition_eleven_two_at_scale", "proposition_eleven_two_along_family", + "proposition_eleven_two_small_epsilon", "ChainCore") DECL = re.compile(r"^\s*(?:(?:private|protected|noncomputable)\s+)*(?:theorem|lemma|def|structure|class|abbrev|instance)\s+([^\s(:]+)") BOUNDARIES = {t: re.compile(r"(? None: root = args.source_root.resolve() result = scan(root) result["identity"] = verify(root) + result["gates"] = audit_gate_sources(root) args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n") print(json.dumps({ @@ -94,5 +99,61 @@ def main() -> None: }, sort_keys=True)) + +# Source-observed witness transitions. No theorem proof terms are re-exported. +GATE_FILES = { + "family": ("src/Formalism/SharpRestriction/GlobalSchurBounds/RamificationTwoAndConjugationAtQAndD.lean", + "1c1495ef81c77fa96f3c1a70106c1da9e24c0c5d"), + "cost": ("src/Development/AutomorphicArithmetic/ConductorsKronecker/CostPropositionBasicBound.lean", + "99e6384355aea45f0b5fe4726b4154444e7e82e1"), + "split": ("src/Formalism/SizeWindowBrackets/ChainSlopeWindows/PChain.lean", + "57559bc6dedbabbac7365c9f31fbbab09164edca"), +} +GATE_CHECKS = { + "windows": ("family", ("SizesAt D s", "PlacesAt D s", "ThickSetMeanBounds.SizeWindows")), + "smallCosts": ("family", ("SizesAt D s", "LargeX s.x", "ThickSetMeanBounds.SmallCosts")), + "proposition_eleven_two_at_scale": ("family", ( + "adm5 D s", "adm6 D s", "adm7 D s", "SizesAt D s", "PlacesAt D s", + "ThickSetMeanBounds.SmallCosts", "ThickSetMeanBounds.SizeWindows", + "cost_proposition_at_scale")), + "proposition_eleven_two_along_family": ("family", ( + "adm5", "adm6", "SizesAt", "PlacesAt", "adm7", + "proposition_eleven_two_at_scale")), + "proposition_eleven_two_small_epsilon": ("family", ( + "FamilyPropTwoSix", "FamilyCharacterSumBounds", "SizesFe", "TOPF")), + "cost_proposition_at_scale": ("cost", ( + "GrowthInequalityHypotheses", "SmallCosts", "SizeWindows", + "proposition_size_bound", "card_mul_delta_le_err")), + "size_windows_split": ("split", ("SizeWindows", "RestSize")), +} + + +def audit_gate_sources(root: Path) -> dict: + sources, file_ids = {}, {} + for key, (name, expected_sha) in GATE_FILES.items(): + raw = (root / name).read_bytes() + if git_blob_sha(raw) != expected_sha: + raise ValueError("upstream gate source blob mismatch: " + name) + sources[key] = raw.decode("utf-8") + file_ids[key] = {"path": name, "git_blob": expected_sha} + sites = {} + for name, (file_key, needles) in GATE_CHECKS.items(): + text = sources[file_key] + marker = "theorem " + name + " " + start = text.find(marker) + if start < 0: + raise ValueError("upstream theorem missing: " + name) + stop = text.find("\ntheorem ", start + len(marker)) + body = text[start:stop if stop >= 0 else len(text)] + absent = [needle for needle in needles if needle not in body] + if absent: + raise ValueError(f"upstream theorem {name} missing markers: {absent}") + sites[name] = {"path": file_ids[file_key]["path"], + "git_blob": file_ids[file_key]["git_blob"], + "start_line": text[:start].count("\n") + 1, + "observed_text_calls": list(needles)} + return {"mode": "pinned_source_text_calls_only", "proof_term_data": False, + "files": file_ids, "gates": sites} + if __name__ == "__main__": main() diff --git a/tests/test_rh_witness_lineage.py b/tests/test_rh_witness_lineage.py index c998a31b..064d733c 100644 --- a/tests/test_rh_witness_lineage.py +++ b/tests/test_rh_witness_lineage.py @@ -21,3 +21,9 @@ def test_declarations_and_references(tmp_path): def test_invalid_limit(tmp_path): with pytest.raises(ValueError): scan(tmp_path, limit=0) + + +def test_gate_catalog_pins_read_only_original_source(): + from spiral_ln.rh_witness_lineage import GATE_CHECKS, GATE_FILES + assert len(GATE_CHECKS) == 7 + assert all(len(blob) == 40 for _, blob in GATE_FILES.values()) From d7d2b6878072e2f42facba5f1bbbb3084a89174a Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 20:10:19 +0800 Subject: [PATCH 28/34] fix(rh): give Lean explicit intermediate inequality in SmallCosts proof --- gyms/RHProofDistillation/gold.jsonl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gyms/RHProofDistillation/gold.jsonl b/gyms/RHProofDistillation/gold.jsonl index 26193cce..90313d15 100644 --- a/gyms/RHProofDistillation/gold.jsonl +++ b/gyms/RHProofDistillation/gold.jsonl @@ -11,5 +11,5 @@ {"id":"RH-D-011","proof":"have hp := mul_le_mul_of_nonneg_left hBracket\n (Real.rpow_nonneg hx.le (C * eps))\nhave hexp : x ^ (C * eps) * x ^ ((1 / 2 : ℝ) + eps) =\n x ^ ((1 / 2 : ℝ) + (C + 1) * eps) := by\n rw [← Real.rpow_add hx]\n congr 1\n ring\nexact hErr.trans (hp.trans_eq hexp)"} {"id":"RH-D-012","proof":"have hp : 0 < x ^ ((1 / 2 : ℝ) - eps) := Real.rpow_pos_of_pos hx _\nhave hchain : x * x ^ ((1 / 2 : ℝ) - eps) ≤\n (n : ℝ) ^ 2 * x ^ ((1 / 2 : ℝ) - eps) := by\n calc\n x * x ^ ((1 / 2 : ℝ) - eps) ≤ x * (m : ℝ) :=\n mul_le_mul_of_nonneg_left hm hx.le\n _ ≤ k := hk_lower\n _ ≤ _ := hk_upper\nby_contra h\nhave hdiff : 0 < x - (n : ℝ) ^ 2 := sub_pos.mpr (lt_of_not_ge h)\nhave hprod : 0 < (x - (n : ℝ) ^ 2) * x ^ ((1 / 2 : ℝ) - eps) :=\n mul_pos hdiff hp\nnlinarith"} {"id":"RH-D-013","proof":"have hnreal : (0 : ℝ) < (n : ℝ) := by exact_mod_cast hn\nhave hpTT : 0 < x ^ (-(eps / 8)) := Real.rpow_pos_of_pos hx _\nhave hTTleft : (0 : ℝ) < x ^ (-(eps / 8)) * (n : ℝ) / 2 :=\n div_pos (mul_pos hpTT hnreal) (by norm_num)\nhave hnTreal : (0 : ℝ) < (nT : ℝ) := lt_of_lt_of_le hTTleft hTT\nhave hpT2 : 0 < x ^ (-eps) := Real.rpow_pos_of_pos hx _\nhave hT2ineq : x ^ (-eps) * (n : ℝ) ≤ (nT2 : ℝ) :=\n (le_div_iff₀ hnreal).mp hT2\nhave hnT2real : (0 : ℝ) < (nT2 : ℝ) :=\n lt_of_lt_of_le (mul_pos hpT2 hnreal) hT2ineq\nhave hmreal : (0 : ℝ) < (m : ℝ) :=\n lt_of_lt_of_le (Real.rpow_pos_of_pos hx _) hm\nexact ⟨by exact_mod_cast hnTreal, by exact_mod_cast hnT2real,\n by exact_mod_cast hmreal⟩"} -{"id":"RH-D-014","proof":"have hfactor : 0 ≤ 6 * f * (x + 1) := by positivity\nhave hone : (1 : ℝ) ≤ eta + 1 := by linarith\nhave hmul := mul_le_mul_of_nonneg_left hone hfactor\nhave hsub : 6 * f * (x + 1) ≤ b / x :=\n (by simpa only [mul_one] using hmul).trans hcost\nhave hbound : (6 * f * (x + 1)) * x ≤ b :=\n (le_div_iff₀ hx).mp hsub\ncalc\n 6 * f * x * (x + 1) = (6 * f * (x + 1)) * x := by ring\n _ ≤ b := hbound"} +{"id":"RH-D-014","proof":"have hfactor : 0 ≤ 6 * f * (x + 1) := by positivity\nhave hone : (1 : ℝ) ≤ eta + 1 := by linarith\nhave hmul := mul_le_mul_of_nonneg_left hone hfactor\nhave hpre : 6 * f * (x + 1) ≤ 6 * f * (x + 1) * (eta + 1) := by\n simpa only [mul_one] using hmul\nhave hsub : 6 * f * (x + 1) ≤ b / x := hpre.trans hcost\nhave hbound : (6 * f * (x + 1)) * x ≤ b :=\n (le_div_iff₀ hx).mp hsub\ncalc\n 6 * f * x * (x + 1) = (6 * f * (x + 1)) * x := by ring\n _ ≤ b := hbound"} {"id":"RH-D-015","proof":"have hden : 0 < 2 * f * x * (x + 1) := by positivity\napply (le_div_iff₀ hden).2\nhave hbound : (2 * f * (x + 1) * theta) * x ≤ 1 :=\n (le_div_iff₀ hx).mp hcost\ncalc\n theta * (2 * f * x * (x + 1)) =\n (2 * f * (x + 1) * theta) * x := by ring\n _ ≤ 1 := hbound"} From 1c5557bb408df6db9531178a760940c384acac55 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 20:14:57 +0800 Subject: [PATCH 29/34] research(rh): certify SizesAt and PlacesAt exact small-epsilon scalar scale --- .../SOURCE_REGIME_SCALE.md | 42 ++++++++ src/spiral_ln/rh_window_feasibility.py | 102 ++++++++++++++++++ tests/test_rh_window_feasibility.py | 20 ++++ 3 files changed, 164 insertions(+) create mode 100644 gyms/RHProofDistillation/SOURCE_REGIME_SCALE.md diff --git a/gyms/RHProofDistillation/SOURCE_REGIME_SCALE.md b/gyms/RHProofDistillation/SOURCE_REGIME_SCALE.md new file mode 100644 index 00000000..5514307c --- /dev/null +++ b/gyms/RHProofDistillation/SOURCE_REGIME_SCALE.md @@ -0,0 +1,42 @@ +# Small-epsilon family scale certificates from original SizesAt and PlacesAt + +Exact pinned upstream source at commit f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3: + +- Formalism/SharpRestriction/GlobalSchurBounds/ZetaZeroFreeRegion.lean, + Git blob 7746e5a5affe67117d4ba907dbcd2788f539db6e, defines + SizesAt and PlacesAt. +- Formalism/SharpRestriction/GlobalSchurBounds/RamificationTwoAndConjugationAtQAndD.lean, + Git blob 1c1495ef81c77fa96f3c1a70106c1da9e24c0c5d, proves + the identity x*delta1 = x^(1-epsilon/8) inside theorem windows. + +To match the actual family theorem, epsilon must be positive and below 1/52. +Take epsilon=2^-j, j=6 or7, and let L=log2(x)=16/epsilon. +Define the integer cardinalities and parameters by their binary logs: + + log2(n) = 2L+128 + log2(nT) = 2L+125 + log2(nT2) = 2L+112 + log2(m) = L/2-1 + log2(k) = 9L/2+160 + +with b=1, C=aE=Err=0 for the scalar-only test. + +The exact-rational checker verifies the six SizesAt inequalities, +the three PlacesAt inequalities, both finite-set cardinality caps +and 0= x^(2+31epsilon/4). + +The test establishes arithmetic consistency of finitely many scalar +inequalities for two specific choices of epsilon. The original family +theorems quantify over every sufficiently small positive epsilon, +arbitrarily large x, and actual groups, character sums and geometric +witnesses. b=1 also does not satisfy SmallCosts in the intended +large-x regime. No part of this certificate proves RH. diff --git a/src/spiral_ln/rh_window_feasibility.py b/src/spiral_ln/rh_window_feasibility.py index 751b5cc3..5f2ff5cf 100644 --- a/src/spiral_ln/rh_window_feasibility.py +++ b/src/spiral_ln/rh_window_feasibility.py @@ -18,6 +18,10 @@ PIN = "f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3" PREDICATE_FILE = "src/Formalism/SizeWindowBrackets/GrowthBoundGivesRiemannHypothesis.lean" PREDICATE_BLOB = "a3ece4b4aea97a95ba2977fa9e8d437e72677774" +SCALE_FILE = "src/Formalism/SharpRestriction/GlobalSchurBounds/ZetaZeroFreeRegion.lean" +SCALE_BLOB = "7746e5a5affe67117d4ba907dbcd2788f539db6e" +WINDOWS_FILE = "src/Formalism/SharpRestriction/GlobalSchurBounds/RamificationTwoAndConjugationAtQAndD.lean" +WINDOWS_BLOB = "1c1495ef81c77fa96f3c1a70106c1da9e24c0c5d" CLAUSES = ( "x_min", "eps_positive", "C_nonnegative", "n_positive", "b_positive", "aE_nonnegative", "aE_cap", "nT_floor", @@ -120,12 +124,101 @@ def source_pin(root: Path) -> dict: "nT2 ≤ n", "Err ≤ x ^ (C * ε)", "x ^ (-(ε / 8)) * n / 2 ≤ nT"): if phrase not in statement: raise ValueError(f"pinned predicate wording no longer matches: {phrase}") + scales = (root / SCALE_FILE).read_bytes() + if git_blob_sha(scales) != SCALE_BLOB: + raise ValueError("pinned SizesAt/PlacesAt source blob differs") + scale_text = scales.decode("utf-8") + for phrase in ("def SizesAt ", "def PlacesAt ", "2 + 8 * s.eps - δ", + "s.delta1 * D.R.n / 2", "s.x ^ (-s.eps)"): + if phrase not in scale_text: + raise ValueError("pinned family scale changed: " + phrase) + windows = (root / WINDOWS_FILE).read_bytes() + if git_blob_sha(windows) != WINDOWS_BLOB: + raise ValueError("pinned family windows source blob differs") + if "s.x * s.delta1 = s.x ^ (1 - s.eps / 8)" not in windows.decode("utf-8"): + raise ValueError("pinned delta1 scale identity missing") return {"source_commit": PIN, "source_file": PREDICATE_FILE, + "family_scale_file": SCALE_FILE, "family_scale_blob": SCALE_BLOB, + "windows_file": WINDOWS_FILE, "windows_blob": WINDOWS_BLOB, "git_blob": PREDICATE_BLOB, "predicate_sha256": hashlib.sha256(statement.encode()).hexdigest(), "original_unlicensed_source_redistributed": False} + + +def scale_witness(level: int) -> WindowParams: + """Central, exact dyadic SizesAt/PlacesAt scales in epsilon < 1/52.""" + if type(level) is not int or level not in (6, 7): + raise ValueError("source-regime epsilon level must be 6 or 7") + inv = 1 << level + xp = 16 * inv + ne = 2 * xp + 128 + me = xp // 2 - 1 + ke = 9 * xp // 2 + 160 + return WindowParams( + x_log2=xp, epsilon=Fraction(1, inv), n=1 << ne, + nT=1 << (ne - 3), nT2=1 << (ne - 16), + m=1 << me, k=Fraction(1 << ke), + ) + + +def binary_exponent(value: int) -> int: + if type(value) is not int or value <= 0 or value & (value - 1): + raise ValueError("positive integer power of two required") + return value.bit_length() - 1 + + +def evaluate_scale(p: WindowParams) -> dict: + """Check six SizesAt, three PlacesAt and caps by rational log2 exponents. + + Assumes the original windows theorem identity x * delta1 = x^(1-eps/8). + """ + xl, eps = Fraction(p.x_log2), p.epsilon + delta = eps / 4 + nlog, ntlog, nt2log, mlog = ( + Fraction(binary_exponent(value)) + for value in (p.n, p.nT, p.nT2, p.m) + ) + if p.k.denominator != 1: + raise ValueError("integer k required for exact power-of-two certificate") + klog = Fraction(binary_exponent(p.k.numerator)) + xdelta = xl * (1 - eps / 8) + checks = { + "epsilon_below_1_52": 0 < eps < Fraction(1, 52), + "SizesAt_n_lower": xl * (2 + 8 * eps - delta) <= nlog, + "SizesAt_n_upper": nlog <= xl * (2 + 8 * eps + delta), + "SizesAt_m_lower": xdelta * (Fraction(1, 2) - delta) <= mlog, + "SizesAt_m_upper": mlog <= xdelta * (Fraction(1, 2) + delta), + "SizesAt_k_lower": xl * (Fraction(9, 2) + 10 * eps - delta) <= klog, + "SizesAt_k_upper": klog <= xl * (Fraction(9, 2) + 10 * eps + delta), + "PlacesAt_TT_lower": nlog - xl * eps / 8 - 1 <= ntlog, + "PlacesAt_TT_upper": ntlog <= nlog - xl * eps / 8 + 1, + "PlacesAt_T2_lower": -xl * eps <= nt2log - nlog, + "finite_TT_cap": ntlog <= nlog, + "finite_T2_cap": nt2log <= nlog, + } + scalar = evaluate(p) + return { + "epsilon": str(eps), + "x_log2": p.x_log2, + "delta": str(delta), + "power_of_two_logs": { + "n": int(nlog), "nT": int(ntlog), "nT2": int(nt2log), + "m": int(mlog), "k": int(klog), + }, + "source_predicates": ["SizesAt", "PlacesAt", "SizeWindows"], + "checks": checks, + "passes": sum(checks.values()), + "total": len(checks), + "all_scale_checks_pass": all(checks.values()), + "sizewindows_passes": scalar["passes"], + "sizewindows_total": scalar["total"], + "sizewindows_pass": scalar["all_pass"], + "full_geometric_witness": False, + } + + def campaign(levels=range(1, 6)) -> dict: examples = [] for level in levels: @@ -145,7 +238,15 @@ def campaign(levels=range(1, 6)) -> dict: early = evaluate(smaller) if early["all_pass"] or early["checks"]["eventual_x"]: raise AssertionError("small x negative control did not fail eventual threshold") + source_cases = [evaluate_scale(scale_witness(j)) for j in (6, 7)] + if not all(c["all_scale_checks_pass"] and c["sizewindows_pass"] for c in source_cases): + raise AssertionError("source-regime scale witness failed an exact inequality") + weak = evaluate_scale(dyadic_witness(6)) + if weak["checks"]["SizesAt_n_lower"]: + raise AssertionError("weak scalar witness meets strong family rank bound") return { + "source_regime_examples": source_cases, + "weak_sizewindows_witness_fails_strong_SizesAt_n_lower": True, "schema_version": 1, "method": "Fraction arithmetic on dyadic integer powers, no floats", "predicate": "Formalism.LFunctionChainParameters.ThickSetMeanBounds.SizeWindows", @@ -174,6 +275,7 @@ def main() -> None: "negative_controls": len(result["negative_controls"]), "all_positive_pass": all(x["all_pass"] for x in result["positive_examples"]), "exact_arithmetic": True, + "strong_source_regime_examples": len(result["source_regime_examples"]), "full_geometric_witness": False}, sort_keys=True)) diff --git a/tests/test_rh_window_feasibility.py b/tests/test_rh_window_feasibility.py index dc49df30..989a7c7b 100644 --- a/tests/test_rh_window_feasibility.py +++ b/tests/test_rh_window_feasibility.py @@ -45,3 +45,23 @@ def test_power_exactness_and_exponent_budget_fail_closed(): def test_pin_rejects_missing_source(tmp_path): with pytest.raises(Exception): source_pin(tmp_path) + + +def test_original_sizesat_placesat_small_epsilon_regime(): + from spiral_ln.rh_window_feasibility import scale_witness, evaluate_scale + for j in (6, 7): + certificate = evaluate_scale(scale_witness(j)) + assert certificate["passes"] == certificate["total"] == 12 + assert certificate["all_scale_checks_pass"] + assert certificate["sizewindows_passes"] == certificate["sizewindows_total"] == 16 + assert certificate["sizewindows_pass"] + assert not evaluate_scale(dyadic_witness(6))["checks"]["SizesAt_n_lower"] + with pytest.raises(ValueError): + scale_witness(5) + + +def test_exact_exponent_log2_requires_power_of_two(): + from spiral_ln.rh_window_feasibility import binary_exponent + assert binary_exponent(2**2176) == 2176 + with pytest.raises(ValueError): + binary_exponent(3) From 5ccbe666d2565ad42f47b5748359fd17f903d81e Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 20:19:07 +0800 Subject: [PATCH 30/34] research(rh): test joint LargeX and SmallCosts scalar feasibility at stronger scales --- .github/workflows/rh-witness-lineage.yml | 10 +- .../JOINT_SCALAR_ENVELOPE.md | 47 ++++++ src/spiral_ln/rh_joint_scalar_envelope.py | 145 ++++++++++++++++++ tests/test_rh_joint_scalar_envelope.py | 24 +++ 4 files changed, 225 insertions(+), 1 deletion(-) create mode 100644 gyms/RHProofDistillation/JOINT_SCALAR_ENVELOPE.md create mode 100644 src/spiral_ln/rh_joint_scalar_envelope.py create mode 100644 tests/test_rh_joint_scalar_envelope.py diff --git a/.github/workflows/rh-witness-lineage.yml b/.github/workflows/rh-witness-lineage.yml index 88929886..8c5732eb 100644 --- a/.github/workflows/rh-witness-lineage.yml +++ b/.github/workflows/rh-witness-lineage.yml @@ -7,6 +7,8 @@ on: - 'src/spiral_ln/rh_witness_lineage.py' - 'tests/test_rh_window_feasibility.py' - 'tests/test_rh_witness_lineage.py' + - 'src/spiral_ln/rh_joint_scalar_envelope.py' + - 'tests/test_rh_joint_scalar_envelope.py' - '.github/workflows/rh-witness-lineage.yml' pull_request: paths: @@ -45,7 +47,7 @@ jobs: working-directory: evalmath run: | python -m pip install -e '.[test]' - python -m pytest -q tests/test_rh_window_feasibility.py tests/test_rh_witness_lineage.py + python -m pytest -q tests/test_rh_window_feasibility.py tests/test_rh_witness_lineage.py tests/test_rh_joint_scalar_envelope.py - name: Exact rational feasibility and negative controls working-directory: evalmath run: | @@ -53,6 +55,12 @@ jobs: python -m spiral_ln.rh_window_feasibility \ --source-root ../upstream \ --levels 5 --output rh-witness/exact-scalar-witnesses.json + - name: Check LargeX and SmallCosts sufficient scalar envelopes + working-directory: evalmath + run: | + python -m spiral_ln.rh_joint_scalar_envelope \ + --source-root ../upstream \ + --output rh-witness/joint-scalar-envelope.json - name: Trace witness source declarations over complete pinned tree working-directory: evalmath run: | diff --git a/gyms/RHProofDistillation/JOINT_SCALAR_ENVELOPE.md b/gyms/RHProofDistillation/JOINT_SCALAR_ENVELOPE.md new file mode 100644 index 00000000..4c30f924 --- /dev/null +++ b/gyms/RHProofDistillation/JOINT_SCALAR_ENVELOPE.md @@ -0,0 +1,47 @@ +# Exact sufficient scalar conditions for LargeX and SmallCosts + +Source pin: f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3. +Original LargeX and smallCosts proofs occur in +Formalism/SharpRestriction/GlobalSchurBounds/RamificationTwoAndConjugationAtQAndD.lean. + +The first two source-regime witnesses chose log2(x)=16/epsilon. +At these scales x^(epsilon/8)=4, so the sufficient logarithmic +criterion for 8*x^5 <= exp(x^(epsilon/8)) fails. + +Increase to log2(x)=256/epsilon, with epsilon=1/64 and 1/128. +Choose binary exponents of the other parameters at the central +SizesAt scales: + + L = log2(x), q = epsilon*L = 256 + log2(n) = 2L+8q + log2(m) = (L-q/8)/2 + log2(k) = 9L/2+10q + log2(nT) = log2(n)-q/8-1 + log2(nT2) = log2(n)-q + +To test scalar SmallCosts choose f=2n, eta=1, +b=12*f*x*(x+1), theta=1/(4*f*x*(x+1)), Cd=CL=0, c=1. +Under these choices the two rational cost inequalities hold directly. + +LargeX includes 8*x^5 <= exp(x^(epsilon/8)) and +48*x^5 <= exp(x^(epsilon/4)). Since x=2^L and log(2)<=1, +log(8*x^5)<=3+5L and log(48*x^5)<=6+5L. +Monotonicity of exp makes the integer inequalities +3+5L <= x^(epsilon/8) and 6+5L <= x^(epsilon/4) +sufficient. The checker verifies them with exact integer arithmetic. + +For Cd=CL=0, moveCost=3 log(x+1). Since x>=1 and x=2^L, +log(x+1)<=L+1, so it suffices that +3(L+1)<=x^(1/2+epsilon). The source's two other power +thresholds are checked with exact dyadic exponents. + +Both examples also pass the six SizesAt and three PlacesAt bounds, +the finite-set cardinality caps, and all sixteen SizeWindows scalar +conditions after substituting the new b. + +These conditions are an exact arithmetic certificate with documented +elementary calculus implications. The Python tests do not formally +prove the general logarithm and exponential comparison facts in Lean. +These free scalar choices are not asserted to be the actual +Scale.b or Scale.theta, nor do they construct any arithmetic +character estimates, adm5/6/7, or the eventual family witness. diff --git a/src/spiral_ln/rh_joint_scalar_envelope.py b/src/spiral_ln/rh_joint_scalar_envelope.py new file mode 100644 index 00000000..fa9adfa7 --- /dev/null +++ b/src/spiral_ln/rh_joint_scalar_envelope.py @@ -0,0 +1,145 @@ +"""Source-pinned sufficient scalar certificates for LargeX and SmallCosts. + +All checks use integer/Fraction inequalities. For exponential/logarithmic +conditions we verify explicit sufficient inequalities using standard analytic +facts log(2) <= 1, log(x+1) <= 1+log2(x) for x a power of 2, and monotonicity +of exp. These facts are explained in the report, not proved in this module. + +This is a scalar envelope, not an actual Scale/D7/FamP construction. +""" +from __future__ import annotations + +import argparse +from dataclasses import replace +from fractions import Fraction +import json +from pathlib import Path + +from spiral_ln.rh_window_feasibility import ( + WindowParams, binary_exponent, evaluate, evaluate_scale, scale_witness, source_pin, +) + + +def enlarged_scale(level: int) -> WindowParams: + """x far beyond the large-x thresholds for epsilon=1/64 or 1/128.""" + if type(level) is not int or level not in (6, 7): + raise ValueError("level must be 6 or 7") + inv = 1 << level + eps = Fraction(1, inv) + L = 256 * inv + q = L // inv + n_exp = 2 * L + 8 * q + m_exp = (L - q // 8) // 2 + k_exp = 9 * L // 2 + 10 * q + nT_exp = n_exp - q // 8 - 1 + nT2_exp = n_exp - q + return WindowParams( + x_log2=L, epsilon=eps, + n=1 << n_exp, nT=1 << nT_exp, nT2=1 << nT2_exp, + m=1 << m_exp, k=Fraction(1 << k_exp), + ) + + +def bounds(p: WindowParams) -> dict: + """Exact arithmetic for sufficient, rather than evaluated transcendental, gates.""" + L = p.x_log2 + eps = p.epsilon + x = p.x + # The original proof uses f = 2*n in smallCosts. Here these are + # independent scalar choices; not claimed to be Scale.b/Scale.theta. + f = 2 * p.n + eta = Fraction(1) + b = Fraction(12 * f) * x * (x + 1) + theta = Fraction(1, 4 * f) / (x * (x + 1)) + revised = replace(p, b=b) + size = evaluate(revised) + scale = evaluate_scale(revised) + checks = { + "large_x_at_least_3": 3 <= x, + # Since log(8) < 3 and log(x)=L*log(2) <= L: + "sufficient_8x5_le_exp_xeps8": 3 + 5 * L <= p.power(eps / 8), + # Since log(48) < 6: + "sufficient_48x5_le_exp_xeps4": 6 + 5 * L <= p.power(eps / 4), + "large_x_power_two": 2 <= p.power(3 * eps / 4), + "large_x_power_26": 26 <= p.power(3 * eps / 8), + # With Cd=CL=0, moveCost = 3*log(x+1) and + # log(x+1) <= (L+1)*log(2) <= L+1. + "sufficient_move_cost": 3 * (L + 1) <= p.power(Fraction(1, 2) + eps), + "eta_positive": 0 < eta, + "eta_log_condition": 1 <= p.power(eps / 4), # log(1)=0 + "theta_positive": 0 < theta, + "small_cost_theta": 2 * f * (x + 1) * theta <= 1 / x, + "small_cost_b": 6 * f * (x + 1) * (eta + 1) <= b / x, + } + return { + "epsilon": str(eps), "x_log2": L, + "log2_n": binary_exponent(p.n), + "log2_k": binary_exponent(p.k.numerator), + "f_relation": "f=2n", + "parameter_choices": { + "eta": 1, "c": 1, "Cd": 0, "CL": 0, + "b_formula": "12*f*x*(x+1)", + "theta_formula": "1/(4*f*x*(x+1))", + "b_bits": b.numerator.bit_length(), + "theta_denominator_bits": theta.denominator.bit_length(), + }, + "sufficient_gate_inequalities": checks, + "all_sufficient_gates_pass": all(checks.values()), + "sizewindows_scalar_passes": size["passes"], + "sizewindows_scalar_total": size["total"], + "source_scale_passes": scale["passes"], + "source_scale_total": scale["total"], + "all_scale_and_sizewindow": size["all_pass"] and scale["all_scale_checks_pass"], + "full_scale_structure_proved": False, + "full_analytic_or_geometric_witness_proved": False, + } + + +def campaign() -> dict: + cases = [bounds(enlarged_scale(j)) for j in (6, 7)] + if not all(c["all_sufficient_gates_pass"] and c["all_scale_and_sizewindow"] for c in cases): + raise AssertionError("a sufficient scalar gate failed") + early = scale_witness(6) + precondition = 3 + 5 * early.x_log2 <= early.power(early.epsilon / 8) + if precondition: + raise AssertionError("short-scale negative control unexpectedly sufficient") + return { + "schema_version": 1, + "kind": "source_regime_exact_scalar_sufficient_conditions", + "method": "exact integers/Fractions, plus cited elementary log-exp inequalities", + "cases": cases, + "negative_control": { + "epsilon": "1/64", "x_log2": early.x_log2, + "short_scale_passes_sufficient_8x5_exp_test": precondition, + "interpretation": "failure of this sufficient test does not alone refute LargeX", + }, + "logical_bridge": [ + "log(2) <= 1", + "for x=2^L and x>=1, log(x+1) <= L+1", + "log(8*x^5) <= 3+5*L and log(48*x^5) <= 6+5*L", + "exp is strictly increasing", + ], + "scope": "Scalar gates for chosen free parameters only; actual Scale.b, Scale.theta, adm5, adm6, adm7 and geometric family data are not constructed", + } + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + result = campaign() + result["source_identity"] = source_pin(args.source_root.resolve()) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, sort_keys=True, indent=2) + "\n") + print(json.dumps({ + "cases": len(result["cases"]), "all_gates_pass": all(c["all_sufficient_gates_pass"] for c in result["cases"]), + "all_sizewindows_and_scale": all(c["all_scale_and_sizewindow"] for c in result["cases"]), + "proof_term_data": False, + "source_commit": result["source_identity"]["source_commit"], + "full_geometric_witness": False, + }, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/tests/test_rh_joint_scalar_envelope.py b/tests/test_rh_joint_scalar_envelope.py new file mode 100644 index 00000000..fe5e7621 --- /dev/null +++ b/tests/test_rh_joint_scalar_envelope.py @@ -0,0 +1,24 @@ +from spiral_ln.rh_joint_scalar_envelope import ( + bounds, campaign, enlarged_scale, +) +from spiral_ln.rh_window_feasibility import scale_witness + + +def test_large_x_and_smallcosts_sufficient_scalar_envelopes(): + receipt = campaign() + assert len(receipt["cases"]) == 2 + for case in receipt["cases"]: + assert case["all_sufficient_gates_pass"] + assert case["sizewindows_scalar_passes"] == case["sizewindows_scalar_total"] == 16 + assert case["source_scale_passes"] == case["source_scale_total"] == 12 + assert case["all_scale_and_sizewindow"] + assert not case["full_scale_structure_proved"] + + +def test_short_scale_fails_sufficient_exponential_check(): + prior = scale_witness(6) + assert prior.power(prior.epsilon / 8) == 4 + assert 3 + 5 * prior.x_log2 > 4 + result = bounds(enlarged_scale(6)) + assert result["x_log2"] == 16384 + assert result["sufficient_gate_inequalities"]["sufficient_8x5_le_exp_xeps8"] From 9aba52d249bd8f126d636de49dc290cfeb058ebe Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 20:22:53 +0800 Subject: [PATCH 31/34] docs(rh): pin verified joint scalar feasibility receipt and caveats --- .../JOINT_SCALAR_ENVELOPE.md | 4 ++ .../joint_scalar_envelope_receipt.json | 57 +++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 gyms/RHProofDistillation/joint_scalar_envelope_receipt.json diff --git a/gyms/RHProofDistillation/JOINT_SCALAR_ENVELOPE.md b/gyms/RHProofDistillation/JOINT_SCALAR_ENVELOPE.md index 4c30f924..39ff1d40 100644 --- a/gyms/RHProofDistillation/JOINT_SCALAR_ENVELOPE.md +++ b/gyms/RHProofDistillation/JOINT_SCALAR_ENVELOPE.md @@ -45,3 +45,7 @@ prove the general logarithm and exponential comparison facts in Lean. These free scalar choices are not asserted to be the actual Scale.b or Scale.theta, nor do they construct any arithmetic character estimates, adm5/6/7, or the eventual family witness. + +## Verified CI receipt + +The exact source-attested [workflow run](https://github.com/MoralityLabAI/EvalMath/actions/runs/44903295524) passed 12 CPU-only tests and emitted the complete [JSON artifact](https://github.com/MoralityLabAI/EvalMath/actions/runs/44903295524/artifacts/14706404309). The archived JSON SHA-256 is `8b28912df718694c1e3978fc8520d270ed3f1b5a845d5ad2430735598c40249d`. The repo retains a [compact machine-readable verification receipt](joint_scalar_envelope_receipt.json) with the same source identities, scale exponents, pass counts and limitations. diff --git a/gyms/RHProofDistillation/joint_scalar_envelope_receipt.json b/gyms/RHProofDistillation/joint_scalar_envelope_receipt.json new file mode 100644 index 00000000..6cc776d6 --- /dev/null +++ b/gyms/RHProofDistillation/joint_scalar_envelope_receipt.json @@ -0,0 +1,57 @@ +{ + "schema_version": 1, + "kind": "pinned_original_source_scalar_joint_feasibility", + "proof_term_data": false, + "source_commit": "f150e02623b1e2bbe1f1da8eab5ffee5e930a6a3", + "evalmath_commit_under_test": "5ccbe666d2565ad42f47b5748359fd17f903d81e", + "workflow_run": "https://github.com/MoralityLabAI/EvalMath/actions/runs/44903295524", + "workflow_artifact": "https://github.com/MoralityLabAI/EvalMath/actions/runs/44903295524/artifacts/14706404309", + "archived_json_sha256": "8b28912df718694c1e3978fc8520d270ed3f1b5a845d5ad2430735598c40249d", + "zip_sha256": "ea433bec65b2f0e4d9e484857ed2108db5e9c13191c408cd6f50d9c91c1c72cf", + "source_blobs": { + "SizeWindows": "a3ece4b4aea97a95ba2977fa9e8d437e72677774", + "SizesAt_PlacesAt": "7746e5a5affe67117d4ba907dbcd2788f539db6e", + "windows_LargeX_smallCosts": "1c1495ef81c77fa96f3c1a70106c1da9e24c0c5d" + }, + "cases": [ + { + "epsilon": "1/64", + "x_log2": 16384, + "n_log2": 34816, + "k_log2": 76288, + "b_bits": 67589, + "theta_denominator_bits": 67588, + "SizesAt_PlacesAt_and_caps": "12/12", + "SizeWindows": "16/16", + "largeX_and_smallCosts_sufficient_tests": "11/11" + }, + { + "epsilon": "1/128", + "x_log2": 32768, + "n_log2": 67584, + "k_log2": 150016, + "b_bits": 133125, + "theta_denominator_bits": 133124, + "SizesAt_PlacesAt_and_caps": "12/12", + "SizeWindows": "16/16", + "largeX_and_smallCosts_sufficient_tests": "11/11" + } + ], + "negative_control": { + "epsilon": "1/64", + "x_log2": 1024, + "finding": "The shorter scale fails the sufficient 8*x^5 exponential comparison; this does not by itself refute LargeX" + }, + "proof_assumptions": [ + "For x=2^L, log(x+1) <= L+1 and log(2) <= 1", + "Monotonicity of exp converts the rational-exponent comparisons into sufficient LargeX bounds", + "Parameter values are chosen freely, not via the original structured Scale object", + "Source predicates are matched by pinned Git blobs; original unlicensed proof bodies are not redistributed" + ], + "limitations": [ + "The numerical checks are exact, but generic logarithmic lemmas were used as mathematical facts rather than independently formalized in Lean", + "Only two epsilon values were tested, with single x values each", + "These checks do not construct the original Scale, D7, FamP, adm5, adm6, adm7, GPsi, or theta/Galois data", + "The overall claimed RH proof has not been independently reconstructed here" + ] +} From b9056a7c012597ccf970912dac202627c7245a2a Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 22:05:07 +0800 Subject: [PATCH 32/34] docs(rh): designate MathCan as proof-math home; keep EvalMath as benchmark --- gyms/RHProofDistillation/README.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/gyms/RHProofDistillation/README.md b/gyms/RHProofDistillation/README.md index 1791ce6c..d95feae0 100644 --- a/gyms/RHProofDistillation/README.md +++ b/gyms/RHProofDistillation/README.md @@ -58,3 +58,18 @@ See [core_gm_proof_map.md](core_gm_proof_map.md) and [core_gm_sources.json](core ## Character-balance and size-window benchmarks Tasks RH-D-009 through RH-D-011 are new isolated Lean subgoals suggested by the source-verified `CharacterBalanceMoves.core` and compiled `proposition_size_bound` references. They test cancellation of finite-group averaging, aggregation of a double-indexed local correction, and real-power bound propagation. The real analytic and geometric hypotheses remain explicit. Each reference proof is compiled by the standard Lean CI grader; the gold proof file is intended only for smoke tests. + +## Canonical mathematical research home: MathCan + +The mathematical analysis, independent Init-only Lean integer exponent +certificates, exact SizeWindows/SizesAt/PlacesAt scalar checks, +and joint LargeX/SmallCosts feasibility oracles have been moved to +[MathCan PR #148](https://github.com/patrickdugan/MathCan/pull/148), +under `research/rh_proof_distillation` and `MathCan/RHWindowExponents.lean`. + +This EvalMath directory retains the **scored Lean reconstruction gym**, +its Mathlib reference proofs, source-pinned published-cache dependency +extractor and CI receipts. MathCan uses Lean 4.35 with Init; the source +proof and this benchmark use a separate Mathlib environment. +Current research should file mathematical propositions and formal lemmas +in MathCan and reuse this gym for evaluation experiments. From b784d90575a7c975f5b4ea6d9cb8dc4d799e4ff9 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 22:56:27 +0800 Subject: [PATCH 33/34] fix(rh): replace backtracking module regexp with linear validation --- src/spiral_ln/rh_full_closure.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/spiral_ln/rh_full_closure.py b/src/spiral_ln/rh_full_closure.py index 10b6b1ce..818c3e08 100644 --- a/src/spiral_ln/rh_full_closure.py +++ b/src/spiral_ln/rh_full_closure.py @@ -12,14 +12,12 @@ import hashlib import json from pathlib import Path -import re import subprocess from typing import Iterable from spiral_ln.rh_distillation import anchor_audit, parse_imports ROOT = Path(__file__).resolve().parents[2] / "gyms" / "RHProofDistillation" -MODULE = re.compile(r"^[^\s/]+(?:\.[^\s/]+)*$", re.UNICODE) INTERNAL = frozenset({ "Statements", "Main", "Development", "Formalism", "GroundTheory", "ReciprocityTheory", "CompanionTheory", "PositivityTheory", @@ -34,10 +32,11 @@ def module_name(path: str) -> str: def module_file(src: Path, module: str) -> Path: - if not MODULE.fullmatch(module) or any(part in ("", ".", "..") for part in module.split(".")): + # Component-wise validation is linear in the input size. + parts = module.split(".") + if any(not part or any(ch.isspace() or ch in ("/", chr(92)) or ord(ch) == 0 for ch in part) for part in parts): raise ValueError(f"invalid Lean module: {module!r}") - return src.joinpath(*module.split(".")).with_suffix(".lean") - + return src.joinpath(*parts).with_suffix(".lean") def verify_full_checkout(root: Path, manifest: dict, minimum: int) -> dict: head = subprocess.check_output(["git", "-C", str(root), "rev-parse", "HEAD"], text=True).strip() From f4955b89842fe3c43520ce12cc36b78a7b52b885 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sat, 21 Nov 2026 22:56:29 +0800 Subject: [PATCH 34/34] test(rh): cover adversarial and invalid Lean module paths --- tests/test_rh_full_closure.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/tests/test_rh_full_closure.py b/tests/test_rh_full_closure.py index ba736ba7..b02e5853 100644 --- a/tests/test_rh_full_closure.py +++ b/tests/test_rh_full_closure.py @@ -25,11 +25,18 @@ def test_bad_module_name_rejected(tmp_path): assert module_name("src/Development/Foo.lean") == "Development.Foo" with pytest.raises(ValueError): module_name("Development/Foo.lean") - for m in ("../evil", "A..B", "C/D"): + for m in ("../evil", "A..B", "C/D", "C\\D", "A. B", "A.\nB", "", "A.", "A\x00B"): with pytest.raises(ValueError): module_file(tmp_path, m) +def test_long_adversarial_module_is_rejected_in_linear_scan(tmp_path): + with pytest.raises(ValueError): + module_file(tmp_path, "!." * 12000 + "/") + assert module_file(tmp_path, "Development.AutomorphicArithmetic.X") == ( + tmp_path / "Development" / "AutomorphicArithmetic" / "X.lean" + ) + def test_unresolved_internal_count(tmp_path): src = tmp_path / "src" src.mkdir()