"""Job 1309 / route 19 rev 8: witness-carrying record (Rw) and lazy-separation checker. Input: return #572's R proofs (r1810-proof.json, rbig-proof.json) and its records.py (sha256 d8c2a9a5...), which supplies the reference semantics (root_state, propagate_only, apply_left/right, find_big_clique, find_hall_violator, check). Subcommands witness replay R with records.py's own primitives and attach, per 'k' leaf, the separated clique find_big_clique returns: row ['k', parent, c]. check --sep full|lazy [--witness] the checker. --sep full re-derives the separation graph per node (records.force_only); --sep lazy keeps only the explicit (branch-made) separations X and answers sep(a,b) = X[a]>>b or domains disjoint, on demand. --witness requires and verifies the record's witness instead of searching for one. audit --sep full|lazy [--witness] same traversal, untimed: materialises the closed separation graph from the checker's own state and compares job1302-ref-trace's state hash on every non-frontier node. corrupt --sep ... re-instantiates the corruption classes on the Rw format. Why lazy is exact (derivation; checked by audit): domains only shrink along a branch (propagation removes values, a merge keeps the intersection), so a pair disjoint at an ancestor stays disjoint. Every separation the reference inherits is either explicit (a right branch, carried through merges by the same rule as apply_left) or was added by a force pass because the pair was disjoint then. Hence the reference's closed graph equals X OR disjoint(closed domains). In propagation the difference never matters: if a and singleton b are disjoint, d[a][q] & v is already 0. Output: one JSON line on stdout (no timings in hashed artifacts; timings go to --out receipts). """ import argparse import json import sys import time import records def load(path): return json.loads(open(path, encoding='utf-8').read()) def offsets(primes): off, o = {}, 0 for q in primes: off[q] = o o += q return off class Lazy: """Per-node separation oracle: explicit bits X plus on-demand disjointness via packed domains.""" __slots__ = ('d', 'X', 'off', 'pk', 'queries') def __init__(self, d, X, off): self.d, self.X, self.off, self.pk, self.queries = d, X, off, {}, 0 def packed(self, a): p = self.pk.get(a) if p is None: off = self.off p = 0 for q, m in self.d[a].items(): p |= m << off[q] self.pk[a] = p return p def sep(self, a, b): self.queries += 1 if (self.X[a] >> b) & 1: return True return not (self.packed(a) & self.packed(b)) def clique_ok_oracle(c, sep, nodeblocks): if len(set(c)) != len(c): return 'witness repeats a block' for a in c: if a not in nodeblocks: return f'witness block {a} is not a block of this node' for i, a in enumerate(c): for b in c[i + 1:]: if not sep(a, b): return f'witness pair ({a},{b}) is not separated' return None def find_big_clique_oracle(ids, sep, nq): for seed in ids: c = [seed] for b in ids: if b != seed and all(sep(b, a) for a in c): c.append(b) if len(c) > nq: return c return None def materialise(d, X): e = dict(X) records.force_only(d, e) return e def check(proof, sep_mode, witness, trace=None): """Returns the same outcome dict as records.check; trace(ix, kind, d, e) is called (audit only).""" problems, kinds, seen = [], {}, set() nodes, slots, primes = proof['nodes'], proof['slots'], proof['Q'] nq = len(primes) off = offsets(primes) d0, e0 = records.root_state(slots, primes) X0 = {i: 0 for i in d0} if sep_mode == 'lazy' else e0 stack = [(proof['root'], d0, X0)] queries = 0 while stack: ix, d, e = stack.pop() if ix in seen: problems.append(f'node {ix} reachable twice'); continue seen.add(ix) row = nodes[ix] if 0 <= ix < len(nodes) else None if row is None: problems.append(f'referenced row {ix} missing'); continue kind = row[0] kinds[kind] = kinds.get(kind, 0) + 1 if kind == 'x': continue if sep_mode == 'full': d2, e2, empty = records.close(d, e) sepf = lambda a, b, e2=e2: bool((e2[a] >> b) & 1) else: d2, empty = records.propagate_only(d, e) e2 = e # explicit separations only; never materialised L = Lazy(d2, e2, off) sepf = L.sep if trace is not None and empty is None: trace(ix, kind, d2, e2 if sep_mode == 'full' else materialise(d2, e2)) if kind == 'e': if empty is None: problems.append(f'node {ix}: no empty domain in the recomputed closure') elif kind == 'k': if empty is not None: problems.append(f'node {ix}: claims cardinality leaf but the node is empty') elif witness: c = row[2] if len(row) > 2 else None if not isinstance(c, list) or not all(isinstance(v, int) for v in c): problems.append(f'node {ix}: cardinality leaf carries no witness') elif len(c) <= nq: problems.append(f'node {ix}: witness |c|={len(c)} <= |Q|') else: err = clique_ok_oracle(c, sepf, d2) if err: problems.append(f'node {ix}: {err}') else: if find_big_clique_oracle(sorted(d2), sepf, nq) is None: problems.append(f'node {ix}: no separated clique > |Q| in the recomputed state') elif kind == 'h': if empty is None and records.find_hall_violator(sorted(d2), d2) is None: problems.append(f'node {ix}: no Hall deficiency in the recomputed state') elif kind == 'b': a, b = row[2], row[3] if a == b: problems.append(f'node {ix}: branch pair is the same block twice'); continue if a not in d2 or b not in d2: problems.append(f'node {ix}: branch block is not a block of this node'); continue if sepf(a, b): problems.append(f'node {ix}: branch pair is already separated'); continue common = {q: d2[a][q] & d2[b].get(q, 0) for q in d2[a] if d2[a][q] & d2[b].get(q, 0)} ld, le = records.apply_left(d2, e2, a, b, common) rd, re = records.apply_right(d2, e2, a, b) stack.append((row[4], ld, le)) stack.append((row[5], rd, re)) else: problems.append(f'node {ix}: unknown verdict {kind!r}') if sep_mode == 'lazy': queries += L.queries if len(seen) != len(nodes): problems.append(f'{len(nodes) - len(seen)} row(s) unreachable from the root') return {'accepted': not problems, 'problems': problems[:12], 'node_count': len(nodes), 'kinds': kinds, 'verified_discharges': sum(v for k, v in kinds.items() if k in ('e', 'k', 'h')), 'frontier_unverified': kinds.get('x', 0), 'lazy_sep_queries': queries} def witness(proof): """Attach the separated clique the reference search finds (the producer's own candidate rule).""" out = json.loads(json.dumps(proof)) nodes, primes = out['nodes'], out['Q'] d0, e0 = records.root_state(out['slots'], primes) stack = [(out['root'], d0, e0)] while stack: ix, d, e = stack.pop() row = nodes[ix] if row[0] == 'x': continue d2, e2, empty = records.close(d, e) if row[0] == 'k': c = records.find_big_clique(sorted(d2), e2, primes) assert c is not None and empty is None nodes[ix] = ['k', row[1], c] elif row[0] == 'b': a, b = row[2], row[3] common = {q: d2[a][q] & d2[b].get(q, 0) for q in d2[a] if d2[a][q] & d2[b].get(q, 0)} stack.append((row[4],) + records.apply_left(d2, e2, a, b, common)) stack.append((row[5],) + records.apply_right(d2, e2, a, b)) return out def corrupt_classes(proof): """Corruption classes on Rw. Each returns (name, corrupted proof) or (name, None) if inapplicable.""" nodes = proof['nodes'] nq = len(proof['Q']) kix = [i for i, r in enumerate(nodes) if r and r[0] == 'k'] bix = [i for i, r in enumerate(nodes) if r and r[0] == 'b'] out = [] def cp(): return json.loads(json.dumps(proof)) p = cp(); p['nodes'][kix[0]] = p['nodes'][kix[0]][:2]; out.append(('missing-witness', p)) p = cp(); r = p['nodes'][kix[0]]; r[2] = r[2][:nq]; out.append(('witness-le-Q', p)) # a witness with one non-separated pair: swap one member for a block not separated from another # member at that node (found by the reference state), keeping |c| > |Q| p = cp() ix = kix[0] st = states_at(proof, {ix})[ix] d2, e2 = st c = list(p['nodes'][ix][2]) repl = None for j in range(len(c)): for cand in sorted(d2): if cand in c: continue others = [v for v in c if v != c[j]] if any(not (e2[cand] >> v) & 1 for v in others): repl = (j, cand); break if repl: break if repl: c[repl[0]] = repl[1]; p['nodes'][ix][2] = c; out.append(('non-separated-pair', p)) else: out.append(('non-separated-pair', None)) p = cp(); r = p['nodes'][kix[0]]; r[2] = r[2] + [r[2][0]]; out.append(('duplicate-block', p)) # fabricated k at an internal node, carrying a real witness copied from a genuine leaf p = cp(); r = p['nodes'][bix[0]]; p['nodes'][bix[0]] = ['k', r[1], list(proof['nodes'][kix[0]][2])] out.append(('fabricated-k-internal', p)) # fabricated k at an internal node deep in the tree whose state admits no big clique: take the # deepest-first internal node whose own reference state has no separated clique > |Q| st_all = states_at(proof, set(bix)) target = next((i for i in bix if records.find_big_clique(sorted(st_all[i][0]), st_all[i][1], proof['Q']) is None), None) if target is not None: p = cp(); r = p['nodes'][target] p['nodes'][target] = ['k', r[1], list(proof['nodes'][kix[0]][2])] out.append(('fabricated-k-no-clique', p)) else: out.append(('fabricated-k-no-clique', None)) p = cp(); r = p['nodes'][bix[0]]; r[3] = r[2]; out.append(('wrong-intersection', p)) # wrong intersection 2: a branch pair that is separated (explicitly) at that node p = cp(); done = False for i in bix: d2, e2 = st_all[i] r = p['nodes'][i] a = r[2] for b in sorted(d2): if b != a and (e2[a] >> b) & 1: r[3] = b; done = True; break if done: break out.append(('separated-branch-pair', p if done else None)) p = cp(); r = p['nodes'][bix[0]]; p['nodes'][r[4]] = None; out.append(('missing-branch', p)) return out def states_at(proof, want): """Reference closed state (records.close) at the requested node indices.""" nodes, primes = proof['nodes'], proof['Q'] d0, e0 = records.root_state(proof['slots'], primes) res, stack = {}, [(proof['root'], d0, e0)] while stack and len(res) < len(want): ix, d, e = stack.pop() row = nodes[ix] if row[0] == 'x': continue d2, e2, empty = records.close(d, e) if ix in want: res[ix] = (d2, e2) if row[0] == 'b': a, b = row[2], row[3] common = {q: d2[a][q] & d2[b].get(q, 0) for q in d2[a] if d2[a][q] & d2[b].get(q, 0)} stack.append((row[4],) + records.apply_left(d2, e2, a, b, common)) stack.append((row[5],) + records.apply_right(d2, e2, a, b)) return res def main(): ap = argparse.ArgumentParser() sub = ap.add_subparsers(dest='cmd', required=True) p = sub.add_parser('witness'); p.add_argument('proof'); p.add_argument('out') for name in ('check', 'audit', 'corrupt'): p = sub.add_parser(name); p.add_argument('proof') if name == 'audit': p.add_argument('trace') p.add_argument('--sep', choices=['full', 'lazy'], required=name != 'corrupt') p.add_argument('--witness', action='store_true') p.add_argument('--reference', action='store_true', help='time records.check instead') p.add_argument('--out') a = ap.parse_args() if a.cmd == 'witness': proof = load(a.proof) out = witness(proof) s = json.dumps(out, separators=(',', ':')) open(a.out, 'w', encoding='utf-8').write(s) print(json.dumps({'nodes': len(out['nodes']), 'record_bytes_R': len(json.dumps(proof, separators=(',', ':')).encode()), 'record_bytes_Rw': len(s.encode()), 'witness_sizes_max': max(len(r[2]) for r in out['nodes'] if r[0] == 'k')}, sort_keys=True)) return proof = load(a.proof) if a.cmd == 'check': t0 = time.process_time() res = records.check(proof, 'R') if a.reference else check(proof, a.sep, a.witness) cpu = time.process_time() - t0 rec = dict(res, checker='records.check' if a.reference else f'check1309 sep={a.sep} witness={a.witness}', record_bytes=len(json.dumps(proof, separators=(',', ':')).encode())) print(json.dumps(rec, sort_keys=True)) if a.out: open(a.out, 'w', encoding='utf-8').write(json.dumps(dict(rec, checker_cpu_seconds=round(cpu, 3)), sort_keys=True, indent=2) + '\n') print(f'checker_cpu_seconds {cpu:.3f}', file=sys.stderr) elif a.cmd == 'audit': import importlib.util spec = importlib.util.spec_from_file_location('rt', 'job1302-ref-trace.py') rt = importlib.util.module_from_spec(spec); spec.loader.exec_module(rt) ref = {} for line in open(a.trace, encoding='utf-8'): j = json.loads(line) if 'node' in j: ref[j['node']] = (j['kind'], j['state_hash']) primes = proof['Q'] qindex = {q: i for i, q in enumerate(primes)} nb = len(proof['slots']) got = {} res = check(proof, a.sep, a.witness, trace=lambda ix, kind, d, e: got.__setitem__(ix, rt.state_hash(d, e, qindex, nb))) nonfront = [ix for ix, (k, h) in ref.items() if k != 'x'] mism = [ix for ix in nonfront if got.get(ix) != ref[ix][1]] print(json.dumps({'accepted': res['accepted'], 'compared': len(nonfront), 'mismatches': len(mism), 'first_mismatches': mism[:5], 'sep': a.sep, 'witness': a.witness}, sort_keys=True)) elif a.cmd == 'corrupt': out = {} for name, p in corrupt_classes(proof): if p is None: out[name] = 'not-applicable'; continue r = {} for sep in ('full', 'lazy'): res = check(p, sep, True) r[sep] = 'rejected' if not res['accepted'] else 'ACCEPTED' out[name] = r print(json.dumps(out, sort_keys=True)) if __name__ == '__main__': main()