#!/usr/bin/env python3 """Route 140, step 3: for every constant that NAMES a document, resolve it against an independent record. Three independent records are available, in increasing strength: (i) the served corpus itself -- the digest of the named document as the store serves it; (ii) the store's object namespace -- GET /files/ returning bytes that hash to the constant, which is an anchor outside the script regardless of which file those bytes are; (iii) a named upstream artifact's own recorded digests (e.g. #1354's verdict-drift-live.json). A constant that resolves to none of the three is pinned to nothing a reader can obtain, which is the failure the route is counting. usage: resolve.py [--out dir] """ import argparse import hashlib import json import os import re import sys import urllib.error import urllib.request sys.stdout.reconfigure(encoding="utf-8", errors="replace") HERE = os.path.dirname(os.path.abspath(__file__)) RUN = os.path.dirname(HERE) CACHE = os.path.join(RUN, "job128", "cache") LIST = os.path.join(RUN, "job128", "docs-list.txt") SERVER = "https://solveathome.org" HEX = re.compile(r"\b([0-9a-f]{64})\b", re.I) PATHLIKE = re.compile(r"[\w./-]+\.(?:json|csv|txt|md|js|py|npy|tsv|zip|bin|dat|log)\b") def token(): p = (os.environ.get("SOLVEATHOME_TOKEN_FILE") or os.path.join(os.environ.get("LOCALAPPDATA", ""), "solveathome", "credentials", "twin-primes.token")) t = open(p, encoding="utf-8").read().strip() return t.split("=", 1)[1].strip() if "=" in t else t def sha(b): return hashlib.sha256(b).hexdigest() def cache_path(p): return os.path.join(CACHE, "_projects_twin-primes_docs_" + p.replace("/", "_") + ".txt") def main(): ap = argparse.ArgumentParser() ap.add_argument("--out", default=HERE) args = ap.parse_args() rows = json.load(open(os.path.join(HERE, "census4.json"), encoding="utf-8"))["rows"] docs = [l.strip() for l in open(LIST, encoding="utf-8") if l.strip()] # (i) every served document's digest, as the store serves it served = {} for p in docs: if os.path.exists(cache_path(p)): served.setdefault(sha(open(cache_path(p), "rb").read()), []).append(p) # what the corpus's own headers say, for the counter-test headers = {} out_headers = {} for p in docs: if not os.path.exists(cache_path(p)): continue text = open(cache_path(p), "rb").read().decode("utf-8", "replace") for m in re.finditer(r"code-sha256:\s*([0-9a-f]{64})", text, re.I): headers.setdefault(m.group(1).lower(), []).append(p) # an `out-sha256` constant's natural independent record is the SERVING document's own tail, which # is a different record from `code-sha256`: testing one against the other is the same wrong-record # mistake in a new place, so both are indexed and both are asked. for m in re.finditer(r"out-sha256:\s*([0-9a-f]{64})", text, re.I): out_headers.setdefault(m.group(1).lower(), []).append(p) tk = token() targets = [r for r in rows if r["role"] in ("declared_input", "compared_in_code")] report = [] for r in targets: c = r["sha256"] rec = {"file": r["file"], "line": r["line"], "sha256": c, "role": r["role"], "identifier": r["identifier"], "path_named": r["path_named"], "text": r["text"]} if r["path_named"]: cand = [p for p in docs if p.endswith(r["path_named"]) or p == r["path_named"]] rec["named_document_served_as"] = cand[:3] rec["named_document_matches_constant"] = any( os.path.exists(cache_path(p)) and sha(open(cache_path(p), "rb").read()) == c for p in cand) else: rec["named_document_served_as"] = [] rec["named_document_matches_constant"] = None rec["equals_a_served_document_digest"] = served.get(c, [])[:3] rec["equals_a_served_code_header"] = headers.get(c, [])[:3] rec["equals_a_served_out_header"] = out_headers.get(c, [])[:3] req = urllib.request.Request("%s/files/%s" % (SERVER, c)) req.add_header("Authorization", "Bearer " + tk) try: with urllib.request.urlopen(req, timeout=90) as f: b = f.read() rec["store_object"] = {"status": 200, "bytes": len(b), "roundtrip": sha(b) == c} rec["store_object_is_a_served_document"] = served.get(sha(b), [])[:3] except urllib.error.HTTPError as e: rec["store_object"] = {"status": e.code, "bytes": None, "roundtrip": False} except Exception as e: rec["store_object"] = {"status": 0, "error": str(e)[:80]} rec["traces_to"] = ("served corpus" if rec["equals_a_served_document_digest"] else "store object" if rec["store_object"].get("status") == 200 else "served code-sha256 header" if rec["equals_a_served_code_header"] else "served out-sha256 header" if rec["equals_a_served_out_header"] else "NOTHING OBTAINABLE") report.append(rec) summ = {} for rec in report: summ[rec["traces_to"]] = summ.get(rec["traces_to"], 0) + 1 out = {"summary": {"document_facing_occurrences": len(report), "traces_to": summ, "distinct": len({r["sha256"] for r in report})}, "resolved": report, "served_documents_indexed": len(served), "code_headers_indexed": len(headers), "out_headers_indexed": len(out_headers)} json.dump(out, open(os.path.join(args.out, "resolve.json"), "w", encoding="utf-8", newline="\n"), indent=1, ensure_ascii=False) print(json.dumps(out["summary"], indent=1)) for rec in report: print(" %-46s %-16s %-22s -> %s" % (rec["file"].split("/")[-1], rec["sha256"][:16], rec["role"], rec["traces_to"])) if rec["path_named"]: print(" names %-34s served=%s matches=%s" % (rec["path_named"], rec["named_document_served_as"][:1], rec["named_document_matches_constant"])) if rec["equals_a_served_code_header"]: print(" also the code-sha256 of: %s" % rec["equals_a_served_code_header"][:2]) if rec["equals_a_served_out_header"]: print(" also the out-sha256 of: %s" % rec["equals_a_served_out_header"][:2]) if rec["store_object"].get("status") == 200: print(" store object %d bytes, is-served-document=%s" % (rec["store_object"]["bytes"], rec["store_object_is_a_served_document"][:1])) return 0 if __name__ == "__main__": sys.exit(main())