#!/usr/bin/env python3
"""Verify return #1555's corrected `lean-compile.log`. Seven checks.
C1 the served `Route27.lean` fetches and hashes to its recorded sha256
C2 the served ORIGINAL `lean-compile.log` (33d34902...) fetches and hashes to its sha256
C3 the SERVED corrected copy (b99705ce...) fetches and hashes to the sha declared in `files`
C4 the corrected copy IS the original minus the hard-coded home prefix, twice, and is otherwise
BYTE-IDENTICAL: canonicalising the two removed spans to one marker makes the two files equal,
so no observation, no verdict, no label and no other byte moved (253 -> 161 bytes, -92)
C5 the corrected copy carries no home path by the platform's own rule
(src/lib/files.ts findHomePath): the file note that opened job #2960 clears
C6 the core Lean toolchain, run from a fresh directory on the freshly verified `Route27.lean`,
exits 0 -- the log's claim is executable here, not merely plausible
C7 two negative controls are refused by the SAME code: a copy with the home prefix re-inserted
(C5's rule must catch it) and a copy with one observed byte changed (C4's equality must
catch it). A check that cannot fail proves nothing.
stdout is the artifact: seven deterministic lines and a verdict -- no timings, no temporary paths,
no machine-specific bytes. The compile's wall time goes to stderr. LF only, on every OS.
Usage:
python verify-lean-log.py # against the project server
python verify-lean-log.py --local-dir
# against local copies of the same three shas
Exit 0 only if all seven pass.
"""
import argparse
import hashlib
import os
import re
import shutil
import subprocess
import sys
import tempfile
import time
import urllib.request
ORIGINAL_SHA = "33d349026dab5269d24435badcd605b0d9f2b42e2c0b09e284443132c0b1df86"
CORRECTED_SHA = "b99705cecede55bbd2884085377f092369c44cb72f3468c2aa56fed73669c736"
LEAN_SHA = "1d710248e0e04f1fe9c2e322037bd741e2901b36ef644e456c8077eff54baa20"
HOME_PREFIX = b"/Users/victor/workspace/twin-prime-conjecture/"
# The platform's own rule, src/lib/files.ts:41, copied as a pattern rather than imported:
# this script must run on a machine with no checkout of the platform.
HOME_RX = re.compile(r"""(?:^|[\s"'(=:])((?:/Users|/home|C:\\Users)[/\\][A-Za-z0-9._-]+[/\\][^\s"')]{0,80})""")
NAMES = {ORIGINAL_SHA: "lean-compile.log.original",
CORRECTED_SHA: "lean-compile.log",
LEAN_SHA: "Route27.lean"}
def fetch(base, sha, local_dir):
if local_dir:
return open(os.path.join(local_dir, NAMES[sha]), "rb").read()
req = urllib.request.Request(f"{base}/files/{sha}")
req.add_header("Accept", "application/octet-stream")
req.add_header("User-Agent", "Buffy-FreebuffDesktop")
with urllib.request.urlopen(req, timeout=120) as r:
return r.read()
def diff_regions(original: bytes, candidate: bytes):
"""Walk both byte strings and return the regions where they differ.
Not `original.replace(...)`: a check that re-applies the very substitution it is
checking is a tautology. This walks the bytes, and a region only counts if the
original side is EXACTLY the prefix -- so a single flipped byte anywhere else
shows up as a region of the wrong length and fails.
"""
regions, i, j = [], 0, 0
while i < len(original) or j < len(candidate):
if i < len(original) and j < len(candidate) and original[i] == candidate[j]:
i += 1
j += 1
continue
span = original[i:i + len(HOME_PREFIX)]
if span == HOME_PREFIX:
regions.append((i, HOME_PREFIX))
i += len(HOME_PREFIX)
continue
return None # a difference that is not the prefix at all
return regions
def is_minimal_repair(original: bytes, candidate: bytes) -> bool:
"""C4's rule, as a predicate, so C7 can call it on a control too."""
regions = diff_regions(original, candidate)
return (regions is not None and len(regions) == 2
and len(candidate) == len(original) - 2 * len(HOME_PREFIX))
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--base", default="https://solveathome.org")
ap.add_argument("--local-dir")
ap.add_argument("--wall", type=float, default=600.0, help="wall limit for the compile, seconds")
a = ap.parse_args()
# stdout is the artifact and must reproduce byte for byte elsewhere: LF only, on every OS.
sys.stdout.reconfigure(newline="\n")
results: list[tuple[str, bool, str]] = []
def check(label, ok, detail=""):
results.append((label, bool(ok), detail))
lean = fetch(a.base, LEAN_SHA, a.local_dir)
check("C1 served Route27.lean hashes to its recorded sha256",
hashlib.sha256(lean).hexdigest() == LEAN_SHA, LEAN_SHA[:12])
orig = fetch(a.base, ORIGINAL_SHA, a.local_dir)
check("C2 served original lean-compile.log hashes to its recorded sha256",
hashlib.sha256(orig).hexdigest() == ORIGINAL_SHA, ORIGINAL_SHA[:12])
fixed = fetch(a.base, CORRECTED_SHA, a.local_dir)
check("C3 served corrected copy hashes to the sha declared in `files`",
hashlib.sha256(fixed).hexdigest() == CORRECTED_SHA, CORRECTED_SHA[:12])
regions = diff_regions(orig, fixed)
check("C4 corrected copy is the original minus the home prefix twice, byte-identical otherwise",
is_minimal_repair(orig, fixed),
f"{len(orig)} -> {len(fixed)} bytes, -{2 * len(HOME_PREFIX)}, "
f"{0 if regions is None else len(regions)} removed spans at "
f"{[] if regions is None else [o for o, _ in regions]}")
check("C5 corrected copy carries no home path (platform rule src/lib/files.ts findHomePath)",
HOME_RX.search(fixed.decode("utf-8", "replace")) is None)
tool = shutil.which("lean")
if not tool:
check("C6 core Lean toolchain compiles the served Route27.lean from a fresh directory", False,
"lean not on PATH")
else:
with tempfile.TemporaryDirectory(prefix="leanlog-") as d:
with open(os.path.join(d, "Route27.lean"), "wb") as fh:
fh.write(lean)
t0 = time.time()
proc = subprocess.run([tool, "Route27.lean"], cwd=d, capture_output=True, timeout=a.wall)
print(f"[stderr] lean Route27.lean: exit {proc.returncode}, wall {time.time() - t0:.1f}s, "
f"stdout {len(proc.stdout)} B, stderr {len(proc.stderr)} B", file=sys.stderr)
if proc.returncode != 0:
print(proc.stdout.decode("utf-8", "replace")[-2000:], file=sys.stderr)
check("C6 core Lean toolchain compiles the served Route27.lean from a fresh directory",
proc.returncode == 0, f"exit {proc.returncode}")
reinserted = fixed.replace(b".solveathome/", HOME_PREFIX + b".solveathome/", 1)
tampered = fixed.replace(b"OK", b"NO", 1)
caught_prefix = HOME_RX.search(reinserted.decode("utf-8", "replace")) is not None
caught_tamper = not is_minimal_repair(orig, tampered)
check("C7 negative controls refused by C5's rule and by C4's equality",
caught_prefix and caught_tamper,
f"re-inserted prefix caught={caught_prefix}, one observed byte changed caught={caught_tamper}")
passed = sum(1 for _, ok, _ in results if ok)
for label, ok, detail in results:
print(f"[{'ok ' if ok else 'FAIL'}] {label}" + (f" ({detail})" if detail else ""))
print(f"verdict: {'PASS' if passed == len(results) else 'FAIL'} {passed}/{len(results)}")
return 0 if passed == len(results) else 1
if __name__ == "__main__":
sys.exit(main())