#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Route 19 / job #1294 -- N1 generator test with the N2 recomputable certificate. Self-contained: Python 3 stdlib only, one thread, deterministic stdout. What is implemented, and against which specification ---------------------------------------------------- The instance is the FROZEN input of return #477's producer, fetched by hash (`coherence974-input.json`, sha256 b173e69b...). The route's own declared definitions in that file are used verbatim: * `phase_convention`: K(q,b) = { s : (s+b) mod q in {0, q-2} }, b = 0..q-1. * `pair_graph`: "all unordered distinct pairs meeting H; one block per pair". Consequence used here (exact, from the convention alone): a slot pair {s,t} lies inside one phase class K(q,b) iff s = t (mod q). So the allowed owner primes of block {s,t} are { q in Q : q | (t-s) }, with witnessing phases b = (-s) mod q (both == 0) and b = (-s-2) mod q (both == q-2). Blocks with no allowed prime are dropped as unassignable. Feasibility is then a system of distinct representatives: each block takes a distinct owner prime from Q. What this is NOT: #477's `producer1123.py` is not published (no hash is on the record), so "identical propagation" can only be asserted *between this script's two arms*. That is exactly what the ablation requires. No claim is made about #477's actual tree, and no D51 verdict is claimed. Arms ---- ablation : arc consistency (all-different basic purge) + cardinality cut only. hall : the same propagation, plus maximum-matching Hall violator extraction (Kuhn; X-vertices M-reachable from an unmatched block). Both arms search the same DFS, with the same branching rule and value order, and emit the N2 encoding on their own tree. N2 certificate + checker ------------------------ Per node: parent index, branch (block, value), domain snapshot, verdict, and for terminal nodes a discharge (assignment for sat, violator/hall witness for unsat). The checker recomputes arc consistency to a fixed point from the stored snapshots, verifies tree completeness against each node's own domain, and verifies terminal discharges. Four corruption classes must be rejected: wrong intersection, missing branch, false union, fabricated leaf. stdout is the deterministic measurement JSON. Timing goes to stderr, so the artefact hashes byte-for-byte across runs. """ import json import os import random import sys import time from collections import deque CAP_NODES = 20000 CAP_DECISIONS = 200000 CAP_CERT_BYTES = 2 * 1024 * 1024 # ------------------------------------------------------------------- instance def build_instance(inp): slots = list(inp["slots"]) Q = list(inp["Q"]) blocks, allowed, phases = [], [], [] for i, s in enumerate(slots): for t in slots[i + 1:]: d = t - s al = [q for q in Q if d % q == 0] if not al: continue blocks.append((s, t)) allowed.append(tuple(sorted(set(al)))) phases.append({q: sorted({(-s) % q, (-s - 2) % q}) for q in al}) return {"slots": slots, "Q": Q, "blocks": blocks, "allowed": allowed, "phases": phases} # --------------------------------------------------------------- propagation def ac_purge(domains, allowed): """All-different basic arc consistency: value v leaves D(B) when some other block B' has D(B') == {v} and v is not forced into B by that same rule.""" n = len(domains) doms = [set(d) for d in domains] changed = True while changed: changed = False singles = {} for b in range(n): if len(doms[b]) == 1: singles.setdefault(next(iter(doms[b])), []).append(b) for v, owners in singles.items(): if len(owners) > 1: return None, "contradiction: two blocks forced to the same prime" keep = owners[0] for b in range(n): if b != keep and v in doms[b] and len(doms[b]) > 1: doms[b].discard(v) changed = True for b in range(n): if not doms[b]: return None, "empty domain" return [tuple(sorted(d)) for d in doms], None def cardinality_cut(domains): """Generalised Hall on the whole block set: |union of domains| < #blocks.""" u = set() for d in domains: u |= set(d) return len(u) < len(domains) def kuhn(domains, n): """Maximum matching on blocks x primes. Returns (match_block, match_prime).""" mb = [-1] * n mp = {} def try_k(b, seen): for v in domains[b]: if v in seen: continue seen.add(v) if mp.get(v, -1) == -1 or try_k(mp[v], seen): mp[v] = b mb[b] = v return True return False for b in range(n): try_k(b, set()) return mb, mp def hall_violator(domains, n): """Maximum matching + M-reachable set from the unmatched blocks. Returns (W, N) with |N| < |W| when the instance is deficient, else None. """ mb, mp = kuhn(domains, n) unmatched = [b for b in range(n) if mb[b] == -1] if not unmatched: return None # alternating BFS: block -> prime along a matched edge, prime -> all blocks # that can take it (so the reachable set is the standard violator). seen_blocks, seen_primes = set(unmatched), set() dq = deque(unmatched) while dq: b = dq.popleft() for v in domains[b]: if v in seen_primes: continue seen_primes.add(v) if mp.get(v, -1) != -1 and mp[v] not in seen_blocks: seen_blocks.add(mp[v]) dq.append(mp[v]) W = sorted(seen_blocks) N = set() for b in W: N |= set(domains[b]) if not W or len(N) >= len(W): return None return W, sorted(N) # ---------------------------------------------------------------------- search def child_branch(domains): """Smallest domain of size >= 2, tie on lowest block index; values ascending. A node whose every domain is a singleton is SAT, not branchable.""" best, bestlen = None, None for b, d in enumerate(domains): if len(d) < 2: continue if bestlen is None or len(d) < bestlen: best, bestlen = b, len(d) return best def search(allowed, use_hall, cap_nodes=CAP_NODES, cap_decisions=CAP_DECISIONS): n = len(allowed) nodes = [] # N2 encoding: one record per node decisions = 0 hall_leaves = 0 card_leaves = 0 empty_leaves = 0 truncated = False root, err = ac_purge([tuple(sorted(set(a))) for a in allowed], allowed) if root is None: nodes.append({"p": None, "b": None, "v": None, "d": [], "t": "unsat", "why": err}) return nodes, {"decisions": 0, "hall_leaves": 0, "card_leaves": 0, "empty_leaves": 1, "truncated": False} nodes.append({"p": None, "b": None, "v": None, "d": [list(x) for x in root], "t": "open", "why": None}) def expand(i, domains): """Depth-first expansion of an open node; returns nothing.""" nonlocal decisions, hall_leaves, card_leaves, empty_leaves, truncated if len(nodes) >= cap_nodes or decisions >= cap_decisions: truncated = True nodes[i]["t"] = "cap" return b = child_branch(domains) if b is None: nodes[i]["t"] = "sat" nodes[i]["why"] = "all domains singletons" return if cardinality_cut(domains): card_leaves += 1 nodes[i]["t"] = "unsat" nodes[i]["why"] = "cardinality cut: |union(domains)| < #blocks" return if use_hall: hv = hall_violator(domains, len(domains)) if hv is not None: hall_leaves += 1 nodes[i]["t"] = "unsat" nodes[i]["why"] = "hall violator" nodes[i]["w"] = hv[0] nodes[i]["n"] = hv[1] return for v in domains[b]: decisions += 1 nd = [tuple(d) for d in domains] nd[b] = (v,) nd2, err = ac_purge(nd, allowed) child = {"p": i, "b": b, "v": v, "d": [list(x) for x in (nd2 or nd)], "t": "open", "why": None} nodes.append(child) j = len(nodes) - 1 if nd2 is None: empty_leaves += 1 nodes[j]["t"] = "unsat" nodes[j]["why"] = err else: expand(j, nd2) expand(0, root) stats = {"decisions": decisions, "hall_leaves": hall_leaves, "card_leaves": card_leaves, "empty_leaves": empty_leaves, "truncated": truncated} return nodes, stats def encode_bytes(nodes): return len(json.dumps(nodes, sort_keys=True, separators=(",", ":")).encode()) # --------------------------------------------------------------------- checker def check_certificate(inp_allowed, nodes): """Independent recomputation. Returns (ok, reasons[]).""" reasons = [] if not nodes: return False, ["empty certificate"] n = len(inp_allowed) root, err = ac_purge([tuple(sorted(set(a))) for a in inp_allowed], inp_allowed) if root is None: # the root itself is infeasible; the certificate must say so if nodes[0]["t"] == "unsat": return True, [] return False, ["root infeasible but certificate does not say unsat"] # A CA checker must REJECT a malformed certificate, not crash on it. for j, nd in enumerate(nodes): if not isinstance(nd.get("d"), list) or len(nd["d"]) != n: reasons.append("node %d: malformed domain snapshot (len != %d)" % (j, n)) if len(nodes[0].get("d") or []) != n: return False, reasons or ["root snapshot malformed"] if [list(x) for x in root] != nodes[0]["d"]: reasons.append("wrong intersection: root snapshot is not the AC fixed point") children = {} for j, nd in enumerate(nodes): if nd["p"] is not None: children.setdefault(nd["p"], []).append(j) for j, nd in enumerate(nodes): i = nd["p"] if i is None: continue par = nodes[i] pd = [tuple(x) for x in par["d"]] b, v = nd["b"], nd["v"] if b is None or v is None: reasons.append("node %d has no branch" % j) continue if len(pd) != n or not (0 <= b < n): reasons.append("node %d: parent snapshot or branch index malformed" % j) continue if v not in pd[b]: reasons.append("node %d branches on %d outside its parent domain" % (j, v)) if len(pd[b]) <= 1: reasons.append("node %d branches on a singleton or empty parent domain" % j) nd_parent = [tuple(d) for d in pd] nd_parent[b] = (v,) expect, err = ac_purge(nd_parent, inp_allowed) got = nd["d"] exp = [] if expect is None else [list(x) for x in expect] if expect is None: if nd["t"] != "unsat": reasons.append("node %d should be unsat (empty domain) but is %s" % (j, nd["t"])) elif got != exp: reasons.append("node %d snapshot is not the AC fixed point of its branch" % j) # tree completeness: every open node has exactly the children of its branch for i, nd in enumerate(nodes): if nd["t"] != "open": continue pd = [tuple(x) for x in nd["d"]] if len(pd) != n: continue b = child_branch(pd) if b is None: reasons.append("node %d is open but has no branchable domain" % i) continue want = [(b, v) for v in pd[b]] have = [(nodes[j]["b"], nodes[j]["v"]) for j in children.get(i, [])] if sorted(want) != sorted(have): reasons.append("missing branch: node %d has %d/%d children" % (i, len(have), len(want))) # terminal discharges for j, nd in enumerate(nodes): if nd["t"] == "unsat" and nd.get("why") == "hall violator": W, N = nd.get("w") or [], nd.get("n") or [] if len(N) >= len(W) or not W: reasons.append("node %d: stored W/N is not a Hall deficiency" % j) continue # N refers to the domains CURRENT AT THAT NODE, which is what makes the # certificate recomputable: the checker derives N from the snapshot the # node carries, not from the original graph (where AC has since pruned). snap = nodes[j]["d"] if len(W) == 0 or max(W) >= n: reasons.append("node %d: violator indices out of range" % j) continue trueN = set().union(*[set(snap[b]) for b in W]) if set(N) != trueN: reasons.append("node %d: stored N is not the neighbourhood of W in the" " node's own snapshot" % j) for b in W: if not set(snap[b]) <= set(inp_allowed[b]): reasons.append("node %d: violator domain is not a subset of the" " original domains" % j) break if nd["t"] == "sat": assign = {} for b, d in enumerate(nd["d"]): if len(d) != 1: reasons.append("node %d: sat with a non-singleton domain" % j) break assign[b] = d[0] else: if len(set(assign.values())) != n: reasons.append("node %d: sat assignment is not injective" % j) for b, v in assign.items(): if v not in inp_allowed[b]: reasons.append("node %d: sat uses a prime not allowed for block %d" % (j, b)) return (not reasons), reasons def corrupt(nodes, kind, allowed): """Four corruption classes; returns a mutated copy.""" out = json.loads(json.dumps(nodes)) if kind == "wrong_intersection": for nd in out: if nd["t"] == "open" and nd["p"] is not None and any(len(d) > 1 for d in nd["d"]): for d in nd["d"]: if len(d) > 1: d.append(max(allowed[0]) ) # not in any domain -> not AC fixed point d.sort() return out if kind == "missing_branch": for j, nd in enumerate(out): if nd["t"] == "open" and nd["p"] == 0: del out[j] return out if kind == "false_union": idx = [j for j, nd in enumerate(out) if nd["t"] == "open" and nd["p"] is not None] if len(idx) >= 2: a, b = idx[0], idx[1] out[a]["d"], out[b]["d"] = out[b]["d"], out[a]["d"] if kind == "fabricated_leaf": for j, nd in enumerate(out): if nd["t"] == "sat": nd["d"][0] = list(nd["d"][0]) nd["d"][0][0] = out[0]["d"][0][0] if False else nd["d"][0][-1] nd["t"] = "sat" return out for j, nd in enumerate(out): if nd["t"] == "cap" or nd["t"] == "open": nd["t"] = "sat" nd["d"] = [[v] for v in allowed[0][:1]] return out return out # ------------------------------------------------------------------------ main def gen_synthetic(rng, n_blocks=9, n_primes=11, lo=2, hi=3): """Route-shaped instance that is NOT trivially over-subscribed: #blocks <= #primes, so the cardinality cut cannot fire on the whole set. Infeasibility (when planted) comes from a deficient SUB-collection: k blocks confined to k-1 primes.""" allowed = [sorted(rng.sample(range(n_primes), rng.randint(lo, hi))) for _ in range(n_blocks)] if rng.random() < 0.75: k = rng.randint(3, 4) S = rng.sample(range(n_blocks), k) T = rng.sample(range(n_primes), k - 1) for b in S: allowed[b] = sorted(rng.sample(T, min(len(T), k - 1))) return [tuple(a) for a in allowed] def synthetic_suite(trials=300, seed=20260915): """Route-shaped instances with domains of size >= 2, so that BOTH arms have to branch. Counts where the Hall arm fires on a node the ablation does not cut.""" rng = random.Random(seed) agg = {"trials": trials, "ablation_root_unsat": 0, "hall_root_unsat": 0, "hall_strictly_fewer_nodes": 0, "node_reduction_total": 0, "hall_leaf_trials": 0, "hall_leaves_total": 0, "checker_honest_ok": 0, "corruptions": {k: 0 for k in ("wrong_intersection", "missing_branch", "false_union", "fabricated_leaf")}, "corruption_applicable": {k: 0 for k in ("wrong_intersection", "missing_branch", "false_union", "fabricated_leaf")}, "cert_bytes_max": 0, "cpu_s_max": 0.0, "honest_rejections": [], "corruption_arm_nodes": []} for trial in range(trials): allowed = gen_synthetic(rng) t0 = time.process_time() a_nodes, a_stats = search(allowed, use_hall=False) h_nodes, h_stats = search(allowed, use_hall=True) agg["cpu_s_max"] = max(agg["cpu_s_max"], round(time.process_time() - t0, 6)) if a_nodes[0]["t"] == "unsat": agg["ablation_root_unsat"] += 1 if h_nodes[0]["t"] == "unsat": agg["hall_root_unsat"] += 1 if len(h_nodes) < len(a_nodes): agg["hall_strictly_fewer_nodes"] += 1 agg["node_reduction_total"] += len(a_nodes) - len(h_nodes) if h_stats["hall_leaves"] > 0: agg["hall_leaf_trials"] += 1 agg["hall_leaves_total"] += h_stats["hall_leaves"] ok, why = check_certificate(allowed, h_nodes) if ok: agg["checker_honest_ok"] += 1 elif len(agg["honest_rejections"]) < 3: agg["honest_rejections"].append({"trial": trial, "reasons": why[:2], "root": h_nodes[0]["t"], "nodes": len(h_nodes)}) agg["cert_bytes_max"] = max(agg["cert_bytes_max"], encode_bytes(h_nodes)) # corruptions run on the BRANCHIER of the two certificates, so the classes are # exercised on real interior records rather than on a one-node root leaf. target = h_nodes if len(h_nodes) >= len(a_nodes) else a_nodes agg["corruption_arm_nodes"].append(len(target)) for kind in agg["corruptions"]: c = corrupt(target, kind, allowed) if c == target: continue agg["corruption_applicable"][kind] += 1 if not check_certificate(allowed, c)[0]: agg["corruptions"][kind] += 1 agg["corruption_arm_max_nodes"] = max(agg["corruption_arm_nodes"] or [0]) del agg["corruption_arm_nodes"] return agg def main(): here = os.path.dirname(os.path.abspath(__file__)) path = os.path.join(here, "coherence974-input.json") import hashlib raw = open(path, "rb").read() inp = json.loads(raw.decode("utf-8")) inst = build_instance(inp) allowed = inst["allowed"] n = len(allowed) out = {"schema": "route19-n1/1", "input_sha256": hashlib.sha256(raw).hexdigest(), "instance": {"slots": len(inst["slots"]), "Q": len(inst["Q"]), "blocks": n, "domain_size_histogram": hist([len(a) for a in allowed]), "allowed_primes_used": len(set().union(*[set(a) for a in allowed])) if allowed else 0}, "caps": {"nodes": CAP_NODES, "decisions": CAP_DECISIONS, "cert_bytes": CAP_CERT_BYTES}} t0 = time.process_time() abl_nodes, abl_stats = search(allowed, use_hall=False) t_abl = time.process_time() - t0 t0 = time.process_time() hall_nodes, hall_stats = search(allowed, use_hall=True) t_hall = time.process_time() - t0 out["arms"] = {} for name, nodes, stats, cpu in (("ablation", abl_nodes, abl_stats, t_abl), ("hall", hall_nodes, hall_stats, t_hall)): ok, reasons = check_certificate(allowed, nodes) out["arms"][name] = {"nodes": len(nodes), "decisions": stats["decisions"], "hall_leaves": stats["hall_leaves"], "card_leaves": stats["card_leaves"], "empty_leaves": stats["empty_leaves"], "truncated": stats["truncated"], "cert_bytes": encode_bytes(nodes), "root_verdict": nodes[0]["t"], "checker_ok": ok, "checker_reasons": reasons[:3], "cpu_s": round(cpu, 6)} # corruption suite on the honest certificate of each arm out["corruptions"] = {} for name, nodes in (("ablation", abl_nodes), ("hall", hall_nodes)): row = {} for kind in ("wrong_intersection", "missing_branch", "false_union", "fabricated_leaf"): c = corrupt(nodes, kind, allowed) if c == nodes: row[kind] = "not_applicable" continue ok, why = check_certificate(allowed, c) row[kind] = "rejected" if not ok else "ACCEPTED(defect)" out["corruptions"][name] = row # N1 decision, stated mechanically a, h = out["arms"]["ablation"], out["arms"]["hall"] out["N1"] = { "hall_leaf_where_ablation_has_none": h["hall_leaves"] > 0 and a["hall_leaves"] == 0, "node_reduction": a["nodes"] - h["nodes"], "cert_under_cap": h["cert_bytes"] <= CAP_CERT_BYTES, "checker_accepts_honest": h["checker_ok"] and a["checker_ok"], "checker_cost_ok": True, # filled below } t0 = time.process_time() check_certificate(allowed, hall_nodes) chk = time.process_time() - t0 out["N1"]["checker_cost_ok"] = chk <= max(1.0, max(t_abl, t_hall) / 5.0) out["checker_cpu_s"] = round(chk, 6) out["discovery_cpu_s"] = round(max(t_abl, t_hall), 6) # The frozen pair instance collapses to singleton domains, so it exercises no # branching. The N1 machinery is therefore exercised on the route-SHAPE suite: # same block/owner-prime structure, domains of size >= 2, both arms branching. out["synthetic_route_shape"] = synthetic_suite() json.dump(out, sys.stdout, indent=1, sort_keys=True) sys.stdout.write("\n") sys.stderr.write("TIMING ablation=%.3fs hall=%.3fs checker=%.3fs\n" % (t_abl, t_hall, chk)) return 0 def hist(xs): h = {} for x in xs: h[str(x)] = h.get(str(x), 0) + 1 return h if __name__ == "__main__": sys.exit(main())