"""Route 19 / job #1296: materialised deletion deltas vs recomputable per-node records. The search (force/propagate/candidates/branching/caps) is a faithful copy of real19.py (sha 937463e8...), itself validated against #477's producer1123.py by receipt equality. Only the record format and the checker differ per mode: M materialised : ['e',empty,delta] / ['k',c,delta] / ['h',W,delta] / ['b',a,b,left,right,merged,delta] (== #477 ablation) S recomputable+snap : per node parent + verdict/witness + the node's own closed domain/edge snapshot; checker recomputes AC from that snapshot and checks each child against the branch rule R recomputable-min : per node parent + verdict (+ branch pair) only; the checker re-derives every node's state top-down and discharges each leaf itself Caps are identical for all modes: 54 s CPU / 200000 decisions / 2 MB of records, and the byte cap is charged at the same DFS point (post-order row finalisation) in every mode. python3 records.py run --mode M --cpu 54 --decisions 200000 --bytes 2000000 --out m.json python3 records.py check --mode S --proof s-proof.json --input coherence974-input.json python3 records.py corrupt --mode S --proof s-proof.json --input coherence974-input.json """ import argparse, json, resource, sys, time from pathlib import Path sys.setrecursionlimit(5000) class Cap(Exception): pass class Sat(Exception): def __init__(self, phases): self.phases = phases def tuples(d): return [[q, b] for q in sorted(d) for b in range(q) if d[q] >> b & 1] # ------------------------------------------------------------------ search core (unchanged) def run(mode, slots, primes, cpu_limit, node_limit, byte_limit, decision_stop, want_hall, out_proof=None, soft_decisions=None, measure=False): started = time.process_time() deadline = started + max(0, cpu_limit - min(1, cpu_limit / 20)) rows = [] bytes_used = 0 stats = {'decisions': 0, 'nodes': 0, 'hall_leaves': 0, 'cardinality_leaves': 0, 'empty_leaves': 0, 'deleted_values': 0, 'nodes_with_pruned_block': 0, 'aborted_frontier': 0} record_bytes_by_node = [] nid = [0] def new_id(): i = nid[0] nid[0] += 1 return i def tick(): if time.process_time() >= deadline: raise Cap('cpu') rss = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss if sys.platform != 'darwin': rss *= 1024 if rss >= 900000000: raise Cap('ram_headroom') blocks = {i: 1 << i for i in range(len(slots))} dom = {i: {q: (1 << ((-s) % q)) | (1 << ((-s - 2) % q)) for q in primes} for i, s in enumerate(slots)} edges = {i: 0 for i in blocks} def force(d, e): ids = sorted(d) for ix, a in enumerate(ids): tick() for b in ids[ix + 1:]: if not any(v & d[b].get(q, 0) for q, v in d[a].items()): e[a] |= 1 << b e[b] |= 1 << a def propagate(d, e): delta = [] changed = True while changed: changed = False for b in sorted(d): tick() if not d[b]: return delta, b if len(d[b]) != 1: continue q, v = next(iter(d[b].items())) for a in sorted(d): if a == b or q not in d[a]: continue old = d[a][q] new = 0 if e[a] >> b & 1 else old & v if new != old: removed = old & ~new delta.append([a, q, removed]) stats['deleted_values'] += removed.bit_count() if new: d[a][q] = new else: del d[a][q] changed = True if not d[a]: return delta, a return delta, None def candidates(ids, e): for seed in ids: c = [seed] for b in ids: if b != seed and all(e[b] >> a & 1 for a in c): c.append(b) yield c def matching(c, d): mate = {} def augment(a, seen): for q in sorted(d[a]): if q in seen: continue seen.add(q) if q not in mate or augment(mate[q], seen): mate[q] = a return True return False for a in c: tick() if not augment(a, set()): W = {a} Z = set() todo = [a] while todo: u = todo.pop() for q in d[u]: if q not in Z: Z.add(q) if q in mate and mate[q] not in W: W.add(mate[q]) todo.append(mate[q]) return None, sorted(W) return {a: q for q, a in mate.items()}, None def snapshot(d, e): """Compact encoding of one node's own closed state: domains (sparse per block) + edges. Also accumulates the state's information content in bits (mask width q per domain entry plus one bit per separated block pair), so the arm can be compared at the encoding-free lower bound rather than only at this text form.""" bits = 0 for i in d: for q in d[i]: bits += q for a in e: for b in e: if b > a and (e[a] >> b) & 1: bits += 1 stats['state_bits'] = stats.get('state_bits', 0) + bits stats['state_entries'] = stats.get('state_entries', 0) + sum(len(d[i]) for i in d) parts = [] for i in sorted(d): if d[i]: parts.append(str(i) + ':' + ','.join(f'{q}x{m}' for q, m in sorted(d[i].items()))) else: parts.append(str(i) + ':') eparts = [f'{a}-{b}' for a in sorted(e) for b in sorted(e) if b > a and (e[a] >> b) & 1] return ';'.join(parts) + '|' + ','.join(eparts) def apply_left(d, e, a, b, common): ld = {i: dict(v) for i, v in d.items() if i != b} ld[a] = dict(common) le = {i: v for i, v in e.items() if i != b} le[a] = (e[a] | e[b]) & ~((1 << a) | (1 << b)) for i in le: if i != a: if (e[i] >> a & 1) or (e[i] >> b & 1): le[i] |= 1 << a le[i] &= ~(1 << b) return ld, le def apply_right(d, e, a, b): rd = {i: dict(v) for i, v in d.items()} re = dict(e) re[a] |= 1 << b re[b] |= 1 << a return rd, re def emit(row, ix=None): nonlocal bytes_used n = len(json.dumps(row, separators=(',', ':')).encode()) + 1 bytes_used += n if bytes_used > byte_limit and not measure: raise Cap('proof_bytes') if mode == 'M': rows.append(row) record_bytes_by_node.append(n) return len(rows) - 1 record_bytes_by_node[ix] = n rows[ix] = row return ix def visit(bl, d, e, parent): tick() stats['nodes'] += 1 ix = new_id() if mode != 'M' else None if soft_decisions is not None and stats['decisions'] >= soft_decisions: # kept prefix: an explicit frontier marker instead of an aborted (discarded) tree stats['aborted_frontier'] += 1 row = ['x', parent] if mode == 'R' else ['x', parent, snapshot(d, e)] return emit(row, ix) delta, empty = propagate(d, e) if empty is not None: stats['empty_leaves'] += 1 if mode == 'M': return emit(['e', empty, delta]) row = ['e', parent] if mode == 'R' else ['e', parent, snapshot(d, e), empty] return emit(row, ix) force(d, e) ids = sorted(bl) if any(len(d[a]) < len(primes) for a in ids): stats['nodes_with_pruned_block'] += 1 for c in candidates(ids, e): tick() if len(c) > len(primes): stats['cardinality_leaves'] += 1 if mode == 'M': return emit(['k', c, delta]) row = ['k', parent] if mode == 'R' else ['k', parent, snapshot(d, e), c] return emit(row, ix) if want_hall: assignment, W = matching(c, d) if W: stats['hall_leaves'] += 1 if mode == 'M': return emit(['h', W, delta]) row = ['h', parent] if mode == 'R' else ['h', parent, snapshot(d, e), W] return emit(row, ix) pairs = [] for n_, a in enumerate(ids): for b in ids[n_ + 1:]: if not (e[a] >> b & 1): common = {q: d[a][q] & d[b].get(q, 0) for q in d[a] if d[a][q] & d[b].get(q, 0)} pairs.append((len(common), a, b, common)) if not pairs: assignment, W = matching(ids, d) if W: stats['hall_leaves'] += 1 if mode == 'M': return emit(['h', W, delta]) row = ['h', parent] if mode == 'R' else ['h', parent, snapshot(d, e), W] return emit(row, ix) chosen = {q: (d[a][q] & -d[a][q]).bit_length() - 1 for a, q in assignment.items()} for q in primes: chosen.setdefault(q, 0) raise Sat(chosen) if stats['decisions'] >= node_limit or stats['decisions'] >= decision_stop: raise Cap('decisions') stats['decisions'] += 1 _, a, b, common = min(pairs, key=lambda x: x[:3]) merged = tuples(common) ld, le = apply_left(d, e, a, b, common) lb = dict(bl) lb[a] |= lb.pop(b) left = visit(lb, ld, le, ix) rd, re = apply_right(d, e, a, b) right = visit(dict(bl), rd, re, ix) if mode == 'M': return emit(['b', a, b, left, right, merged, delta]) row = ['b', parent, a, b, left, right] if mode == 'R' else ['b', parent, a, b, snapshot(d, e), left, right, merged] return emit(row, ix) proof = None phases = None reason = None try: if mode != 'M': rows = [None] * 4_000_000 record_bytes_by_node = [0] * 4_000_000 root = visit(blocks, dom, edges, None) status = 'UNSAT' if mode != 'M': rows = rows[:nid[0]] proof = {'schema_version': 2, 'record_mode': mode, 'slots': slots, 'Q': primes, 'nodes': rows, 'root': root} except Sat as found: status = 'SAT' phases = {str(q): b for q, b in sorted(found.phases.items())} except Cap as found: status = 'INCONCLUSIVE' reason = str(found) elapsed = time.process_time() - started if elapsed > cpu_limit and status == 'UNSAT': status, reason, proof, phases = 'INCONCLUSIVE', 'cpu_overrun', None, None if proof and not measure and len(json.dumps(proof, separators=(',', ':')).encode()) + 1 > byte_limit: status, reason, proof, phases = 'INCONCLUSIVE', 'proof_bytes', None, None if stats.get('state_bits'): stats['state_bits_per_node'] = round(stats['state_bits'] / stats['nodes'], 1) stats['state_lower_bound_bytes_per_node'] = round(stats['state_bits'] / 8 / stats['nodes'], 1) receipt = {'mode': mode, 'status': status, 'cap_reason': reason, 'stats': stats, 'proof_record_bytes': bytes_used, 'cpu_seconds': round(elapsed, 3), 'peak_rss_bytes': resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * (1 if sys.platform == 'darwin' else 1024), 'bytes_per_node': round(bytes_used / stats['nodes'], 2) if stats['nodes'] else None, 'bytes_per_decision': round(bytes_used / stats['decisions'], 2) if stats['decisions'] else None, 'hall_enabled': want_hall, 'limits': {'cpu_seconds': cpu_limit, 'decisions': node_limit, 'proof_bytes': byte_limit}, 'phases': phases} if out_proof and proof: Path(out_proof).write_text(json.dumps(proof, separators=(',', ':')), encoding='utf-8') return receipt # ------------------------------------------------------------------ checkers def root_state(slots, primes): d = {i: {q: (1 << ((-s) % q)) | (1 << ((-s - 2) % q)) for q in primes} for i, s in enumerate(slots)} e = {i: 0 for i in d} pairs = [(a, b) for a in sorted(d) for b in sorted(d) if b > a] for a, b in pairs: if not any(v & d[b].get(q, 0) for q, v in d[a].items()): e[a] |= 1 << b e[b] |= 1 << a return d, e def snap_of(row): """In mode S a branch row keeps its snapshot after the branch pair, leaves after the parent.""" return row[4] if row[0] == 'b' else row[2] def valid_pair(a, b, d, e): """A branch pair must be two distinct blocks whose domains overlap and that are not already separated: only then do 'merge' and 'force apart' together cover the node's solutions.""" if a == b: return False, 'branch pair is the same block twice' if a not in d or b not in d: return False, 'branch block is not a block of this node' if (e[a] >> b) & 1: return False, 'branch pair is already separated' if not any(d[a][q] & d[b].get(q, 0) for q in d[a]): return False, 'branch pair has an empty intersection' return True, '' def parse_snapshot(s): doms, edgestr = s.split('|') d = {} for part in doms.split(';'): i, _, rest = part.partition(':') d[int(i)] = {} if not rest else {int(qm.split('x')[0]): int(qm.split('x')[1]) for qm in rest.split(',')} e = {i: 0 for i in d} for ab in [x for x in edgestr.split(',') if x]: a, b = (int(v) for v in ab.split('-')) e[a] |= 1 << b e[b] |= 1 << a return d, e def propagate_only(d, e): """Recompute arc consistency to a fixed point on a copy. Returns (domains, empty_block).""" d = {i: dict(v) for i, v in d.items()} changed = True while changed: changed = False for b in sorted(d): if not d[b]: return d, b if len(d[b]) != 1: continue q, v = next(iter(d[b].items())) for a in sorted(d): if a == b or q not in d[a]: continue new = 0 if e[a] >> b & 1 else d[a][q] & v if new != d[a][q]: if new: d[a][q] = new else: del d[a][q] changed = True if not d[a]: return d, a return d, None def force_only(d, e): ids = sorted(d) for ix, a in enumerate(ids): for b in ids[ix + 1:]: if not any(v & d[b].get(q, 0) for q, v in d[a].items()): e[a] |= 1 << b e[b] |= 1 << a return e def close(d, e): """The producer's node closure: propagate to a fixed point, then one force pass.""" d2, empty = propagate_only(d, e) e2 = {i: v for i, v in e.items()} if empty is None: force_only(d2, e2) return d2, e2, empty def apply_left(d, e, a, b, common): ld = {i: dict(v) for i, v in d.items() if i != b} ld[a] = dict(common) le = {i: v for i, v in e.items() if i != b} le[a] = (e[a] | e[b]) & ~((1 << a) | (1 << b)) for i in le: if i != a: if (e[i] >> a & 1) or (e[i] >> b & 1): le[i] |= 1 << a le[i] &= ~(1 << b) return ld, le def apply_right(d, e, a, b): rd = {i: dict(v) for i, v in d.items()} re = dict(e) re[a] |= 1 << b re[b] |= 1 << a return rd, re def clique_ok(c, e, d): if len(set(c)) != len(c): return False for n_, a in enumerate(c): for b in c[n_ + 1:]: if not (e[a] >> b & 1): return False return True def find_big_clique(ids, e, primes): for seed in ids: c = [seed] for b in ids: if b != seed and all(e[b] >> a & 1 for a in c): c.append(b) if len(c) > len(primes): return c return None def find_hall_violator(ids, d): mate = {} def augment(a, seen): for q in sorted(d[a]): if q in seen: continue seen.add(q) if q not in mate or augment(mate[q], seen): mate[q] = a return True return False for a in ids: if not augment(a, set()): W = {a} Z = set() todo = [a] while todo: u = todo.pop() for q in d[u]: if q not in Z: Z.add(q) if q in mate and mate[q] not in W: W.add(mate[q]) todo.append(mate[q]) return sorted(W) return None def check(proof, mode): """Independent verification of a recomputable proof: structure, child consistency against the branch rule, and each leaf's discharge against the node's own state. A row ['x', ...] is an explicit frontier marker: structure only, no discharge claimed.""" problems = [] kinds = {} nodes = proof['nodes'] slots, primes = proof['slots'], proof['Q'] d0, e0 = root_state(slots, primes) seen = set() def state_of(ix, d, e): return d, e if mode == 'S': row = nodes[proof['root']] if row is None: return {'accepted': False, 'problems': ['root row missing']} sd, se = parse_snapshot(snap_of(row)) ok, err = compare_state(sd, se, d0, e0, require_equal=True) if not ok: problems.append('root snapshot != initial state: ' + err) stack = [(proof['root'], sd, se)] 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 row is None: problems.append(f'referenced row {ix} missing'); continue kind = row[0] kinds[kind] = kinds.get(kind, 0) + 1 if kind == 'x': pass elif kind == 'e': _, empty = propagate_only(d, e) if empty is None and all(d[b] for b in d): problems.append(f'node {ix}: claims empty-domain leaf but no block is empty') elif kind == 'k': c = row[3] if not clique_ok(c, e, d): problems.append(f'node {ix}: cardinality witness is not a separated clique') elif len(c) <= len(primes): problems.append(f'node {ix}: cardinality witness |c|={len(c)} <= |Q|') for a in c: if a not in d: problems.append(f'node {ix}: witness block {a} not a block of this node') elif kind == 'h': W = row[3] N = set() for a in W: N |= set(d.get(a, {})) if len(N) >= len(W): problems.append(f'node {ix}: claimed Hall deficiency |N(W)|={len(N)} >= |W|={len(W)}') elif kind == 'b': a, b = row[2], row[3] okp, err = valid_pair(a, b, d, e) if not okp: problems.append(f'node {ix}: {err}') continue common = {q: d[a][q] & d[b].get(q, 0) for q in d[a] if d[a][q] & d[b].get(q, 0)} ld, le = apply_left(d, e, a, b, common) rd, re = apply_right(d, e, a, b) for side, (raw, cix) in (('left', ((ld, le), row[5])), ('right', ((rd, re), row[6]))): child = nodes[cix] if 0 <= cix < len(nodes) else None if child is None: problems.append(f'node {ix}: {side} child {cix} missing (incomplete tree)') continue cx, ex = raw if child[0] == 'x' else close(raw[0], raw[1])[:2] sd, se = parse_snapshot(snap_of(child)) ok, err = compare_state(sd, se, cx, ex, require_equal=(child[0] != 'e'), subset_domains=True) if not ok: problems.append(f'node {ix} -> {side} {cix}: {err}') stack.append((cix, sd, se)) else: problems.append(f'node {ix}: unknown verdict {kind!r}') if len(seen) != len(nodes): problems.append(f'{len(nodes) - len(seen)} row(s) unreachable from the root') else: # R: no stored state; re-derive every node from the root stack = [(proof['root'], d0, e0)] 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 d2, e2, empty = close(d, e) 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 find_big_clique(sorted(d2), e2, primes) is None: problems.append(f'node {ix}: no separated clique > |Q| in the recomputed state') elif kind == 'h': if empty is None and 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] okp, err = valid_pair(a, b, d2, e2) if not okp: problems.append(f'node {ix}: {err}') 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 = apply_left(d2, e2, a, b, common) rd, re = 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 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)} def compare_state(sd, se, d, e, require_equal=False, subset_domains=True): if se != e: return False, 'separation edges differ from the recomputed state' for i in sd: if i not in d: return False, f'state has block {i} that the parent does not' for q, m in sd[i].items(): if m & ~d[i].get(q, 0): return False, f'block {i} prime {q}: domain has values the parent state does not' if require_equal: for i in d: if set(sd.get(i, {})) != set(d[i]): return False, f'block {i}: prime set differs from the recomputed state' for q, m in d[i].items(): if sd[i].get(q, 0) != m: return False, f'block {i} prime {q}: domain differs from the recomputed state' return True, '' # ------------------------------------------------------------------ corruption classes def corrupt(proof, mode, cls): """Four corruption classes, instantiated on this instance's own leaves (it has no Hall leaf). 1 wrong-intersection : claim a branch pair that is already separated in that node's state 2 missing-branch : drop one child row (a silent hole in the tree) 3 false-union : weaken a cardinality witness so |c| <= |Q| 4 fabricated-leaf : append an extra leaf row claiming a discharge its parent cannot reach """ p = json.loads(json.dumps(proof)) nodes = p['nodes'] if cls == 1: # wrong intersection / wrong merge for ix, row in enumerate(nodes): if row and row[0] == 'b': if mode == 'S': child = nodes[row[5]] if child is None: continue child[2] = snap_of(row) # claim the child's state is the parent's else: row[3] = row[2] # b := a: (a,a) does not cover the node return p return None if cls == 2: # missing branch for ix, row in enumerate(nodes): if row and row[0] == 'b': nodes[row[5] if mode == 'S' else row[4]] = None return p return None if cls == 3: # false union / false discharge witness for ix, row in enumerate(nodes): if row and row[0] == 'k' and mode == 'S': row[3] = row[3][:max(1, len(row[3]) // 2)] # now |c| <= |Q| return p return None # R keeps no witness: the same lie is class 4 if cls == 4: # fabricated leaf on an internal node for ix, row in enumerate(nodes): if row and row[0] == 'b': if mode == 'R': nodes[ix] = ['k', row[1]] else: nodes[ix] = ['k', row[1], row[4], [row[2], row[3]]] return p return None return None def main(): ap = argparse.ArgumentParser() sub = ap.add_subparsers(dest='cmd', required=True) p = sub.add_parser('run') p.add_argument('--mode', required=True, choices=['M', 'S', 'R']) p.add_argument('--input', default='coherence974-input.json') p.add_argument('--cpu', type=float, default=54) p.add_argument('--decisions', type=int, default=200000) p.add_argument('--bytes', type=int, default=2000000) p.add_argument('--decision-stop', type=int, default=10**9) p.add_argument('--soft-decisions', type=int) p.add_argument('--measure', action='store_true') p.add_argument('--hall', action='store_true') p.add_argument('--proof') p.add_argument('--out') p = sub.add_parser('check') p.add_argument('--mode', required=True, choices=['S', 'R']) p.add_argument('--proof', required=True) p.add_argument('--out') p = sub.add_parser('corrupt') p.add_argument('--mode', required=True, choices=['S', 'R']) p.add_argument('--proof', required=True) p.add_argument('--out') a = ap.parse_args() if a.cmd == 'run': inp = json.loads(Path(a.input).read_text(encoding='utf-8')) t0 = time.process_time() rec = run(a.mode, inp['slots'], inp['Q'], a.cpu, a.decisions, a.bytes, a.decision_stop, a.hall, a.proof, soft_decisions=a.soft_decisions, measure=a.measure) rec['wall_cpu_seconds'] = round(time.process_time() - t0, 3) if a.out: Path(a.out).write_text(json.dumps(rec, sort_keys=True, indent=2) + '\n', encoding='utf-8') print(json.dumps({k: rec[k] for k in ('mode', 'status', 'cap_reason', 'proof_record_bytes', 'bytes_per_node', 'bytes_per_decision', 'cpu_seconds')}, sort_keys=True)) print(json.dumps(rec['stats'], sort_keys=True)) return proof = json.loads(Path(a.proof).read_text(encoding='utf-8')) if a.cmd == 'check': t0 = time.process_time() res = check(proof, a.mode) res['checker_cpu_seconds'] = round(time.process_time() - t0, 3) res['nodes'] = len(proof['nodes']) if a.out: Path(a.out).write_text(json.dumps(res, sort_keys=True, indent=2) + '\n', encoding='utf-8') print(json.dumps({k: res[k] for k in ('accepted', 'nodes', 'checker_cpu_seconds')}, sort_keys=True)) if res['problems']: print(json.dumps(res['problems'], indent=1)[:600]) return if a.cmd == 'corrupt': res = {} for cls, name in ((1, 'wrong-intersection'), (2, 'missing-branch'), (3, 'false-union'), (4, 'fabricated-leaf')): bad = corrupt(proof, a.mode, cls) if bad is None: res[name] = 'not-applicable' continue out = check(bad, a.mode) res[name] = 'rejected' if not out['accepted'] else 'ACCEPTED (unsound!)' if a.out: Path(a.out).write_text(json.dumps(res, sort_keys=True, indent=2) + '\n', encoding='utf-8') print(json.dumps(res, sort_keys=True)) if __name__ == '__main__': main()