#!/usr/bin/env python3 """rebase-list.py -- route 114 (job 2829 continuation): extend the rebase list to the 26 returns whose accepted revision has NO store version. The store-version half was measured by #1447: 10/10 accepted texts answer byte-for-byte at `/files/`, anonymously. This instrument measures the other half. Population: the rows of #1373's enumeration whose `patch_status` is the by-hand integration queue (36 rows, 26 distinct returns). For each return it reads the return's declared artifacts through `GET /return/`, fetches each one **anonymously** at `/files/`, and for every row naming a served corpus path it reads the served base and compares its sha to the row's recorded `served_sha256`. Falsifiers P1..P4 and the artifact-kind rule are pre-registered in `prereg-rebase-list.md`; the kind rule is applied mechanically, and the *applicability* half of P3 is `apply-check.py`. python3 rebase-list.py # network; writes rebase-list.json and base/ text files """ import hashlib import json import os import sys import urllib.error import urllib.request BASE = "https://solveathome.org/projects/twin-primes" TOK = os.path.join(os.environ.get("LOCALAPPDATA", ""), "solveathome", "credentials", "twin-primes.token") ROOT = os.path.dirname(os.path.abspath(__file__)) # #1373's enumeration, read-only, produced by a sibling run; its sha256 is recorded in the output. ENUM2 = ".solveathome/twin-primes/runs/bf5-8fb00a6176edcba2/scratch-records/r1373/fresh2744.json" PENDING = "pending integration" TRANSPORT_FAILED = 0 def get(path, token=None, binary=False): headers = {"Accept": "*/*", "User-Agent": "sahreq/1.0"} if token: headers["Authorization"] = "Bearer " + token try: with urllib.request.urlopen(urllib.request.Request(BASE + path, headers=headers), timeout=120) as r: raw = r.read() return r.status, raw if binary else raw.decode("utf-8", "replace") except urllib.error.HTTPError as e: raw = e.read() return e.code, raw if binary else raw.decode("utf-8", "replace") except urllib.error.URLError as e: return TRANSPORT_FAILED, (b"" if binary else json.dumps({"error": str(e)})) def kind_of(text): """The pre-registered rule, applied to the first 2000 bytes.""" head = text[:2000] lines = head.splitlines() hunks = any(l.startswith("@@ ") for l in lines) minus = any(l.startswith("--- ") for l in lines) plus = any(l.startswith("+++ ") for l in lines) return "diff" if (hunks or (minus and plus)) else "document" def main(): # The enumeration lives in a sibling run under the project's .solveathome tree; resolve it from # the caller's cwd (the project root) rather than by counting directories up from this file. enum_path = os.path.join(os.getcwd(), ENUM2) if not os.path.exists(enum_path): raise SystemExit("run this from the project root: %s not found" % enum_path) enum_sha = hashlib.sha256(open(enum_path, "rb").read()).hexdigest() enum = json.load(open(enum_path, encoding="utf-8")) rows = [r for r in enum["rows"] if (r.get("patch_status") or "").startswith(PENDING)] returns = sorted({r["return"] for r in rows}) tok = open(TOK, encoding="utf-8").read().strip() os.makedirs(os.path.join(ROOT, "files"), exist_ok=True) os.makedirs(os.path.join(ROOT, "base"), exist_ok=True) # ---- returns -> declared artifacts, each fetched anonymously ------------------------------ ret_records, file_records = {}, {} for rid in returns: code, body = get("/return/%d" % rid, tok) if code != 200: ret_records[rid] = {"code": code, "transport": code == TRANSPORT_FAILED} continue rr = json.loads(body) arts = [] for f in rr.get("files") or []: sha = f.get("sha256") acode, blob = get("/files/%s" % sha, None, binary=True) got = hashlib.sha256(blob).hexdigest() if acode == 200 else None rec = {"name": f.get("name"), "declared_sha256": sha, "declared_bytes": f.get("bytes"), "anon_code": acode, "got_sha256": got, "got_bytes": len(blob) if acode == 200 else None, "retrievable": bool(acode == 200 and got == sha and (f.get("bytes") in (None, len(blob))))} text = blob.decode("utf-8", "replace") if acode == 200 else "" rec["kind"] = kind_of(text) if acode == 200 else None if acode == 200: p = os.path.join(ROOT, "files", "%s" % sha) with open(p, "wb") as fh: fh.write(blob) rec["local"] = p arts.append(rec) file_records[sha] = rec ret_records[rid] = {"code": code, "type": rr.get("type"), "status": rr.get("status"), "handle": rr.get("handle") or rr.get("author"), "patch_status": rr.get("patch_status"), "n_files": len(arts), "artifacts": arts} # ---- rows: base identity + artifact match ------------------------------------------------- out_rows, bases = [], {} for r in rows: rid, path = r["return"], r["path"] rec = ret_records.get(rid) or {} cand = [] base_name = os.path.basename(path) for a in rec.get("artifacts") or []: n = a.get("name") or "" if n == base_name or n == path or n.startswith(base_name + ".") or \ n.split("/")[-1] == base_name or n.split("/")[-1].startswith(base_name + "."): cand.append(a) artifact = cand[0] if len(cand) == 1 else None row = {"return": rid, "type": r["type"], "via": r["via"], "path": path, "recorded_served_sha256": r.get("served_sha256"), "served_flag": r.get("served"), "in_manifest": r.get("in_manifest"), "effects_applied_at": r.get("effects_applied_at"), "artifact": None if artifact is None else {k: artifact.get(k) for k in ("name", "declared_sha256", "got_sha256", "kind", "retrievable", "local")}, "artifact_candidates": [a.get("name") for a in (rec.get("artifacts") or [])] if artifact is None else [], "why_no_match": None if artifact is not None else ("no declared artifact name matches %r" % base_name if (rec.get("artifacts") or []) else "return declares no artifacts")} # served base, only for rows that name a served corpus path if "/" in path or path.endswith(".md") or path.endswith(".js"): bcode, base_text = get("/docs/" + path, tok) if bcode == 200: bsha = hashlib.sha256(base_text.encode("utf-8")).hexdigest() row["served_base"] = {"docs_code": bcode, "sha256": bsha, "matches_recorded": bsha == r.get("served_sha256"), "bytes": len(base_text.encode("utf-8"))} with open(os.path.join(ROOT, "base", path.replace("/", "__")), "w", encoding="utf-8", newline="") as fh: fh.write(base_text) else: row["served_base"] = {"docs_code": bcode, "sha256": None, "matches_recorded": False, "bytes": None} out_rows.append(row) # ---- the pre-registered verdicts ---------------------------------------------------------- retr = {rid: any(a["retrievable"] for a in (rec.get("artifacts") or [])) for rid, rec in ret_records.items()} f1 = sorted(rid for rid, ok in retr.items() if not ok) f2 = [r["path"] for r in out_rows if r.get("served_base") and r["served_base"]["docs_code"] == 200 and not r["served_base"]["matches_recorded"]] corpus_rows = [r for r in out_rows if r.get("served_base") and r["served_base"]["docs_code"] == 200] diff_rows = [r for r in corpus_rows if r["artifact"] and r["artifact"]["kind"] == "diff"] kinds = {r["artifact"]["kind"] for r in out_rows if r["artifact"]} res = { "job": "2829-continuation", "route": 114, "tool": "rebase-list.py/1.0", "enumeration": {"path": ENUM2, "sha256": enum_sha, "n_rows": len(enum["rows"]), "n_returns": len(enum["population"])}, "population": {"pending_rows": len(rows), "pending_returns": len(returns), "corpus_path_rows": len(corpus_rows)}, "returns": ret_records, "rows": out_rows, "F1_returns_without_retrievable_artifact": f1, "F2_bases_moved": f2, "F4_degenerate_kinds": (len(kinds) < 2), "kinds_seen": sorted(kinds), "diff_rows_awaiting_apply_check": [ {"return": r["return"], "path": r["path"], "artifact": r["artifact"]["declared_sha256"], "base": r["served_base"]["sha256"]} for r in diff_rows], "verdicts": { "P1_all_returns_retrievable": not f1, "P2_bases_unmoved": not f2, "P4_classification_not_degenerate": len(kinds) >= 2, }, } json.dump(res, open(os.path.join(ROOT, "rebase-list.json"), "w", encoding="utf-8", newline="\n"), indent=1, ensure_ascii=False, sort_keys=True) print(json.dumps({ "pending_rows": res["population"]["pending_rows"], "pending_returns": res["population"]["pending_returns"], "corpus_path_rows": res["population"]["corpus_path_rows"], "retrievable_returns": sum(1 for v in retr.values() if v), "F1": f1, "F2": f2, "kinds": res["kinds_seen"], "diff_rows": len(diff_rows), "rows_without_artifact_match": [r["path"] for r in out_rows if r["artifact"] is None], "verdicts": res["verdicts"], }, indent=1, ensure_ascii=False)) return 0 if __name__ == "__main__": sys.exit(main())