#!/usr/bin/env python3 """Job #3758's whole verification chain, re-runnable: does the requested hunk still apply, and is the served document still defective? Reads the six objects it checks from its own directory (they are the served bytes and the store objects, fetched by sha) and prints one check per line: C1 shas every object is the object its address names C2 one line base -> served and served -> revised each differ in exactly ONE line, the ledger verdict, and the line counts are equal C3 base + hunk the reviewer's own chain: applying the extracted hunk to the FINDING'S BASE gives byte-identical revised bytes (this is what "strict git apply on served d37c00fa gives ba4e7285" means) C4 served + hunk the same hunk against the CURRENTLY SERVED bytes: git apply --check must FAIL, and patch(1) --dry-run with it C5 not a subset every clause of the served ledger line is supported by the served body, with the body line that supports it; and the hunk's replacement text is a strict subset of the served line's substance (so hand-applying it would drop information) C6 registry the served index's row carries the HUNK's text, and a regeneration over the served corpus carries the SERVED document's text python check.py [--regenerated PATH] [--out check.out] Exit 0 iff every check passes. """ import argparse import difflib import hashlib import json import os import re import shutil import subprocess import sys import tempfile import urllib.request HERE = os.path.dirname(os.path.abspath(__file__)) SHA = { "base.txt": "d37c00fa21d3e5153942778d081000114af96302e7dd99fa5efab67996e42fc5", "revised.txt": "ba4e728554f46339f31f56792d3ad35080c0146e2694ac1841010d2d8026bcd8", "patch.txt": "b0f9df3245bf324287c4aaf20aff351722e38aedb159d2da9f224d598ef0e903", "served.md": "b6c8ec902bd5c51893411a48cf62cf74e20ab5a4a3954e2f1daf0c0bedad84ae", "questions-served.md": "d47cc818ba743a989de21c32f99fa948c530f9320d25426c57a0438e50424b29", } # the clauses of the SERVED verdict line, and what in the served body supports each CLAUSES = [ ("the exact-terms absence survives on both range conventions", ["absent from OEIS in both range conventions"]), ("the 20 DATA terms ... are cross-checked by two independent Miller-Rabin implementations", ["cross-checked by an independent Python", "BigInt Miller-Rabin, 40 fixed bases", "each verified prime-prime by two independent"]), ("ten further terms a(21)..a(30) left to the submitter", ["a(21)..a(30) are now computed and verified to the same standard", "it is left to the submitter"]), ("CROSSREFS now includes A367739 and A384545", ["**A367739**", "**A384545**"]), ("the LINKS entry is a path rather than a public URL", ['The LINKS entry "primeoire repository']), ("the publication moratorium is unresolved", ["under the publication\nmoratorium neither exists yet"]), ("No new OEIS absence search or submission is claimed", ["That blocks submission on its own"]), ] VERDICT = re.compile(r"^verdict: (.*)$", re.M) ROW = re.compile(r"^\| `Q-oeis-seam-submission` \|.*?\| (.*?) \| none \|", re.M) class Report: def __init__(self): self.checks = [] def check(self, name, ok, detail=""): self.checks.append((name, bool(ok), detail)) print("%-4s %-34s %s" % ("ok" if ok else "FAIL", name, detail if not ok else detail[:120])) return ok @property def failed(self): return [c for c in self.checks if not c[1]] def sha(path): with open(path, "rb") as fh: return hashlib.sha256(fh.read()).hexdigest() def ensure_objects(): """Fetch any object that is not beside this script, by its own address, from the public store. The store is content-addressed and public, so this needs no credential: a reader who has only this file and the served set can reproduce the whole check. """ got = [] for name, want in sorted(SHA.items()): path = os.path.join(HERE, name) if os.path.isfile(path) and sha(path) == want: continue url = "https://solveathome.org/files/" + want with urllib.request.urlopen(url, timeout=60) as r: blob = r.read() if hashlib.sha256(blob).hexdigest() != want: raise SystemExit("%s did not arrive as the object it was asked for" % url) with open(path, "wb") as fh: fh.write(blob) got.append(name) if got: print("(fetched by address: %s)\n" % ", ".join(got)) return got def run(cmd, cwd): p = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True) return p.returncode, (p.stdout or "") + (p.stderr or "") def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--regenerated", default=None, help="the regenerated index to compare the served row against") ap.add_argument("--out", default=None) a = ap.parse_args() sys.stdout.reconfigure(newline="\n", encoding="utf-8", errors="replace") r = Report() ensure_objects() print("C1 sha256 of every object") ok = True for name, want in sorted(SHA.items()): got = sha(os.path.join(HERE, name)) ok &= r.check("%s is %s..." % (name, want[:12]), got == want, got) if not ok: return 1 base = open(os.path.join(HERE, "base.txt"), encoding="utf-8").read() revised = open(os.path.join(HERE, "revised.txt"), encoding="utf-8").read() served = open(os.path.join(HERE, "served.md"), encoding="utf-8").read() print("\nC2 how the three texts differ") out = {} for label, (x, y) in {"base->served": (base, served), "served->revised": (served, revised), "base->revised": (base, revised)}.items(): dx = [l for l in difflib.unified_diff(x.splitlines(), y.splitlines(), n=0, lineterm="") if l.startswith(("+", "-")) and not l.startswith(("+++", "---"))] same_lines = len(x.splitlines()) == len(y.splitlines()) out[label] = dx r.check("%s is %d line(s)" % (label, len(dx) / 2), len(dx) == 2 and same_lines, "diff lines %d, equal line counts %s" % (len(dx), same_lines)) # the diff carries the file's line with a +/- prefix; the captured verdict is the text AFTER the # `verdict: ` label, so the two are compared as whole lines (the first wording of this check # compared a label-stripped string to a labelled line and failed for its own reason) vb = "verdict: " + VERDICT.search(base).group(1) vs = "verdict: " + VERDICT.search(served).group(1) vr = "verdict: " + VERDICT.search(revised).group(1) r.check("the single differing line is the ledger verdict", {d[1:] for d in out["base->served"]} == {vb, vs}, "not the verdict line") r.check("the hunk's replacement is the revised verdict", {d[1:] for d in out["served->revised"]} == {vs, vr}, "not the verdict line") print("\nC3 the reviewer's chain: base + hunk == revised") tmp = tempfile.mkdtemp(prefix="sah3758-") try: tree = os.path.join(tmp, "base") os.makedirs(os.path.join(tree, "research")) # a repo with autocrlf OFF, so the applied bytes are the patch's bytes and a CRLF conversion # cannot masquerade as a content difference (measured: it does, on this host, by default) run(["git", "init", "-q"], tree) run(["git", "config", "core.autocrlf", "false"], tree) shutil.copyfile(os.path.join(HERE, "base.txt"), os.path.join(tree, "research", "oeis-seam-submission.md")) code_check, text_check = run(["git", "apply", "--check", "-p1", os.path.join(HERE, "hunk-oeis-seam-submission.patch")], tree) r.check("git apply --check succeeds on the hunk's own base", code_check == 0, text_check[:200]) code_apply, text_apply = run(["git", "apply", "-p1", os.path.join(HERE, "hunk-oeis-seam-submission.patch")], tree) got = sha(os.path.join(tree, "research", "oeis-seam-submission.md")) r.check("applying it reproduces the revised bytes exactly", code_apply == 0 and got == SHA["revised.txt"], "sha %s; %s" % (got[:16], text_apply[:200])) print("\nC4 the same hunk against the CURRENTLY SERVED bytes") tree2 = os.path.join(tmp, "served") os.makedirs(os.path.join(tree2, "research")) shutil.copyfile(os.path.join(HERE, "served.md"), os.path.join(tree2, "research", "oeis-seam-submission.md")) # a repo, so the only possible failure is the patch itself and not "not a work tree" run(["git", "init", "-q"], tree2) run(["git", "config", "core.autocrlf", "false"], tree2) code2, text2 = run(["git", "apply", "--check", "-p1", os.path.join(HERE, "hunk-oeis-seam-submission.patch")], tree2) r.check("git apply --check FAILS on the served bytes", code2 != 0, "exit %d" % code2) print(" git: %s" % text2.strip().replace("\n", " | ")[:300]) code3, text3 = run(["patch", "--dry-run", "-p1", "-i", os.path.join(HERE, "hunk-oeis-seam-submission.patch")], tree2) r.check("patch --dry-run FAILS too (second implementation)", code3 != 0, "exit %d" % code3) print(" patch: %s" % text3.strip().replace("\n", " | ")[:300]) print("\nC5 was the served line already carrying the hunk's substance?") body_start = served.index("Status: DRAFT for review before submission") # the body is hard-wrapped, so a phrase that spans a line break must be searched for # whitespace-normalised (this is how the first run of this check produced a false FAIL) norm = re.sub(r"\s+", " ", served[body_start:]) body = norm for clause, supports in CLAUSES: missing = [s for s in supports if re.sub(r"\s+", " ", s) not in body] r.check("body supports: %s" % clause[:30], not missing, "absent: %s" % missing) # the hunk's replacement text, clause by clause, must be inside the served line's substance pairs = [("Status DRAFT", "Status DRAFT"), ("twenty DATA terms plus ten further", "the 20 DATA terms"), ("A367739 and A384545", "A367739 and A384545"), ("missing-neighbour objection is resolved", "missing-neighbour objection is resolved"), ("LINKS entry as a path rather than a public URL", "LINKS entry is a path rather than a public URL"), ("publication moratorium unresolved", "publication moratorium is unresolved"), ("No new OEIS absence search or submission is claimed", "No new OEIS absence search or submission is claimed")] absent = [want for want, _ in pairs if want.split()[0] not in vr or _ not in vs] r.check("every clause of the hunk's replacement is already in the served line", not absent, "not carried: %s" % absent) dropped = [s for s in ("both range conventions", "two independent Miller-Rabin implementations") if s in vs and s not in vr] r.check("the served line carries two clauses the hunk's replacement DROPS (hand-applying it " "would lose them)", len(dropped) == 2, "dropped-by-hunk: %s" % dropped) print("\nC6 the registry's own row") def verdict_cell(text): """The Q-oeis-seam-submission row's verdict cell: cell 4 of the table row.""" for line in text.splitlines(): if line.startswith("| `Q-oeis-seam-submission`"): return [c.strip() for c in line.split(" | ")][3] return None q = open(os.path.join(HERE, "questions-served.md"), encoding="utf-8").read() # the index's row carries the verdict TEXT, without the `verdict: ` label; the diff checks # above work on whole lines, so both forms are used and each is compared to its own vb_t, vs_t, vr_t = vb[len("verdict: "):], vs[len("verdict: "):], vr[len("verdict: "):] cell = verdict_cell(q) r.check("the served index carries the row", cell is not None, "row not found") def which(text): if text == vr_t: return "revised (the hunk's text)" if text == vs_t: return "served document" if text == vb_t: return "base (the finding's own text)" return "other" print(" served index row -> %s" % which(cell)) r.check("the served index row carries the HUNK's text, not the served document's", cell == vr_t, which(cell)) if a.regenerated: q2 = open(a.regenerated, encoding="utf-8").read() cell2 = verdict_cell(q2) r.check("a regeneration of the index carries the row", cell2 is not None, "row not found") print(" regenerated index row -> %s" % which(cell2)) r.check("regeneration moves the row to the SERVED document's text", cell2 == vs_t, which(cell2)) finally: shutil.rmtree(tmp, ignore_errors=True) summary = {"checks": len(r.checks), "passed": len(r.checks) - len(r.failed), "failed": len(r.failed), "ok": not r.failed, "failures": [c[0] for c in r.failed]} print("\n" + json.dumps(summary, indent=1)) if a.out: detail = "\n".join("%-4s %-34s %s" % ("ok" if ok_ else "FAIL", n, d) for n, ok_, d in r.checks if not ok_) or "(no failures)" with open(a.out, "w", encoding="utf-8", newline="\n") as fh: fh.write(detail + "\n" + json.dumps(summary, indent=1) + "\n") return 0 if not r.failed else 1 if __name__ == "__main__": sys.exit(main())