#!/usr/bin/env python3 # -*- coding: utf-8 -*- """rescue19_probe.py - two local experiments for the route 19 rescue. Route 19's obstruction (return #477): the registered binary-tree proof format hits its 2 MB counter before a complete refutation, with 0 Hall cuts in the explored prefix, and the Hall arm produced IDENTICAL counts to its ablation (1821 decisions / 3631 nodes / 1810 cardinality leaves / 110816 deletions) while costing 7.17 s vs 3.95 s. Two questions this file answers with measurements, not prose: E1 (generator). Was the Hall rule weak, or was the CANDIDATE GENERATOR the binding constraint? #477 built candidates from "ascending greedy clique" seeds. A Hausdorff fact from matching theory: the canonical Hall violator is the set of X-vertices M-reachable from an unmatched X-vertex, which is INCLUSION-MINIMAL; a maximal greedy clique is the opposite shape. E1 compares, on the same instances: G-maximal : ascending greedy maximal cliques, Hall-tested as-is G-shrink : the same candidates, shrunk to an inclusion-minimal deficient subset G-violator : maximum matching + M-reachable set (guaranteed violator) and cross-checks all three against brute-force subset enumeration on tiny instances. E2 (encoding). Is the 2 MB cap a SEARCH cost or a CERTIFICATE cost? Same deterministic propagation, same tree, two encodings: Enc-A (materialised): every deleted value is stored with its witness pair Enc-B (recomputable): per node, the domain snapshot + decision; the checker re-derives arc consistency to fixed point measured in bytes and checker CPU, with four corruption classes that must reject. Everything is a local synthetic model of the route's shape. It does NOT rerun D51 and imports no published count. Deterministic: fixed seeds, sorted iteration everywhere. """ from __future__ import annotations import itertools import json import random import sys import time # --------------------------------------------------------------------------- model # Route 19's shape: X = blocks forced to carry distinct owner primes; allowed[x] = the # prime labels still present in x's domain. Infeasible <=> no matching saturating X # <=> a Hall violator exists (Hall's theorem, both directions). def gen_instance(rng, n, m, max_deg): """Random set system: n blocks, primes 0..m-1, each block allows 1..max_deg primes.""" hi = max(1, min(max_deg, m)) return [sorted(rng.sample(range(m), rng.randint(1, hi))) for _ in range(n)] def union_size(allowed, idxs): u = set() for i in idxs: u.update(allowed[i]) return len(u) def is_violator(allowed, idxs): """Hall's condition for the sub-collection idxs: |N(W)| < |W|.""" return union_size(allowed, idxs) < len(idxs) # ------------------------------------------------------------------- matching tools def kuhn(allowed, n): """Maximum matching by Kuhn's augmenting paths. Returns (matchX, matchY).""" matchY = {} matchX = {} def try_augment(x, seen): for y in allowed[x]: if y in seen: continue seen.add(y) if y not in matchY or try_augment(matchY[y], seen): matchY[y] = x matchX[x] = y return True return False for x in range(n): try_augment(x, set()) return matchX, matchY def matching_violator(allowed, n): """The canonical inclusion-minimal Hall violator, or None if X is saturated. Maximum matching, then the set of X-vertices reachable by M-alternating paths from an unmatched X-vertex. Guaranteed to be a violator when one exists (Hall's theorem), and inclusion-minimal by construction. Polynomial. """ matchX, matchY = kuhn(allowed, n) unmatched = [x for x in range(n) if x not in matchX] if not unmatched: return None x0 = unmatched[0] W = {x0} stack = [x0] while stack: x = stack.pop() for y in allowed[x]: x2 = matchY.get(y) if x2 is not None and x2 not in W: W.add(x2) stack.append(x2) W = sorted(W) return W if is_violator(allowed, W) else None def conflict_graph(allowed, n): """H: blocks whose allowed sets overlap are forced to distinct owners.""" adj = {i: set() for i in range(n)} for i, j in itertools.combinations(range(n), 2): if set(allowed[i]) & set(allowed[j]): adj[i].add(j) adj[j].add(i) return adj def greedy_maximal_cliques(allowed, n): """#477's generator: for each seed, ascend vertex indices, adding any vertex adjacent to every current member. Yields maximal cliques.""" adj = conflict_graph(allowed, n) seen = set() out = [] for s in range(n): C = {s} changed = True while changed: changed = False for v in range(n): if v in C: continue if all(v in adj[u] for u in C): C.add(v) changed = True break key = tuple(sorted(C)) if key not in seen: seen.add(key) out.append(sorted(C)) return out def shrink_to_minimal_deficient(allowed, C): """Greedily drop any vertex whose removal keeps the sub-collection deficient.""" C = sorted(C) changed = True while changed: changed = False for v in list(C): trial = [u for u in C if u != v] if trial and is_violator(allowed, trial): C = trial changed = True break return C def brute_force_minimum(allowed, n): """Ground truth for tiny n: minimum-cardinality Hall violator, by enumeration.""" best = None for k in range(2, n + 1): for sub in itertools.combinations(range(n), k): if is_violator(allowed, sub): return list(sub) return best # -------------------------------------------------------------------------- E1 run def experiment_generator(trials=400, seed=20260915, n=14, m=9, max_deg=3): rng = random.Random(seed) stat = {"instances": 0, "infeasible": 0, "maximal_found": 0, "shrink_found": 0, "violator_found": 0, "shrink_beats_maximal": 0, "sizes_maximal_hit": [], "sizes_shrink_hit": [], "sizes_violator": []} for _ in range(trials): allowed = gen_instance(rng, n, m, max_deg) stat["instances"] += 1 truth = matching_violator(allowed, n) infeasible = truth is not None if infeasible: stat["infeasible"] += 1 # G-maximal: the generator as #477 actually used it hit_max = None for C in greedy_maximal_cliques(allowed, n): if is_violator(allowed, C): hit_max = C break # G-shrink: same candidates, minimised hit_shrink = None for C in greedy_maximal_cliques(allowed, n): S = shrink_to_minimal_deficient(allowed, C) if is_violator(allowed, S): hit_shrink = S break if hit_max is not None: stat["maximal_found"] += 1 stat["sizes_maximal_hit"].append(len(hit_max)) if hit_shrink is not None: stat["shrink_found"] += 1 stat["sizes_shrink_hit"].append(len(hit_shrink)) if hit_max is None: stat["shrink_beats_maximal"] += 1 if infeasible: stat["violator_found"] += 1 stat["sizes_violator"].append(len(truth)) # soundness: the canonical violator must actually be deficient, and a maximum # matching must exist exactly when no violator does if infeasible: assert is_violator(allowed, truth), "canonical violator is not deficient" # and it must be inclusion-minimal for the single-vertex removal test if infeasible and len(truth) > 1: assert not any(is_violator(allowed, [u for u in truth if u != v]) for v in truth), "canonical violator is not inclusion-minimal" return stat def cross_check_small(seed=7, n_max=7, trials=300): """Every generator must agree with exhaustive enumeration on tiny instances.""" rng = random.Random(seed) checked = 0 for _ in range(trials): n = rng.randint(3, n_max) m = rng.randint(2, 5) allowed = gen_instance(rng, n, m, 3) truth = brute_force_minimum(allowed, n) got = matching_violator(allowed, n) ok_exist = (truth is None) == (got is None) if not ok_exist: return {"agree": False, "n": n, "allowed": allowed, "brute": truth, "matching": got} if truth is not None: # canonical violator can be larger than the minimum (that is NP-hard), but it # must not be deficient when enumeration finds none, and vice versa if not is_violator(allowed, got): return {"agree": False, "reason": "matching violator not deficient", "n": n, "allowed": allowed} checked += 1 return {"agree": True, "checked": checked} # -------------------------------------------------------------------------- E2 run # CSP of the route's shape: variables = blocks, domain = allowed owners, pairwise != on # conflicting pairs. "Ordinary binary propagation" = AC to fixed point. Branching = # assign a value; contradiction = empty domain. def ac3(domains, adj): """Deterministic AC to fixed point. Returns (new_domains, deletions). deletions: ordered list of (var, value, witness_var) - exactly the reason #477's format materialised for every removed value. """ dom = {v: set(d) for v, d in domains.items()} deletions = [] queue = sorted((u, v) for u in dom for v in adj[u]) qi = 0 while qi < len(queue): u, v = queue[qi] qi += 1 if qi > 400000: break removed = [] for val in sorted(dom[u]): if not any(w != val for w in dom[v]): removed.append(val) for val in removed: dom[u].discard(val) deletions.append((u, val, v)) if removed: for w in sorted(adj[u]): if w != v: queue.append((w, u)) return dom, deletions def search_tree(allowed, n, cap_nodes=4000, cap_bytes=2000000): """Deterministic assignment branching with AC. Returns the tree and both encodings.""" adj = conflict_graph(allowed, n) enc_a = [] # materialised: one record per deletion enc_b = [] # recomputable: one record per node (snapshot + decision) honest_a = [] # ground-truth deletions in order: (node, var, val, why) nodes = leaves = deletions_total = 0 bytes_a = bytes_b = 0 def snapshot(dom): return {str(v): sorted(dom[v]) for v in sorted(dom)} def walk(dom, trail, decision): nonlocal nodes, leaves, deletions_total, bytes_a, bytes_b nodes += 1 dom2, dels = ac3(dom, adj) deletions_total += len(dels) # Enc-A: materialise every reason (this is what #477's format did) for (u, val, w) in dels: rec = {"n": nodes, "var": u, "val": val, "why": w} enc_a.append(rec) honest_a.append((nodes, u, val, w)) bytes_a += len(json.dumps(rec, sort_keys=True)) empty = [v for v in sorted(dom2) if not dom2[v]] target = None for v in sorted(dom2): if len(dom2[v]) > 1: target = v break if empty: verdict, branches = "unsat", [] elif target is None: verdict, branches = "sat", [] elif bytes_a >= cap_bytes or bytes_b >= cap_bytes or nodes >= cap_nodes: verdict, branches = "capped", [] else: verdict, branches = "open", sorted(dom2[target]) # Enc-B: store the domain snapshot, the branch set and the verdict; the checker # recomputes the fixed point instead of replaying any deletion reason. rec = {"n": nodes, "trail": list(trail), "decision": decision, "branches": branches, "verdict": verdict, "dom": snapshot(dom2)} enc_b.append(rec) bytes_b += len(json.dumps(rec, sort_keys=True, separators=(",", ":"))) if verdict == "open": for val in branches: sub = {u: set(dom2[u]) for u in dom2} sub[target] = {val} r = walk(sub, trail + [(target, val)], [target, val]) if r == "sat": leaves += 1 return "sat" leaves += 1 return verdict start = {v: set(allowed[v]) for v in range(n)} verdict = walk(start, [], None) return {"verdict": verdict, "nodes": nodes, "leaves": leaves, "deletions": deletions_total, "enc_a_bytes": bytes_a, "enc_a_records": len(enc_a), "enc_b_bytes": bytes_b, "enc_b_records": len(enc_b), "enc_a": enc_a, "enc_b": enc_b, "honest_deletions": honest_a, "adj": {k: sorted(v) for k, v in adj.items()}} def check_enc_b(allowed, n, enc_b): """Independent checker for the recomputable certificate. Trusts no deletion. Two obligations, both cheap: (1) each record's domain snapshot really IS the arc-consistent fixed point reached from the root along its own trail (recomputation, the RUP idea: the checker re-derives the reason instead of replaying a stored one); (2) the tree is COMPLETE: every record marked "open" has child records covering its branch set, and the leaves partition consistently. A dropped branch therefore fails even though no deletion was ever written down. """ adj = conflict_graph(allowed, n) for rec in enc_b: dom = {v: set(allowed[v]) for v in range(n)} for (v, val) in rec["trail"]: dom[v] = {val} dom, _ = ac3(dom, adj) got = ac3(dom, adj)[0] want = {int(v): set(vals) for v, vals in rec["dom"].items()} if got != want: return False, "snapshot-not-a-fixed-point@%s" % rec["n"] # (2) completeness of the branch structure by_trail = {tuple(r["trail"]): r for r in enc_b} if tuple() not in by_trail: return False, "no root record" for rec in enc_b: if rec["verdict"] != "open": continue t = tuple(rec["trail"]) kids = {k for k in by_trail if len(k) == len(t) + 1 and k[:len(t)] == t} if len(kids) != len(rec["branches"]): return False, "incomplete-branches@%s" % rec["n"] for k in kids: if k[-1][1] not in rec["branches"]: return False, "branch-outside-recorded-set@%s" % rec["n"] return True, None def witness_only_check(adj, enc_a): """The strongest check a per-deletion witness record supports. A record (var, val, why) can only be tested for the NECESSARY condition that `why` is a neighbour of `var`. Whether val really lost every support is a statement about `why`'s CURRENT domain - a state the record does not carry. This function is therefore deliberately weak, and the point of the experiment is that it is weak. """ for rec in enc_a: if rec["why"] not in adj.get(rec["var"], []): return False return True def replay_check(allowed, n, enc_a, honest): """The check that actually certifies: recompute the deterministic propagation and require the recorded deletion multiset to match. Needs the domain state, which is the thing the materialised format does not store.""" if len(enc_a) != len(honest): return False, "deletion-count %d != replayed %d" % (len(enc_a), len(honest)) for got, want in zip(enc_a, honest): if (got["n"], got["var"], got["val"], got["why"]) != tuple(want): return False, "deletion mismatch at node %s" % got["n"] return True, None def find_nontrivial_instance(cap_nodes=1200): """Pick a deterministic instance whose tree is non-trivial, so no control is vacuous. Deterministic scan in fixed order; returns the largest tree found. Most random instances of this shape collapse at the root (pairwise propagation is strong), which is itself worth knowing, so the scan is part of the record. """ best = None for n in (12, 16, 20, 24): for m in (7, 12, 19): for max_deg in (3, 4): for s in range(0, 80): allowed = gen_instance(random.Random(s), n, m, max_deg) t = search_tree(allowed, n, cap_nodes=cap_nodes) if best is None or t["nodes"] > best[2]["nodes"]: best = (s, allowed, t, n, m, max_deg) if best is None: return None, None, None s, allowed, t, n, m, max_deg = best t["instance_seed"] = s t["instance_params"] = {"n": n, "m": m, "max_deg": max_deg} return s, allowed, t def experiment_encoding(): seed, allowed, tree = find_nontrivial_instance() if tree is None: return {"error": "no non-trivial instance found"}, None, None, {} n = len(allowed) ok, bad = check_enc_b(allowed, n, tree["enc_b"]) controls = {} # 1. wrong intersection / false fixed point: claim a value the propagation removes enc_b1 = [{**r} for r in tree["enc_b"]] d = {k: list(v) for k, v in enc_b1[-1]["dom"].items()} k0 = sorted(d)[0] d[k0] = sorted(set(d[k0]) | {999}) enc_b1[-1] = {**enc_b1[-1], "dom": d} controls["wrong_intersection"] = not check_enc_b(allowed, n, enc_b1)[0] # 2. missing branch: drop an interior record enc_b2 = [{**r} for r in tree["enc_b"] if r["verdict"] != "open"] + \ [{**r} for r in tree["enc_b"] if r["verdict"] == "open"][1:] controls["missing_branch"] = not check_enc_b(allowed, n, enc_b2)[0] # 3. false union: swap two nodes' snapshots enc_b3 = [{**r} for r in tree["enc_b"]] a, b = enc_b3[0], enc_b3[-1] enc_b3[0] = {**a, "dom": b["dom"]} enc_b3[-1] = {**b, "dom": a["dom"]} controls["false_union"] = not check_enc_b(allowed, n, enc_b3)[0] # 4. unsupported deletion: corrupt a witness to a non-neighbour enc_a4 = [dict(r) for r in tree["enc_a"]] enc_a4[0] = {**enc_a4[0], "why": 12345} controls["non_neighbour_witness"] = not witness_only_check(tree["adj"], enc_a4) # The decisive Enc-A measurement: a FABRICATED deletion that looks perfectly # plausible. The witness-only check cannot see it; only a replay can. This is the # structural reason the materialised format is not a certificate. honest_ok_w, _ = witness_only_check(tree["adj"], tree["enc_a"]), None rep_ok, rep_err = replay_check(allowed, n, tree["enc_a"], tree["honest_deletions"]) last = tree["enc_b"][-1]["n"] v0, y0 = 0, sorted(tree["adj"].get(0, []))[0] if tree["adj"].get(0) else 0 fabricate = [dict(r) for r in tree["enc_a"]] + [ {"n": last, "var": v0, "val": -7, "why": y0}] controls["fabricated_deletion_caught_by_witness_only"] = not witness_only_check( tree["adj"], fabricate) # expected False: the format is blind to it controls["fabricated_deletion_caught_by_replay"] = not replay_check( allowed, n, fabricate, tree["honest_deletions"])[0] tree["instance_seed"] = seed tree["n"] = n tree["honest_materialised_passes_witness_only"] = honest_ok_w tree["honest_materialised_passes_replay"] = rep_ok tree["replay_error_on_honest"] = rep_err for k in ("enc_a", "enc_b", "adj", "honest_deletions"): tree.pop(k, None) return tree, ok, bad, controls # ------------------------------------------------------------------------ d51 arithmetic def reported_receipt_arithmetic(): """The published #477 figures, and what they imply about where the cap was spent. No new computation of D51: this is arithmetic on the numbers #477 itself recorded. """ attempted_bytes = 2000250 nodes, leaves, deletions = 3631, 1810, 110816 return { "attempted_proof_bytes": attempted_bytes, "nodes": nodes, "leaves": leaves, "deletions": deletions, "bytes_per_node": round(attempted_bytes / nodes, 2), "bytes_per_deletion": round(attempted_bytes / deletions, 2), "deletions_per_leaf": round(deletions / leaves, 1), # if the certificate materialised one reason per deletion at ~18 bytes, the cap is # reached by the reason log alone well before the 200000-decision budget: "reason_log_bytes_at_18B": deletions * 18, "deletion_log_dominates": deletions * 18 > attempted_bytes * 0.9, } def main() -> int: t0 = time.time() out = {} out["E1_generator"] = experiment_generator() out["E1_cross_check"] = cross_check_small() tree, ok, bad, controls = experiment_encoding() out["E2_encoding"] = { "instance_seed": tree.get("instance_seed"), "instance_params": tree.get("instance_params"), "n_vars": tree.get("n"), "verdict": tree["verdict"], "nodes": tree["nodes"], "leaves": tree["leaves"], "deletions": tree["deletions"], "bytes_per_node_materialised": round(tree["enc_a_bytes"] / max(1, tree["nodes"]), 2), "enc_a_bytes": tree["enc_a_bytes"], "enc_a_records": tree["enc_a_records"], "enc_b_bytes": tree["enc_b_bytes"], "enc_b_records": tree["enc_b_records"], "enc_a_over_enc_b": round(tree["enc_a_bytes"] / max(1, tree["enc_b_bytes"]), 2), "checker_accepts_honest_b": ok, "checker_rejected_at_node": bad, "honest_materialised_passes_witness_only": tree.get( "honest_materialised_passes_witness_only"), "honest_materialised_passes_replay": tree.get("honest_materialised_passes_replay"), "controls": controls, } out["D51_reported_arithmetic"] = reported_receipt_arithmetic() # stdout is the artifact and must reproduce byte for byte elsewhere: no timing, no # progress, no host paths. Elapsed time goes to stderr only. print(json.dumps(out, indent=2, ensure_ascii=False, sort_keys=True)) print("\n[wall %.3f s on this host]" % (time.time() - t0), file=sys.stderr) g = out["E1_generator"] e = out["E2_encoding"] print("\n--- headline ---", file=sys.stderr) print("E1 on %d instances (%d infeasible): greedy-maximal cliques found a Hall " "violator on %d; the canonical matching violator exists on %d; shrinking the " "SAME candidates found %d (+%d that maximality hid)" % (g["instances"], g["infeasible"], g["maximal_found"], g["violator_found"], g["shrink_found"], g["shrink_beats_maximal"]), file=sys.stderr) c = e["controls"] print("E2 same tree, two encodings: materialised %d B in %d reason records vs " "recomputable %d B in %d node records (%.2fx smaller); recomputable checker " "accepts honest=%s and rejects wrong_intersection=%s missing_branch=%s " "false_union=%s; witness-only sees non-neighbour=%s but sees a FABRICATED " "deletion=%s, which the replay check catches=%s" % (e["enc_a_bytes"], e["enc_a_records"], e["enc_b_bytes"], e["enc_b_records"], e["enc_a_over_enc_b"], e["checker_accepts_honest_b"], c.get("wrong_intersection"), c.get("missing_branch"), c.get("false_union"), c.get("non_neighbour_witness"), c.get("fabricated_deletion_caught_by_witness_only"), c.get("fabricated_deletion_caught_by_replay")), file=sys.stderr) return 0 if __name__ == "__main__": sys.exit(main())