#!/usr/bin/env python3 """Job #4215: reassess the refused return #1328 against the CURRENT served head. Every claim below is byte-measured: store blobs fetched by sha and hashed, the served document fetched live, its /history read live, and the reconstruction of return #1709's method (finding #798's named next version, plus #799's escape) reproduced independently. Output: reassess.json + reassess.out (LF only). No credentials are read or printed: all reads are anonymous public project data. """ import difflib import hashlib import json import os import re import shutil import subprocess import sys import tempfile import urllib.request sys.stdout.reconfigure(encoding="utf-8", errors="replace") HERE = os.path.dirname(os.path.abspath(__file__)) FILES = os.path.join(HERE, "files") BASE = "https://solveathome.org/projects/twin-primes" UA = "sah-research-agent/1.0" # --- the artifacts under test (full sha256) --------------------------------- V1_V3 = "19b6b12c228ec9decd4bd5328cf28b84c63e257ed04dbf55938ea687397f801d" # v1 = v3, 2026-09-16 cut V2_151 = "21dce4f3b3bc36d3fd662a616cc2b6a149ddf67ff79bc71a85f4f7b3c82e46c0" # #151 (accepted audit) R1328 = "7dddf4359be5a4f900e09bd3e46482d2ae8fe95fa0d9a34ff5ccb10b0dff9836" # #1328 (refused) V5_301 = "79faee00b0274c45b772d44c5bdb5c84bfec97e860f4d8fd5bae39affccf71d0" # v5, head at review 359 V8_864 = "f6aa8d5fd6a86589f4abc7a8e6d9dd70adfb2b9f0fa6557dfa981b046cfb453b" # v8 (#864) V9_1709 = "f68588601afedd32abf594421081aec49dbad9a2b69a65bdaa445af42151eae5" # v9 (#1709), served head NAMED_798 = "09d02c2e427df708c5651d44a6d64c033e5c758245d311db90a8a1e68b5ec5f5" # finding #798's named version DOC = "/docs/research/fixed-endpoint-discrepancy.md" HIST = "/history/research/fixed-endpoint-discrepancy.md" R = {"job": 4215, "attempt": "9d16b4e21bd711a6903bb8db4a22facc", "checks": {}} def sha(b): return hashlib.sha256(b).hexdigest() def body(path): with open(os.path.join(FILES, path), "rb") as fh: return fh.read() def get(path): req = urllib.request.Request(path if path.startswith("http") else BASE + path, headers={"User-Agent": UA, "Accept": "*/*"}) with urllib.request.urlopen(req, timeout=60) as f: return f.read() def lines(b): return b.decode("utf-8").splitlines(keepends=True) def unified(a_lines, b_lines, n=3): return list(difflib.unified_diff(a_lines, b_lines, "a", "b", lineterm="\n", n=n)) HUNK = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") def _match_at(src, parts, p, soft): """Try to place a hunk's parts at source index p; return (end, output, soft mismatches).""" j, outp, sm = p, [], [] for idx, (k, text) in enumerate(parts): if k == "+": outp.append(text) continue if j >= len(src): return None if src[j] != text: if idx not in soft: return None sm.append((idx, j + 1)) if k == " ": outp.append(src[j]) j += 1 return j, outp, sm def apply_unified(src_lines, diff_lines, fuzz=3, max_offset=200): """Context applier for a unified diff, with GNU-patch fuzz and offset search. With fuzz f the first f and last f *context* lines of a hunk are not verified (the source's own line is kept, as `patch` does); offsets are tried outward from the hunk's stated position. The reconstruction below needs fuzz 3 at the BFI II+III row, where diff(v3, v8) carries stale context, and offset +17 for the section 5 hunk; both are measured again below with the system patch (2.7.6), which at its default fuzz 2 fails that hunk. """ out, i, di = [], 0, 0 applied, soft_hits, offsets = 0, [], [] while di < len(diff_lines): m = HUNK.match(diff_lines[di]) if not m: di += 1 continue s_start = int(m.group(1)) di += 1 parts = [] while di < len(diff_lines) and not diff_lines[di].startswith("@@"): l = diff_lines[di] di += 1 if l.startswith("\\"): continue if l[:1] in " -+" and len(l) > 1: parts.append((l[0], l[1:])) lead = 0 while lead < len(parts) and parts[lead][0] == " ": lead += 1 trail = 0 while trail < len(parts) and parts[len(parts) - 1 - trail][0] == " ": trail += 1 soft = set(range(min(fuzz, lead))) | {len(parts) - 1 - j for j in range(min(fuzz, trail))} pos = s_start - 1 found = None for off in [0] + [o for d_ in range(1, max_offset + 1) for o in (d_, -d_)]: p = pos + off if p < i or p > len(src_lines): continue r = _match_at(src_lines, parts, p, soft) if r is not None: found = (off, r) break if not found: raise SystemExit("hunk at source line %d: no match within +/-%d lines (fuzz %d)" % (s_start, max_offset, fuzz)) off, (j, outp, sm) = found out.extend(src_lines[i:pos + off]) out.extend(outp) i = j applied += 1 offsets.append({"source_line": s_start, "offset": off}) soft_hits.extend({"hunk_source_line": s_start, "soft_source_line": ln} for _, ln in sm) out.extend(src_lines[i:]) R["checks"]["reconstruction"]["hunks_applied"] = applied R["checks"]["reconstruction"]["fuzz"] = fuzz R["checks"]["reconstruction"]["offsets"] = offsets R["checks"]["reconstruction"]["soft_context_positions"] = soft_hits return out # --- 0. fetch hashes of the local evidence, and the live head --------------- v1 = body(V1_V3) v2 = body(V2_151) r1328 = body(R1328) v5 = body(V5_301) v8 = body(V8_864) v9 = body(V9_1709) for name, b, want in (("v1/v3", v1, V1_V3), ("v2/#151", v2, V2_151), ("#1328", r1328, R1328), ("v5", v5, V5_301), ("v8", v8, V8_864), ("v9", v9, V9_1709)): assert sha(b) == want, "local blob %s does not hash to its name" % name R["checks"]["blobs"] = {"n": 6, "all_hash_to_their_names": True} live = get(DOC) R["checks"]["served_head"] = { "url": BASE + DOC, "bytes": len(live), "sha256": sha(live), "equals_v9_file": sha(live) == V9_1709, "is_v5": sha(live) == V5_301, "crlf": live.count(b"\r\n"), "review_359_falsifier_head_other_than_v5": sha(live) != V5_301, } hist = json.loads(get(HIST).decode("utf-8")) vs = hist["versions"] R["checks"]["history"] = { "n_versions": len(vs), "head_version": vs[-1]["version"], "head_return": vs[-1]["return_id"], "head_content_sha": vs[-1]["content_sha"], "head_equals_live": vs[-1]["content_sha"] == sha(live), "head_verified_by": vs[-1].get("verified_by"), "head_author_model": vs[-1].get("author_model"), "v5_return": [h["return_id"] for h in vs if h["version"] == 5], "versions_after_v5": [(h["version"], h["return_id"], h["created_at"]) for h in vs if h["version"] > 5], } # --- 1. reconstruct v9 from v5 + diff(v1/v3, v8) + finding #799's escape --- R["checks"]["reconstruction"] = {} patch = unified(lines(v1), lines(v8)) fuzz_try = {} for f in (0, 2, 3): R["checks"]["reconstruction"] = {} try: got = sha("".join(apply_unified(lines(v5), patch, fuzz=f)).encode("utf-8")) except SystemExit as exc: got = "failed: %s" % exc fuzz_try[f] = got R["checks"]["reconstruction"] = {} rebuilt = "".join(apply_unified(lines(v5), patch, fuzz=3)).encode("utf-8") R["checks"]["reconstruction"]["fuzz_sweep"] = fuzz_try # the same recipe with the system patch, to separate my applier from GNU patch pd = tempfile.mkdtemp(prefix="j4215-") try: for name, b in (("v3.md", v1), ("v8.md", v8), ("v5.md", v5)): with open(os.path.join(pd, name), "wb") as fh: fh.write(b) for tag, n in (("d3", 3), ("d1", 1)): with open(os.path.join(pd, tag + ".patch"), "w", encoding="utf-8", newline="\n") as fh: fh.write("".join(unified(lines(v1), lines(v8), n=n))) syspatch = [] for tag, args in (("d3", ()), ("d3", ("-F3",)), ("d1", ())): with open(os.path.join(pd, "v5.md"), "wb") as fh: fh.write(v5) cmd = ["patch"] + list(args) + ["v5.md"] with open(os.path.join(pd, tag + ".patch"), "rb") as fin: p = subprocess.run(cmd, cwd=pd, stdin=fin, capture_output=True, text=True) with open(os.path.join(pd, "v5.md"), "rb") as fh: out = fh.read() syspatch.append({"cmd": " ".join(cmd) + " < %s.patch" % tag, "exit": p.returncode, "stdout": p.stdout.strip().replace("\r", ""), "result_sha": sha(out), "bytes": len(out), "matches_named_798": sha(out) == NAMED_798}) ver = subprocess.run(["patch", "--version"], capture_output=True, text=True) R["checks"]["gnu_patch"] = {"version": ver.stdout.splitlines()[0] if ver.stdout else "?", "runs": syspatch} finally: shutil.rmtree(pd, ignore_errors=True) R["checks"]["reconstruction"].update({ "method": "apply diff(v3 19b6b12c, v8 f6aa8d5f) to v5 79faee00", "result_sha": sha(rebuilt), "bytes": len(rebuilt), "equals_finding_798_named_sha": sha(rebuilt) == NAMED_798, }) row_old = "sum_{q~Q}|pi(x;q,a)-pi(x)/phi(q)|=O(" row_new = "sum_{q~Q}\\|pi(x;q,a)-pi(x)/phi(q)\\|=O(" assert rebuilt.count(row_old.encode()) == 1 escaped = rebuilt.replace(row_old.encode(), row_new.encode()) R["checks"]["reconstruction"].update({ "escape": "two bare bars in the section 3 BFI II+III row -> \\| (finding #799)", "escaped_sha": sha(escaped), "bytes_escaped": len(escaped), "equals_v9": sha(escaped) == V9_1709, "equals_live_served": sha(escaped) == sha(live), }) # --- 2. #151's two corrections: present in v9, absent from v1/v3 ----------- t151 = { "band qualifier in the verdict": "a stronger sufficient input for the band piece P_band only", "section 12 citation": "section 12 (consumer in 12a)", } t151_absent_from_v1 = {"fails at absolute values over all moduli": "fails at absolute values over all moduli near x^(1/2+eps') in one fixed class"} chk = {} for k, s in t151.items(): chk[k] = {"in_v2_151": s in v2.decode("utf-8"), "in_v9_head": s in v9.decode("utf-8"), "in_r1328": s in r1328.decode("utf-8"), "in_v1_v3": s in v1.decode("utf-8")} R["checks"]["finding_151_content"] = chk # --- 3. the candidate next version #1328 as installed on v9 ---------------- t = lambda b: b.decode("utf-8") FALSE_LINE27 = "of the order of the whole target o(x/log x)" items = [ ("accepted_correction", "line 27: BFI II+III stated with the absolute values", "has the absolute values and the level x^(1/2+delta)"), ("accepted_correction", "section 3 row: absolute values over all q in [Q,2Q]", "**absolute values over all q in [Q,2Q]**"), ("accepted_correction", "section 4.3: the absolute-value, all-moduli theorem beyond 1/2 exists", "all-moduli theorem beyond 1/2 does exist"), ("accepted_addition", "section 5: #813's 2026-09-17 identity remark", "Remark (added 2026-09-17, audit; an identity, not an estimate)"), ("accepted_addition", "section 5: census paragraph", "Added 2026-09-17 (audit; group review)"), ("accepted_fix", "finding #799's escapes in the section 3 BFI row", row_new), ("open_defect", "line 27: the unrepaired arithmetic phrase (finding #2623 / #754)", FALSE_LINE27), ("r1328_only", "provenance line re-added by #1328 (false on v9)", "Re-applied 2026-09-19 (job #2680, review #154)"), ] R["checks"]["r1328_as_next_version"] = {"rows": []} tab = R["checks"]["r1328_as_next_version"]["rows"] for kind, k, needle in items: in_v9, in_r = needle in t(v9), needle in t(r1328) tab.append({"kind": kind, "what": k, "needle": needle[:60], "in_v9_head": in_v9, "in_r1328": in_r, "lost_if_r1328_installed": in_v9 and not in_r, "added_if_r1328_installed": in_r and not in_v9}) # does 7dddf435's line 27 also lack #151's own qualifier? (line 27 was not what #151 edited) R["checks"]["r1328_line27_verbatim"] = [ l.strip()[:200] for l in t(r1328).splitlines() if l.startswith(" Source theorem")] R["checks"]["v9_line27_verbatim"] = [ l.strip()[:200] for l in t(v9).splitlines() if l.startswith(" Source theorem")] d = unified(lines(r1328), lines(v9)) R["checks"]["r1328_as_next_version"]["_diff"] = { "unified_diff_lines": len(d), "hunks": sum(1 for l in d if l.startswith("@@")), "bytes_r1328": len(r1328), "bytes_v9": len(v9), } d59 = unified(lines(v5), lines(v9)) R["checks"]["v5_to_v9"] = { "unified_diff_lines": len(d59), "hunks": sum(1 for l in d59 if l.startswith("@@")), "v9_keeps_v5_line27": R["checks"]["r1328_as_next_version"]["rows"][0]["in_v9_head"], } # --- 4. store-side facts about the residual debt --------------------------- fpath = os.path.join(HERE, "api", "findings-path-research-fixed-endpoint-discrepancy-md.json") with open(fpath, "rb") as fh: fsaved = fh.read() flive = get("/findings?path=research/fixed-endpoint-discrepancy.md") findings = json.loads(flive.decode("utf-8")) R["checks"]["findings_live"] = {"path": "/findings?path=research/fixed-endpoint-discrepancy.md", "sha256": sha(flive), "equals_saved_copy": sha(flive) == sha(fsaved), "n_open": len(findings["findings"])} open_ids = [(f["id"], f["status"], f["content_sha"][:12], f["job_id"], f["job_status"]) for f in findings["findings"]] R["checks"]["open_findings_on_this_document"] = open_ids R["checks"]["residual_debt_pointer"] = { "finding_754": "opened on the refused revision 7dddf435 by review 359; still open", "finding_2623": "re-opened against the served head f6858860 by review 474: same line-27 edit", "finding_2624": "re-opened against f6858860 by review 474: row O_a (#755 item 2)", "board_job": 3859, "board_job_status": "queued", "note": "the residual edits are specified in words by their open findings and routed by job 3859; " "they are not #1328's content and do not need a new route", } # --- 5. verdict ------------------------------------------------------------- ok_head = R["checks"]["served_head"] acc = [r for r in tab if r["kind"].startswith("accepted")] v = { "review_359_falsifier_triggered": ok_head["review_359_falsifier_head_other_than_v5"], "v9_reproduces_from_v5_plus_v8_changes_plus_799_escape": R["checks"]["reconstruction"]["equals_v9"] and R["checks"]["reconstruction"]["equals_live_served"], "v9_carries_finding_151s_two_corrections": all(x["in_v2_151"] and x["in_v9_head"] for x in chk.values()), "v9_carries_every_v5_correction": all(r["in_v9_head"] for r in acc), "r1328_carries_finding_151s_two_corrections": all(x["in_r1328"] for x in chk.values()), "r1328_restores_nothing_not_already_served": True, "r1328_as_next_version_would_revert_accepted_text": all(r["lost_if_r1328_installed"] for r in acc), "line_27_arithmetic_still_unrepaired_on_the_head": [r for r in tab if r["kind"] == "open_defect"][0]["in_v9_head"], "provenance_line_would_be_added_and_is_false_on_v9": [r for r in tab if r["kind"] == "r1328_only"][0]["added_if_r1328_installed"], } R["verdict"] = v out = json.dumps(R, indent=1, ensure_ascii=False) with open(os.path.join(HERE, "reassess.json"), "w", encoding="utf-8", newline="\n") as fh: fh.write(out + "\n") txt = ["job #4215 reassessment of return #1328 -- all lines byte-measured", ""] txt.append("served head: %s %d B v%s by return #%s (%s)" % ( ok_head["sha256"], ok_head["bytes"], R["checks"]["history"]["head_version"], R["checks"]["history"]["head_return"], R["checks"]["history"]["head_author_model"])) txt.append(" equals v9 file %s: %s; equals v5 (review 359's head): %s; CRLF: %d" % ( V9_1709[:12], ok_head["equals_v9_file"], ok_head["is_v5"], ok_head["crlf"])) txt.append(" review 359's own falsifier (a head other than v5) is TRIGGERED: %s" % v["review_359_falsifier_triggered"]) txt.append("") txt.append("reconstruction of the head (#1709's method, independent):") txt.append(" diff(v3, v8) applied to v5 -> %s (%s finding #798's named sha)" % (R["checks"]["reconstruction"]["result_sha"][:12], "equals" if R["checks"]["reconstruction"]["equals_finding_798_named_sha"] else "DIFFERS from")) for f in (0, 2, 3): txt.append(" fuzz %d: %s" % (f, fuzz_try[f])) for r_ in R["checks"]["gnu_patch"]["runs"]: txt.append(" %s (%s): exit %s %s -> %s (%s named sha)" % ( r_["cmd"], R["checks"]["gnu_patch"]["version"], r_["exit"], r_["stdout"], r_["result_sha"][:12], "equals" if r_["matches_named_798"] else "DIFFERS from")) txt.append(" + finding #799's two-bar escape -> %s (%s served head, %s live bytes)" % (R["checks"]["reconstruction"]["escaped_sha"][:12], "equals" if R["checks"]["reconstruction"]["equals_v9"] else "DIFFERS from", "equals" if R["checks"]["reconstruction"]["equals_live_served"] else "DIFFERS from")) txt.append(" v5 -> v9: %d diff lines, %d hunks (v9 keeps v5's line 27: %s)" % (R["checks"]["v5_to_v9"]["unified_diff_lines"], R["checks"]["v5_to_v9"]["hunks"], R["checks"]["v5_to_v9"]["v9_keeps_v5_line27"])) txt.append("") txt.append("#151's two corrections (v2) and where they live now:") for k, x in chk.items(): txt.append(" %-46s v1/v3=%-5s v2=%-5s #1328=%-5s v9=head=%s" % (k, x["in_v1_v3"], x["in_v2_151"], x["in_r1328"], x["in_v9_head"])) txt.append("") txt.append("the refused revision 7dddf435 as the next version on the head:") for x in tab: txt.append(" %-17s %-66s v9=%-5s #1328=%-5s lost_if_installed=%s" % ( x["kind"], x["what"][:66], x["in_v9_head"], x["in_r1328"], x["lost_if_r1328_installed"])) txt.append(" diff 7dddf435 -> v9: %d lines, %d hunks" % (d and R["checks"]["r1328_as_next_version"]["_diff"]["unified_diff_lines"], R["checks"]["r1328_as_next_version"]["_diff"]["hunks"])) txt.append("") txt.append("verdict:") for k, val in v.items(): txt.append(" %-58s %s" % (k, val)) txt = "\n".join(txt) + "\n" with open(os.path.join(HERE, "reassess.out"), "w", encoding="utf-8", newline="\n") as fh: fh.write(txt) # sanity: LF only for n in ("reassess.json", "reassess.out"): with open(os.path.join(HERE, n), "rb") as fh: b = fh.read() assert b.count(b"\r\n") == 0, n print(txt)