#!/usr/bin/env python3 """patch-sha-probe2.py v2 -- is the accepted text of the queue half retrievable BY ITS SHA? THE BUG THIS VERSION FIXES (found by demanding a positive control): v1 of this probe prefixed /files with BASE = ".../projects/twin-primes", so every /files/ answered 404 -- INCLUDING the shas of versions known to be served. A 404 that arrives for a known-present object is not a fact about the data, it is a fact about the URL. The server's own version records put `content_url` = "/files/" and `diff_url` = "/projects/twin-primes/history/...", i.e. LISTS live under the project, but the CONTENT ADDRESS lives at the host root: https://solveathome.org/files/. So each sha is probed under both prefixes, anonymous and credentialed, and the run is only believed if the positive control passes (a known stored version's content_sha must answer 200 and hash back). Carriers, per return of the 26 pending-integration rows of route 114: in-band GET /projects/twin-primes/return/ -> the `patch` field by sha GET /files/ -> the address the return NAMES by sha GET /files/ -> the address of the actual text as version any served /history record naming either sha (1211-path walk cached in hist/) 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 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(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 0, json.dumps({"error": str(e)}).encode() def sha_of(b): return hashlib.sha256(b).hexdigest() def probe_sha(sha, tok): """Every URL form for one content address, anonymous and credentialed.""" out = {} for label, pref in (("root", ROOT_BASE), ("proj", PROJ)): for auth, t in (("anon", None), ("auth", tok)): c, b = get("%s/files/%s" % (pref, sha), t) out["%s_%s" % (label, auth)] = c if c == 200 and sha_of(b) == sha: out["resolved_by"] = "%s_%s" % (label, auth) 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() # the served version records (1211 paths, one JSON per path) hist = os.path.join(HERE, "hist") version_shas, cands = set(), [] for fn in sorted(os.listdir(hist)): if not fn.endswith(".json"): continue j = json.load(open(os.path.join(hist, fn), encoding="utf-8")) for v in (j.get("versions") or []): if not isinstance(v, dict) or not v.get("content_sha"): continue version_shas.add(v["content_sha"]) cands.append((j.get("path"), v.get("version"), v.get("return_id"), v["content_sha"])) out = [] for rid in returns: code, body = get("%s/return/%d" % (PROJ, rid), tok) if code != 200: out.append({"return": rid, "in_band": False, "code": code}) continue rr = json.loads(body) patch = rr.get("patch") or "" true_sha = sha_of(patch.encode("utf-8")) ph = rr.get("patch_hash") rec = {"return": rid, "patch_chars": len(patch), "patch_hash": ph, "patch_hash_equals_sha256_of_text": ph == true_sha, "true_content_sha": true_sha, "true_sha_in_served_versions": true_sha in version_shas, "patch_hash_in_served_versions": bool(ph and ph in version_shas)} rec["probe_named"] = probe_sha(ph, tok) if ph else {} rec["probe_true"] = probe_sha(true_sha, tok) out.append(rec) # POSITIVE CONTROL, and this run is void if it fails: known stored versions must resolve. controls = [] cands.sort(key=lambda t: (t[2] is None, t[0] or "")) for path, ver, rid, sha in cands[:5]: p = probe_sha(sha, tok) controls.append({"path": path, "version": ver, "return_id": rid, "resolved_by": p.get("resolved_by"), "probe": p}) n_ok = sum(1 for c in controls if c["resolved_by"]) res = { "job": "2829-continuation", "route": 114, "tool": "patch-sha-probe2.py/2.0", "url_fix": "content address lives at the host root, not under /projects/twin-primes", "control_pass": n_ok, "control_total": len(controls), "controls": controls, "returns": returns, "n_returns": len(returns), "walk_paths_scanned": len([f for f in os.listdir(hist) if f.endswith(".json")]), "version_shas_scanned": len(version_shas), "n_in_band": sum(1 for r in out if r.get("patch_chars")), "n_patch_hash_equals_true_sha": sum(1 for r in out if r.get("patch_hash_equals_sha256_of_text")), "n_named_sha_resolvable": sum(1 for r in out if (r.get("probe_named") or {}).get("resolved_by")), "n_true_sha_resolvable": sum(1 for r in out if r["probe_true"].get("resolved_by")), "n_true_sha_in_served_versions": sum(1 for r in out if r.get("true_sha_in_served_versions")), "n_patch_hash_in_served_versions": sum(1 for r in out if r.get("patch_hash_in_served_versions")), "rows": out, } dst = os.path.join(HERE, "patch-sha-probe2.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 not in ("rows", "controls")}, indent=1, sort_keys=True)) print("CONTROL:", json.dumps(controls, indent=1)[:900]) print("wrote", dst) if __name__ == "__main__": sys.exit(main())