/* * parfold.mjs — the streaming fold of streamfold.mjs, parallelised across worker threads. * * The instrument is unchanged: the certificate at a fold p -> q is a maximum over windows of the * OLD word's gap stream, where each interior step must land on the qualifying residues 0, +-2 * (mod q); the local alternation test then says whether the argmax window is realizable. What is * new is only the traversal. T_37 has 217,929,355,875 gaps and is never stored: the word is emitted * in sorted order x = k3*W2 + k2*W1 + k1*W0 + s, ordered lexicographically by (k3, k2, k1, s), and a * ring of the last 512 gaps evaluates every window as its last gap arrives. * * Parallel decomposition. The task index is t = k3*l2 + k2, so consecutive task indices are * consecutive in the word's order. A worker owns a contiguous range of tasks and primes its ring by * re-emitting the last CAP+2 gaps of the task before its range, so windows spanning a boundary are * evaluated by the worker that owns their last gap. The last worker owns the wrap: it pushes the * closing gap (x_0 + W_q - x_last) and replays the first CAP+3 gaps, exactly the single-threaded * seam. Memory per worker is O(CAP) plus the previous tile's slot array, shared as one copy. * * Gates: the fold 11 -> 13 -> 17 -> 19 certified at 23 (small; exercises every boundary of the * parallel path), and the fold 23 -> 29 -> 31 -> 37 certified at 41 (D = 217929355875 = A059861, * max gap = 528 = the record's twelfth ladder term, certificate 546 = G2(41#)). * * Deterministic: the worker count changes the traversal only, never the report. stdout is the * artifact; progress and timing go to stderr. `probe` runs a fixed number of tasks per worker and * prints a rate instead of a verdict. */ import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads'; import fs from 'node:fs'; const P = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43]; const prim = (p) => P.filter((r) => r <= p).reduce((a, r) => a * r, 1); const CAP = 128; const MASK = 511; const HEADC = CAP + 3; // 131 head gaps, as in streamfold.mjs const PREFILL = CAP + 2; // 130 gaps of context before a worker's range const QMAX = 65536; function slotsSmall(p) { const W = prim(p), rs = P.filter((r) => r <= p); const cop = new Uint8Array(W).fill(1); for (const r of rs) for (let x = r; x < W; x += r) cop[x] = 0; cop[0] = 0; const out = new Uint32Array(W); let n = 0; for (let x = 1; x < W; x++) if (cop[x] && cop[(x + 2) % W]) out[n++] = x; return out.subarray(0, n).slice(); } function foldSpec(p0, levels) { const [l1, l2, l3] = levels; const W0 = prim(p0), W1 = W0 * l1, W2 = W1 * l2, W3 = W2 * l3; return { l1, l2, l3, W0, W1, W2, W3, nTasks: l2 * l3 }; } class Certifier { constructor(qCert) { this.q = qCert; this.buf = new Int32Array(MASK + 1); this.pos = 0; this.D = 0; this.maxg = 0; this.M = 0; this.hits = 0; this.arg = []; this.lAtCap = 0; this.head = new Int32Array(HEADC); this.headN = 0; this.qualTab = new Uint8Array(QMAX); for (let g = 0; g < QMAX; g++) { const r = g % qCert; this.qualTab[g] = (r === 0 || r === 2 || r === qCert - 2) ? 1 : 0; } } qual(x) { const r = x % this.q; return r === 0 || r === 2 || r === this.q - 2; } qualifies(g) { return g >= 0 && g < QMAX ? this.qualTab[g] === 1 : this.qual(g); } consider(i, L, s, seam) { if (L >= CAP) this.lAtCap++; if (s > this.M) { this.M = s; this.hits = 0; this.arg = []; } if (s === this.M) { this.hits++; if (this.arg.length < 8) { const gs = new Int32Array(L + 1); for (let j = L; j >= 0; j--) gs[L - j] = this.buf[(this.pos - 1 - j + MASK + 1) & MASK]; this.arg.push({ i, L, gs: Array.from(gs), seam }); } } } scan(i, seam) { const buf = this.buf, qt = this.qualTab, q = this.q; const p = this.pos; let s = buf[(p - 2 + MASK + 1) & MASK] + buf[(p - 1) & MASK]; if (seam ? 1 > i : 1 <= i) this.consider(i, 1, s, seam); for (let L = 2; L <= CAP; L++) { const g = buf[(p - 1 - (L - 1) + MASK + 1) & MASK]; if (g >= 0 && g < QMAX ? qt[g] === 0 : !this.qual(g)) break; s += buf[(p - 1 - L + MASK + 1) & MASK]; if (seam ? L > i : L <= i) this.consider(i, L, s, seam); } } push(g, count = true) { const i = this.D; this.buf[this.pos++ & MASK] = g; if (!count) return; this.D++; if (g > this.maxg) this.maxg = g; if (this.headN < HEADC) this.head[this.headN++] = g; this.scan(i, false); } nu(gs) { const G = []; let s = 0; for (const v of gs) { s += v; G.push(s); } const L = gs.length - 1; let c = 0; for (let a = 0; a < this.q; a++) { if (a === 0 || a === 2) continue; if (a === G[L] % this.q || a === (G[L] + 2) % this.q) continue; let ok = true; for (let j = 0; j < L; j++) { const rr = G[j] % this.q; if (rr !== a && rr !== (a - 2 + this.q) % this.q) { ok = false; break; } } if (ok) c++; } return c; } } function runWorker({ p0, levels, q, t0, t1, wid, nW, slots }) { const spec = foldSpec(p0, levels); const { l1, l2, l3, W0, W1, W2, W3, nTasks } = spec; const n = slots.length; const rm = new Uint32Array(n); // packed: s%l1 | s%l2<<8 | s%l3<<16 for (let i = 0; i < n; i++) { const s = slots[i]; rm[i] = (s % l1) | ((s % l2) << 8) | ((s % l3) << 16); } const W0m1 = W0 % l1, W0m2 = W0 % l2, W0m3 = W0 % l3; const W1m2 = W1 % l2, W1m3 = W1 % l3, W2m3 = W2 % l3; const f1 = l1 - 2, f2 = l2 - 2, f3 = l3 - 2; const c = new Certifier(q); let prev = -1, cx = 0, mode = 0, firstVal = -1; const emit = (x) => { // one closure, so V8 can inline the call if (mode === 1) { if (firstVal < 0) firstVal = x; return; } if (prev >= 0) c.push(x - prev, true); prev = x; cx++; }; const sweep = (A, B) => { const b2 = (B * W1m2) % l2, b3 = (A * W2m3 + B * W1m3) % l3; const X = A * W2 + B * W1; for (let k1 = 0; k1 < l1; k1++) { const base1 = (k1 * W0m1) % l1; const base2 = (b2 + k1 * W0m2) % l2; const base3 = (b3 + k1 * W0m3) % l3; const xb = X + k1 * W0; for (let i = 0; i < n; i++) { const pk = rm[i]; let m = base1 + (pk & 255); if (m >= l1) m -= l1; if (m === 0 || m === f1) continue; m = base2 + ((pk >>> 8) & 255); if (m >= l2) m -= l2; if (m === 0 || m === f2) continue; m = base3 + ((pk >>> 16) & 255); if (m >= l3) m -= l3; if (m === 0 || m === f3) continue; emit(xb + slots[i]); } } }; // Prime the ring with the previous task's own tail x's. Only the last k1 slice can supply them, // and one slice holds ~6.5M survivors, so this stops after a few hundred i steps -- never a sweep. const tailOf = (A, B, need) => { const b2 = (B * W1m2) % l2, b3 = (A * W2m3 + B * W1m3) % l3, X = A * W2 + B * W1; const out = []; for (let k1 = l1 - 1; k1 >= 0 && out.length < need; k1--) { // walk slices downward const base1 = (k1 * W0m1) % l1, base2 = (b2 + k1 * W0m2) % l2, base3 = (b3 + k1 * W0m3) % l3; const xb = X + k1 * W0; for (let i = n - 1; i >= 0 && out.length < need; i--) { const pk = rm[i]; let m = base1 + (pk & 255); if (m >= l1) m -= l1; if (m === 0 || m === f1) continue; m = base2 + ((pk >>> 8) & 255); if (m >= l2) m -= l2; if (m === 0 || m === f2) continue; m = base3 + ((pk >>> 16) & 255); if (m >= l3) m -= l3; if (m === 0 || m === f3) continue; out.push(xb + slots[i]); } } out.reverse(); return out; }; if (t0 > 0) { // prime the ring with the previous task's tail const t = t0 - 1; const tail = tailOf(Math.floor(t / l2), t % l2, PREFILL + 1); for (const x of tail) { if (prev >= 0) c.push(x - prev, false); prev = x; } process.stderr.write(` w${wid} prefill ${tail.length} gaps from task ${t}\n`); } const tStart = Date.now(); const prog = `progress-w${wid}.txt`; // per-worker, so a stall is visible without stderr let lastLog = tStart, lastCx = 0; fs.writeFileSync(prog, `w${wid} range [${t0},${t1}) of ${nTasks}, started ${new Date(tStart).toISOString()}\n`); for (let t = t0; t < t1; t++) { sweep(Math.floor(t / l2), t % l2); const now = Date.now(); if (now - lastLog > 20000 || t === t1 - 1) { // every 20 s of wall clock, per worker fs.appendFileSync(prog, `task ${t - t0 + 1}/${t1 - t0} cx=${cx} elapsed=${((now - tStart) / 1000).toFixed(1)}s since_last=${((cx - lastCx) / ((now - lastLog) / 1000) / 1e6).toFixed(1)}M/s\n`); lastLog = now; lastCx = cx; } } let wrapped = false; if (t1 === nTasks) { // the wrap, and the seam, belong to the last worker mode = 1; sweep(0, 0); mode = 0; const f = firstVal; c.push(f + W3 - prev, true); wrapped = true; for (let j = 0; j < c.headN; j++) { c.push(c.head[j], false); c.scan(j, true); } process.stderr.write(` w${wid} wrap gap ${f + W3 - prev} pushed, seam replayed over ${c.headN} head gaps\n`); } return { wid, D: c.D, cx, maxg: c.maxg, M: c.M, hits: c.hits, arg: c.arg, wrapped, lAtCap: c.lAtCap }; } if (!isMainThread) { parentPort.postMessage(runWorker(workerData)); } else { const mode = process.argv[2] ?? 'validate'; const nW = Number(process.argv[3] ?? 4); const limit = Number(process.argv[4] ?? 0); // probe: tasks per worker const cfg = mode === 'validate' ? { p0: 11, levels: [13, 17, 19], q: 23, label: 'fold 11# -> 13# -> 17# -> 19# (old word T_19), certifying at 23' } : { p0: 23, levels: [29, 31, 37], q: 41, label: 'fold 23# -> 29# -> 31# -> 37# (old word T_37), certifying at 41' }; const spec = foldSpec(cfg.p0, cfg.levels); console.log(`# parfold.mjs mode=${mode}, workers=${nW}, CAP=${CAP}, levels=${cfg.levels.join(',')} from T_${cfg.p0}${limit ? `, probe limit ${limit} tasks/worker` : ''}`); console.log(''); const t0 = Date.now(); const slots = slotsSmall(cfg.p0); process.stderr.write(`slots T_${cfg.p0}: ${slots.length} (${(slots.length * 4 / 1e6).toFixed(0)} MB)\n`); const bounds = []; for (let w = 0; w < nW; w++) { const a = Math.floor((w * spec.nTasks) / nW), b = Math.floor(((w + 1) * spec.nTasks) / nW); bounds.push([a, limit ? Math.min(b, a + limit) : b]); } const partial = limit > 0 && bounds.some(([, b]) => b < spec.nTasks); const parts = await Promise.all(bounds.map(([a, b], w) => new Promise((res, rej) => { const wk = new Worker(new URL(import.meta.url), { workerData: { ...cfg, t0: a, t1: b, wid: w, nW, slots } }); wk.on('message', res); wk.on('error', rej); }))); const D = parts.reduce((a, p) => a + p.D, 0); const cx = parts.reduce((a, p) => a + p.cx, 0); const maxg = Math.max(...parts.map((p) => p.maxg)); const M = Math.max(...parts.map((p) => p.M)); const hits = parts.filter((p) => p.M === M).reduce((a, p) => a + p.hits, 0); const lAtCap = parts.reduce((a, p) => a + p.lAtCap, 0); const offsets = []; let off = 0; for (let w = 0; w < parts.length; w++) { offsets.push(off); off += parts[w].cx; } const arg = []; for (let w = 0; w < parts.length; w++) if (parts[w].M === M) for (const h of parts[w].arg) arg.push({ ...h, i: h.i + (w === 0 ? 0 : offsets[w] - 1) }); const cq = new Certifier(cfg.q); const nus = arg.map((h) => cq.nu(h.gs)); const real = nus.filter((v) => v > 0).length; console.log(`--- ${cfg.label}`); console.log(`old word: D = ${D} (sum of ${parts.length} worker counts), x emitted = ${cx}, max gap = ${maxg}, longest L reaching CAP: ${lAtCap}`); console.log(`certificate M = ${M}; argmax windows ${hits} (${arg.length} shown)`); for (let k = 0; k < arg.length; k++) { const h = arg[k]; const runs = []; let s = 0; for (let j = 0; j < h.gs.length - 1; j++) { s += h.gs[j]; runs.push(s % cfg.q); } console.log(` i = ${String(h.i).padStart(12)} L = ${h.L} sum = ${M} = ${h.gs.join('+')} nu_q = ${nus[k]} interiors mod ${cfg.q} [${runs.join(',')}]${h.seam ? ' SEAM' : ''}`); } console.log(`LOCAL TEST: ${real}/${arg.length} argmax windows realizable => ${arg.length > 0 && real === arg.length ? 'certificate EXACT at this fold' : 'certificate LOOSE here (phantom argmax)'}`); console.log(''); const el = (Date.now() - t0) / 1000; process.stderr.write(`total ${el.toFixed(1)}s, ${nW} workers, ${(cx / el / 1e6).toFixed(1)}M gaps/s aggregate\n`); if (partial) { const expect = mode === 'validate' ? 378675 : 217929355875; const rate = cx / el; // gaps/s, aggregate over workers process.stderr.write(`PROBE: ${cx} gaps in ${el.toFixed(1)}s = ${(rate / 1e6).toFixed(1)}M gaps/s aggregate; full word ~${expect} gaps -> ETA ${((expect - cx) / rate / 60).toFixed(1)} min more (${(((cx / expect) * 100).toFixed(2))}% done)\n`); } else if (mode === 'validate') { console.log(`GATE T_19: D = ${D} (expect 378675) ${D === 378675 ? 'PASS' : 'FAIL'}, max gap = ${maxg} (expect 150) ${maxg === 150 ? 'PASS' : 'FAIL'}`); console.log(`GATE certificate at 23: M = ${M} (record 204) ${M === 204 ? 'PASS' : 'FAIL'}`); } else { console.log(`GATE T_37: D = ${D} (expect 217929355875) ${D === 217929355875 ? 'PASS' : 'FAIL'}, max gap = ${maxg} (expect 528) ${maxg === 528 ? 'PASS' : 'FAIL'}`); console.log(`cross-check: certificate at fold 37 -> 41 M = ${M} (record's G2(41#) = 546) ${M === 546 ? 'PASS' : 'MISMATCH'}`); } }