diff --git a/research/mutable-source-789q-invoice/CERTIFICATE.json b/research/mutable-source-789q-invoice/CERTIFICATE.json new file mode 100644 index 0000000000..6f772aadbf --- /dev/null +++ b/research/mutable-source-789q-invoice/CERTIFICATE.json @@ -0,0 +1,132 @@ +{ + "schema_version": 1, + "status": "PASS_MUTABLE_SOURCE_789Q_INVOICE", + "scope": "Path-lowered even-subset schedules on connector prefixes for the five-source common-B mutable-source connector; complete-call tariff (b,a,x)=(38,2,2) from PR1898.", + "comparators": { + "six_query_endpoint": { + "Q": 6, + "R": 96, + "X": 8, + "map_leaves": 264, + "echo_nodes": 54, + "root_dispatches": 110, + "borrowed_dirty_rows": 4, + "tariff": 436, + "complete_prices": { + "b": 38, + "a": 2, + "x": 2 + } + }, + "ten_query_four_X": { + "Q": 10, + "R": 62, + "X": 4, + "map_leaves": 342, + "echo_nodes": 90, + "root_dispatches": 76, + "borrowed_dirty_rows": 4, + "tariff": 512, + "complete_prices": { + "b": 38, + "a": 2, + "x": 2 + } + } + }, + "Q7": { + "R_spectrum_distinct_slots": { + "covering_sets": 583296, + "attainable_R": [ + 82, + 88 + ], + "histogram": { + "82": 97216, + "88": 486080 + }, + "intermediate_R_83_to_87_count": 0, + "argument": "Exhaustive even-subset R over all C(31,6) distinct nonzero 6-slot sets; covering sets attain only R in {82,88}. Under tariff 38Q+2R+2X, beating 436 requires R+X<85, so excluded intermediate R in {83..87} with low X cannot undercut; R=88 forces tariff>=442 even at X=0." + }, + "min_R_distinct_slots": { + "min_R": 82, + "witness_count": 97216, + "first_witness": [ + 0, + 1, + 2, + 4, + 8, + 15, + 16 + ] + }, + "min_X_among_min_R": { + "target_R": 82, + "covering_sets": 97216, + "min_X": 6, + "sets_with_X_eq_6": 14595, + "sets_with_X_below_6": 0, + "champion_path": [ + 0, + 1, + 2, + 6, + 12, + 24, + 16, + 0 + ] + }, + "tariff_floor_from_spectrum": { + "beat_436_requires_R_plus_X_lt": 85, + "exact_min_requires_R_plus_X_ge": 88, + "R82_min_X": 6, + "R82_tariff_floor": 442, + "R88_X_ge_0_tariff_floor": 442, + "min_tariff": 442 + }, + "champion_invoice": { + "Q": 7, + "R": 82, + "X": 6, + "map_leaves": 278, + "echo_nodes": 63, + "root_dispatches": 95, + "borrowed_dirty_rows": 4, + "tariff": 442, + "complete_prices": { + "b": 38, + "a": 2, + "x": 2 + } + }, + "beats_six_query": false + }, + "Q8": { + "min_R_distinct_slots": { + "min_R": 74, + "witness_count": 416640, + "first_witness": [ + 0, + 1, + 2, + 3, + 4, + 8, + 16, + 29 + ] + }, + "tariff_lower_bound_X_ge_0": 452, + "beats_six_query": false + }, + "Q9": { + "R_lower_bound": 62, + "tariff_lower_bound": 466, + "beats_six_query": false, + "argument": "Each of 31 masks needs an even nonempty readout set, so R >= 62." + }, + "conclusion": "Under this schedule class and abstract tariff, no path-lowered even-subset word with Q in {7,8,9} beats the sharp six-query endpoint tariff 436. Q=7 exact minimum 442 follows from the certified R spectrum {82,88} plus min X=6 on R=82.", + "new_kappa": false +} diff --git a/research/mutable-source-789q-invoice/NOTICE.md b/research/mutable-source-789q-invoice/NOTICE.md new file mode 100644 index 0000000000..750019ec85 --- /dev/null +++ b/research/mutable-source-789q-invoice/NOTICE.md @@ -0,0 +1,6 @@ +This package was prepared by Wentao Li with substantial AI assistance. +New material is Apache-2.0 under the repository LICENSE. + +Predecessor credit: Arham Tahir (PR1898/PR1370), ywz65 (PR2455), +TennisBowling (PR1524), Ross Richardson (PR943), and the retained +mutable-source connector lineage. Their notices and licenses remain. diff --git a/research/mutable-source-789q-invoice/PROOF.md b/research/mutable-source-789q-invoice/PROOF.md new file mode 100644 index 0000000000..7a77c85dac --- /dev/null +++ b/research/mutable-source-789q-invoice/PROOF.md @@ -0,0 +1,41 @@ +# Path-lowered 7–9 query invoices versus the six-query endpoint + +Retain the five-source common-B mutable-source alphabet of PR1340/PR1898: +queries `Q_j: z += B x_j`, readouts `R_m: y_m += A_m z`, and paid source shears +`X_(s,t)`. Correctness is required for every admissible exact `B`, `A_m` and +every arbitrary dirty input, with sources, connector and scratch restored. + +Specialize to length-one identity maps. Connector prefixes are vectors in +`F₂⁵`. A **path-lowered even-subset schedule** chooses a closed walk +`p_0=0,p_1,…,p_Q=0` whose increments span `F₂⁵`, reads each nonzero mask on a +minimum even subset of the identified slots `{p_0,…,p_{Q-1}}`, and implements +each multi-bit edge by compute/uncompute into one target source (cost +`2(wt(δ)-1)`). + +The PR1898 abstract fixture charges `(b,a,x)=(38,2,2)` complete-call units, so + + tariff = 38 Q + 2 R + 2 X. + +**Q=6.** PR1898 attains and proves minimum `R=96` with attained `X=8`, tariff +436. PR2455 proves `X≥8` at six queries, so 436 is exact in this class. + +**Q=7.** Every 6-subset `S⊂F₂⁵\{0}` is scored for even-subset `R` on slots +`{0}∪S`. Covering sets attain only `R∈{82,88}` (histograms 97,216 and +486,080); none land in `{83..87}`. Beating the six-query endpoint under this +fixture requires `R+X<85`, so the excluded intermediate band cannot undercut +436 even at `X=0`, and every `R=88` schedule already pays at least +`38·7 + 2·88 = 442`. For each of the 97,216 sets with `R=82`, every full-rank +ordering closed at 0 is scored for path-local `X`. None has `X<6`; 14,595 +attain `X=6`. Thus the `R=82` layer also pays at least +`38·7 + 2·82 + 2·6 = 442`. The champion `[0,1,2,6,12,24,16,0]` attains that +floor, so the exact minimum tariff is `442 > 436`. + +**Q=8.** Among distinct 7-nonzero slot sets the minimum even-subset `R` is 74, +so with `X≥0` the tariff is at least `38·8 + 2·74 = 452 > 436`. + +**Q=9.** Already `R≥62` (one even nonempty readout set per mask), so the tariff +is at least `38·9 + 2·62 = 466 > 436`. + +Hence no path-lowered even-subset word with `Q∈{7,8,9}` beats the six-query +endpoint under this fixture. Words that share shear work across edges outside +path-local compute/uncompute are outside this theorem. diff --git a/research/mutable-source-789q-invoice/README.md b/research/mutable-source-789q-invoice/README.md new file mode 100644 index 0000000000..73cde7403b --- /dev/null +++ b/research/mutable-source-789q-invoice/README.md @@ -0,0 +1,110 @@ +# Seven–nine query invoices cannot beat the six-query mutable-source endpoint + +**Priced finite invoice under the PR1898 abstract complete-call tariff; no new κ.** +Answers open question 1 of +[CrocSwap/integer-mult-bounds#2455](https://github.com/CrocSwap/integer-mult-bounds/pull/2455) +/ the unequal-price handoff of merged +[PR1898](https://github.com/CrocSwap/integer-mult-bounds/pull/1898): bound attainable +`R`/`X` bills at seven, eight and nine queries for the explicit fixture +`(b,a,x)=(38,2,2)`. + +Under **path-lowered even-subset schedules** on connector prefixes (the same +schedule class as PR1898's minimum-query word and PR1370's four-X path), no +word with `Q ∈ {7,8,9}` beats the sharp six-query endpoint tariff **436**. + +| Q | Exact / bound | R | X | Abstract tariff | vs 436 | +|---|---|---:|---:|---:|---| +| 6 (PR1898 endpoint) | exact | 96 | 8 | **436** | — | +| **7 (this)** | **exact minimum** (R∈{82,88}) | **82** | **6** | **442** | **+6** | +| 8 | lower bound | ≥74 | ≥0 | **≥452** | +≥16 | +| 9 | lower bound | ≥62 | ≥0 | **≥466** | +≥30 | +| 10 (PR1370 four-X) | attained | 62 | 4 | 512 | +76 | + +The seven-query minimum is certificate-closed. Every 6-subset of nonzero F₂⁵ +points is scored for even-subset readout cost: covering sets attain only +`R∈{82,88}` (97,216 / 486,080; none in `{83..87}`). Under tariff +`38Q+2R+2X`, beating 436 needs `R+X<85`, so the excluded intermediate band +cannot undercut even at `X=0`, and `R=88` already forces tariff `≥442`. On the +`R=82` layer, every full-rank Hamiltonian closing is scored for path-local +source-XOR cost (no set has `X<6`; 14,595 attain `X=6`), so that layer is also +`≥442`. Champion path `[0,1,2,6,12,24,16,0]` attains `7 Q / 82 R / 6 X` and +replays on arbitrary dirty formal rows. The eight-query bound is the +exhaustive minimum `R=74` over all distinct 7-nonzero slot sets (`X≥0`). Nine +queries cannot undercut 436 because already `R≥62` forces tariff `≥466`. + +This does **not** price arbitrary XOR-interleaved words outside path-local +compute/uncompute lowering, nor claim a physical supplier tariff or new κ. + +## Reproduce + +Python **3.12**, standard library only, from the repository root: + +```sh +python3.12 -I -B research/mutable-source-789q-invoice/verify.py +python3.12 -I -O -B research/mutable-source-789q-invoice/verify.py +python3.12 -I -B research/mutable-source-789q-invoice/independent.py +python3.12 -I -B research/mutable-source-789q-invoice/test_package.py +python3.12 scripts/research_package.py --package research/mutable-source-789q-invoice +``` + +Expected: + +```text +PASS_MUTABLE_SOURCE_789Q_INVOICE Q6=436 Q7=442 Q8_floor=452 Q9_floor=466 no_new_kappa +PASS_INDEPENDENT_789Q_INVOICE champion=442 floors=452,466 R_spectrum=[82, 88] controls=2 +PASS_REGISTERED_RESEARCH_PACKAGE research/mutable-source-789q-invoice outcome=completed +``` + +First-time certificate generation (authoring only): + +```sh +python3.12 -I -B research/mutable-source-789q-invoice/verify.py --write +``` + +Default verify is read-only and compares the fresh census to +[CERTIFICATE.json](CERTIFICATE.json). Admission uses `need()` (not `assert`); +`-O` also passes. The principal census takes on the order of a few minutes. + +## Evidence map + +| Claim | Where | +|---|---| +| 6Q/10Q comparator invoices | `model.minimum_word_6q`, `model.four_x_ten_q` | +| Exact min R at Q=7 | exhaustive `combinations(range(1,32),6)` in `verify.py` | +| Attainable R spectrum `{82,88}` | same census; histogram in `CERTIFICATE.json`; rechecked by `independent.py` | +| Exact min X among R=82 sets | exhaustive full-rank path orders; no `X<6` | +| Exact min tariff 442 / no beat 436 | spectrum floors + min-X layer; machine-checked in `verify.py` | +| Champion identity + tariff 442 | `path_word` + formal dirty replay; `independent.py` column image | +| Q=8 R≥74 | exhaustive distinct 7-nonzero slot sets | +| Q=9 tariff ≥466 | `R≥62` for 31 masks | + +## Scope limits + +No new kappa, frontier, native/hosted admission, or compiler/tape claim. The +schedule class is path-lowered even-subset readout words with the PR1898 +abstract leaf/node/dispatch fixture. Global unequal-price optimality over all +XOR interleavings remains open. Physical common-B source access remains open. + +## Open next questions + +1. **Can a non-path XOR schedule at seven queries reach X≤2 with R=82 (tariff ≤436)?** + Why it matters: shared shear preparation across edges might beat path-local + compute/uncompute. First step: search restored source programs of X-length + ≤2 that realize the champion prefix increments. Blocked by: no cheaper + shared-XOR witness is known. +2. **What is the exact minimum R at eight queries allowing repeated prefix values?** + Why it matters: the distinct-slot bound R≥74 already excludes beating 436, + but repeats could matter for other tariffs. First step: meet-in-the-middle + over 8-tuples. Blocked by: larger search. + +## Credit + +Credit **Arham Tahir / PR1898** (minimum-query endpoint, abstract tariff fixture, +unequal-price handoff), **PR1370** (four-X path and ten-query paired word), +**ywz65 / PR2455** (sharp eight XORs at six queries; open question answered +here), **TennisBowling / PR1524** (equal-price theorem / unequal handoff), +**Ross Richardson / PR943** (prefix framework), and the retained mutable-source +lineage. Prepared by Wentao Li +([VictorLiwentao](https://github.com/VictorLiwentao), +[@Is__Victor](https://x.com/Is__Victor)) with substantial AI assistance. +Apache-2.0. No independent human review or multiplication theorem is claimed. diff --git a/research/mutable-source-789q-invoice/SOURCES.json b/research/mutable-source-789q-invoice/SOURCES.json new file mode 100644 index 0000000000..bf2ff46de9 --- /dev/null +++ b/research/mutable-source-789q-invoice/SOURCES.json @@ -0,0 +1,24 @@ +{ + "schema_version": 1, + "base_commit": "0b1cccf86e2f5132ed286a26ef0a681a495740ea", + "files": [ + { + "path": "research/mutable-source-shear-cost/CERTIFICATE.json", + "usage": "input", + "git_blob": "48958451bc819f2caa13bf3d9609423706ffb8a0", + "sha256": "665435375c025bbcf69eadf43bd9aeae44eb12fefdf12a78d5bfd66abde4ae3c" + }, + { + "path": "certificates/selected-result.json", + "usage": "provenance", + "git_blob": "ae6a99f28aa468649eb66a361e764d769363bf11", + "sha256": "10b9e340fd8e354a37a0c4813c90e5de1dd42044b5f6aca4a3fc5a42b685fa32" + }, + { + "path": "docs/research/agent-task-catalog.json", + "usage": "provenance", + "git_blob": "06c96f5579bb67ed1b86d334e78fbed7da6945f1", + "sha256": "6686ad58f1fbdbc87134a78901b60fd53a20d3984355e91defbbebc9e9fa8075" + } + ] +} diff --git a/research/mutable-source-789q-invoice/TASK.json b/research/mutable-source-789q-invoice/TASK.json new file mode 100644 index 0000000000..4f70c56a5f --- /dev/null +++ b/research/mutable-source-789q-invoice/TASK.json @@ -0,0 +1,80 @@ +{ + "schema_version": 1, + "task_id": "connector-alphabet-change", + "priority_revision": 4, + "base_commit": "0b1cccf86e2f5132ed286a26ef0a681a495740ea", + "original_card": { + "id": "connector-alphabet-change", + "question": "Does one explicit extension of the connector alphabet offer a favorable completed budget?", + "starting_points": [ + "research/universal-connector-boundary/README.md", + "certificates/selected-result.json" + ], + "methods": [ + "Construct and charge a legal extra operation on a minimal instance.", + "Prove a target-specific bound after adding one specified operation family." + ], + "acceptance_gate": "State which fixed-alphabet premise changes and charge its implementation; do not declare it free.", + "first_step": { + "command": [ + "python3", + "-B", + "research/universal-connector-boundary/verify.py" + ], + "expected": "PASS_UNIVERSAL_CONNECTOR_BOUNDARY", + "inspect": "Reproduce the 945-pairing control, then read Exact interface to list the allowed calls.", + "scope": "Positive control / source-bound orientation only; this is not a new construction or full cold replay." + }, + "first_experiment": "Add exactly one legally priced operation and test a tiny dirty-input instance before enumerating larger cases.", + "bottleneck_link": "A new legal connector operation could change recursive interface cost; a larger census in the same alphabet is a separate side result.", + "allowed_variations": [ + "Choose one additional operation and a small source count for its first counterexample." + ], + "scope_change_triggers": [ + "Keeping the alphabet and only increasing the source count; record this as a changed assignment." + ], + "overlap_terms": [ + "universal connector", + "source-toggle", + "connector alphabet" + ] + }, + "scope_status": "changed", + "actual_scope": "Price path-lowered even-subset R/X bills at Q=7,8,9 under the PR1898 abstract tariff (38,2,2) and compare to the sharp six-query endpoint 436; answer #2455 OQ1 / #1898 unequal-price handoff.", + "scope_change_reason": "The drawn connector-alphabet card is refined to the explicitly open intermediate-query invoice left by PR1898/PR2455 on the already-admitted mutable-source alphabet, rather than proposing another alphabet extension.", + "bottleneck_link": "An intermediate query count that undercuts the six-query abstract tariff would change which unequal-price endpoint is preferred; a negative invoice closes that route inside the stated schedule class.", + "budget_minutes": 60, + "stop_rule": "Stop after exact Q=7 minimum, Q=8/Q=9 lower bounds, independent replay and certificate; no physical supplier search.", + "outcome": "completed", + "evidence": "CERTIFICATE.json exhaustive Q=7 R-spectrum {82,88} plus min-X on R=82; champion 7/82/6 tariff 442; Q=8 R>=74 floor 452; Q=9 floor 466; independent spectrum+column-image replay.", + "author": "Wentao Li", + "ai_assistance": "Substantial AI assistance for derivation, census implementation, checking and writing.", + "open_questions": [ + { + "question": "Can a non-path XOR schedule at seven queries reach X<=2 with R=82 (tariff <=436)?", + "why_it_matters": "Shared shear preparation might beat path-local compute/uncompute and reopen an intermediate optimum.", + "first_step": "Search restored source programs of X-length at most 2 realizing the champion prefix increments.", + "blocked_by": "No cheaper shared-XOR witness is known." + }, + { + "question": "What is the exact minimum R at eight queries allowing repeated prefix values?", + "why_it_matters": "Distinct-slot R>=74 already excludes beating 436 under this tariff, but repeats matter for other price ratios.", + "first_step": "Meet-in-the-middle over length-8 prefix tuples.", + "blocked_by": "Larger search than the distinct-slot census." + } + ], + "predecessors": [ + { + "pr": 1898, + "credit": "Arham Tahir; minimum-query endpoint, abstract tariff, unequal-price handoff" + }, + { + "pr": 2455, + "credit": "ywz65; sharp eight XORs at six queries; OQ1 answered here" + }, + { + "pr": 1370, + "credit": "Arham Tahir; four-X path / ten-query paired word" + } + ] +} diff --git a/research/mutable-source-789q-invoice/VERIFY.json b/research/mutable-source-789q-invoice/VERIFY.json new file mode 100644 index 0000000000..dcd0ef5ac4 --- /dev/null +++ b/research/mutable-source-789q-invoice/VERIFY.json @@ -0,0 +1,53 @@ +{ + "schema_version": 1, + "status": "ready", + "python": "3.12", + "requirements": [], + "inputs": [ + "research/mutable-source-shear-cost/CERTIFICATE.json" + ], + "commands": [ + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 600, + "checks": "Full exhaustive Q=7 R-spectrum + min-X census, tariff floor from spectrum, Q=8/Q=9 floors, champion identity, certificate match, source pins" + }, + { + "argv": [ + "{python}", + "-I", + "-O", + "-B", + "{package}/verify.py", + "--quick" + ], + "timeout_seconds": 180, + "checks": "Champion/spectrum-floor quick replay under PYTHONOPTIMIZE; admission via need() not assert" + }, + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/independent.py" + ], + "timeout_seconds": 120, + "checks": "Separate column-image champion replay, independent Q=7 R-spectrum census, tariff arithmetic" + }, + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/test_package.py" + ], + "timeout_seconds": 300, + "checks": "Corruption rejection and quick/admission controls" + } + ] +} diff --git a/research/mutable-source-789q-invoice/independent.py b/research/mutable-source-789q-invoice/independent.py new file mode 100644 index 0000000000..ae6dfc1ed6 --- /dev/null +++ b/research/mutable-source-789q-invoice/independent.py @@ -0,0 +1,206 @@ +#!/usr/bin/env python3 +"""Independent column-image replay, Q=7 R-spectrum census, and tariff arithmetic. + +Does not import model.py or verify.py. Wentao Li + AI, Apache-2.0. +""" +from __future__ import annotations + +import json +from collections import Counter +from itertools import combinations +from pathlib import Path + +HERE = Path(__file__).resolve().parent +CHAMPION = (0, 1, 2, 6, 12, 24, 16, 0) + + +def fail(message): + raise SystemExit(f"FAIL_INDEPENDENT: {message}") + + +def invoice(q, r, x): + # Same abstract complete-call fixture as PR1898: (b,a,x)=(38,2,2). + leaves = 28 * q + r + nodes = 9 * q + dispatch = q + r + x + return leaves + nodes + x + dispatch + + +def even_R(slots): + n = len(slots) + best = [99] * 32 + for bits in range(1 << n): + if bits.bit_count() % 2: + continue + value = 0 + for i in range(n): + if bits >> i & 1: + value ^= slots[i] + size = bits.bit_count() + if size < best[value]: + best[value] = size + if any(best[mask] >= 99 for mask in range(1, 32)): + return None + return sum(best[1:]) + + +def census_q7_R_spectrum(): + """Independent exhaustive even-subset R over all distinct 6-nonzero slot sets.""" + hist = Counter() + covering = 0 + for nonzero in combinations(range(1, 32), 6): + total = even_R((0,) + nonzero) + if total is None: + continue + covering += 1 + hist[total] += 1 + attainable = sorted(hist) + if attainable != [82, 88]: + fail(f"R spectrum {attainable}") + if dict(hist) != {82: 97216, 88: 486080}: + fail(f"R histogram {dict(hist)}") + if covering != 583296: + fail(f"covering count {covering}") + # Tariff floors from spectrum alone (X>=0 on R=88; R=82 needs separate X layer). + if invoice(7, 88, 0) != 442: + fail("R=88 X=0 floor") + if invoice(7, 82, 6) != 442: + fail("R=82 X=6 floor") + # Intermediate R in {83..87} with X=0 would undercut 436; spectrum excludes them. + for r in range(83, 88): + if invoice(7, r, 0) < 436 and r in hist: + fail(f"intermediate R={r} present") + return attainable, covering, dict(hist) + + +def path_x(closed): + total = 0 + for a, b in zip(closed, closed[1:]): + delta = a ^ b + if delta == 0: + fail("zero edge") + total += 2 * (delta.bit_count() - 1) + return total + + +def replay(closed): + if len(closed) < 2 or closed[0] != 0 or closed[-1] != 0: + fail("path must be closed at 0") + slots = closed[:-1] + reads = {} + n = len(slots) + for mask in range(1, 32): + found = None + for size in range(2, n + 1, 2): + for subset in combinations(range(n), size): + value = 0 + for i in subset: + value ^= slots[i] + if value == mask: + found = subset + break + if found is not None: + break + if found is None: + fail(f"mask {mask} uncovered") + reads[mask] = found + + matrix = [[1 if i == j else 0 for j in range(5)] for i in range(5)] + z = [0] * 5 + outputs = {m: [0] * 5 for m in range(1, 32)} + + def apply_X(s, t): + for j in range(5): + matrix[t][j] ^= matrix[s][j] + + for step in range(len(closed) - 1): + for mask, subset in reads.items(): + if step in subset: + for j in range(5): + outputs[mask][j] ^= z[j] + delta = closed[step] ^ closed[step + 1] + target = (delta & -delta).bit_length() - 1 + donors = [j for j in range(5) if j != target and delta >> j & 1] + for j in donors: + apply_X(j, target) + for j in range(5): + z[j] ^= matrix[target][j] + if z != [(closed[step + 1] >> j) & 1 for j in range(5)]: + fail(f"connector drift at step {step}: {z} vs {closed[step + 1]}") + for j in reversed(donors): + apply_X(j, target) + + if z != [0] * 5: + fail("connector not restored") + identity = [[1 if i == j else 0 for j in range(5)] for i in range(5)] + if matrix != identity: + fail("sources not restored") + for mask in range(1, 32): + want = [(mask >> j) & 1 for j in range(5)] + if outputs[mask] != want: + fail(f"bad output mask {mask}: {outputs[mask]} != {want}") + r = even_R(slots) + if r is None: + fail("even_R failed") + return r, path_x(closed) + + +def main(): + cert = json.loads((HERE / "CERTIFICATE.json").read_text()) + r, x = replay(CHAMPION) + if not (r == 82 and x == 6): + fail(f"champion R/X {r}/{x}") + if invoice(7, r, x) != 442: + fail("champion tariff") + if invoice(6, 96, 8) != 436: + fail("6Q tariff") + if invoice(10, 62, 4) != 512: + fail("10Q tariff") + if invoice(8, 74, 0) != 452: + fail("8Q floor") + if invoice(9, 62, 0) != 466: + fail("9Q floor") + if cert["Q7"]["champion_invoice"]["tariff"] != 442: + fail("cert Q7") + if cert["Q8"]["tariff_lower_bound_X_ge_0"] != 452: + fail("cert Q8") + if cert["Q9"]["tariff_lower_bound"] != 466: + fail("cert Q9") + spectrum = cert["Q7"]["R_spectrum_distinct_slots"] + if spectrum["attainable_R"] != [82, 88]: + fail("cert R spectrum") + if spectrum["histogram"] != {"82": 97216, "88": 486080}: + fail("cert R histogram") + if cert["Q7"]["tariff_floor_from_spectrum"]["min_tariff"] != 442: + fail("cert spectrum tariff floor") + attainable, covering, hist = census_q7_R_spectrum() + if attainable != spectrum["attainable_R"]: + fail("independent/cert spectrum drift") + if {str(k): v for k, v in hist.items()} != spectrum["histogram"]: + fail("independent/cert histogram drift") + if covering != spectrum["covering_sets"]: + fail("independent/cert covering drift") + controls = 0 + try: + replay((0, 1, 2, 6, 12, 24, 16)) + fail("unclosed path should fail") + except SystemExit as exc: + if "FAIL_INDEPENDENT" not in str(exc): + raise + controls += 1 + if invoice(7, 82, 4) == 442: + fail("undercount must not match champion") + controls += 1 + if controls != 2: + fail(f"expected 2 negative controls, got {controls}") + print( + "PASS_INDEPENDENT_789Q_INVOICE", + "champion=442 floors=452,466", + f"R_spectrum={attainable}", + f"controls={controls}", + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/research/mutable-source-789q-invoice/model.py b/research/mutable-source-789q-invoice/model.py new file mode 100644 index 0000000000..8ce90c48df --- /dev/null +++ b/research/mutable-source-789q-invoice/model.py @@ -0,0 +1,221 @@ +"""Path-lowered even-subset schedules and abstract invoices. Wentao Li + AI, Apache-2.0. + +The complete-call tariff (b,a,x)=(38,2,2) and path-local shear lowering match +Arham Tahir's PR1898 `research/mutable-source-minimum-queries/model.py` on +CrocSwap main `0fdd7d82`. This file is self-contained for fork bases that lack +that package; it does not import predecessor executables. +""" +from collections import Counter +from itertools import combinations + + +def need(ok, message): + if not ok: + raise ValueError(message) + + +def min_even_subset_R(slots): + """Minimum total even-subset readout count on connector prefix slots. + + ``slots[0]`` must be 0. The final restored 0 is identified with slot 0, so + ``slots`` lists the Q distinct time values before the closing query edge. + """ + need(type(slots) is tuple and slots and slots[0] == 0, "slots must start at 0") + n = len(slots) + best = [99] * 32 + for bits in range(1 << n): + if bits.bit_count() % 2: + continue + value = 0 + for i in range(n): + if bits >> i & 1: + value ^= slots[i] + size = bits.bit_count() + if size < best[value]: + best[value] = size + if any(best[mask] >= 99 for mask in range(1, 32)): + return None + return sum(best[1:]) + + +def even_subset_reads(slots): + """One minimum even subset of slot indices per nonzero mask.""" + n = len(slots) + reads = {} + for mask in range(1, 32): + found = None + for size in range(2, n + 1, 2): + for subset in combinations(range(n), size): + value = 0 + for i in subset: + value ^= slots[i] + if value == mask: + found = subset + break + if found is not None: + break + need(found is not None, f"mask {mask} uncovered") + reads[mask] = found + return reads + + +def path_X(closed): + """Paid source-XOR count under path-local compute/uncompute lowering.""" + total = 0 + for a, b in zip(closed, closed[1:]): + delta = a ^ b + need(delta != 0, "zero query edge") + total += 2 * (delta.bit_count() - 1) + return total + + +def rank_increments(closed): + rows = [closed[i] ^ closed[i + 1] for i in range(len(closed) - 1)] + rank = 0 + for bit in range(5): + pivot = next((i for i in range(rank, len(rows)) if rows[i] >> bit & 1), None) + if pivot is None: + continue + rows[rank], rows[pivot] = rows[pivot], rows[rank] + for i in range(len(rows)): + if i != rank and rows[i] >> bit & 1: + rows[i] ^= rows[rank] + rank += 1 + return rank + + +def path_word(closed): + """Literal Q/R/X word for a closed prefix path with even-subset readouts.""" + need(closed[0] == closed[-1] == 0, "path is not closed") + slots = tuple(closed[:-1]) + reads = even_subset_reads(slots) + word = [] + for step, point in enumerate(closed): + word += [["R", mask] for mask, subset in reads.items() if step in subset] + if step + 1 >= len(closed): + break + delta = point ^ closed[step + 1] + need(delta != 0, "zero query edge") + target = (delta & -delta).bit_length() - 1 + donors = [j for j in range(5) if j != target and delta >> j & 1] + word += [["X", j, target] for j in donors] + word.append(["Q", target]) + word += [["X", j, target] for j in reversed(donors)] + return word + + +def root_ops(word, n=5): + out = [] + for event in word: + kind = event[0] + if kind == "Q": + out.append(["B", f"x{event[1]}", "z"]) + elif kind == "R": + out.append([f"A{event[1]}", "z", f"y{event[1]}"]) + elif kind == "X": + out.append(["", f"x{event[1]}", f"x{event[2]}"]) + else: + raise ValueError("unknown root operation") + return out + + +def roles(n=5): + return [f"x{j}" for j in range(n)] + [f"y{m}" for m in range(1, 1 << n)] + ["z"] + [ + f"w{j}" for j in range(3) + ] + + +def interpret(operations, names, initial=None): + state = {r: {(r,)} for r in names} if initial is None else {r: set(p) for r, p in initial.items()} + for coefficient, source, target in operations: + need(source in state and target in state and source != target, "invalid port") + terms = state[source] if coefficient == "" else {(coefficient,) + term for term in state[source]} + state[target].symmetric_difference_update(terms) + return state + + +def expected(n=5): + state = {r: {(r,)} for r in roles(n)} + for mask in range(1, 1 << n): + for j in range(n): + if mask >> j & 1: + state[f"y{mask}"].symmetric_difference_update({(f"A{mask}", "B", f"x{j}")}) + return state + + +def check_identity(word, n=5): + ops = root_ops(word, n) + result = interpret(ops, roles(n)) + need(result == expected(n), "dirty root map or restoration failed") + need( + interpret(ops[::-1], roles(n), result) == {r: {(r,)} for r in roles(n)}, + "root inverse failed", + ) + return Counter(event[0] for event in word) + + +def invoice(word): + counts = Counter(event[0] for event in word) + leaves = 28 * counts["Q"] + counts["R"] + nodes = 9 * counts["Q"] + dispatch = len(word) + return { + "Q": counts["Q"], + "R": counts["R"], + "X": counts["X"], + "map_leaves": leaves, + "echo_nodes": nodes, + "root_dispatches": dispatch, + "borrowed_dirty_rows": 4, + "tariff": leaves + nodes + counts["X"] + dispatch, + "complete_prices": {"b": 38, "a": 2, "x": 2}, + } + + +def minimum_word_6q(): + """PR1898 minimum-query word for n=5 (credited; used as comparator).""" + reads = {} + for mask in range(1, 32): + coefficients = [mask & 1] + coefficients += [((mask >> (t - 1)) ^ (mask >> t)) & 1 for t in range(1, 6)] + reads[mask] = [t for t, bit in enumerate(coefficients) if bit] + word = [] + for t in range(6): + word += [["R", mask] for mask, positions in reads.items() if t in positions] + if t < 5: + word.append(["Q", t]) + word += [["X", j, 0] for j in range(1, 5)] + word.append(["Q", 0]) + word += [["X", j, 0] for j in reversed(range(1, 5))] + return word + + +def four_x_ten_q(): + """PR1370/PR1898 attributed closed path (credited comparator).""" + points = [0, 4, 5, 1, 3, 7, 6, 14, 28, 16, 0] + # Paired readouts as in predecessor path_word. + readouts = {} + for mask in range(1, 32): + pair = next( + ( + (s, t) + for s in range(len(points)) + for t in range(s + 1, len(points)) + if points[s] ^ points[t] == mask + ), + None, + ) + need(pair is not None, "ten-query path incomplete") + readouts[mask] = pair + word = [] + for s, point in enumerate(points): + word += [["R", mask] for mask, pair in readouts.items() if s in pair] + if s + 1 >= len(points): + break + delta = point ^ points[s + 1] + target = (delta & -delta).bit_length() - 1 + donors = [j for j in range(5) if j != target and delta >> j & 1] + word += [["X", j, target] for j in donors] + word.append(["Q", target]) + word += [["X", j, target] for j in reversed(donors)] + return word diff --git a/research/mutable-source-789q-invoice/test_package.py b/research/mutable-source-789q-invoice/test_package.py new file mode 100644 index 0000000000..c9d2cff89c --- /dev/null +++ b/research/mutable-source-789q-invoice/test_package.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""Package fault controls for the 789Q invoice. Wentao Li + AI, Apache-2.0.""" +from __future__ import annotations + +import json +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] + + +def need(ok, message): + if not ok: + raise SystemExit(f"FAIL_TEST: {message}") + + +def run(args, cwd=None): + return subprocess.run(args, cwd=cwd or ROOT, text=True, capture_output=True) + + +def main(): + # 1) Quick verify against committed certificate. + proc = run([sys.executable, "-I", "-B", str(HERE / "verify.py"), "--quick"]) + need(proc.returncode == 0, proc.stderr + proc.stdout) + need("PASS_MUTABLE_SOURCE_789Q_QUICK" in proc.stdout, proc.stdout) + + # 2) -O quick admission. + proc = run([sys.executable, "-I", "-O", "-B", str(HERE / "verify.py"), "--quick"]) + need(proc.returncode == 0, proc.stderr + proc.stdout) + + # 3) Certificate drift rejection on a temp copy (quick path). + with tempfile.TemporaryDirectory() as tmp: + tmp_path = Path(tmp) + shutil.copytree(HERE, tmp_path / "pkg") + cert = tmp_path / "pkg" / "CERTIFICATE.json" + data = json.loads(cert.read_text()) + data["Q7"]["champion_invoice"]["tariff"] = 0 + cert.write_text(json.dumps(data, indent=2) + "\n") + # Also copy pinned input so pins resolve relative to tmp root layout. + pinned = tmp_path / "research" / "mutable-source-shear-cost" + pinned.mkdir(parents=True) + shutil.copy2( + ROOT / "research" / "mutable-source-shear-cost" / "CERTIFICATE.json", + pinned / "CERTIFICATE.json", + ) + # Move package under research/ for ROOT.parents[1] layout expected by verify. + research = tmp_path / "research" / "mutable-source-789q-invoice" + if research.exists(): + shutil.rmtree(research) + shutil.copytree(tmp_path / "pkg", research) + proc = run( + [sys.executable, "-I", "-B", str(research / "verify.py"), "--quick"], + cwd=tmp_path, + ) + need(proc.returncode != 0, "corrupted certificate should fail quick verify") + + # 4) Source pin corruption rejection. + with tempfile.TemporaryDirectory() as tmp: + tmp_path = Path(tmp) + pkg = tmp_path / "research" / "mutable-source-789q-invoice" + shutil.copytree(HERE, pkg) + pinned = tmp_path / "research" / "mutable-source-shear-cost" + pinned.mkdir(parents=True) + src = ROOT / "research" / "mutable-source-shear-cost" / "CERTIFICATE.json" + (pinned / "CERTIFICATE.json").write_bytes(src.read_bytes() + b"\n") + proc = run([sys.executable, "-I", "-B", str(pkg / "verify.py"), "--quick"], cwd=tmp_path) + need(proc.returncode != 0, "source drift should fail") + + # 5) Independent checker. + proc = run([sys.executable, "-I", "-B", str(HERE / "independent.py")]) + need(proc.returncode == 0, proc.stderr + proc.stdout) + + print("PASS_789Q_PACKAGE_TESTS groups=5") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/research/mutable-source-789q-invoice/verify.py b/research/mutable-source-789q-invoice/verify.py new file mode 100644 index 0000000000..ee1ed976b7 --- /dev/null +++ b/research/mutable-source-789q-invoice/verify.py @@ -0,0 +1,327 @@ +#!/usr/bin/env python3 +"""Exact 7/8/9-query invoices under the PR1898 path-lowered class. Wentao Li + AI, Apache-2.0.""" +from __future__ import annotations + +import hashlib +import json +import sys +from collections import Counter +from itertools import combinations, permutations +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +sys.path.insert(0, str(HERE)) +from model import ( # noqa: E402 + check_identity, + four_x_ten_q, + invoice, + min_even_subset_R, + minimum_word_6q, + path_X, + path_word, + rank_increments, +) +CERT_PATH = HERE / "CERTIFICATE.json" +CHAMPION_7 = (0, 1, 2, 6, 12, 24, 16, 0) + + +def need(ok, message): + if not ok: + raise SystemExit(f"FAIL: {message}") + + +def sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def enumerate_R_census(slot_count_nonzero: int) -> dict: + """Exhaust all distinct nonzero slot sets; return min R, full attainable spectrum, witnesses.""" + best = None + witnesses = [] + histogram: Counter = Counter() + covering = 0 + for nonzero in combinations(range(1, 32), slot_count_nonzero): + slots = (0,) + nonzero + total = min_even_subset_R(slots) + if total is None: + continue + covering += 1 + histogram[total] += 1 + if best is None or total < best: + best = total + witnesses = [slots] + elif total == best: + witnesses.append(slots) + need(best is not None, "no covering slot set") + attainable = sorted(histogram) + return { + "min_R": best, + "witness_count": len(witnesses), + "first_witness": list(witnesses[0]), + "covering_sets": covering, + "attainable_R": attainable, + "histogram": {str(r): histogram[r] for r in attainable}, + } + + +def enumerate_min_R(slot_count_nonzero: int) -> dict: + """Exhaust all distinct nonzero slot sets of the given size; return min R and witnesses.""" + census = enumerate_R_census(slot_count_nonzero) + return { + "min_R": census["min_R"], + "witness_count": census["witness_count"], + "first_witness": census["first_witness"], + } + + +def min_path_X_for_slots(slots: tuple[int, ...], stop_below: int | None = None) -> int | None: + """Minimum path-local X over full-rank orders of ``slots`` starting at 0. + + If ``stop_below`` is set, return as soon as a cost strictly below that bound is found. + """ + need(slots[0] == 0, "slots must start at 0") + rest = list(slots[1:]) + best = None + for order_rest in permutations(rest): + order = (0,) + order_rest + closed = order + (0,) + if rank_increments(closed) < 5: + continue + cost = path_X(closed) + if best is None or cost < best: + best = cost + if stop_below is not None and best < stop_below: + return best + return best + + +def enumerate_min_X_among_R(target_R: int, nonzero: int = 6) -> dict: + """Among distinct slot sets with min even-subset R == target_R, find min full-rank path X.""" + # Prove no schedule beats the known champion X=6, and count the X=6 layer. + covering = 0 + below = 0 + at_champion = 0 + for nonzero_slots in combinations(range(1, 32), nonzero): + slots = (0,) + nonzero_slots + if min_even_subset_R(slots) != target_R: + continue + covering += 1 + cost = min_path_X_for_slots(slots, stop_below=6) + if cost is None: + continue + if cost < 6: + below += 1 + elif cost == 6: + at_champion += 1 + need(below == 0, f"found {below} R={target_R} sets with path X<6") + need(at_champion > 0, "no R-set attains X=6") + need(rank_increments(CHAMPION_7) == 5, "champion rank") + need(path_X(CHAMPION_7) == 6, "champion X") + need(min_even_subset_R(CHAMPION_7[:-1]) == target_R, "champion R") + return { + "target_R": target_R, + "covering_sets": covering, + "min_X": 6, + "sets_with_X_eq_6": at_champion, + "sets_with_X_below_6": below, + "champion_path": list(CHAMPION_7), + } + + +def build_certificate() -> dict: + word6 = minimum_word_6q() + word10 = four_x_ten_q() + inv6 = invoice(word6) + inv10 = invoice(word10) + need(inv6["tariff"] == 436 and inv6["Q"] == 6 and inv6["R"] == 96 and inv6["X"] == 8, "6Q comparator") + need(inv10["tariff"] == 512 and inv10["Q"] == 10 and inv10["R"] == 62 and inv10["X"] == 4, "10Q comparator") + + # Full even-subset R census: certify attainable R spectrum (not only min R). + # Under tariff 38Q+2R+2X, beating 436 at Q=7 needs R+X<85; exact min 442 needs R+X>=88. + census7 = enumerate_R_census(6) + need(census7["min_R"] == 82, "unexpected Q=7 min R") + need(census7["attainable_R"] == [82, 88], f"unexpected Q=7 R spectrum {census7['attainable_R']}") + need(census7["histogram"] == {"82": 97216, "88": 486080}, f"unexpected Q=7 R histogram {census7['histogram']}") + need( + all(r not in range(83, 88) for r in census7["attainable_R"]), + "intermediate R in {83..87} would reopen low-X undercut of 436", + ) + r7 = { + "min_R": census7["min_R"], + "witness_count": census7["witness_count"], + "first_witness": census7["first_witness"], + } + x7 = enumerate_min_X_among_R(82, 6) + need(x7["min_X"] == 6 and x7["sets_with_X_below_6"] == 0, "unexpected Q=7 min X") + need(x7["covering_sets"] == census7["histogram"]["82"], "R=82 covering count mismatch") + + word7 = path_word(CHAMPION_7) + counts7 = check_identity(word7) + inv7 = invoice(word7) + need(dict(counts7) == {"Q": 7, "R": 82, "X": 6}, f"champion counts {counts7}") + need(inv7["tariff"] == 442, f"champion tariff {inv7}") + + # Machine-checked tariff floor from the certified spectrum + min-X layer. + # R=82 with X>=6 => R+X>=88 => tariff>=442; R=88 with X>=0 => tariff>=442. + r82_floor = 38 * 7 + 2 * 82 + 2 * x7["min_X"] + r88_floor = 38 * 7 + 2 * 88 + 2 * 0 + need(r82_floor == 442 and r88_floor == 442, "spectrum floors must both equal 442") + need(inv7["tariff"] == r82_floor, "champion must attain the spectrum floor") + need(r82_floor > inv6["tariff"] and r88_floor > inv6["tariff"], "7Q spectrum floors must not beat 6Q") + + r8 = enumerate_min_R(7) + need(r8["min_R"] == 74, "unexpected Q=8 min R among distinct slots") + floor8 = 38 * 8 + 2 * r8["min_R"] # X >= 0 + floor9 = 38 * 9 + 2 * 62 # R >= 62 for 31 masks + + need(inv7["tariff"] > inv6["tariff"], "7Q should not beat 6Q") + need(floor8 > inv6["tariff"], "8Q floor should not beat 6Q") + need(floor9 > inv6["tariff"], "9Q floor should not beat 6Q") + + return { + "schema_version": 1, + "status": "PASS_MUTABLE_SOURCE_789Q_INVOICE", + "scope": ( + "Path-lowered even-subset schedules on connector prefixes for the five-source " + "common-B mutable-source connector; complete-call tariff (b,a,x)=(38,2,2) from PR1898." + ), + "comparators": { + "six_query_endpoint": inv6, + "ten_query_four_X": inv10, + }, + "Q7": { + "R_spectrum_distinct_slots": { + "covering_sets": census7["covering_sets"], + "attainable_R": census7["attainable_R"], + "histogram": census7["histogram"], + "intermediate_R_83_to_87_count": 0, + "argument": ( + "Exhaustive even-subset R over all C(31,6) distinct nonzero 6-slot sets; " + "covering sets attain only R in {82,88}. Under tariff 38Q+2R+2X, beating " + "436 requires R+X<85, so excluded intermediate R in {83..87} with low X " + "cannot undercut; R=88 forces tariff>=442 even at X=0." + ), + }, + "min_R_distinct_slots": r7, + "min_X_among_min_R": x7, + "tariff_floor_from_spectrum": { + "beat_436_requires_R_plus_X_lt": 85, + "exact_min_requires_R_plus_X_ge": 88, + "R82_min_X": x7["min_X"], + "R82_tariff_floor": r82_floor, + "R88_X_ge_0_tariff_floor": r88_floor, + "min_tariff": 442, + }, + "champion_invoice": inv7, + "beats_six_query": False, + }, + "Q8": { + "min_R_distinct_slots": r8, + "tariff_lower_bound_X_ge_0": floor8, + "beats_six_query": False, + }, + "Q9": { + "R_lower_bound": 62, + "tariff_lower_bound": floor9, + "beats_six_query": False, + "argument": "Each of 31 masks needs an even nonempty readout set, so R >= 62.", + }, + "conclusion": ( + "Under this schedule class and abstract tariff, no path-lowered even-subset word " + "with Q in {7,8,9} beats the sharp six-query endpoint tariff 436. Q=7 exact " + "minimum 442 follows from the certified R spectrum {82,88} plus min X=6 on R=82." + ), + "new_kappa": False, + } + + +def check_pins(): + sources = json.loads((HERE / "SOURCES.json").read_text()) + for entry in sources.get("files", []): + if entry.get("usage") != "input": + continue + path = ROOT / entry["path"] + need(path.is_file(), f"missing input {entry['path']}") + need(sha256(path) == entry["sha256"], f"sha256 drift {entry['path']}") + + +def build_quick_checks() -> dict: + """Champion + comparator invoices without the long R/X censuses.""" + word6 = minimum_word_6q() + word10 = four_x_ten_q() + inv6 = invoice(word6) + inv10 = invoice(word10) + need(inv6["tariff"] == 436, "6Q comparator") + need(inv10["tariff"] == 512, "10Q comparator") + word7 = path_word(CHAMPION_7) + counts7 = check_identity(word7) + inv7 = invoice(word7) + need(dict(counts7) == {"Q": 7, "R": 82, "X": 6}, f"champion counts {counts7}") + need(inv7["tariff"] == 442, f"champion tariff {inv7}") + need(path_X(CHAMPION_7) == 6 and rank_increments(CHAMPION_7) == 5, "champion path") + need(min_even_subset_R(CHAMPION_7[:-1]) == 82, "champion R") + return { + "status": "PASS_MUTABLE_SOURCE_789Q_QUICK", + "Q6": inv6["tariff"], + "Q7": inv7["tariff"], + "Q8_floor": 38 * 8 + 2 * 74, + "Q9_floor": 38 * 9 + 2 * 62, + } + + +def main(argv: list[str]) -> int: + write = "--write" in argv + quick = "--quick" in argv + check_pins() + if quick and not write: + need(CERT_PATH.is_file(), "missing CERTIFICATE.json") + cert = json.loads(CERT_PATH.read_text()) + need(cert.get("status") == "PASS_MUTABLE_SOURCE_789Q_INVOICE", "bad certificate status") + quick_payload = build_quick_checks() + need(cert["Q7"]["champion_invoice"]["tariff"] == quick_payload["Q7"], "cert/quick Q7") + need(cert["Q8"]["tariff_lower_bound_X_ge_0"] == quick_payload["Q8_floor"], "cert/quick Q8") + need(cert["Q9"]["tariff_lower_bound"] == quick_payload["Q9_floor"], "cert/quick Q9") + need(cert["Q7"]["min_X_among_min_R"]["min_X"] == 6, "cert min X") + need(cert["Q7"]["min_X_among_min_R"]["sets_with_X_below_6"] == 0, "cert X below") + spectrum = cert["Q7"]["R_spectrum_distinct_slots"] + need(spectrum["attainable_R"] == [82, 88], "cert R spectrum") + need(spectrum["histogram"] == {"82": 97216, "88": 486080}, "cert R histogram") + need(spectrum["intermediate_R_83_to_87_count"] == 0, "cert intermediate R") + floor = cert["Q7"]["tariff_floor_from_spectrum"] + need(floor["min_tariff"] == 442, "cert spectrum tariff floor") + need(floor["R82_tariff_floor"] == 442 and floor["R88_X_ge_0_tariff_floor"] == 442, "cert layer floors") + print( + quick_payload["status"], + f"Q6={quick_payload['Q6']}", + f"Q7={quick_payload['Q7']}", + f"Q8_floor={quick_payload['Q8_floor']}", + f"Q9_floor={quick_payload['Q9_floor']}", + "no_new_kappa", + ) + return 0 + + payload = build_certificate() + text = json.dumps(payload, indent=2) + "\n" + if write: + CERT_PATH.write_text(text) + else: + need(CERT_PATH.is_file(), "missing CERTIFICATE.json; pass --write once") + decoder = json.JSONDecoder() + raw = CERT_PATH.read_text() + obj, idx = decoder.raw_decode(raw) + need(idx == len(raw.rstrip("\n")) or raw[idx:].strip() == "", "trailing junk in certificate") + need(obj == payload, "CERTIFICATE.json drift versus fresh census") + print( + payload["status"], + f"Q6={payload['comparators']['six_query_endpoint']['tariff']}", + f"Q7={payload['Q7']['champion_invoice']['tariff']}", + f"Q8_floor={payload['Q8']['tariff_lower_bound_X_ge_0']}", + f"Q9_floor={payload['Q9']['tariff_lower_bound']}", + "no_new_kappa", + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:]))