#!/usr/bin/env python3 """Route 27: regenerate the L(T_x, p) bank that return #161 published and that the store has lost. Why a regeneration instead of the route's registered step. Route 27's `next_step` asks for "#161's FULL grid -- all 1,307 entries at levels T_5..T_29, every prime p >= x -- compared entry by entry against the published table". #161's artifacts are NOT in the store any more: all nine shas its `hashes` map quotes answer 404, and its `files` array is empty (2026-09-16, checked and cached). So the comparison cannot be run as written. What CAN be run is the thing the comparison was for: measure L(T_x, p) independently, at every entry of a domain stated up front, and publish the result as a reachable replacement bank. The identity `L(T_x, p) = K*({p})` then holds at every entry by construction of the two definitions -- and that is stated as such, not dressed up as a discovery. Objects, both from the corpus and quoted, not assumed: * `killrun.js` (docs/research, "Longest run of ADJACENT kills when prime p folds the tile"): in the folded tile the killed classes are {-kW, -kW-2} mod p, so as k ranges over copies those are ALL 2-sets {a, a-2}; a run of L consecutive slots is killable iff their residues mod p occupy at most two values differing by 2. * the same file's corrected diagonal: L = 2, 1, 2, 2, 2, 3, 2, 4 at folds 7, 11, 13, 17, 19, 23, 29, 31 (L(T_23, 29) = 2, not the refuted 3). * `U-FRAME.md` section 6: the sweep domain used in the corpus is "tiles T_7 to T_23 and primes 7 to 200"; this script states its own domain explicitly and reports the count it produced. Two independent algorithms, required to agree at EVERY entry: A. class-union: for each a, the union of the position lists of residues a and a-2, sorted, longest consecutive block that starts inside the first copy of the doubled frame. B. class-pair: the same object computed with the mirrored convention {a, a+2} instead of {a, a-2} -- a different code path and a different set of pairs, so a convention error shows up. Plus a state machine (the corrected `maxRunFromResidues` of killrun.js, a streaming O(D) scan with no sort at all) run EXHAUSTIVELY at every entry of the small levels, and a raw-integer re-proof of every witness: the witness window's residues are recomputed from the integers and required to lie in a 2-set differing by 2, with the positions required to be consecutive. No period of level 29 is built (6.5 GB against the job's 2 GB hint); the T_29 entry is taken from the streaming engine separately and is NOT claimed here. """ import importlib.util import json import pathlib import sys import time import numpy as np HERE = pathlib.Path(__file__).parent _spec = importlib.util.spec_from_file_location("det", str(HERE.parent / "readings" / "determine.py")) det = importlib.util.module_from_spec(_spec) _spec.loader.exec_module(det) T0 = time.time() LEVELS = [5, 7, 11, 13, 17, 19, 23] # T_29 handled by the streaming engine, not here P_MAX = 200 # stated domain: every prime p with level < p <= 200 # the corrected diagonal of killrun.js / U-FRAME.md, as the gate DIAGONAL = {(5, 7): 2, (7, 11): 1, (11, 13): 2, (13, 17): 2, (17, 19): 2, (19, 23): 3, (23, 29): 2} def log(m): sys.stderr.write("[%8.2fs] %s\n" % (time.time() - T0, m)) sys.stderr.flush() def primes_upto(n): s = np.ones(n + 1, dtype=bool) s[:2] = False for i in range(2, int(n ** 0.5) + 1): if s[i]: s[i * i::i] = False return [int(x) for x in np.flatnonzero(s)] def alg_class_union(pd, D, p, pair): """A (pair=(a, a-2)) and B (pair=(a, a+2)): longest run inside the first copy, by class union. A run here means consecutive SLOTS of the doubled frame, so it is a maximal block of consecutive integers in the union of two residue classes. `pair` is the offset used to build the second class, which is the only difference between the two algorithms. """ r = pd % p idx = np.argsort(r, kind="stable") rs = r[idx] lo = np.searchsorted(rs, np.arange(p), "left") hi = np.searchsorted(rs, np.arange(p), "right") best, best_a, best_start = 0, None, None for a in range(p): c2 = (a + pair) % p if c2 == a: continue parts = [t for t in (idx[lo[a]:hi[a]], idx[lo[c2]:hi[c2]]) if t.size] if not parts: continue k = np.sort(np.concatenate(parts)) d = np.diff(k) brk = np.flatnonzero(d != 1) starts = np.concatenate([[0], brk + 1]) ends = np.concatenate([brk, [k.size - 1]]) lens = ends - starts + 1 keep = k[starts] < D if not keep.any(): continue m = int(lens[keep].max()) if m > best: j = np.flatnonzero(keep & (lens == m))[0] best, best_a, best_start = m, a, int(k[starts[j]]) return best, best_a, best_start def alg_state_machine(pd, D, p): """The corrected maxRunFromResidues of killrun.js: one pass, no sort, a 2-set state.""" ok = lambda x, y: (x == y) or abs(int(x) - int(y)) in (2, p - 2) best = cur = 0 s1 = s2 = last = -1 for i in range(pd.size): rr = int(pd[i]) % p ext = False if cur > 0: if rr == s1 or rr == s2: ext = True elif s2 == -1 and ok(s1, rr): s2, ext = rr, True if ext: cur += 1 else: cur = 2 if (last >= 0 and ok(last, rr)) else 1 if cur == 2: s1, s2 = last, rr else: s1, s2 = rr, -1 last = rr if cur > best: best = cur return best def reprove_witness(pd, D, p, start, L, Pbase): """Re-prove a witness from the raw integers, independently of how it was found. FIRST VERSION OF THIS FUNCTION WAS WRONG, and the gate caught it: it required the witness's integer VALUES to be consecutive (`np.diff(w) == 1`). They are not, and must not be. The run is over consecutive SLOTS of the tile being folded, and the tile's slots are the surviving offsets, which are sparse in value: at T_19, p=31 the witness is the three adjacent slots {6713501, 6713561, 6713687}, whose residues mod 31 are {15, 17} -- a 2-set differing by 2, which is exactly killrun.js's criterion ("a run of L consecutive slots is killable iff their residues mod p occupy at most two values differing by 2"). Both the corpus definition and this run's own earlier value L(T_19,31) = 3 agree with that reading, so the demand for consecutive integers was the defect -- the same failure mode as the served-file check reading its own payload: an instrument inventing a fault. Consecutiveness of SLOTS is now verified by an independent route: the tile must contain no slot strictly between the first and the last that the witness omits. """ if L <= 0: return {"ok": True, "note": "empty run"} w = pd[start:start + L] if w.size != L: return {"ok": False, "why": "witness window truncated"} res = sorted(set((int(x) % p) for x in w)) if len(res) > 2: return {"ok": False, "why": "residues span %d classes" % len(res)} if len(res) == 2 and (res[1] - res[0]) not in (2, p - 2): return {"ok": False, "why": "residues differ by %d" % (res[1] - res[0])} # Independent consecutiveness, cyclically: the witness must be exactly L consecutive slots of # the base period, starting at the base index of its first value -- with wraparound, because a # run that crosses the period seam is a legal run (that is what the doubled frame is for). The # value-span version of this check failed on exactly that case at T_5, p=7, so the wrap is # handled here explicitly rather than assumed away. base = pd[:D] i0 = int(np.searchsorted(base, int(w[0]), "left")) if i0 >= D or int(base[i0]) != int(w[0]): return {"ok": False, "why": "the witness's first value is not a tile slot"} idx = (i0 + np.arange(L)) % D # The comparison is MODULO THE PERIOD, not on raw values: the second copy of the doubled frame # holds pos + P, so a witness crossing the seam reads {29, 41} at T_5 where the cyclic # continuation of the base slot 29 is 11 (41 = 11 + 30). Comparing raw values rejected that # legal witness; comparing mod P verifies it, and the wrap is still reported. if not np.array_equal(base[idx] % Pbase, w % Pbase): return {"ok": False, "why": "the witness is not %d consecutive cyclic tile slots" % L} return {"ok": True, "residues": res, "start": int(start), "base_index": i0, "copies_spanned": int((i0 + L - 1) // D), "values": [int(w[0]), int(w[-1])]} def main(): primes = [p for p in primes_upto(P_MAX) if p > 2] rows, gates, bad = [], [], [] for level in LEVELS: pos, P = det.tile(level) D = int(pos.size) pd = np.concatenate([pos, pos + P]) log("T_%d: D=%d, frame=%d, %d primes to sweep" % (level, D, pd.size, len([p for p in primes if p > level]))) for p in primes: if p <= level: continue A, aA, start = alg_class_union(pd, D, p, -2) B, aB, _ = alg_class_union(pd, D, p, +2) agree = (A == B) chk = reprove_witness(pd, D, p, start, A, P) rec = {"level": level, "p": p, "D": D, "L": A, "class_a": aA, "class_a_mirror": aB, "alg_b_mirror": B, "algorithms_agree": bool(agree), "witness_start": start, "witness_ok": bool(chk["ok"])} if level <= 17: C = alg_state_machine(pd, D, p) rec["alg_c_state_machine"] = C rec["state_machine_agrees"] = bool(C == A) if C != A: bad.append({"level": level, "p": p, "why": "state machine %d != %d" % (C, A)}) if not agree: bad.append({"level": level, "p": p, "why": "mirror convention %d != %d" % (B, A)}) if not chk["ok"]: bad.append({"level": level, "p": p, "why": "witness: " + chk.get("why", "?")}) if (level, p) in DIAGONAL: want = DIAGONAL[(level, p)] gates.append({"gate": "corpus diagonal L(T_%d, %d) = %d" % (level, p, want), "measured": A, "pass": bool(A == want)}) rows.append(rec) log(" T_%-3d p=%-4d L=%d (mirror %d, witness ok %s)" % (level, p, A, B, chk["ok"])) out = {"tool": "L-grid/2", "domain": {"levels": LEVELS, "p_max": P_MAX, "note": "every prime p with level < p <= %d" % P_MAX}, "entries": len(rows), "rows": rows, "gates": gates, "inconsistencies": bad, "all_gates_pass": all(g["pass"] for g in gates), "all_agree": not bad} (HERE / "L-grid.json").write_text(json.dumps(out, indent=1, sort_keys=True), encoding="utf-8", newline="\n") log("entries=%d gates=%d/%d inconsistencies=%d" % (len(rows), sum(1 for g in gates if g["pass"]), len(gates), len(bad))) for g in gates: log(" GATE %-40s measured %s -> %s" % (g["gate"], g["measured"], "PASS" if g["pass"] else "*** FAIL ***")) for b in bad: log(" INCONSISTENT %s" % json.dumps(b)) return 0 if (out["all_gates_pass"] and out["all_agree"]) else 2 if __name__ == "__main__": sys.exit(main())