#!/usr/bin/env python3 """patch-sha-probe3.py -- why do 13 of the 26 resolve by sha and 13 not? v2 (URL-corrected) found: sha256(patch text) resolves anonymously at the host root for 13 of the 26 pending-integration returns, and `patch_hash` (the address the return itself names) resolves for 0 of 26. Three questions follow, and this script answers all three: 1. CANONICALISATION. Are the other 13 merely hashed over a different normalisation? For each failure, sha256 over a small family of variants (LF, CRLF, CR, trailing-newline trimmed / appended, UTF-8 BOM, leading-blank stripped) and probe each. A hit names the store's canonical form; total 404 across the family says the text is genuinely absent. 2. FOOTING. For the 13 that DO resolve: anonymous or credential-only? (Anonymous puts the queue half on the same footing as the store half; credential-only does not.) 3. COVERAGE. Cross-tabulate resolvability against `git apply --check`'s verdict from apply-check.json: does "content-addressed" mean "reconstructible over the served base"? These are different properties and the repair needs the second. Read-only. """ import hashlib import json import os import sys import urllib.error import urllib.request ROOT_BASE = "https://solveathome.org" PROJ = ROOT_BASE + "/projects/twin-primes" TOK = os.path.join(os.environ.get("LOCALAPPDATA", ""), "solveathome", "credentials", "twin-primes.token") HERE = os.path.dirname(os.path.abspath(__file__)) ENUM = ".solveathome/twin-primes/runs/bf5-8fb00a6176edcba2/scratch-records/r1373/fresh2744.json" PENDING = "pending integration" def fetch(url, token=None): headers = {"Accept": "*/*", "User-Agent": "sahreq/1.0"} if token: headers["Authorization"] = "Bearer " + token try: with urllib.request.urlopen(urllib.request.Request(url, 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 0, json.dumps({"error": str(e)}).encode() def variants(text): """The normalisations a store might have canonicalised over. Name -> bytes.""" out = {"as_returned": text.encode("utf-8")} out["crlf"] = text.replace("\n", "\r\n").encode("utf-8") out["cr"] = text.replace("\n", "\r").encode("utf-8") body = text[:-1] if text.endswith("\n") else text out["no_final_nl"] = body.encode("utf-8") out["one_final_nl"] = (body + "\n").encode("utf-8") out["two_final_nl"] = (body + "\n\n").encode("utf-8") out["crlf_no_final_nl"] = body.replace("\n", "\r\n").encode("utf-8") out["bom"] = b"\xef\xbb\xbf" + text.encode("utf-8") out["strip_all"] = text.strip().encode("utf-8") out["strip_all_nl"] = (text.strip() + "\n").encode("utf-8") return out def main(): enum = json.load(open(os.path.join(os.getcwd(), ENUM), 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() apply_check = {} ac_path = os.path.join(HERE, "apply-check.json") if os.path.exists(ac_path): ac = json.load(open(ac_path, encoding="utf-8")) for r in (ac.get("rows") or []): apply_check[r.get("return")] = r.get("verdict") or r.get("outcome") out, n_resolved = [], 0 for rid in returns: code, body = fetch("%s/return/%d" % (PROJ, rid), tok) if code != 200: out.append({"return": rid, "in_band": False, "code": code}) continue patch = (json.loads(body).get("patch") or "") base = hashlib.sha256(patch.encode("utf-8")).hexdigest() rec = {"return": rid, "true_sha": base, "apply_check": apply_check.get(rid)} # the exact form first c, b = fetch("%s/files/%s" % (ROOT_BASE, base), None) cac, _ = fetch("%s/files/%s" % (ROOT_BASE, base), tok) rec["exact_anon"] = c rec["exact_auth"] = cac if c == 200 and hashlib.sha256(b).hexdigest() == base: rec["resolved_as"] = "as_returned" rec["anon"] = True n_resolved += 1 out.append(rec) continue # then the variant family hits = [] for name, blob in variants(patch).items(): if name == "as_returned": continue s = hashlib.sha256(blob).hexdigest() vc, vb = fetch("%s/files/%s" % (ROOT_BASE, s), None) if vc == 200 and hashlib.sha256(vb).hexdigest() == s: hits.append({"variant": name, "sha": s, "anon": True}) else: va, _ = fetch("%s/files/%s" % (ROOT_BASE, s), tok) if va == 200: hits.append({"variant": name, "sha": s, "anon": False}) rec["variant_hits"] = hits rec["resolved_as"] = hits[0]["variant"] if hits else None rec["anon"] = bool(hits and hits[0]["anon"]) if hits: n_resolved += 1 out.append(rec) def cross(pred): c = {} for r in out: key = (bool(r.get("resolved_as")), r.get("apply_check")) if pred(r): c[key] = c.get(key, 0) + 1 return {"%s/%s" % k: v for k, v in sorted(c.items(), key=lambda t: str(t[0]))} res = { "job": "2829-continuation", "route": 114, "tool": "patch-sha-probe3.py/1.0", "n_returns": len(returns), "n_resolved_by_sha": n_resolved, "n_resolved_as_returned": sum(1 for r in out if r.get("resolved_as") == "as_returned"), "n_resolved_by_variant": sum(1 for r in out if r.get("resolved_as") and r["resolved_as"] != "as_returned"), "variant_histogram": {v: sum(1 for r in out if r.get("resolved_as") == v) for v in sorted({r.get("resolved_as") for r in out if r.get("resolved_as")})}, "cross_resolvable_x_apply": cross(lambda r: True), "apply_check_verdicts": sorted({str(v) for v in apply_check.values()}), "rows": out, } dst = os.path.join(HERE, "patch-sha-probe3.json") json.dump(res, open(dst, "w", encoding="utf-8"), indent=1, sort_keys=True) print(json.dumps({k: v for k, v in res.items() if k != "rows"}, indent=1, sort_keys=True)) print("wrote", dst) if __name__ == "__main__": sys.exit(main())