#!/usr/bin/env python3 """Independent checker for job #3013's revision of research/fold-profile-13-hotspot-sweep.js. python verify-revision.py --file [--base ] --apply apply-revision.py --retired reproduce-retired.py --repo [--workdir DIR] Prints one JSON object with a boolean per check and `ok`. Exit 0 iff ok. WHAT IT ASSERTS, and each one on its own evidence: V1 the bytes offered as the served base are the sha this return declares; V2 applying `apply-revision.py` to those bytes reproduces the filed file's pre-embed form byte for byte; V3 the difference between base and revision is EXACTLY the five declared anchors and nothing else -- the concatenated removed lines and the concatenated added lines each hash to a frozen value (OLD_SHA / NEW_SHA), so a stray edit anywhere else fails even if apply-revision.py was altered; V4 the embedded fingerprint's code-sha256 is recomputed here, from the bytes above the OUTPUT banner, and equal; out-sha256 is the frozen block hash; V5 the re-embed that the code change forced moved nothing but fingerprint fields and the four volatile timestamp lines; V6 reading 4's six seam z values are the six the embedded table prints (read out of the block, not from prose); V7 the six retired digits appear nowhere in the block; V8 the provenance note records them, names the pre-2026-08-20 plain-multiply form and the reason it is inexact; V9 `research/qc/embed.js --check` -- the corpus's own gate -- exits 0; V10 the block reproduces on a host whose locale does not group with commas (both plain and grouping-pinned runs match), which is what the revision's locale pin buys; V11 the retired six are the plain-multiply LCG's own output, reproduced here from the served bytes by `reproduce-retired.py`. """ import argparse import difflib import hashlib import json import os import re import subprocess import sys import tempfile BASE_SHA = "0ebd512033257c82aca3130512fd917c239b81f0e23bcd25e7200d5c43472177" PRE_EMBED_SHA = "300f20fd012f8b09ecaa0de9de6d429cbd6b13548e2ea86f24b3af38ed036c61" OUT_SHA = "2f869b3a66f5b4b4727893d4197c3db3ab8f01bca37029a8fd431a33322708eb" BODY_LINES = 86 # sha256 of the concatenated removed lines and of the concatenated added lines of the # base -> revision diff, as a diff computes them: 8 removed, 30 added. Any edit outside # the five anchors moves one of these, whatever apply-revision.py says. OLD_SHA = "1ef3209e07e78e728cb2d3dd73b82a5b091a0a09acb18384ad00b6379332d74e" NEW_SHA = "678b7f700ae14c1ccd6500fa7a60cf06c529b4af921bee8a3e2e417c8a40b3fc" PATH_IN_REPO = "research/fold-profile-13-hotspot-sweep.js" RETIRED = {"T19": ["-1.41", "-0.19", "-0.09"], "T23": ["-0.65", "+0.13", "-0.50"]} CURRENT = {"T19": ["-1.42", "-0.07", "-0.13"], "T23": ["-0.68", "+0.26", "-0.53"]} BANNER = re.compile(r"^\s*//\s*={10,}\s*$") OUT_HEAD = re.compile(r"^\s*//\s*OUTPUT\s*(?:$|[\u2014\-(])") READ_HEAD = re.compile(r"^\s*//\s*READINGS\b") HDR_FIELD = re.compile(r"^\s*//\s*(code-sha256|out-sha256|body-lines|streams|node|embedded|elapsed)\s*:") VOLATILE = re.compile(r"\[TIME\]|\[\d+(?:\.\d+)?m?s\]|\b\d+(?:\.\d+)?\s*(?:ms|s|sec|secs|seconds)\b" r"|\b\d+(?:\.\d+)?[ ](?:min|mins|minutes|h|hr|hrs|hours|day|days)\b" r"|\b\d{4}-\d{2}-\d{2}\b|\bv\d+\.\d+\.\d+\b|\b\d+(?:\.\d+)?\s*(?:MB|GB|KB)\b") def sha(s): return hashlib.sha256(s.encode("utf-8")).hexdigest() def read(path): with open(path, encoding="utf-8", newline="") as fh: return fh.read() def locate(lines): """The tail's line indices: same three fields tailfmt.locate uses, recomputed here.""" out = -1 for i in range(len(lines) - 1, -1, -1): if OUT_HEAD.match(lines[i]): out = i break if out == -1: return None start = out - 1 if out > 0 and BANNER.match(lines[out - 1]) else out hdr_end = -1 for j in range(out + 1, len(lines)): if BANNER.match(lines[j]): hdr_end = j break return {"out": out, "tail_start": start, "hdr_end": hdr_end} def body_lines(lines, loc): body = [] for raw in lines[loc["hdr_end"] + 1: loc["hdr_end"] + 1 + BODY_LINES]: m = re.match(r"^// ?(.*)$", raw) body.append(m.group(1) if m else raw) return body def seam_rows(body, multiple): """The three z values the block prints under `SEAMS at multiples of `.""" zs, seen = [], False for i, l in enumerate(body): if l.strip().startswith("SEAMS at multiples of " + multiple): seen = True continue if seen and l.strip().startswith("half-width"): continue if seen: if not l.strip(): break parts = [p.strip() for p in l.split("|")] if len(parts) >= 5: zs.append(parts[4]) return zs def run(cmd, cwd=None): return subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, encoding="utf-8", errors="replace") def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--file", required=True) ap.add_argument("--base") ap.add_argument("--apply", required=True) ap.add_argument("--retired", required=True) ap.add_argument("--repo") ap.add_argument("--workdir") a = ap.parse_args() checks, notes = {}, {} revision = read(a.file) rev_lines = revision.split("\n") loc = locate(rev_lines) if loc is None: print(json.dumps({"ok": False, "error": "no OUTPUT banner in the filed file"}, indent=1)) return 1 body = body_lines(rev_lines, loc) body_text = "\n".join(body) # ---- V1: the served base ---------------------------------------------------- if a.base: base = read(a.base) checks["V1_base_bytes_are_the_declared_served_sha"] = sha(base) == BASE_SHA else: base = None checks["V1_base_bytes_are_the_declared_served_sha"] = True notes["V1"] = "no --base given; the served-bytes check was not run" # ---- V2/V3: the minimal-repair proof --------------------------------------- work = tempfile.mkdtemp(prefix="job3013-verify-", dir=a.workdir) pre = os.path.join(work, "pre-embed.js") if base is not None: r = run([sys.executable, a.apply, "--base", a.base, "--out", pre]) checks["V2_apply_reproduces_the_filed_pre_embed_bytes"] = ( r.returncode == 0 and sha(read(pre)) == PRE_EMBED_SHA) if r.returncode != 0: notes["V2"] = (r.stderr or r.stdout).strip()[:200] removed, added = [], [] for line in difflib.unified_diff(base.splitlines(keepends=True), read(pre).splitlines(keepends=True), n=0): if line.startswith("---") or line.startswith("+++"): continue if line.startswith("+"): added.append(line[1:]) elif line.startswith("-"): removed.append(line[1:]) checks["V3_the_diff_is_exactly_the_declared_anchors"] = ( sha("".join(removed)) == OLD_SHA and sha("".join(added)) == NEW_SHA) else: checks["V2_apply_reproduces_the_filed_pre_embed_bytes"] = sha(revision) == PRE_EMBED_SHA checks["V3_the_diff_is_exactly_the_declared_anchors"] = True notes["V3"] = "no --base given; the diff was not recomputed" # ---- V4: the fingerprint, recomputed --------------------------------------- fp = {} for i in range(loc["out"], loc["hdr_end"]): m = HDR_FIELD.match(rev_lines[i]) if m: fp[m.group(1)] = rev_lines[i].split(":", 1)[1].strip() head = "\n".join(rev_lines[:loc["tail_start"]]) checks["V4_code_sha256_is_the_bytes_above_the_banner"] = fp.get("code-sha256") == sha(head) checks["V4_out_sha256_is_the_frozen_block"] = fp.get("out-sha256") == OUT_SHA checks["V4_body_lines_and_streams"] = (fp.get("body-lines") == str(BODY_LINES) and fp.get("streams") == "stdout+stderr") # ---- V5: the re-embed moved only the fingerprint and the timings ----------- if base is not None and os.path.exists(pre): ok = True # splitlines(), not split('\n'): the latter leaves a trailing '' that a unified # diff reads as an extra added line, which is a checker artifact, not a change. for line in difflib.unified_diff(read(pre).splitlines(), revision.splitlines(), n=0): if line.startswith(("---", "+++", "@@")): continue if line.startswith(("+", "-")): if not (HDR_FIELD.match(line[1:]) or VOLATILE.search(line[1:])): ok = False notes.setdefault("V5", []).append(line[:120]) checks["V5_reembed_touched_only_the_fingerprint_and_timings"] = ok else: checks["V5_reembed_touched_only_the_fingerprint_and_timings"] = True notes["V5"] = "no --base given; the re-embed diff was not recomputed" # ---- V6: reading 4's six values are the block's ---------------------------- read4 = None for i, l in enumerate(rev_lines): if re.match(r"^// 4\. GAP 3 IS CLOSED", l): read4 = "\n".join(rev_lines[i:i + 6]) break m = re.search(r"z = ([^\n]+?) at T19 and ([^\n]+?) at T23", read4 or "") got = None if m: got = {"T19": [t.strip() for t in m.group(1).split(",")], "T23": [t.strip() for t in m.group(2).split(",")]} block = {"T19": seam_rows(body, "510,510"), "T23": seam_rows(body, "9,699,690")} norm = lambda d: {k: [v.lstrip("+") for v in vs] for k, vs in d.items()} checks["V6_reading_4_quotes_the_blocks_six_values"] = (got is not None and norm(got) == norm(block)) notes["V6"] = {"reading_4": got, "block": block} # ---- V7: the retired six are not in the block ------------------------------ checks["V7_retired_values_are_absent_from_the_block"] = not any( v in body_text for v in RETIRED["T19"] + RETIRED["T23"]) # ---- V8: the provenance note records them ---------------------------------- tail = "\n".join(rev_lines[loc["hdr_end"] + BODY_LINES:]) checks["V8_provenance_note_records_the_retired_values"] = ( "RETIRED 2026-09-24, AND NOT A DIFFERENT DRAW" in tail and all(v.lstrip("+") in tail for v in RETIRED["T19"] + RETIRED["T23"]) and "1103515245" in tail and "2**53" in tail and "NOT A" in tail) # ---- V9/V10: the gate, and the locale --------------------------------------- if a.repo: r = run(["node", "research/qc/embed.js", "--check", PATH_IN_REPO], cwd=a.repo) out = (r.stdout or "") + (r.stderr or "") notes["V9"] = out.strip().splitlines() checks["V9_embed_check_exits_0"] = r.returncode == 0 rb = os.path.join(os.path.dirname(os.path.abspath(__file__)), "reproduce-block.js") if not os.path.exists(rb): rb = "reproduce-block.js" r2 = run(["node", rb, "--repo", a.repo, PATH_IN_REPO]) out2 = (r2.stdout or "") + (r2.stderr or "") notes["V10"] = out2.strip().splitlines() plain = re.search(r"plain\s+([0-9a-f]{64})\s+(.*)", out2) pinned = re.search(r"pinned to en-US\s+([0-9a-f]{64})\s+(.*)", out2) checks["V10_reproduces_with_the_locale_pinned_and_plain"] = ( r2.returncode == 0 and plain is not None and pinned is not None and plain.group(1) == OUT_SHA and pinned.group(1) == OUT_SHA) else: checks["V9_embed_check_exits_0"] = True checks["V10_reproduces_with_the_locale_pinned_and_plain"] = True notes["V9"] = notes["V10"] = "no --repo given; the run checks were not executed" # ---- V11: the retired six are the old LCG's own output --------------------- if base is not None: r = run([sys.executable, a.retired, "--served", a.base]) out = (r.stdout or "") + (r.stderr or "") notes["V11"] = out.strip().splitlines()[-1:] or [] checks["V11_retired_six_reproduce_from_the_plain_multiply_lcg"] = ( r.returncode == 0 and "candidates reproducing all six retired z values" in out and "NONE" not in out.split("candidates reproducing all six")[1]) else: checks["V11_retired_six_reproduce_from_the_plain_multiply_lcg"] = True notes["V11"] = "no --base given; the LCG probe was not run" # 13 booleans: V4 is three of them, and the count is asserted so a check that # silently stops running cannot leave a shorter, greener verdict. ok = all(checks.values()) and len(checks) == 13 print(json.dumps({"ok": ok, "checks": checks, "notes": notes, "file": a.file, "file_sha256": sha(revision), "path": PATH_IN_REPO}, indent=1, sort_keys=True)) return 0 if ok else 1 if __name__ == "__main__": sys.exit(main())