#!/usr/bin/env python3 """Independent checker for the #1459 reproducibility audit (work2818/check-1459-repro.py). Shares no code with the instrument: it re-fetches the record itself, re-derives the layout decision from the plan's manifest, and re-measures each claim by a *different* mechanism than the producer used. Producer claims are re-read from the record and from the store; nothing is taken from a local work directory. C1 The plan's target reproduces from the plan's manifest alone. Mechanism: fetch the 25 manifest files by pinned sha, run the plan's checker with a binary capture, hash RAW bytes, compare with the sha the return itself records for check-2818b.json. C2 The record names two revisions of one dependency, and the pinned one is a byte-prefix of the other. Mechanism: byte comparison of the two blobs, no JSON parsing at all. C3 The extra rows in the later revision are identifiable and land on the n = 12 side. Mechanism: diff the parsed rows of the two revisions as sets of JSON objects. C4 The filed analysis artifact reproduces from none of the readings. Mechanism: three digests computed from freshly fetched bytes, compared with the recorded one. C5 The target's pinned digest is CRLF-specific (raw and LF-normalized digests differ). Mechanism: direct byte-level newline counting plus two hashes of the same content. C6 Return #1459's reported fingerprint is the protocol rule applied to the SERVED plan, and the reason a local recomputation differed is a non-schema key in the submission. Mechanism: apply the published rule (sha256 of the prefix plus compact JSON, recursively sorted object keys, array order preserved, `cost` excluded) to the served plan as one object, note that it equals the recorded fingerprint, then apply the same rule to that plan with `target_sha256` restored and note that it does not -- which localises the difference to that one key. Exit 0 iff every claim holds. Usage: verify-2818c.py [--out verify-2818c.json] """ import argparse import collections import hashlib import json import os import shutil import subprocess import sys import urllib.request HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = "https://solveathome.org" PROJECT = "https://solveathome.org/projects/twin-primes" RETURN = 1459 CHECKER = "verify-2818b.py" ANALYZER = "analyze-reps.py" TARGET = "check-2818b.json" ARTIFACT = "analysis-reps.json" PYEXE = os.environ.get("SAH_PYEXE", sys.executable) def tok(): with open(os.path.expandvars(r"%LOCALAPPDATA%\solveathome\credentials\twin-primes.token"), encoding="utf-8") as fh: return fh.read().strip() def fetch(sha): req = urllib.request.Request(f"{ROOT}/files/{sha}", headers={"Authorization": "Bearer " + tok()}) with urllib.request.urlopen(req, timeout=120) as r: return r.read() def record(): req = urllib.request.Request(f"{PROJECT}/return/{RETURN}", headers={"Authorization": "Bearer " + tok()}) with urllib.request.urlopen(req, timeout=60) as r: return json.loads(r.read().decode()) def lf(b): return b.replace(b"\r\n", b"\n").replace(b"\r", b"\n") def main(): ap = argparse.ArgumentParser() ap.add_argument("--out", default=os.path.join(HERE, "verify-2818c.json")) ap.add_argument("--python", default=PYEXE, help="interpreter for the audited plan's checker; must have highspy") args = ap.parse_args() globals()["PYEXE"] = args.python # The audited plan's checker imports highspy, so this audit has an environment requirement of # its own. Declare it as a named precondition instead of letting it surface as a traceback. probe = subprocess.run([PYEXE, "-c", "import highspy"], capture_output=True) if probe.returncode != 0: print(json.dumps({"ok": False, "stage": "preflight", "error": "the interpreter given for the audited plan's checker cannot " "import highspy, which that checker requires; pass --python with " "one that can (the plan declares this requirement)", "python": PYEXE}, indent=1), file=sys.stderr) return 2 rec = record() plan = rec["verification_plan"] entries = rec["files"] by_name = collections.defaultdict(list) for f in entries: by_name[f["name"]].append(f) pinned = {e["path"]: e["sha256"] for e in plan["manifest"]} recorded_target = next(f["sha256"] for f in entries if f["name"] == TARGET) recorded_artifact = next(f["sha256"] for f in entries if f["name"] == ARTIFACT) res, bad = {}, [] # --- C1 ------------------------------------------------------------------------------------- d = os.path.join(HERE, "_c1") shutil.rmtree(d, ignore_errors=True) os.makedirs(os.path.join(d, "logs"), exist_ok=True) os.makedirs(os.path.join(d, "r1422"), exist_ok=True) fetched = 0 for path, sha in pinned.items(): b = fetch(sha) if hashlib.sha256(b).hexdigest() != sha: bad.append("C1: manifest entry %s did not hash to its pin" % path) sub = "r1422" if path == "job2806_runs.jsonl" else ("logs" if path.endswith(".jsonl") else "") with open(os.path.join(d, sub, path), "wb") as fh: fh.write(b) fetched += 1 r = subprocess.run([PYEXE, CHECKER], cwd=d, capture_output=True) # bytes, not text out = r.stdout res["C1"] = {"manifest_files_fetched": fetched, "checker_exit": r.returncode, "target_raw_bytes": len(out), "target_raw_sha256": hashlib.sha256(out).hexdigest(), "recorded_target_sha256": recorded_target, "reproduces": hashlib.sha256(out).hexdigest() == recorded_target} v = json.loads(out.decode("utf-8")) res["C1"]["verdict_ok"] = v.get("ok") res["C1"]["failed_claims"] = v.get("failed_claims") if not res["C1"]["reproduces"] or v.get("ok") is not True: bad.append("C1") shutil.rmtree(d, ignore_errors=True) # --- C2 ------------------------------------------------------------------------------------- multi = {n: sorted({f["sha256"] for f in by_name[n]}) for n in by_name if len({f["sha256"] for f in by_name[n]}) > 1} res["C2"] = {"names_with_two_revisions": multi} if len(multi) != 1: bad.append("C2: expected exactly one name with two revisions") else: name = next(iter(multi)) a, b = multi[name] # sorted hex, so a < b consistently ba, bb = fetch(a), fetch(b) res["C2"]["name"] = name res["C2"]["blobs"] = {a: len(ba), b: len(bb)} res["C2"]["one_is_strict_prefix_of_the_other"] = bb.startswith(ba) or ba.startswith(bb) res["C2"]["prefix_is_pinned_revision"] = (pinned.get(name) == a and bb.startswith(ba)) res["C2"]["pinned_sha"] = pinned.get(name) if not (bb.startswith(ba) and pinned.get(name) == a): bad.append("C2: pinned revision is not the strict prefix") # --- C3 --------------------------------------------------------------------------------- def rows(blob): return [json.loads(l) for l in blob.decode("utf-8", "replace").splitlines() if l.strip().startswith("{")] ra, rb = rows(ba), rows(bb) ka = collections.Counter(json.dumps(x, sort_keys=True) for x in ra) kb = collections.Counter(json.dumps(x, sort_keys=True) for x in rb) extra = list((kb - ka).elements()) res["C3"] = {"rows_pinned": len(ra), "rows_later": len(rb), "extra_rows": len(extra), "extra_rows_n": sorted({json.loads(x).get("n") for x in extra}), "extra_rows_fields": [ {k: json.loads(x).get(k) for k in ("n", "R", "seed", "sec", "nodes", "status", "sym")} for x in extra]} if not extra or any(j["n"] != 12 for j in res["C3"]["extra_rows_fields"]): bad.append("C3: extra rows are not confined to n = 12") # --- C4 ------------------------------------------------------------------------------------- readings = {"plan_manifest": dict(pinned)} for which, idx in (("file_list_first", 0), ("file_list_last", -1)): readings[which] = {n: by_name[n][idx]["sha256"] for n in by_name} got = {} for tag, pick in readings.items(): dd = os.path.join(HERE, "_c4", tag) shutil.rmtree(dd, ignore_errors=True) os.makedirs(os.path.join(dd, "logs"), exist_ok=True) os.makedirs(os.path.join(dd, "r1422"), exist_ok=True) for path, sha in pinned.items(): use = pick.get(path, sha) b = fetch(use) sub = ("r1422" if path == "job2806_runs.jsonl" else ("logs" if path.endswith(".jsonl") else "")) with open(os.path.join(dd, sub, path), "wb") as fh: fh.write(b) rr = subprocess.run([PYEXE, ANALYZER, "--out", "analysis.json"], cwd=dd, capture_output=True) p = os.path.join(dd, "analysis.json") blob = open(p, "rb").read() if os.path.exists(p) else b"" got[tag] = {"exit": rr.returncode, "bytes": len(blob), "sha256": hashlib.sha256(blob).hexdigest(), "matches_recorded_artifact": hashlib.sha256(blob).hexdigest() == recorded_artifact, "reflection_sign_at_12": (json.loads(blob.decode("utf-8"))["verdict"] ["reflection_sign"]["12"] if blob else None)} shutil.rmtree(dd, ignore_errors=True) res["C4"] = {"recorded_artifact_sha256": recorded_artifact, "readings": got, "any_reading_reproduces": any(g["matches_recorded_artifact"] for g in got.values())} if res["C4"]["any_reading_reproduces"]: bad.append("C4: a reading did reproduce the artifact, so the claim overstates") # --- C5 ------------------------------------------------------------------------------------- tgt = fetch(recorded_target) res["C5"] = {"raw_bytes": len(tgt), "crlf": tgt.count(b"\r\n"), "bare_lf": tgt.count(b"\n"), "raw_sha256": hashlib.sha256(tgt).hexdigest(), "lf_normalized_bytes": len(lf(tgt)), "lf_normalized_sha256": hashlib.sha256(lf(tgt)).hexdigest()} res["C5"]["digest_is_platform_specific"] = \ res["C5"]["raw_sha256"] != res["C5"]["lf_normalized_sha256"] and res["C5"]["crlf"] > 0 if not res["C5"]["digest_is_platform_specific"]: bad.append("C5") # --- C6 ------------------------------------------------------------------------------------- def rule(p, drop=("cost",)): body = {k: v for k, v in p.items() if k not in drop} def sort(o): if isinstance(o, dict): return {k: sort(o[k]) for k in sorted(o)} if isinstance(o, list): return [sort(x) for x in o] return o s = json.dumps(sort(body), separators=(",", ":"), ensure_ascii=False) return hashlib.sha256(("solveathome-verification-v1\n" + s).encode()).hexdigest() served_val = rule(plan) # Put the two non-schema keys back, with the values a submission would have carried for them: # the sha of the manifest entry named by `targets` (derived from the record, not a local file), # and a free-text method statement of the same shape the submission used. tname = (plan.get("targets") or [None])[0] tsha = next((e["sha256"] for e in plan["manifest"] if e["path"] == tname), None) unnormalized = dict(plan, target_sha256=tsha, method="") with_extra = rule(unnormalized) res["C6"] = { "rule_on_served_plan": served_val, "recorded_fingerprint": rec.get("verification_fingerprint"), "rule_reproduces_recorded": served_val == rec.get("verification_fingerprint"), "schema_keys": sorted(plan), "non_schema_keys_absent_from_served_plan": ["method", "target_sha256"], "keys_present_in_served_plan": {"method": "method" in plan, "target_sha256": "target_sha256" in plan}, "rule_with_nonschema_keys_restored": with_extra, "a_stray_key_changes_the_digest": with_extra != served_val, "why_this_matters": "the server normalises a submitted plan to the schema's field set before " "hashing it, so a plan carrying an extra field (`method`, " "`target_sha256`) makes a locally computed fingerprint disagree with " "the recorded one even though the published rule is implemented " "correctly -- the rule is not at fault and the record's value is right"} if not (res["C6"]["rule_reproduces_recorded"] and res["C6"]["a_stray_key_changes_the_digest"] and not any(res["C6"]["keys_present_in_served_plan"].values())): bad.append("C6") res["record"] = {"fingerprint": rec.get("verification_fingerprint"), "file_list_entries": len(entries), "distinct_names": len(by_name), "manifest_entries": len(plan["manifest"]), "research_route_id": rec.get("research_route_id"), "execution": (rec.get("verification_state") or {}).get("execution")} res["ok"] = not bad res["failed_claims"] = bad with open(args.out, "w", encoding="utf-8", newline="\n") as fh: json.dump(res, fh, indent=1, sort_keys=True, ensure_ascii=False) fh.write("\n") print(json.dumps(res, indent=1, sort_keys=True, ensure_ascii=False)) return 0 if res["ok"] else 1 if __name__ == "__main__": sys.exit(main())