#!/usr/bin/env python3 """Independent V2 checker for job #1088 (route 13 rev7), true set unions: rebuild the run from the definitions. Imports neither the producer nor the tightcert kernel. It re-derives, in its own code: * trial-division primality and the admissible-slot scan over [a, a+CAP) (s and s+2 both coprime to p#), so every member is rebuilt from scratch, not read; * N_F (first prefix with F1 > 0) and the member slots[:N_F-1], its sha256, N_member, F1 -- with F1 computed by an explicit q x |D| kill matrix AND by the plain integer definition sum over (q, b) of the count of killed slots; * every one of the 741 unions: recomputed from the member slot lists, sorted, truncated to the common N = min |D_i|, with |U| <= k*N, duplicate removal, the sha256, F1 by the kill matrix, F1/k, the member-F1 sum, the gain, subadditivity F1_union >= sum member F1, and the strict uniform-weight inequality sum_q max_b W(q,b) < sum_s w_s with its slack equal to F1; * the per-k min/mean, the min-slack increments, the affine fit of min F1_union against k, the fit of min F1/k against 1/k, the density minima F1_union/|U| and F1_union/N, the N_F statistics, b/mean N_F, and a within-group size control (corr(common_N, F1) per (p,k)); * completeness of the subset enumeration (C(8,k) per k), the summary counts and the outcome. Paths and their scope, stated because they differ: the explicit kill matrix runs on every member and every union; the plain-Python integer definition runs on every member and on a deterministic sample of unions (every 100th); the general weighted-inequality routine runs on the same sample. Exit status is 0 only if every check passes and every recomputed quantity matches the artifact. """ import hashlib import itertools import json import math import sys from fractions import Fraction from pathlib import Path import numpy as np ART = Path(sys.argv[1] if len(sys.argv) > 1 else 'union1088-v2.json') SRC443 = Path(sys.argv[2] if len(sys.argv) > 2 else '../job1068/kfold1068.json') CAP = 20000 PLAIN_STRIDE = 100 fails = [] nchk = 0 n_mask = 0 n_plain = 0 def check(ok, label): global nchk nchk += 1 if not ok: fails.append(label) print('FAIL', label) raise SystemExit(1) # Fail early so corrupted-input controls stay cheap. return ok def is_prime(n): if n < 2: return False d = 2 while d * d <= n: if n % d == 0: return False d += 1 return True def slots_of(p, a, cap): old = [r for r in range(2, p + 1) if is_prime(r)] return [s for s in range(a, a + cap) if all(s % r and (s + 2) % r for r in old)] def f1_plain(D, qs): """Plain integer definition, no numpy.""" return len(D) - sum(max(sum(1 for s in D if (s + b) % q == 0 or (s + b + 2) % q == 0) for b in range(q)) for q in qs) def kill_sums(D, qs): """Explicit q x |D| kill matrix; returns (sum_q max_b |K(q,b)|, per-(q,b) sizes).""" Dn = np.asarray(D, dtype=np.int64) tot = 0 for q in qs: bb = np.arange(q, dtype=np.int64) A = ((Dn[:, None] + bb[None, :]) % q == 0) | ((Dn[:, None] + bb[None, :] + 2) % q == 0) tot += int(A.sum(axis=0).max()) return tot def f1_mask(D, qs): return len(D) - kill_sums(D, qs) def weights_decisive(D, qs, w): """sum_q max_b W(q,b) with general weights, plain Python, for the sampled unions.""" lhs = 0 for q in qs: mx = 0 for b in range(q): mx = max(mx, sum(ws for s, ws in zip(D, w) if (s + b) % q == 0 or (s + b + 2) % q == 0)) lhs += mx return lhs, sum(w) def fit(xs, ys): n = len(xs) sx, sy = sum(xs), sum(ys) sxx = sum(x * x for x in xs) sxy = sum(x * y for x, y in zip(xs, ys)) den = n * sxx - sx * sx m = (n * sxy - sx * sy) / den c = (sy - m * sx) / n return m, c, max(abs(y - (m * x + c)) for x, y in zip(xs, ys)) art = json.loads(ART.read_text(encoding='utf-8')) src = json.loads(SRC443.read_text(encoding='utf-8')) ref = {(m['p'], m['a']): m for m in src['members']} starts = art['starts'] KMAX = len(starts) check(art['job'] == 1088 and art['revision'] == 7, 'job/revision') check(art['primes'] == [199, 211, 223], 'only the assigned new primes') check(starts == [10007, 20011, 40009, 60013, 80021, 100003, 120011, 140009], 'eight published starts') # the compact artifact must carry every member's slot list, and each must match the checker's own check(sorted(art['member_slots']) == sorted('%d:%d' % (m['p'], m['a']) for m in art['members']), 'member_slots covers exactly the members') # ------------------------------------------------------------------ members, from scratch mems = {} for m in art['members']: p, a = m['p'], m['a'] qs = [n for n in range(p + 1, 2 * p + 1) if is_prime(n)] slots = slots_of(p, a, CAP) nf = None for N in range(1, len(slots) + 1): if f1_mask(slots[:N], qs) > 0: nf = N break D = slots[:nf - 1] sha = hashlib.sha256(','.join(map(str, D)).encode()).hexdigest() check(sha == m['slot_sha256'], 'member sha p=%d a=%d' % (p, a)) check(len(D) == m['N_member'] and nf == m['N_F'], 'member N/N_F p=%d a=%d' % (p, a)) fm = f1_mask(D, qs) n_mask += 1 check(fm == m['F1_member'], 'member F1 p=%d a=%d (%d vs %d)' % (p, a, fm, m['F1_member'])) check(fm <= 0, 'member silent p=%d a=%d' % (p, a)) check(f1_mask(slots[:nf], qs) > 0, 'N_F is the FIRST positive prefix p=%d a=%d' % (p, a)) check(f1_plain(D, qs) == fm, 'member F1 plain path p=%d a=%d' % (p, a)) n_plain += 1 r = ref.get((p, a)) # #443 used exactly four starts per prime; the four added starts have no row there and must be # reported as unproved, and the four #443 starts must all be present and hash-identical check((r is not None) == ((p, a) in ref), 'member row presence matches the declared starts p=%d a=%d' % (p, a)) check(r is None or (r['slot_sha256'] == sha and r['N_F'] == nf and r['F1_member'] == fm), 'member proved against #443 p=%d a=%d' % (p, a)) check(m['proved_against_443'] is (r is not None), 'proved flag p=%d a=%d' % (p, a)) artslots = art['member_slots'].get('%d:%d' % (p, a)) check(artslots == D, 'artifact member slot list matches the checker p=%d a=%d' % (p, a)) mems[(p, a)] = {'qs': qs, 'D': D, 'N_F': nf} # ------------------------------------------------------------------ unions seen = {} for i, rec in enumerate(art['unions']): p, combo = rec['p'], tuple(rec['members']) qs = mems[(p, combo[0])]['qs'] check(rec['k'] == len(combo) == len(set(combo)), 'k matches members p=%d %s' % (p, combo)) N = min(len(mems[(p, a)]['D']) for a in combo) parts = [mems[(p, a)]['D'][:N] for a in combo] raw = sorted(s for part in parts for s in part) U = sorted(set(raw)) check(N == rec['common_N'] and len(U) == rec['union_size'] <= rec['k'] * N, 'true set union size p=%d k=%d' % (p, rec['k'])) check(rec['source_multiset_size'] == len(raw) == rec['k']*N, 'source multiset size p=%d k=%d' % (p,rec['k'])) check(rec['duplicates_removed'] == len(raw)-len(U), 'deduplicated coordinates p=%d k=%d' % (p,rec['k'])) if rec['duplicates_removed']: check(p == 223 and f1_mask(raw,qs) == rec['source_multiset_F1'], 'preserved multiset F1 p=%d k=%d' % (p,rec['k'])) check(hashlib.sha256(','.join(map(str, U)).encode()).hexdigest() == rec['U_sha256'], 'union sha p=%d k=%d' % (p, rec['k'])) # artifact-internal reconstruction: the compact artifact carries the member slot lists, so the # union must also be rebuildable from what the artifact itself states Uart = sorted(set(s for a in combo for s in art['member_slots']['%d:%d' % (p, a)][:N])) check(Uart == U, 'union rebuilt from the artifact member_slots p=%d k=%d' % (p, rec['k'])) f1 = f1_mask(U, qs) n_mask += 1 check(f1 == rec['F1_union'], 'union F1 p=%d k=%d %s (%d vs %d)' % (p, rec['k'], combo, f1, rec['F1_union'])) check(abs(f1 / rec['k'] - rec['F1_per_k']) < 1e-12, 'F1/k p=%d k=%d' % (p, rec['k'])) check(rec['member_F1_sum'] == sum( next(x['F1_member'] for x in art['members'] if x['p'] == p and x['a'] == a) for a in combo), 'member F1 sum p=%d k=%d' % (p, rec['k'])) check(rec['gain_over_members'] == f1 - rec['member_F1_sum'], 'gain p=%d k=%d' % (p, rec['k'])) check(f1 >= rec['member_F1_sum'], 'measured gain over full members p=%d k=%d' % (p, rec['k'])) cert = rec.get('certificate') check(rec['rule'] == 'uniform_weights', 'rule is uniform weights p=%d k=%d' % (p, rec['k'])) check(cert is not None and 'slots' not in cert and 'weights' not in cert, 'certificate carries no per-union slot list p=%d k=%d' % (p, rec['k'])) check(cert['weights_len'] == len(U) and cert['weights_all_one'] is True, 'certificate weights are len |U| and all ones p=%d k=%d' % (p, rec['k'])) w = [1] * len(U) check(cert['ratio'] == [len(U) - f1, len(U)], 'certificate ratio p=%d k=%d' % (p, rec['k'])) # the strict inequality, from the mask path: lhs = |U| - F1 (the covering side), rhs = |U| lhs = len(U) - f1 check(lhs < len(U), 'STRICT inequality p=%d k=%d (%d < %d)' % (p, rec['k'], lhs, len(U))) check(len(U) - lhs == f1, 'slack equals F1 p=%d k=%d' % (p, rec['k'])) check(rec['kernel_verify_ok'] is True and rec['independent_check'] is True, 'producer two-path flags p=%d k=%d' % (p, rec['k'])) if i % PLAIN_STRIDE == 0: check(rec['certificate']['weights_len'] == len(w), 'weights_len sample p=%d k=%d' % (p, rec['k'])) check(f1_plain(U, qs) == f1, 'union F1 plain path p=%d k=%d' % (p, rec['k'])) wl, wr = weights_decisive(U, qs, w) check(wl < wr and wr - wl == f1, 'general weight inequality p=%d k=%d' % (p, rec['k'])) n_plain += 1 seen.setdefault((p, rec['k']), []).append(rec) # ------------------------------------------------------------------ completeness for p in art['primes']: for k in range(2, KMAX + 1): got = {tuple(r['members']) for r in seen.get((p, k), [])} want = set(itertools.combinations(starts, k)) check(got == want, 'all C(%d,%d) subsets present p=%d (%d vs %d)' % (KMAX, k, p, len(got), len(want))) # ------------------------------------------------------------------ fits, density and tracking ok_all = True density = {} for p in art['primes']: rows = [r for r in art['unions'] if r['p'] == p] ks = sorted({r['k'] for r in rows}) mins = {k: min(r['F1_per_k'] for r in rows if r['k'] == k) for k in ks} means = {k: sum(r['F1_per_k'] for r in rows if r['k'] == k) / len([r for r in rows if r['k'] == k]) for k in ks} umin = {k: min(r['F1_union'] for r in rows if r['k'] == k) for k in ks} umax = {k: max(r['F1_union'] for r in rows if r['k'] == k) for k in ks} dens = {k: min(r['F1_union'] / r['union_size'] for r in rows if r['k'] == k) for k in ks} densN = {k: min(r['F1_union'] / r['common_N'] for r in rows if r['k'] == k) for k in ks} density[str(p)] = {'F1_over_U': [dens[k] for k in ks], 'F1_over_N': [densN[k] for k in ks]} f = art['fit'][str(p)] for k in ks: check(abs(mins[k] - f['F1_per_k_min'][str(k)]) < 1e-12, 'fit min F1/k p=%d k=%d' % (p, k)) check(abs(means[k] - f['F1_per_k_mean'][str(k)]) < 1e-12, 'fit mean F1/k p=%d k=%d' % (p, k)) check(umin[k] == f['F1_union_min_by_k'][str(k)], 'fit min union p=%d k=%d' % (p, k)) check(umax[k] == f['F1_union_max_by_k'][str(k)], 'fit max union p=%d k=%d' % (p, k)) check([umin[k + 1] - umin[k] for k in ks[:-1]] == f['F1_union_min_increments'], 'min union increments p=%d' % p) mono = all(mins[k] <= mins[k + 1] for k in ks[:-1]) pos = all(mins[k] > 0 for k in ks) check(mono == f['min_nondecreasing'] and pos == f['min_positive'], 'flags p=%d' % p) ok_all = ok_all and mono and pos b, c, res = fit(ks, [umin[k] for k in ks]) check(abs(b - f['affine_min_union_slope_b']) < 1e-9, 'affine slope p=%d' % p) check(abs(c - f['affine_min_union_intercept']) < 1e-9, 'affine intercept p=%d' % p) check(abs(res - f['affine_min_union_max_residual']) < 1e-9, 'affine residual p=%d' % p) b2, c2, res2 = fit([1.0 / k for k in ks], [mins[k] for k in ks]) check(abs(c2 - f['per_k_vs_inv_k_intercept']) < 1e-9, 'inv-k intercept p=%d' % p) check(abs(b2 - f['per_k_vs_inv_k_slope']) < 1e-9, 'inv-k slope p=%d' % p) check(abs(res2 - f['per_k_vs_inv_k_max_residual']) < 1e-9, 'inv-k residual p=%d' % p) check(c2 > 0, 'inv-k intercept positive p=%d' % p) check(all(dens[k] <= dens[k + 1] for k in ks[:-1]), 'density min F1/|U| nondecreasing p=%d' % p) check(all(densN[k] <= densN[k + 1] for k in ks[:-1]), 'density min F1/N nondecreasing p=%d' % p) nfs = [m['N_F'] for m in art['members'] if m['p'] == p] check(abs(sum(nfs) / len(nfs) - f['N_F_mean']) < 1e-12, 'N_F mean p=%d' % p) check(min(nfs) == f['N_F_min'] and max(nfs) == f['N_F_max'], 'N_F range p=%d' % p) check(abs(b / (sum(nfs) / len(nfs)) - f['b_over_mean_N_F']) < 1e-12, 'b/N_F p=%d' % p) rho_by_k = {} for k in ks: g = [r for r in rows if r['k'] == k] if len(g) < 3: continue Ns, Fs = [r['common_N'] for r in g], [r['F1_union'] for r in g] n = len(g) mn, mf = sum(Ns) / n, sum(Fs) / n sdn = math.sqrt(sum((x - mn) ** 2 for x in Ns) / n) sdf = math.sqrt(sum((y - mf) ** 2 for y in Fs) / n) rho = (sum((x - mn) * (y - mf) for x, y in zip(Ns, Fs)) / n) / (sdn * sdf) if sdn and sdf \ else 0.0 rho_by_k[str(k)] = rho check(rho > -0.5, 'size control: corr(N,F1) not strongly negative p=%d k=%d (%.2f)' % (p, k, rho)) print('p=%d size control corr(common_N, F1): %s' % (p, {k: round(v, 3) for k, v in rho_by_k.items()})) check(ok_all == art['summary']['min_nondecreasing_at_every_prime'], 'summary monotone flag') check(ok_all is True, 'F1/k nondecreasing and positive at every prime') check(art['summary']['unions'] == len(art['unions']), 'summary union count') check(art['summary']['by_rule'] == {'uniform_weights': len(art['unions'])}, 'summary by_rule') check(art['summary']['by_k'] == {str(k): len(art['primes']) * len(list(itertools.combinations( starts, k))) for k in range(2, KMAX + 1)}, 'summary by_k') check(art['summary']['members'] == len(art['primes']) * len(starts), 'summary member count') check(art['summary']['members_proved_against_443'] == sum((m['p'], m['a']) in ref for m in art['members']), 'summary proved count') check(art['summary']['all_certificates_pass'] is True, 'summary certificates pass') check(art['outcome'].startswith('success:'), 'outcome string') check('inconclusive' not in art['outcome'], 'outcome is not inconclusive') # Rescaling the response changes the OLS objective, not the curve family. # NumPy weights multiply unsquared residuals, hence w=1/k implements 1/k^2. for p in art['primes']: f = art['fit'][str(p)] kk = np.asarray(sorted(int(k) for k in f['F1_union_min_by_k']), dtype=float) yy = np.asarray([f['F1_union_min_by_k'][str(int(k))] for k in kk], dtype=float) slope, intercept = np.polyfit(kk, yy, 1, w=1 / kk) c = f['per_k_vs_inv_k_intercept'] d = f['per_k_vs_inv_k_slope'] check(abs(slope - c) < 1e-9 and abs(intercept - d) < 1e-9, 'reciprocal-response fit equals weighted raw-affine fit p=%d' % p) check(np.max(np.abs(yy / kk - (c + d / kk))) < 1e-9 + f['per_k_vs_inv_k_max_residual'], 'same prediction curve in rescaled coordinates p=%d' % p) print('p=%d mean_N_F=%.6f c=%.9f c/mean_N_F=%.9f; reciprocal fit = weighted raw-affine fit' % (p, f['N_F_mean'], c, c / f['N_F_mean'])) # The fitted intercept is a fixed linear functional at k=2..8. # With positive min slack and complete subsets, 0 0) check(ccap == Fraction(394298, 261397), 'exact positive intercept weight sum') for p in art['primes']: f = art['fit'][str(p)] nm = min(m['N_member'] for m in art['members'] if m['p'] == p) ys = [Fraction(f['F1_union_min_by_k'][str(k)], k) for k in range(2,9)] check(all(0 < y <= nm for y in ys), 'finite positive slack range p=%d' % p) exact_c = sum(h*y for h,y in zip(hh,ys)) check(abs(float(exact_c)-f['per_k_vs_inv_k_intercept']) < 1e-9, 'exact rational intercept matches finite fit p=%d' % p) check((1-ccap)*nm <= exact_c <= ccap*nm, 'fixed-design positive-slack intercept bound p=%d' % p) print('fit audit: fixed-design c/mean_N_F < 394298/261397 = %.9f under positive min slack' % float(ccap)) print('members %d, unions %d; kill-matrix paths %d, plain-Python paths %d (sample stride %d)' % (len(art['members']), len(art['unions']), n_mask, n_plain, PLAIN_STRIDE)) print('density min F1/|U| by k: %s' % {p: [round(x, 4) for x in density[p]['F1_over_U']] for p in density}) print('checks: %d, failures: %d' % (nchk, len(fails))) for f in fails: print(' ', f) print('CHECKER', 'PASS' if not fails else 'FAIL') raise SystemExit(0 if not fails else 1)