#!/usr/bin/env python3 """Independent reproducibility audit of return #1459's record (route 132 follow-up -> route 144). Three questions, each answered from served bytes only -- nothing is read from a local work dir: A. Does the plan's own manifest reproduce the plan's target byte for byte? The plan names `check-2818b.json` as the target with a pinned sha256, and a manifest of 25 files with pinned shas. Rebuild the package from that manifest alone, run the plan's checker command, compare RAW bytes against the pin -- and separately compare the LF-normalized bytes, because the pin was taken on Windows and a POSIX worker will normalize. (Harness note: a subprocess capture in text mode decodes and universal-newline-translates the child's stdout. Hashing that string re-encodes LF bytes and silently produces a DIFFERENT digest for identical output. Everything here is bytes in, bytes out.) B. What happens if a worker takes the files by NAME from the return's `files` list instead of from the plan's manifest? The return's file list is checked for names that carry more than one distinct revision; where one does, the alternative revision is fetched from the store by its own sha and the whole comparison is repeated. A name with two revisions in one record is the defect being measured, not an assumption. C. Is the return's filed `analysis-reps.json` reproducible from the record? The analyzer is run against the plan-manifest log set and against the file-list log set, and both digests are compared with the digest the return records for that artifact. Exit 0 only if (A) reproduces the target in raw bytes. Every intermediate digest is reported either way. Usage: check-1459-repro.py [--out check-1459-repro.json] [--python PATH] [--keep] """ import argparse import collections import hashlib import json import os import shutil import subprocess import sys import urllib.error import urllib.request HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = "https://solveathome.org" PROJECT = "https://solveathome.org/projects/twin-primes" RETURN = 1459 ANALYZER = "analyze-reps.py" CHECKER = "verify-2818b.py" TARGET_NAME = "check-2818b.json" ARTIFACT_NAME = "analysis-reps.json" def token(): p = os.path.expandvars(r"%LOCALAPPDATA%\solveathome\credentials\twin-primes.token") with open(p, encoding="utf-8") as fh: return fh.read().strip() def http_json(path): base = ROOT if path.startswith("/files") else PROJECT req = urllib.request.Request(base + path, headers={"Authorization": "Bearer " + token()}) with urllib.request.urlopen(req, timeout=60) as r: return json.loads(r.read().decode()) def http_bytes(sha): req = urllib.request.Request(f"{ROOT}/files/{sha}", headers={"Authorization": "Bearer " + token()}) with urllib.request.urlopen(req, timeout=120) as r: return r.read() def sha256(b): return hashlib.sha256(b).hexdigest() def lf(b): """The same bytes as a POSIX worker would see them: CRLF collapsed to LF, CR alone dropped.""" return b.replace(b"\r\n", b"\n").replace(b"\r", b"\n") def layout(root, tag, plan, pick, report): """Write one package. `pick(path, pinned) -> sha` chooses the revision for each manifest path.""" d = os.path.join(root, tag) 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) for e in plan["manifest"]: path, role, pinned = e["path"], e["role"], e["sha256"] want = pick(path, pinned) try: b = http_bytes(want) except urllib.error.HTTPError as ex: report["unfetchable"].append({"path": path, "sha256": want, "http": ex.code}) continue if sha256(b) != want: report["unfetchable"].append({"path": path, "sha256": want, "reason": "download did not hash to the request"}) continue if want != pinned: report["alternative_revisions_used"].append( {"path": path, "role": role, "pinned": pinned, "used": want, "bytes": len(b)}) 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) return d def run(pyexe, d, script, extra=()): r = subprocess.run([pyexe, script, *extra], cwd=d, capture_output=True) # BYTES, never text=True return r.returncode, r.stdout, r.stderr.decode("utf-8", "replace")[-400:] def run_analyzer(pyexe, d): """The analyzer is a FILE producer: hash the file it writes, not the little it prints.""" rc, out, err = run(pyexe, d, ANALYZER, extra=("--out", "analysis.json")) p = os.path.join(d, "analysis.json") b = open(p, "rb").read() if os.path.exists(p) else b"" return rc, b, err def digests(b): return {"raw_sha256": sha256(b), "raw_bytes": len(b), "crlf": b.count(b"\r\n"), "lf_sha256": sha256(lf(b)), "lf_bytes": len(lf(b))} def verdict(b): try: return json.loads(b.decode("utf-8")) except Exception: return None def delta(x, y, path=""): out = [] if type(x) is not type(y): return [(path, x, y)] if isinstance(x, dict): for k in sorted(set(x) | set(y)): if k not in x or k not in y: out.append((path + "/" + k, x.get(k), y.get(k))) else: out += delta(x[k], y[k], path + "/" + k) elif isinstance(x, list): if len(x) != len(y): out.append((path + "/len", len(x), len(y))) for i, (u, v) in enumerate(zip(x, y)): out += delta(u, v, f"{path}[{i}]") elif x != y: out.append((path, x, y)) return out def main(): ap = argparse.ArgumentParser() ap.add_argument("--out", default=os.path.join(HERE, "check-1459-repro.json")) ap.add_argument("--python", default=sys.executable, help="interpreter for the plan's checker (needs highspy, so the project venv)") ap.add_argument("--keep", action="store_true") args = ap.parse_args() ret = http_json(f"/return/{RETURN}") plan = ret.get("verification_plan") or {} manifest = plan.get("manifest") or [] entries = ret.get("files") or [] by_name = collections.defaultdict(list) for f in entries: by_name[f["name"]].append(f) names = sorted(by_name) report = { "return": RETURN, "server_fingerprint": ret.get("verification_fingerprint"), "plan_manifest_entries": len(manifest), "plan_manifest_distinct_paths": len({e["path"] for e in manifest}), "file_list_entries": len(entries), "file_list_distinct_names": len(names), "names_with_more_than_one_revision": [ {"name": n, "revisions": [{"sha256": f["sha256"], "bytes": f["bytes"]} for f in by_name[n]]} for n in names if len({f["sha256"] for f in by_name[n]}) > 1], "unfetchable": [], "alternative_revisions_used": [], "expected": {}, "runs": {}, } # what the plan tells a worker to compare against exp = plan.get("expected") report["expected"] = {"target": exp if not isinstance(exp, (dict, list)) else exp, "target_sha256": plan.get("target_sha256"), "targets": plan.get("targets"), "filed_target_sha256": next((f["sha256"] for f in entries if f["name"] == TARGET_NAME), None), "filed_artifact_sha256": next((f["sha256"] for f in entries if f["name"] == ARTIFACT_NAME), None)} # (A) strictly the plan: every file at its pinned sha d = layout(HERE, "repro-1459/pinned", plan, lambda p, s: s, report) rc, out, err = run(args.python, d, CHECKER) pin = {"exit": rc, "stderr": err, **digests(out)} pin["verdict_ok"] = (verdict(out) or {}).get("ok") pin["failed_claims"] = (verdict(out) or {}).get("failed_claims") pin["matches_pin_raw"] = pin["raw_sha256"] == plan.get("target_sha256") or \ pin["raw_sha256"] == report["expected"]["filed_target_sha256"] report["runs"]["plan_manifest"] = pin # (B) the return's file list, taken by NAME. Where a name carries more than one revision the # choice is real, so every revision is exercised instead of one being assumed. readings = {"plan_manifest": d} for which, idx in (("file_list_first_revision", 0), ("file_list_last_revision", -1)): pick_by_name = {n: by_name[n][idx]["sha256"] for n in names} readings[which] = layout(HERE, f"repro-1459/{which}", plan, lambda p, s, m=pick_by_name: m.get(p, s), report) tree = {"plan_manifest": verdict(out)} for which, dd in readings.items(): if which == "plan_manifest": continue rc2, out2, err2 = run(args.python, dd, CHECKER) v = {"exit": rc2, "stderr": err2, **digests(out2)} v["verdict_ok"] = (verdict(out2) or {}).get("ok") v["failed_claims"] = (verdict(out2) or {}).get("failed_claims") v["matches_pin_raw"] = v["raw_sha256"] == report["expected"]["filed_target_sha256"] report["runs"][which] = v tree[which] = verdict(out2) report.setdefault("target_verdict_deltas_vs_plan_manifest", {})[which] = [ {"path": p, "plan": x, "this_reading": y} for p, x, y in delta(verdict(out), verdict(out2))] # (C) the analyzer's artifact -- a FILE it writes -- under every reading for tag, dd in readings.items(): rc3, b3, err3 = run_analyzer(args.python, dd) a = {"exit": rc3, "stderr": err3, **digests(b3)} a["matches_filed_artifact"] = a["raw_sha256"] == report["expected"]["filed_artifact_sha256"] try: a["reflection_sign_at_12"] = json.loads(b3.decode("utf-8"))["verdict"][ "reflection_sign"]["12"] except Exception: a["reflection_sign_at_12"] = None report.setdefault("analyzer_artifact", {})[tag] = a report["ok"] = bool(pin["matches_pin_raw"] and pin["verdict_ok"]) if not args.keep: shutil.rmtree(os.path.join(HERE, "repro-1459"), ignore_errors=True) with open(args.out, "w", encoding="utf-8", newline="\n") as fh: json.dump(report, fh, indent=1, sort_keys=True, ensure_ascii=False) fh.write("\n") print(json.dumps(report, indent=1, sort_keys=True, ensure_ascii=False)) print("ok:", report["ok"], "->", args.out) return 0 if report["ok"] else 1 if __name__ == "__main__": sys.exit(main())