#!/usr/bin/env python3 """apply-check.py -- can the accepted text of the queue half be reconstructed from served bytes? `rebase-list.py` looked for the accepted text among a return's *uploaded artifacts*. It is not there: the patch lives in the return object itself, in the `patch` field (a unified diff), beside `revision_path`, `revision_sha`, `patch_hash` and `target`. This instrument reads that carrier and answers the question the rebase list actually needs: served base + the return's own `patch` == the accepted text ? by running `git apply --check` against the CURRENT served base, at the row's relative path, in a scratch directory. Three outcomes are distinguished, because they mean different things for a repair: applies the accepted text is reconstructible from served bytes alone (the list is sufficient) already_applied `git apply --reverse --check` succeeds: the served base IS the accepted text (the row is already integrated and current -- #1333's case, and a control on this instrument) refuses neither direction applies: the base moved, or the diff does not match this base Every row is reported with its own text; no row is dropped. Read-only on the project; the scratch directory is temporary. Falsifiers F2/F3 and the kind rule are pre-registered in `prereg-rebase-list.md`. """ import hashlib import json import os import shutil import subprocess import sys import tempfile 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__)) ENUM = ".solveathome/twin-primes/runs/bf5-8fb00a6176edcba2/scratch-records/r1373/fresh2744.json" PENDING = "pending integration" CONTROL_RETURN = 1333 # audit accepted 2026-09-22T22:58:59Z, patch_status "integrated" TRANSPORT_FAILED = 0 def get(path, token=None): 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: return r.status, r.read() except urllib.error.HTTPError as e: return e.code, e.read() except urllib.error.URLError as e: return TRANSPORT_FAILED, json.dumps({"error": str(e)}).encode() def kind_of(text): lines = text[:2000].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 try_apply(base_bytes, rel_path, patch_text): """(applies, already_applied, detail) against the served base in a scratch dir.""" tmp = tempfile.mkdtemp(prefix="sah-apply-") try: target = os.path.join(tmp, rel_path.replace("/", os.sep)) os.makedirs(os.path.dirname(target), exist_ok=True) with open(target, "wb") as fh: fh.write(base_bytes) pf = os.path.join(tmp, "_patch.diff") with open(pf, "w", encoding="utf-8", newline="\n") as fh: fh.write(patch_text) out = {} for name, args in (("forward", ["git", "apply", "-p1", "--check", pf]), ("reverse", ["git", "apply", "-p1", "--reverse", "--check", pf])): p = subprocess.run(args, cwd=tmp, capture_output=True, text=True) out[name] = {"rc": p.returncode, "stderr": (p.stderr or "").strip()[:200]} return (out["forward"]["rc"] == 0, out["reverse"]["rc"] == 0, out["forward"]["stderr"] or out["reverse"]["stderr"]) finally: shutil.rmtree(tmp, ignore_errors=True) def main(): enum_path = os.path.join(os.getcwd(), ENUM) 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() cache, out_rows = {}, [] for rid in returns + [CONTROL_RETURN]: code, body = get("/return/%d" % rid, tok) cache[rid] = (json.loads(body) if code == 200 else None) bodies = {} for r in rows: rid, path = r["return"], r["path"] rr = cache.get(rid) or {} patch = rr.get("patch") or "" rel = rr.get("revision_path") or rr.get("target") or path bcode, base = get("/docs/" + path, tok) if rel == path or "/" in path else (0, b"") base_sha = hashlib.sha256(base).hexdigest() if bcode == 200 else None rec = {"return": rid, "path": path, "via": r["via"], "type": r.get("type"), "revision_path": rr.get("revision_path"), "revision_sha": rr.get("revision_sha"), "patch_hash": rr.get("patch_hash"), "patch_kind": kind_of(patch) if patch else None, "patch_chars": len(patch), "return_status": rr.get("status"), "recorded_served_sha256": r.get("served_sha256"), "served_sha256_now": base_sha, "base_moved": (base_sha is not None and base_sha != r.get("served_sha256")), "target": rr.get("target"), "also_fix": rr.get("also_fix")} if bcode == 200 and patch and kind_of(patch) == "diff": applies, already, detail = try_apply(base, rel if rel == path else path, patch) rec.update({"applies": applies, "already_applied": already, "git_detail": detail, "reconstructible": bool(applies or already)}) key = (rid, path) bodies[key] = {"base_bytes": len(base), "patch_chars": len(patch)} else: rec.update({"applies": None, "already_applied": None, "git_detail": None, "reconstructible": None, "why_skipped": ("no patch text" if not patch else "not a diff per the pre-registered rule" if kind_of(patch) == "document" else "target is not a served corpus path (docs %s)" % bcode)}) out_rows.append(rec) # ---- control C4: #1333 is integrated and current, so its patch must NOT apply forward ---- ctrl = cache.get(CONTROL_RETURN) or {} cpatch = ctrl.get("patch") or "" crel = ctrl.get("revision_path") ccode, cbase = get("/docs/" + crel, tok) if crel else (0, b"") cap = cal = None if ccode == 200 and cpatch: cap, cal, cdetail = try_apply(cbase, crel, cpatch) else: cdetail = "unavailable" control = {"return": CONTROL_RETURN, "revision_path": crel, "patch_status": ctrl.get("patch_status"), "served_sha_matches_revision_sha": bool( crel and hashlib.sha256(cbase).hexdigest() == ctrl.get("revision_sha")), "applies_forward": cap, "already_applied_reverse": cal, "detail": cdetail, "C4_holds": (cap is False and cal is True)} res = { "job": "2829-continuation", "route": 114, "tool": "apply-check.py/1.0", "population": {"pending_rows": len(rows), "pending_returns": len(returns)}, "rows": out_rows, "control_C4": control, "n_reconstructible": sum(1 for r in out_rows if r["reconstructible"]), "n_applies_forward": sum(1 for r in out_rows if r["applies"]), "n_already_applied": sum(1 for r in out_rows if r["already_applied"]), "n_refuses": sum(1 for r in out_rows if r["applies"] is False and r["already_applied"] is False), "n_skipped": sum(1 for r in out_rows if r["reconstructible"] is None), "F2_bases_moved": [r["path"] for r in out_rows if r["base_moved"]], "F3_refusals": [{"return": r["return"], "path": r["path"], "detail": r["git_detail"]} for r in out_rows if r["applies"] is False and r["already_applied"] is False], "verdicts": { "P3_all_served_diffs_reconstructible": not any( r["applies"] is False and r["already_applied"] is False for r in out_rows), "C4_control_holds": control["C4_holds"], }, } json.dump(res, open(os.path.join(ROOT, "apply-check.json"), "w", encoding="utf-8", newline="\n"), indent=1, ensure_ascii=False, sort_keys=True) print(json.dumps({k: res[k] for k in ("population", "n_reconstructible", "n_applies_forward", "n_already_applied", "n_refuses", "n_skipped", "F2_bases_moved", "verdicts")}, indent=1, ensure_ascii=False)) print(json.dumps(control, indent=1, ensure_ascii=False)) for r in out_rows: print("%-4s %-52s kind=%-8s fwd=%-5s rev=%-5s rec=%-5s %s" % ( r["return"], r["path"][:52], r["patch_kind"], r["applies"], r["already_applied"], r["reconstructible"], (r.get("why_skipped") or "")[:40])) return 0 if __name__ == "__main__": sys.exit(main())