#!/usr/bin/env python3 """Deterministic checker for job #4586 (route 128 first look / step check). Stdlib only. Re-derives every decisive number in REPORT.md from the shipped inputs under `served/`, plus the workspace-local registration receipt for the brief's own step text. Prints `passed/total` and exits non-zero on any failure. A missing input is a FAILED check, not a crash. Inputs (all under served/ unless stated): route-128.json, return-.json, hist__.json, ver____vN.md, doc__research__qc__questions.js, dep__research__gen-questions-index.js, dep__research__qc__questions.js, dep__research__qc__corpus.js, f1828_manifest-3289.txt, f1828_others-ledger-3289.json, f1828_restore-83-153.patch, f1828_QUESTIONS.restored-83-153.md, f2057_/f2058_/f2059_derive-*, carriers.json, lines.json, probe.json, scan.json, gitapply.json, divergence.json, census.json, price.json, deps.json, newstep.json, step.json, fetch_manifest.json and, for the brief's step, the run's registration receipt. """ import hashlib import json import os import re import sys HERE = os.path.dirname(os.path.abspath(__file__)) SERVED = os.path.join(HERE, "served") ROOT = os.path.abspath(os.path.join(HERE, "..", "..")) REG = os.path.join(ROOT, ".solveathome", "private", "runs", "launch-npy486cd2xxr4v66zlen749c", "receipts", "registration.json") SETTER = 1987 RANGE = (1988, 2110) CHECKS = [] FAILED = [] BLOCK_RE = re.compile(r"") ROW_RE = re.compile(r"^\|\s*`([^`]+)`\s*\|([^|]*)\|([^|]*)\|([^|]*)\|") def check(name, ok, detail=""): CHECKS.append({"id": len(CHECKS) + 1, "name": name, "ok": bool(ok), "detail": detail}) print("%-4s %s%s" % ("PASS" if ok else "FAIL", name, (" -- " + detail) if detail else "")) if not ok: FAILED.append(len(CHECKS)) def load(p): try: return json.load(open(p, encoding="utf-8")) except Exception: # noqa: BLE001 return None def art(name): """Resolve a shipped artefact: beside the checker first, then under served/.""" p = os.path.join(HERE, name) if os.path.exists(p): return p return os.path.join(SERVED, name) def art_load(name): return load(art(name)) def art_rd(name): return rd(art(name)) def art_txt(name): return txt(art(name)) def body(o): return o.get("body", o) if isinstance(o, dict) else o def rd(p): try: with open(p, "rb") as fh: return fh.read() except OSError: return b"" def txt(p): return rd(p).decode("utf-8", "replace") def sha(b): return hashlib.sha256(b).hexdigest() def canon(o): return sha(json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")) def slug(p): return p.replace("/", "__") def parse_block(t): head = "\n".join(t.split("\n")[:60]) m = BLOCK_RE.search(head) if not m: return None f = {} for raw in m.group(1).split("\n"): ln = raw.strip() if not ln: continue km = re.match(r"^([a-z]+):\s*(.*)$", ln) if km: f[km[1]] = km[2].strip() return f def diff_counts(a, b): import difflib d = list(difflib.unified_diff(a.split("\n"), b.split("\n"), lineterm="", n=0)) minus = [x for x in d if x[:1] == "-" and x[:3] != "---"] plus = [x for x in d if x[:1] == "+" and x[:3] != "+++"] return len(minus), len(plus) def main(): # ---------------------------------------------------------------- inputs req = ["route-128.json", "step.json", "carriers.json", "lines.json", "probe.json", "scan.json", "gitapply.json", "divergence.json", "census.json", "price.json", "deps.json", "newstep.json", "fetch_manifest.json", "f1828_manifest-3289.txt", "f1828_others-ledger-3289.json", "f1828_restore-83-153.patch", "f1828_QUESTIONS.restored-83-153.md", "doc__research__qc__questions.js", "dep__research__gen-questions-index.js", "dep__research__qc__questions.js", "dep__research__qc__corpus.js"] for t in ("corner-correlation.md", "fold-arithmetic-bridge.md", "history__staging__derive-0904-L7-transfer.md", "proposals__prop-staircase-note.md"): pass paths = {"corner": ("research/corner-correlation.md", 4), "fold": ("research/fold-arithmetic-bridge.md", 3), "derive": ("research/history/staging/derive-0904-L7-transfer.md", 3), "prop": ("paper/proposals/prop-staircase-note.md", 3), "questions": ("research/QUESTIONS.md", 10), "centered": ("research/centered-discrepancy-estimate.md", 3), "global": ("research/global-factor-signs.md", 3)} for tag, (rel, n) in paths.items(): req.append("hist__%s.json" % slug(rel)) for v in range(1, n + 1): req.append("ver__%s__v%d.md" % (slug(rel), v)) missing = [r for r in req if not os.path.exists(art(r))] check("I0 every required shipped input is present", not missing, "missing=%s" % missing) # ------------------------------------------------------------ A the step brief = None try: d = json.load(open(REG, encoding="utf-8")) b = d["body"]["brief_md"] i = b.index("The step:\n") j = b.index("\n\nReturns to compare it with", i) brief = json.loads(b[i + len("The step:\n"):j].strip()) except Exception as exc: # noqa: BLE001 check("A1 the brief's step parses from the registration receipt", False, repr(exc)) if brief is not None: check("A1 the brief's step parses from the registration receipt", True) route = body(load(os.path.join(SERVED, "route-128.json"))) check("A2 the served route-128 next_step equals the brief's step", canon(route.get("next_step")) == canon(brief), "route=%s brief=%s" % (canon(route.get("next_step"))[:16], canon(brief)[:16])) check("A3 the stored step.json equals the served route step", canon(art_load("step.json")) == canon(route.get("next_step"))) c = art_load("carriers.json") eq = [x for x in c["carriers"] if x["equal_to_brief"]] ids = sorted({str(x["return_id"]) for x in eq if x.get("return_id")}, key=lambda z: int(z)) check("A4 exactly two returns carry the step (the setter #1987 and #2051)", ids == ["1987", "2051"], "carriers=%s" % ids) check("A5 the canonical step sha is 47bb03e1…", c["brief_step_sha"].startswith("47bb03e1"), c["brief_step_sha"][:16]) route = body(load(os.path.join(SERVED, "route-128.json"))) check("A6 route 128 is active, revision 9, last_return_id 2051", route.get("state") == "active" and route.get("revision") == 9 and str(route.get("last_return_id")) == "2051", "%s/%s/%s" % (route.get("state"), route.get("revision"), route.get("last_return_id"))) jobs = {j["id"]: j["status"] for j in route.get("jobs", [])} check("A7 route 128's job history: 4586 assigned, 4580 returned, 4471 expired", jobs.get("4586") == "assigned" and jobs.get("4580") == "returned" and jobs.get("4471") == "expired", str({k: jobs.get(k) for k in ("4586", "4580", "4471")})) # ------------------------------------------------- B lineages and the pins lines = art_load("lines.json") check("B1 all 33 fetched version bodies match their published content_sha", lines["versions_sha_ok"] == 33 and lines["versions_sha_bad"] == [], "ok=%d bad=%s" % (lines["versions_sha_ok"], lines["versions_sha_bad"])) want_served = {"corner": "3b83a562", "fold": "2d41665a", "derive": "6ffd659c", "prop": "ee28e195", "questions": "a3e07372", "centered": "0e472838", "global": "0509638b"} for tag, pre in want_served.items(): e = lines["paths"][tag] if tag == "questions": # the registry is itself versioned; it has later real edits by design check("B2.questions the served registry is v10 a3e07372 and is the newest version", e["served_sha"].startswith(pre) and e["served_is_newest_version"] and e["n_versions"] == 10 and e["v3_eq_v1"], "served=%s n=%d" % (e["served_sha"][:8], e["n_versions"])) continue check("B2.%s %s serves %s, v3 == v1, no later real edit" % (tag, tag, pre), e["served_sha"].startswith(pre) and e["v3_eq_v1"] and e["noncopy_versions_after_v3_differing_from_served"] == [] and e["served_is_newest_version"], "served=%s v3eqv1=%s later=%s" % (e["served_sha"][:8], e["v3_eq_v1"], e["noncopy_versions_after_v3_differing_from_served"])) check("B3 corner-correlation serves v4 and v4 is return #1954", lines["paths"]["corner"]["n_versions"] == 4 and str(lines["paths"]["corner"]["returns"][3]) == "1954", "returns=%s" % lines["paths"]["corner"]["returns"]) check("B4 the three displaced paths have exactly 3 versions, accepted v2 from #101/#152/#13", all(lines["paths"][t]["n_versions"] == 3 for t in ("fold", "derive", "prop")) and lines["paths"]["fold"]["v2_return"] == "101" and lines["paths"]["derive"]["v2_return"] == "152" and lines["paths"]["prop"]["v2_return"] == "13", "%s" % {t: lines["paths"][t]["v2_return"] for t in ("fold", "derive", "prop")}) # ------------------------------------------------------- C the cell fields cells = lines["cells"] check("C1 #152 derive: only the verdict field changes, 562 -> 1014 chars", cells["derive"]["changed_cells"] == ["verdict"] and cells["derive"]["verdict_len_v1"] == 562 and cells["derive"]["verdict_len_v2"] == 1014 and cells["derive"]["ledger_v1"]["status"] == cells["derive"]["ledger_v2"]["status"] == "PARTIAL", "cells=%s %d->%d" % (cells["derive"]["changed_cells"], cells["derive"]["verdict_len_v1"], cells["derive"]["verdict_len_v2"])) check("C2 #101 fold: all six ledger fields equal, 0 cells", cells["fold"]["changed_cells"] == [] and cells["fold"]["changed_fields"] == [], "changed=%s" % cells["fold"]["changed_fields"]) check("C3 #13 prop: no ledger block in the served version", cells["prop"]["indexed"] is False, "indexed=%s" % cells["prop"]["indexed"]) check("C4 corner: no registry cell moves", cells["corner"]["changed_cells"] == [], "changed=%s" % cells["corner"]["changed_cells"]) check("C5 the served generator's cell fields are id/status/question/verdict", lines["generator"]["cell_fields"] == ["id", "status", "question", "verdict"], str(lines["generator"]["cell_fields"])) check("C6 the generator's own drift check compares section-2 rows 'and nothing else'", lines["generator"]["drift_check_sentence"] is True) # --------------------------------------------------------- D the baseline r = lines["registry"] check("D1 v8 ccf2cf0f -> served v10 a3e07372 is -9 / +12 lines", r["v8_to_v10_minus"] == 9 and r["v8_to_v10_plus"] == 12 and r["v8_sha"].startswith("ccf2cf0f") and r["served_sha"].startswith("a3e07372"), "-%d +%d" % (r["v8_to_v10_minus"], r["v8_to_v10_plus"])) g = lines["regen3289"] check("D2 #1828's shipped B output vs served v10 is -10 / +13 and not byte-equal", g["B_vs_served_v10_minus"] == 10 and g["B_vs_served_v10_plus"] == 13 and g["B_equals_served_v10"] is False, "-%d +%d equal=%s" % (g["B_vs_served_v10_minus"], g["B_vs_served_v10_plus"], g["B_equals_served_v10"])) check("D3 the shipped B output hashes to cda1e669", g["B_sha_shipped"].startswith("cda1e669"), g["B_sha_shipped"][:16]) q10 = art_rd("ver__research__QUESTIONS.md__v10.md") check("D4 the served registry has 557 section-2 rows", len([1 for ln in q10.decode("utf-8").split("\n") if ROW_RE.match(ln)]) == 557, str(len([1 for ln in q10.decode("utf-8").split("\n") if ROW_RE.match(ln)]))) check("D5 #1828's others-ledger records verdict_same=true for derive (the wrong flag)", art_load("f1828_others-ledger-3289.json")[ "research/history/staging/derive-0904-L7-transfer.md"]["verdict_same"] is True) ga = art_load("gitapply.json") check("D6 restore-83-153.patch: exit 0 on v8, non-zero on served v10 and on the shipped B", ga["control_v8_applies"] and ga["treatment_v10_rejected"] and ga["treatment_freshA_rejected"] and ga["failing_file_is_QUESTIONS"], "v8=%s v10=%s B=%s" % (ga["runs"][0]["exit"], ga["runs"][1]["exit"], ga["runs"][2]["exit"])) check("D7 the failing hunk names research/QUESTIONS.md:70 against the served v10 bytes", "research/QUESTIONS.md:70" in (ga["runs"][1]["message"] or ""), ga["runs"][1]["message"][:80]) # ---------------------------------------------- E the mirror-cut signature dv = art_load("divergence.json") check("E1 the served row is faithful to the served block on all 5 named ids that carry one", dv["n_registry_faithful_to_served"] == 5, str(dv["n_registry_faithful_to_served"])) check("E2 the served block differs from the accepted block on 3 of the 6 named ids", dv["n_served_differs_from_accepted"] == 3 and {i["id"] for i in dv["items"] if i["served_differs_from_accepted"]} == {"Q-centered-discrepancy-estimate", "Q-global-factor-signs", "Q-derive-0904-L7-transfer"}, str(dv["n_served_differs_from_accepted"])) check("E3 only the derive id's verdict cell moves among the three displaced paths", dv["n_verdict_cells_move"] == 3 and dv["n_status_cells_move"] == 2) check("E4 Q-prop-staircase-note has no registry row and no ledger block", next(i for i in dv["items"] if i["id"] == "Q-prop-staircase-note")[ "registry_row_present"] is False and next(i for i in dv["items"] if i["id"] == "Q-prop-staircase-note")[ "served_block_present"] is False) # ----------------------------------------------------- F the decisive returns files = art_load("carriers_files.json") v2 = rd(os.path.join(SERVED, "ver__%s__v2.md" % slug("research/history/staging/derive-0904-L7-transfer.md"))) v2s = {sha(v2), sha(v2.replace(b"\r\n", b"\n"))} check("F1 #2057 and #2058 publish a file byte-identical to #152's accepted v2 bytes", files["files_equal_accepted_v2"]["2057/derive-0904-L7-transfer.md"] is True and files["files_equal_accepted_v2"]["2058/derive-0904-L7-transfer.md"] is True) check("F2 #2058's revision_sha is #152's accepted content sha (c60a250d)", str(files["2058"]["revision_sha"]).startswith("c60a250d") and any(s.startswith("c60a250d") for s in v2s), str(files["2058"]["revision_sha"])[:16]) r2058 = body(load(os.path.join(SERVED, "return-2058.json"))) check("F3 #2058 is superseded by return #152", r2058.get("status") == "superseded" and str(r2058.get("superseded_by")) == "152", "%s by %s" % (r2058.get("status"), r2058.get("superseded_by"))) r2057 = body(load(os.path.join(SERVED, "return-2057.json"))) check("F4 #2057 is recorded, routeless, and names the mirror cut as the cause", r2057.get("status") == "recorded" and r2057.get("research_route_id") in (None, "") and "mirror cut" in (r2057.get("report_md") or "")) r2059 = body(load(os.path.join(SERVED, "return-2059.json"))) check("F5 #2059 is a pending audit of the same path", r2059.get("status") == "pending" and r2059.get("revision_path") == "research/history/staging/derive-0904-L7-transfer.md") patch = art_txt("f2057_derive-restore-152.patch") check("F6 #2057's patch is a one-line re-application against the served base 6ffd659c", patch.count("\n-verdict:") == 1 and patch.count("\n+verdict:") == 1 and "@@ -5,7 +5,7 @@" in patch) # --------------------------------------------------- G the window is complete pr = art_load("probe.json") check("G1 present + absent = the probed range size (1988..2110, 123)", pr["present_plus_absent_equals_range"] and pr["range_size"] == 123 and pr["present_in_range"] + pr["absent_in_range"] == 123, "%d + %d" % (pr["present_in_range"], pr["absent_in_range"])) check("G2 the observed head is #2071 and every id above it 404s", pr["observed_head"] == 2071 and pr["above_head_present"] == [] and pr["above_head_absent_count"] == len(pr["head_probe"]), "head=%s above_present=%s" % (pr["observed_head"], pr["above_head_present"])) check("G3 created_at is monotone over the present ids", pr["created_at_monotone"] is True) scan = art_load("scan.json") check("G4 the post-#1987 window holds 79 rows, 23 of them routeless", scan["window_rows"] == 79 and scan["routeless_rows"] == 23, "%d rows, %d routeless" % (scan["window_rows"], scan["routeless_rows"])) check("G4b the shipped window records re-hash to the rows scan.json declares", all(os.path.exists(os.path.join(SERVED, "return-%d.json" % row["id"])) and str(body(load(os.path.join(SERVED, "return-%d.json" % row["id"]))).get("id")) == str(row["id"]) for row in scan["rows"] if os.path.exists(os.path.join(SERVED, "return-%d.json" % row["id"]))) and len([r for r in scan["rows"] if os.path.exists(os.path.join(SERVED, "return-%d.json" % r["id"]))]) >= 8, "%d of %d window records shipped" % (len([r for r in scan["rows"] if os.path.exists(os.path.join(SERVED, "return-%d.json" % r["id"]))]), len(scan["rows"]))) check("G4c the full window's per-id status table is carried in probe.json", len(pr["id_status"]) >= 119 and all( pr["id_status"][str(i)] is not None for i in (2051, 2057, 2058, 2059, 2071)), "%d ids in the table" % len(pr["id_status"])) check("G5 the only route-128 return in the window is #2051", scan["route_128_rows"] == [2051], str(scan["route_128_rows"])) ids = {h["id"] for h in scan["vocab_hits"]} check("G6 the three decisive routeless returns are in the window", {2057, 2058, 2059} <= ids, str(sorted({2057, 2058, 2059} - ids))) # ----------------------------------------- H the generator-chains invariance deps = art_load("deps.json") gen = art_txt("dep__research__gen-questions-index.js") qjs = art_txt("dep__research__qc__questions.js") cjs = art_txt("dep__research__qc__corpus.js") check("H1 the generator chain is exactly three files and names no risk capability", gen.startswith("#!/usr/bin/env node") and "require('./qc/questions')" in gen and "require('./corpus')" in qjs and not any("fetch" in deps[k]["risks"] or "clock" in deps[k]["risks"] or "env" in deps[k]["risks"] or "random" in deps[k]["risks"] for k in deps), "deps=%s" % sorted(deps)) check("H2 corpus.ROOT is the tree the generator runs in", "path.resolve(__dirname, '..', '..')" in cjs and "OUT_PATH = path.join(C.RESEARCH, 'QUESTIONS.md')" in qjs) check("H3 the only environment dependency is the git-derived Display dates line", "Display dates:" in qjs and "git log" in qjs and "no git: path order" in qjs and "fileLastDates" in qjs) check("H4 the shipped fresh-A-vs-served diff differs on exactly that one preamble line", "Display dates" in "\n".join(lines["regen3289"]["B_minus_lines"]) and "Display dates" in "\n".join(lines["regen3289"]["B_plus_lines"])) pr2 = art_load("price.json") check("H5 the replacement step is priced by measurement: 680 paths, 0.017 GB corpus", pr2["manifest_paths"] == 680 and 0.015 < pr2["estimated_corpus_gb"] < 0.020 and pr2["pilot_generator"]["exit"] == 0, "%d paths, %.4f GB, pilot exit %s" % (pr2["manifest_paths"], pr2["estimated_corpus_gb"], pr2["pilot_generator"]["exit"])) # --------------------------------------------------- I the replacement step cx = art_load("census.json") check("I0b the static census ran over the full 680-path mirror and anchors on the derive id", cx["manifest_paths"] == 680 and cx["manifest_paths_not_fetched_here"] == 0 and cx["ids_checked"] == 554 and cx["ids_differing"] >= 45 and cx["derive_verdict_lengths"]["Q-derive-0904-L7-transfer"]["served"] == 562 and cx["derive_verdict_lengths"]["Q-derive-0904-L7-transfer"]["implied"] == 562, "checked=%d differ=%d" % (cx["ids_checked"], cx["ids_differing"])) ns = art_load("newstep.json") check("I1 newstep.json is a complete step object (question/method/success/failure)", all(isinstance(ns.get(k), str) and ns[k].strip() for k in ("question", "method", "success", "failure"))) check("I2 its length limits hold (question<=1000, method<=4000, success/failure<=2000)", len(ns["question"]) <= 1000 and len(ns["method"]) <= 4000 and len(ns["success"]) <= 2000 and len(ns["failure"]) <= 2000, "%d/%d/%d/%d" % (len(ns["question"]), len(ns["method"]), len(ns["success"]), len(ns["failure"]))) check("I3 budget_hours is in 0.1..4 and compute is an object", 0.1 <= float(ns["budget_hours"]) <= 4 and isinstance(ns["compute"], dict), "budget=%s" % ns["budget_hours"]) check("I4 the replacement names the fresh baseline, both controls, and the four-way attribution", "manifest-3289" in ns["method"] and "Display dates" in ns["method"] and "byte-identical" in ns["method"] and "0 unattributed" in ns["success"] and "unattributed" in ns["failure"]) check("I5 the replacement removes the already-restored #152 item and forbids the stale patch", "#152" in ns["method"] and "#2057/#2058" in ns["question"] and "being restored already" in ns["question"] and "Do NOT apply restore-83-153.patch" in ns["method"]) check("I6 the replacement carries no route_scope/lane guess and no asymptotic claim", not any(w in json.dumps(ns) for w in ("G2(x#) bound", "beta_2 bound", "twin prime proof"))) total = len(CHECKS) print("\n%d/%d checks passed" % (total - len(FAILED), total)) if FAILED: print("FAILED: %s" % FAILED) result = {"job_id": "4586", "route_id": 128, "checks": total, "failed": FAILED, "all_pass": not FAILED, "detail": CHECKS} with open(os.path.join(HERE, "check.out.json"), "w", encoding="utf-8", newline="\n") as fh: json.dump(result, fh, indent=1, ensure_ascii=False) return 1 if FAILED else 0 if __name__ == "__main__": sys.exit(main())