#!/usr/bin/env python3 """Cycle 16 WILD — home re-judgement harness for C3 BAD-5 exhibits. FRESH-PROCESS, SECOND-PATH checker, independent of wild/cycle15_classify.py: this file does NOT import it (shared code would void the second path). The deciding machinery is the MULTIPLICATIVE subset-product path of CYCLE15_FINDINGS S4: given a prime p and a candidate BAD-5, form the minimal pattern's residues (forced residues F(p) + one residue g^e per candidate log e) and enumerate every sign vector in {-1,0,1}^{|F|+5} over those residues mod p, counting the products equal to -1 mod p, bucketed by the number of NR positions carrying a nonzero coefficient (the NR support). All arithmetic is exact integer arithmetic. Definitions (frozen in wild/CYCLE13_NOTES.md SS3.1-3.2 and wild/CYCLE15_BRIEF.md SS2, 5; used unchanged): p prime, p = 3 mod 4, p >= 7; g = smallest primitive root mod p; logs are base g in Z/(p-1); T = (p-1)/2; F(p) = {2 if p = 7 mod 8} + {3 if p = 2 mod 3} (forced residues, always QR, forced logs even); S = signed sums of the forced logs; an odd log e is 1-covered iff some signed sum of {e} plus an s in S hits T; U(p) = the odd logs that are not 1-covered; a residue is NR iff its log is odd. A BAD-5 is a 5-multiset of U-logs with (i) every entry in U(p), (ii) no 3-subset 3-covered, (iii) no signed sum of all 5 plus an s in S hitting T. Repeated logs are in scope: a repeated log stands for distinct NR primes sharing that residue class (CYCLE15_BRIEF S2.2). Checks (all exact; a candidate is CLEAN iff every check passes): (i) exactly 5 entries; each entry's log is odd (NR) and lies in U(p) as computed from S; cross-checked multiplicatively: no sign vector with NR-support exactly {that entry} has product -1 (support-1 hit == 1-coverage, by definition). (ii) no sign vector with NR-support of size exactly 3 has product -1 (== no 3-subset is 3-covered). (iii) no sign vector with NR-support of size exactly 5 has product -1 (== no signed 5-sum hits the target). (iv) the total count of sign vectors with product -1 is exactly 0 (the direct subset-product N_{-1} of the minimal pattern; supports 0, 2, 4 are reported too -- support 0 is mechanism (A), supports 2 and 4 are parity-impossible and must come out 0). Input representations (both handled, converted exactly): --logs "e1,e2,e3,e4,e5" logs base the smallest primitive root g mod p (the kernel's smallest_bad5 representation); --residues "r1,r2,r3,r4,r5" the five NR residues mod p, converted to logs via the discrete log table base g. Modes: single exhibit: --p P (--logs ... | --residues ...) validation: --validate (the frozen control suite: the 12 stored exhibits must judge CLEAN; the frozen negative controls must judge REJECTED with the named check; writes nothing itself -- the runner redirects/saves the JSON report) reconcile: --reconcile FILE [--undecided FILE] FILE is a kernel checkpoint (.jsonl, one record per line) or summary (.json with a "results" list); every record is accounted for as FAILS-with-clean-exhibit / counting-re-derived / exhaustive-exhibit-clean / NEVER-ZERO-flagged (needs full home enumeration; not asserted) / UNDECIDED / NOT ATTEMPTED. Exit code 0 iff the requested judgements come out as expected (single: CLEAN; validate: every control behaves; reconcile: no REJECTED exhibit and no unaccounted undecided prime when an undecided list is supplied). """ import itertools import json import sys import time PILOT = "/home/hatch/workspace/erdos-straus-pilot" # ---------------------------------------------------------------- # Shift data, derived from the frozen definitions in this file. # ---------------------------------------------------------------- def smallest_prim_root(p): phi = p - 1 facs = set() x = phi d = 2 while d * d <= x: if x % d == 0: facs.add(d) while x % d == 0: x //= d d += 1 if d == 2 else 2 if x > 1: facs.add(x) g = 2 while True: if all(pow(g, phi // q, p) != 1 for q in facs): return g g += 1 def dlog_table(p, g): tab = {} v = 1 for e in range(p - 1): tab[v] = e v = v * g % p return tab def forced_residues(p): F = [] if p % 8 == 7: F.append(2) if p % 3 == 2: F.append(3) return F def shift_sets(p): """Return (g, tab, F, S, U_set): S = signed sums of forced logs (subset of Z/(p-1)); U_set = odd logs not 1-covered.""" mod = p - 1 T = mod // 2 g = smallest_prim_root(p) tab = dlog_table(p, g) F = forced_residues(p) sums = {0} for q in F: f = tab[q] sums = {s + c * f for s in sums for c in (-1, 0, 1)} S = {s % mod for s in sums} covered = {(T - s) % mod for s in S} U_set = {e for e in range(1, mod, 2) if e not in covered} return g, tab, F, S, U_set # ---------------------------------------------------------------- # The multiplicative subset-product re-judgement. # ---------------------------------------------------------------- def subset_product_hits(p, F, nr_residues): """Enumerate all sign vectors over F + nr_residues; count the products equal to -1 mod p, bucketed by NR-support size, and the support-1 hits per NR position. Exact integers only.""" residues = list(F) + list(nr_residues) nf = len(F) hits_by_support = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0} hits_support1_at = [0, 0, 0, 0, 0] total = 0 for signs in itertools.product((-1, 0, 1), repeat=len(residues)): v = 1 support = 0 single_pos = -1 for j in range(len(residues)): c = signs[j] if c == 0: continue if c == 1: v = v * residues[j] % p else: v = v * pow(residues[j], -1, p) % p if j >= nf: support += 1 single_pos = j - nf if v == p - 1: total += 1 hits_by_support[support] += 1 if support == 1: hits_support1_at[single_pos] += 1 return total, hits_by_support, hits_support1_at def rejudge(p, logs): """Judge one candidate BAD-5 given as 5 logs base g. Returns a report dict: verdict CLEAN, or REJECTED with failed checks named from {(i), (ii), (iii), (iv)}.""" t0 = time.perf_counter_ns() g, tab, F, S, U_set = shift_sets(p) mod = p - 1 failed = [] detail = {} # ---- check (i), definitional part i_ok = True if len(logs) != 5: i_ok = False detail["entry_count"] = len(logs) for e in logs: if e < 0 or e >= mod: i_ok = False detail.setdefault("out_of_range_logs", []).append(e) elif e % 2 == 0: i_ok = False detail.setdefault("even_logs_not_NR", []).append(e) elif e not in U_set: i_ok = False detail.setdefault("logs_not_in_U", []).append(e) # ---- multiplicative subset-product path over the minimal # pattern (forced residues + the five NR residues) nr_residues = [pow(g, e, p) for e in logs] total, by_support, sup1_at = subset_product_hits(p, F, nr_residues) detail["subset_product_hits_total"] = total detail["subset_product_hits_by_NR_support"] = by_support detail["g"] = g detail["F"] = F detail["S_size"] = len(S) detail["u"] = len(U_set) detail["nr_residues"] = nr_residues # ---- check (i), multiplicative cross-check: a support-1 hit # at a position is exactly 1-coverage of that entry's log. for pos in range(5): if sup1_at[pos] != 0: i_ok = False detail.setdefault("support1_hit_positions", []).append(pos) if not i_ok: failed.append("(i) entry not a U(p) NR log") # ---- check (ii): no 3-subset 3-covered if by_support[3] != 0: failed.append("(ii) a 3-subset is 3-covered") # ---- check (iii): no signed 5-sum hits the target if by_support[5] != 0: failed.append("(iii) a signed 5-sum hits the target") # ---- check (iv): direct subset-product N_{-1} == 0 exactly if total != 0: failed.append("(iv) subset-product N_{-1} != 0") elapsed_ms = (time.perf_counter_ns() - t0) // 1_000_000 return { "p": p, "logs": list(logs), "verdict": "CLEAN" if not failed else "REJECTED", "failed_checks": failed, "detail": detail, "elapsed_ms": int(elapsed_ms), } def logs_from_residues(p, residues): g = smallest_prim_root(p) tab = dlog_table(p, g) logs = [] for r in residues: if r not in tab: raise ValueError("residue %d not in (Z/%d)*" % (r, p)) logs.append(tab[r]) return logs # ---------------------------------------------------------------- # Frozen validation suite (controls selected against stored data; # every expectation below is fixed before the scored run). # ---------------------------------------------------------------- def load_stored_exhibits(): with open(PILOT + "/results/wild_cycle15_classify.json") as fh: classify = json.load(fh) by_p = {} for row in classify["shifts"]: by_p[row["p"]] = row positives = [] for p in (19, 31, 43, 47, 59, 67, 71, 79, 83, 103): positives.append((p, by_p[p]["smallest_bad5"], "classify")) with open(PILOT + "/results/wild_cycle15_smoke.json") as fh: smoke = json.load(fh) for rec in smoke["smoke_decided"]: positives.append((rec["p"], rec["smallest_bad5"], "smoke")) return positives # Negative controls: (p, logs, the check that must name the failure, # why this multiset is independently known not to be a BAD-5). NEGATIVE_CONTROLS = [ # One entry of p=19's exhibit replaced by the 1-covered log 9 # (at p=19, F is empty, S = {0}, T = 9, so 9 is 1-covered and # not in U(19) = {1,3,5,7,11,13,15,17}): fails (i) by the # definition of U. (19, [9, 1, 1, 1, 1], "(i)"), # One entry of p=19's exhibit replaced by the even log 2: an # even log is a QR class, not an NR log at all: fails (i). (19, [2, 1, 1, 1, 1], "(i)"), # p=31's exhibit (1,1,1,1,1) with one entry moved 1 -> 7: # single-entry perturbation; its support-3 subset-product # bucket is nonzero, so it must be REJECTED with (ii) named. # (Control selection note: the neighbouring perturbation # 1 -> 3 at p=31 is itself a genuine BAD-5 -- p=31 has 32 -- # and was rejected as a control for exactly that reason.) (31, [1, 1, 1, 1, 7], "(ii)"), # p=31's exhibit with one entry moved 1 -> 5: single-entry # perturbation whose only nonzero buckets are support 5, so # it must be REJECTED with (iii) named and (ii) NOT named -- # it isolates the 5-sum check. (31, [1, 1, 1, 1, 5], "(iii)"), # A 5-multiset at p=11, where BAD-5 = 0 was exhaustively # proved in Cycle 15 (all 6 candidates checked): any # 5-multiset of U(11) = {1,9} is a known non-BAD multiset. (11, [1, 1, 1, 1, 1], None), # A second p=11 known non-BAD multiset (same exhaustive proof). (11, [1, 9, 9, 9, 9], None), ] def run_validation(): report = {"positives": [], "negatives": [], "residue_form": None, "all_behaved": True} for p, logs, src in load_stored_exhibits(): r = rejudge(p, logs) r["source"] = src report["positives"].append(r) if r["verdict"] != "CLEAN": report["all_behaved"] = False # Residue-form input: p=47's exhibit, given as residues, must # convert exactly and judge CLEAN. p47_logs = None for p, logs, src in load_stored_exhibits(): if p == 47: p47_logs = logs g47 = smallest_prim_root(47) residues47 = [pow(g47, e, 47) for e in p47_logs] back = logs_from_residues(47, residues47) r = rejudge(47, back) report["residue_form"] = { "p": 47, "residues": residues47, "logs_recovered": back, "logs_expected": p47_logs, "verdict": r["verdict"], "elapsed_ms": r["elapsed_ms"], } if back != list(p47_logs) or r["verdict"] != "CLEAN": report["all_behaved"] = False for p, logs, want in NEGATIVE_CONTROLS: r = rejudge(p, logs) named_ok = True if want is not None: named_ok = any(f.startswith(want) for f in r["failed_checks"]) ok = (r["verdict"] == "REJECTED") and named_ok r["expected_check"] = want r["control_behaved"] = ok report["negatives"].append(r) if not ok: report["all_behaved"] = False report["summary"] = { "positives_clean": sum(1 for r in report["positives"] if r["verdict"] == "CLEAN"), "positives_total": len(report["positives"]), "negatives_rejected": sum(1 for r in report["negatives"] if r["verdict"] == "REJECTED"), "negatives_total": len(report["negatives"]), "max_elapsed_ms": max( [r["elapsed_ms"] for r in report["positives"]] + [r["elapsed_ms"] for r in report["negatives"]] + [report["residue_form"]["elapsed_ms"]]), } return report # ---------------------------------------------------------------- # Reconciliation of a returned kernel output. # ---------------------------------------------------------------- def counting_rederived(p, rec): """Re-derive a counting-tier FAILS at home: recompute (u, |S|) from the definitions and check the frozen inequality Cand(u) > 2|S|u^3(u+1) + 16|S|u^4 with actual values.""" g, tab, F, S, U_set = shift_sets(p) u = len(U_set) from math import comb cand5 = comb(u + 4, 5) if u else 0 excl = 2 * len(S) * u ** 3 * (u + 1) + 16 * len(S) * u ** 4 if u else 0 ok = (rec["u"] == u and rec["S_size"] == len(S) and cand5 > excl and rec["verdict"] == "FAILS") return {"p": p, "accounted": "counting-re-derived" if ok else "counting-MISMATCH", "u_home": u, "S_size_home": len(S), "cand5_home": cand5, "excl_home": excl} def reconcile(path, undecided_path): records = [] if path.endswith(".jsonl"): with open(path) as fh: for line in fh: line = line.strip() if line: records.append(json.loads(line)) else: with open(path) as fh: doc = json.load(fh) if "results" in doc: records = doc["results"] elif "smoke_decided" in doc: records = doc["smoke_decided"] else: raise ValueError("unrecognised kernel-output JSON shape") accounted = [] bad = False seen = set() for rec in records: p = rec["p"] seen.add(p) verdict = rec["verdict"] route = rec["route"] if verdict == "FAILS" and route == "search-exhibit": logs = rec["smallest_bad5"] if "residues" in rec and logs is None: logs = logs_from_residues(p, rec["residues"]) r = rejudge(p, logs) accounted.append({"p": p, "accounted": "FAILS-with-clean-exhibit" if r["verdict"] == "CLEAN" else "FAILS-exhibit-REJECTED", "rejudge": r["verdict"], "failed_checks": r["failed_checks"]}) if r["verdict"] != "CLEAN": bad = True elif verdict == "FAILS" and route == "counting": a = counting_rederived(p, rec) accounted.append(a) if a["accounted"] != "counting-re-derived": bad = True elif verdict == "FAILS" and route == "exhaustive": if rec["smallest_bad5"] is not None: r = rejudge(p, rec["smallest_bad5"]) accounted.append({"p": p, "accounted": "exhaustive-exhibit-clean" if r["verdict"] == "CLEAN" else "exhaustive-exhibit-REJECTED", "rejudge": r["verdict"]}) if r["verdict"] != "CLEAN": bad = True else: accounted.append({"p": p, "accounted": "exhaustive-no-exhibit-flagged"}) elif verdict == "C3 NEVER-ZERO": accounted.append({"p": p, "accounted": "NEVER-ZERO-flagged-needs-home-enumeration"}) bad = True elif verdict == "UNDECIDED": accounted.append({"p": p, "accounted": "still UNDECIDED"}) else: accounted.append({"p": p, "accounted": "UNRECOGNISED-RECORD", "record": rec}) bad = True out = {"records_seen": len(records), "accounted": accounted} if undecided_path is not None: with open(undecided_path) as fh: und = json.load(fh) want = set(und["undecided_band_primes"]) missing = sorted(want - seen) extra = sorted(seen - want) out["undecided_reconciliation"] = { "expected": len(want), "seen": len(seen & want), "missing_primes": missing, "extra_primes": extra} if missing: bad = True out["reconcile_ok"] = not bad return out # ---------------------------------------------------------------- def main(argv): if "--validate" in argv: report = run_validation() print(json.dumps(report, indent=1, sort_keys=True)) return 0 if report["all_behaved"] else 1 if "--reconcile" in argv: path = argv[argv.index("--reconcile") + 1] und = None if "--undecided" in argv: und = argv[argv.index("--undecided") + 1] out = reconcile(path, und) print(json.dumps(out, indent=1, sort_keys=True)) return 0 if out["reconcile_ok"] else 1 p = None logs = None for i, a in enumerate(argv): if a == "--p": p = int(argv[i + 1]) elif a == "--logs": logs = [int(x) for x in argv[i + 1].split(",")] elif a == "--residues": residues = [int(x) for x in argv[i + 1].split(",")] logs = ("RESIDUES", residues) if p is None or logs is None: print("usage: --p P (--logs e1,..,e5 | --residues r1,..,r5)" " | --validate | --reconcile FILE [--undecided FILE]", file=sys.stderr) return 2 if isinstance(logs, tuple): logs = logs_from_residues(p, logs[1]) r = rejudge(p, logs) print(json.dumps(r, indent=1, sort_keys=True)) return 0 if r["verdict"] == "CLEAN" else 1 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))