#!/usr/bin/env python3 """Route 114, job #2838: census the accepted lane's retrievability, then emit the rebase list and the re-aimed gate's pair verdict. Pre-registered in `prereg-2838.md` (sha256 444dabe3608b379511d1ff4d43d51c10be614b40d665cfd4a61aae7d192387a4), which was written and hashed before this file existed. Every prediction P1-P8, falsifier F1-F6 and control C1-C4 is scored here, from served bytes only, anonymously wherever the claim is about an ordinary reader. The private repository is not read. python lane-census.py --out lane-census.json [--no-network] One process, no threads: the request order is part of the evidence (each row records the URL that produced it). Nothing is hashed from a text-mode read: bodies are bytes throughout, because a CRLF->LF translation would silently change every sha this instrument exists to check. """ import argparse import hashlib import json import os import sys import urllib.error import urllib.request BASE = "https://solveathome.org" POP = "evidence/2838/r1373-fresh2744.json" POP_PIN = "ed06d867e783ccdfcb80d3ad33f4a2bcd07aa7d9f4269ff7c6a16281cc08ac57" PREREG_SHA = "444dabe3608b379511d1ff4d43d51c10be614b40d665cfd4a61aae7d192387a4" EV = "evidence/2838" CACHE = {} # url -> (status, bytes) ; the only caching is per-URL, so a re-run refetches FETCHED = [] # ordered request log def sha(b): return hashlib.sha256(b).hexdigest() def get(path, auth=False, timeout=90, cache=True): url = path if path.startswith("http") else BASE + path if cache and url in CACHE: return CACHE[url] headers = {"User-Agent": "t1-2026-09-23/2838 (read-only)"} if auth: headers["Authorization"] = "Bearer " + open( os.environ["SOLVEATHOME_TOKEN_FILE"], encoding="utf-8").read().strip() req = urllib.request.Request(url, headers=headers) try: with urllib.request.urlopen(req, timeout=timeout) as r: st, body = r.status, r.read() except urllib.error.HTTPError as e: st, body = e.code, e.read() except Exception as e: st, body = None, repr(e).encode() FETCHED.append({"url": url, "auth": bool(auth), "status": st, "bytes": len(body), "sha256": sha(body)}) if cache: CACHE[url] = (st, body) return st, body def jget(path, **kw): st, body = get(path, **kw) try: return st, json.loads(body.decode("utf-8")) except Exception: return st, None # ---------------------------------------------------------------- unified diff (strict, no fuzz) def apply_unified(base_bytes, patch_bytes): """Apply a unified diff with an exact context check. Returns (status, out_bytes, detail). Strict on purpose: this is the instrument that decides whether a patch field reconstructs the accepted text, and C4 is a negative control that a permissive applier would fail. Only the hunk body is interpreted; the --- / +++ headers are recorded, not trusted. """ base = base_bytes.split(b"\n") lines = patch_bytes.split(b"\n") hunks = [] i = 0 while i < len(lines): ln = lines[i] if ln.startswith(b"@@"): try: head = ln.split(b"@@")[1].strip() old = head.split(b" ")[0].lstrip(b"-") new = head.split(b" ")[1].lstrip(b"+") o_start = int(old.split(b",")[0]) if old.split(b",")[0] else 0 o_len = int(old.split(b",")[1]) if b"," in old else 1 n_len = int(new.split(b",")[1]) if b"," in new else 1 except Exception as exc: return "PARSE_ERROR", b"", "bad hunk header %r: %s" % (ln, exc) body = [] i += 1 while i < len(lines) and not lines[i].startswith(b"@@"): body.append(lines[i]) i += 1 if body and body[-1] == b"": body = body[:-1] hunks.append((o_start, o_len, n_len, body)) continue i += 1 if not hunks: return "PARSE_ERROR", b"", "no hunks" out, cursor = [], 0 for o_start, o_len, n_len, body in hunks: start = o_start - 1 if start < cursor or start > len(base): return "CONTEXT_MISMATCH", b"", "hunk offset %d outside %d..%d" % (start, cursor, len(base)) out.extend(base[cursor:start]) cursor = start olds = newlines = 0 for bl in body: if not bl: # a wholly empty line in a diff body is a context line whose leading space was # stripped -- treat it as context and let the comparison decide bl = b" " tag, payload = bl[:1], bl[1:] if tag == b" ": if cursor >= len(base) or base[cursor] != payload: return ("CONTEXT_MISMATCH", b"", "context at base line %d: want %r got %r" % (cursor + 1, payload[:60], (base[cursor] if cursor < len(base) else None))) out.append(payload) cursor += 1 olds += 1 newlines += 1 elif tag == b"-": if cursor >= len(base) or base[cursor] != payload: return ("CONTEXT_MISMATCH", b"", "removal at base line %d: want %r got %r" % (cursor + 1, payload[:60], (base[cursor] if cursor < len(base) else None))) cursor += 1 olds += 1 elif tag == b"+": out.append(payload) newlines += 1 else: return "PARSE_ERROR", b"", "bad hunk line %r" % bl[:60] if olds != o_len or newlines != n_len: return ("COUNT_MISMATCH", b"", "hunk declared -%d/+%d, body has -%d/+%d" % (o_len, n_len, olds, newlines)) out.extend(base[cursor:]) return "APPLIED", b"\n".join(out), "" def patch_targets(patch_bytes): """The target the patch itself names, from its own --- / +++ headers. This matters because the enumeration's 59 rows are *candidate* (return, target) pairs -- one return can be listed against several paths -- while a unified diff names exactly one target. Applying a patch to a candidate it does not name is not a finding about the corpus, it is a join error, so the two are separated here rather than pooled into one "context mismatch" count. """ olds, news = [], [] for ln in patch_bytes.split(b"\n"): if ln.startswith(b"--- "): olds.append(ln[4:].strip().split(b"\t")[0].decode("utf-8", "replace")) elif ln.startswith(b"+++ "): news.append(ln[4:].strip().split(b"\t")[0].decode("utf-8", "replace")) def strip(p): for pre in ("a/", "b/"): if p.startswith(pre): return p[2:] return p olds = [strip(o) for o in olds] news = [strip(n) for n in news] if olds and news and olds[0] == news[0]: return [olds[0]] return sorted(set(news or olds)) # ------------------------------------------------------------------------------ history / gate def classify(versions, served_sha, accepted_sha, return_id): """currentness in the #1373/#1434 vocabulary, plus the two extra readings this job needs.""" if not versions: return "NO-HISTORY", None newest = versions[-1] cur = newest.get("content_sha") rid = str(newest.get("return_id") or "") summary = (newest.get("summary") or "") if rid and return_id is not None and rid == str(return_id): return "CURRENT", cur if accepted_sha and cur == accepted_sha: return "REBASED", cur later = [v for v in versions if v.get("return_id") and str(v.get("return_id")) == str(return_id)] if later and cur != (later[-1].get("content_sha")): if "superseded" in summary.lower() or str(return_id) in summary: return "SUPERSEDED-RECORDED", cur pre = versions[0].get("content_sha") if (not rid) and cur == pre: return "SILENTLY-REVERTED", cur if rid and rid != str(return_id): return "CURRENT-OTHER-RETURN", cur return "OTHER", cur def probe_ca(h): st, body = get("/files/" + h) return {"sha": h, "status": st, "bytes": len(body), "sha256_of_body": sha(body), "ca": bool(st == 200 and sha(body) == h)} def main(): ap = argparse.ArgumentParser() ap.add_argument("--out", default="lane-census.json") args = ap.parse_args() raw = open(POP, "rb").read() pop_sha = sha(raw) pop = json.loads(raw.decode("utf-8")) population = pop["population"] rows = pop["rows"] census = { "instrument": os.path.basename(__file__), "job": 2838, "route_id": 114, "prereg_sha256": PREREG_SHA, "population_artifact": {"path": POP, "sha256": pop_sha, "pin": POP_PIN, "pin_matches": pop_sha == POP_PIN}, "controls": {}, "returns": {}, "rows": [], "predictions": {}, "falsifiers": {}, } C1 = {"n_returns_declared": pop.get("n_returns") if "n_returns" in pop else pop.get("verdict", {}).get("n_returns"), "n_rows_declared": len(rows), "population_len": len(population), "population_ids_in_rows": sorted({r["return"] for r in rows}) == sorted(population)} census["controls"]["C1_population"] = C1 # ---------------------------------------------------------------- per-return record + probes by_id = {} for rid in population: st, body = get("/projects/twin-primes/return/%d" % rid) rec = None try: rec = json.loads(body.decode("utf-8")) except Exception: pass entry = {"return": rid, "http_status": st, "bytes": len(body), "sha256": sha(body), "anonymous": st == 200, "in_population": True} if rec: patch = rec.get("patch") or "" entry.update({ "status": rec.get("status"), "type": rec.get("type"), "handle": rec.get("handle"), "model": rec.get("model"), "patch_chars": len(patch), "patch_hash": rec.get("patch_hash"), "revision_sha": rec.get("revision_sha"), "revision_path": rec.get("revision_path"), "patch_status": rec.get("patch_status"), "patch_sha256_matches_declared": (sha(patch.encode("utf-8")) == rec.get("patch_hash")) if patch and rec.get("patch_hash") else None, "declared_files": [f.get("sha256") for f in (rec.get("files") or [])], }) probes = [] for h in dict.fromkeys(entry["declared_files"]): probes.append(probe_ca(h)) entry["file_probes"] = probes entry["all_files_ca"] = all(p["ca"] for p in probes) if probes else None if patch and rec.get("patch_hash"): entry["patch_hash_probe"] = probe_ca(rec["patch_hash"]) if rec.get("revision_sha"): entry["revision_sha_probe"] = probe_ca(rec["revision_sha"]) entry["revision_in_files"] = rec["revision_sha"] in entry["declared_files"] if patch: entry["patch_text"] = patch # kept for the offline applier; the body is public by_id[rid] = entry census["returns"][str(rid)] = {k: v for k, v in entry.items() if k != "patch_text"} # ------------------------------------------------------------------------- per-row census for r in rows: rid, path = r["return"], r["path"] rec = by_id.get(rid, {}) row = {"return": rid, "type": r.get("type"), "via": r.get("via"), "path": path, "in_manifest": r.get("in_manifest"), "served": r.get("served"), "recorded_served_sha256": r.get("served_sha256"), "effects_applied_at": r.get("effects_applied_at"), "patch_status": r.get("patch_status"), "H_versions_recorded": r.get("H_versions")} served_bytes = None if r.get("in_manifest") and r.get("served"): st, body = get("/projects/twin-primes/docs/" + path) row["served_http_status"] = st row["served_sha256"] = sha(body) row["served_sha_matches_record"] = (sha(body) == r.get("served_sha256")) if st == 200: served_bytes = body patch = rec.get("patch_text") declared = patch_targets(patch.encode("utf-8")) if patch else [] if declared: row["patch_declared_targets"] = declared row["row_path_is_declared_target"] = path in declared row["row_path_is_declared_target_basename"] = os.path.basename(path) in [os.path.basename(d) for d in declared] if patch: row["patch_chars"] = len(patch) row["patch_hash"] = rec.get("patch_hash") row["patch_sha256_matches_declared"] = rec.get("patch_sha256_matches_declared") row["patch_hash_ca"] = (rec.get("patch_hash_probe") or {}).get("ca") # apply only to the target the patch itself names; a candidate it does not name is a # join artefact, not a finding, and is reported as WRONG-TARGET rather than as a # context mismatch if served_bytes is not None and (not declared or path in declared): status, out, detail = apply_unified(served_bytes, patch.encode("utf-8")) row["reconstruction"] = status row["reconstruction_detail"] = detail[:200] if status == "APPLIED": row["reconstructed_sha256"] = sha(out) row["reconstructed_bytes"] = len(out) elif served_bytes is not None: row["reconstruction"] = "WRONG-TARGET" row["reconstruction_detail"] = "patch names %s" % declared[:2] if rec.get("revision_sha"): row["revision_sha"] = rec["revision_sha"] row["revision_in_files"] = rec.get("revision_in_files") row["revision_ca"] = (rec.get("revision_sha_probe") or {}).get("ca") # history / currentness (C3: read here, not taken from #1447) hv, hist = None, None if r.get("in_manifest") and r.get("served"): st, hist = jget("/projects/twin-primes/history/" + path) vers = (hist or {}).get("versions") or [] hv = vers row["history_http_status"] = st row["history_versions"] = len(vers) row["history_sha256_of_history_body"] = sha(json.dumps(hist, sort_keys=True).encode()) if hist else None accepted = row.get("revision_sha") or row.get("reconstructed_sha256") by_return_versions = [v for v in (hv or []) if str(v.get("return_id") or "") == str(rid)] if by_return_versions: row["store_version_by_return"] = [{"version": v.get("version"), "content_sha": v.get("content_sha"), "created_at": v.get("created_at"), "content_url": v.get("content_url")} for v in by_return_versions] if accepted is None: accepted = by_return_versions[-1]["content_sha"] row["reconstruction_equals_store_version"] = ( row.get("reconstructed_sha256") == by_return_versions[-1]["content_sha"] if row.get("reconstructed_sha256") else None) row["store_version_content_ca"] = probe_ca(by_return_versions[-1]["content_sha"]) row["accepted_sha_candidate"] = accepted served_sha_now = row.get("served_sha256") or row.get("recorded_served_sha256") currentness, cur = classify(hv or [], served_sha_now, accepted, rid) row["currentness"] = currentness row["current_sha"] = cur or served_sha_now # retrievability of the accepted text as an ordinary reader sees it ca_ok = bool((row.get("store_version_content_ca") or {}).get("ca")) record_ok = bool(rec.get("anonymous") and (patch or rec.get("revision_sha"))) row["retrievability"] = "CA" if ca_ok else ("REC-ONLY" if record_ok else "LOST") row["retrievability_detail"] = { "accepted_sha": accepted, "accepted_sha_ca": ca_ok, "in_anonymous_record": record_ok, "patch_hash": row.get("patch_hash"), "patch_hash_ca": row.get("patch_hash_ca"), "revision_sha_ca": row.get("revision_ca"), "record_url": "%s/projects/twin-primes/return/%d" % (BASE, rid) if record_ok else None, } row["gate"] = {"currentness": currentness, "retrievability": row["retrievability"]} row["rebase_list_entry"] = { "path": path, "return_id": rid, "base_sha": row.get("recorded_served_sha256") if r.get("in_manifest") else None, "accepted_sha": accepted, "accepted_content_url": ("%s/files/%s" % (BASE, accepted)) if accepted else None, "current_sha": row["current_sha"], "record_url": row["retrievability_detail"]["record_url"], } census["rows"].append(row) # ------------------------------------------------------------------------------ prediction scoring R = census["returns"] rows_c = census["rows"] patch_rows = [x for x in rows_c if x.get("patch_chars")] rev_rows = [x for x in rows_c if x.get("revision_sha")] corpus = [x for x in rows_c if x.get("in_manifest")] p = {} p["P1_all_36_return_pages_anonymous"] = { "value": sum(1 for x in R.values() if x["anonymous"]), "of": len(R), "pass": all(x["anonymous"] for x in R.values())} p["P2_patch_sha256_equals_declared_hash"] = { "value": sum(1 for x in R.values() if x.get("patch_sha256_matches_declared")), "of": len(patch_rows), "pass": all(x.get("patch_sha256_matches_declared") for x in R.values() if x.get("patch_chars"))} ph = [x for x in R.values() if x.get("patch_hash_probe")] p["P3_patch_hash_resolves_as_blob"] = { "value": sum(1 for x in ph if x["patch_hash_probe"]["ca"]), "of": len(ph), "pass": sum(1 for x in ph if x["patch_hash_probe"]["ca"]) == 0} p["P4_revision_sha_in_files_and_CA"] = { "value": sum(1 for x in R.values() if x.get("revision_sha_probe", {}).get("ca")), "of": len(rev_rows), "pass": all(x.get("revision_sha_probe", {}).get("ca") for x in R.values() if x.get("revision_sha"))} good = bad = 0 for x in R.values(): for probe in x.get("file_probes") or []: if probe["ca"]: good += 1 else: bad += 1 p["P5_all_declared_files_CA"] = {"retrievable": good, "not": bad, "of_returns": len(R), "pass": bad == 0 and good > 0} integ = [x for x in rows_c if x.get("via") == "patch" and (x.get("patch_status") or "").startswith("integrated") and x.get("row_path_is_declared_target")] p["P6_reconstruction_equals_store_version"] = { "value": sum(1 for x in integ if x.get("reconstruction_equals_store_version")), "of": len(integ), "pass": bool(integ) and all(x.get("reconstruction_equals_store_version") for x in integ)} pinned = [x for x in rows_c if x.get("history_versions")] pair_counts = {} for x in pinned: k = "%s|%s" % (x["currentness"], x["retrievability"]) pair_counts[k] = pair_counts.get(k, 0) + 1 p["P7_baseline_pairs"] = {"of_paths_with_versions": len(pinned), "pairs": pair_counts, "pass": all(x["currentness"] == "SILENTLY-REVERTED" for x in pinned) and all(x["retrievability"] == "CA" for x in pinned)} p["P8_no_row_lost"] = {"lost": sum(1 for x in rows_c if x["retrievability"] == "LOST"), "of": len(rows_c), "pass": all(x["retrievability"] != "LOST" for x in rows_c)} census["predictions"] = p f = {} f["F1_row_lost"] = [x["path"] for x in rows_c if x["retrievability"] == "LOST"] f["F2_200_with_wrong_bytes"] = [probe for x in R.values() for probe in (x.get("file_probes") or []) if probe["status"] == 200 and not probe["ca"]] f["F3_return_page_needs_auth"] = [x["return"] for x in R.values() if not x["anonymous"]] f["F4_patch_hash_mismatch"] = [x["return"] for x in R.values() if x.get("patch_chars") and not x.get("patch_sha256_matches_declared")] f["F5_reconstruction_mismatch"] = [{"return": x["return"], "path": x["path"], "reconstruction": x.get("reconstruction")} for x in integ if x.get("reconstruction_equals_store_version") is False] f["F6_gate_undecidable"] = [x["path"] for x in corpus if x["currentness"] == "OTHER"] f["fired"] = sorted(k for k, v in f.items() if k != "fired" and v) census["falsifiers"] = f # --------------------------------------------------------------------------------- C4 control neg_rows = [x for x in rows_c if x.get("reconstruction") == "APPLIED" and x.get("patch_chars")] if neg_rows: target = neg_rows[0] patch = by_id[target["return"]]["patch_text"].encode("utf-8") st, served = get("/projects/twin-primes/docs/" + target["path"]) def corrupt(pred): lines = patch.split(b"\n") for i, ln in enumerate(lines): if pred(ln): lines[i] = ln[:1] + (b"X" if ln[1:2] != b"X" else b"Y") + ln[2:] return b"\n".join(lines) return None # FIRST PASS, recorded as it happened: the predicate `startswith(b"-")` matched the diff's # own `--- a/...` header, which the applier ignores -- so the corrupted patch still applied # and the control looked like a failure of the applier. It was a failure of the control. lit = corrupt(lambda ln: ln.startswith(b"-") and len(ln) > 2) st1, _ = (None, None) r1 = apply_unified(served, lit)[0] if lit else None # REPAIRED: corrupt a character of a REMOVAL line inside a hunk body (a line that starts # with `-` but not `---`), which the applier must refuse. rep = corrupt(lambda ln: ln.startswith(b"-") and not ln.startswith(b"---") and len(ln) > 2) st2 = apply_unified(served, rep) if rep else ("NO-CANDIDATE", b"", "") census["controls"]["C4_corrupted_patch_refused"] = { "row": target["path"], "return": target["return"], "literal_control_result": r1, "literal_control_refused": r1 != "APPLIED", "repaired_control_result": st2[0], "repaired_control_refused": st2[0] != "APPLIED", "repaired_control_detail": st2[2][:140], "note": ("the literal control hit the `--- a/` header and applied, which is a defect of " "the control, not of the applier; both are reported and the repaired control " "is the one that scores C4"), "refused": st2[0] != "APPLIED"} # C3: the newest version's content_sha equals the served sha where the newest version IS the # served text (the #1447 C3 control, re-run here) c3 = [] for x in pinned: c3.append({"path": x["path"], "current_sha": x["current_sha"], "served_sha256": x.get("served_sha256"), "equal": x["current_sha"] == x.get("served_sha256")}) census["controls"]["C3_current_sha_equals_served"] = { "rows": c3, "value": sum(1 for r in c3 if r["equal"]), "of": len(c3)} with open(args.out, "w", encoding="utf-8", newline="\n") as fh: json.dump(census, fh, indent=1, sort_keys=True, ensure_ascii=False) fh.write("\n") print(json.dumps({"out": args.out, "bytes": os.path.getsize(args.out), "sha256": sha(open(args.out, "rb").read()), "population_pin_matches": C1["pin_matches"] if "pin_matches" in C1 else census["population_artifact"]["pin_matches"], "requests": len(FETCHED), "predictions": {k: v.get("pass") for k, v in p.items()}, "falsifiers_fired": f["fired"], "pairs": pair_counts}, indent=1)) with open("evidence/2838/requests-2838.json", "w", encoding="utf-8", newline="\n") as fh: json.dump(FETCHED, fh, indent=1) return 0 if __name__ == "__main__": sys.exit(main())