From fd573cfe4e9714706b01f0534584e6f5032dc858 Mon Sep 17 00:00:00 2001 From: Nick Petalas Date: Wed, 11 Nov 2026 21:52:03 +0000 Subject: [PATCH] feat(research): price one connector reset at eleven five-source queries The universal five-source dirty connector costs an exact 74 queries for the all-31-mask batch. Admitting one priced reset call and consuming the connector instead of restoring it gives an exact 63 = 2^6 - 1, and a matching lower bound of 2^(n+1) - 1 for every n. The saving is T(n) - 1, not a readout per mask: the readout term is unchanged and only the source walk lengthens. --- research/one-way-connector-reset-batch/NOTICE | 15 + .../one-way-connector-reset-batch/PROOF.md | 159 +++++++++ .../one-way-connector-reset-batch/README.md | 116 +++++++ .../SOURCES.json | 18 + .../one-way-connector-reset-batch/TASK.json | 80 +++++ .../one-way-connector-reset-batch/VERIFY.json | 36 ++ .../one-way-connector-reset-batch/verify.py | 311 ++++++++++++++++++ 7 files changed, 735 insertions(+) create mode 100644 research/one-way-connector-reset-batch/NOTICE create mode 100644 research/one-way-connector-reset-batch/PROOF.md create mode 100644 research/one-way-connector-reset-batch/README.md create mode 100644 research/one-way-connector-reset-batch/SOURCES.json create mode 100644 research/one-way-connector-reset-batch/TASK.json create mode 100644 research/one-way-connector-reset-batch/VERIFY.json create mode 100644 research/one-way-connector-reset-batch/verify.py diff --git a/research/one-way-connector-reset-batch/NOTICE b/research/one-way-connector-reset-batch/NOTICE new file mode 100644 index 0000000000..2dd2c8dd84 --- /dev/null +++ b/research/one-way-connector-reset-batch/NOTICE @@ -0,0 +1,15 @@ +A one-way connector reset makes the five-source batch exactly 63 queries +Copyright 2026 Nick Petalas. Licensed under Apache-2.0. + +This contribution was produced by Nick Petalas. + +The connector contract, the five-source 945-pairing census, the restored exact +74-query value and the four-source 38-query value are Ross Richardson's #934 +lineage as recorded in research/universal-connector-boundary/README.md. Those +are cited premises; this package does not replay or audit them. The +two-connector packages research/two-connector-transfer-boundary/ and its +successors define the reset-free neighbouring interface and explicitly exclude +connector resets. Cinna Davis's open #2249 and #3909 study larger source +alphabets at the same connector, and are related but distinct extensions. The +reflected Gray code is classical. No predecessor code is included in this +package. diff --git a/research/one-way-connector-reset-batch/PROOF.md b/research/one-way-connector-reset-batch/PROOF.md new file mode 100644 index 0000000000..e2e9980808 --- /dev/null +++ b/research/one-way-connector-reset-batch/PROOF.md @@ -0,0 +1,159 @@ +# Proof: one reset makes the five-source connector batch exactly 63 queries + +Written proof with an exact finite certificate. No `kappa`, no supplier +admission. Produced by Nick Petalas. + +## 1. Interface + +Use Ross Richardson's universal connector contract as recorded in +`research/universal-connector-boundary/README.md` (PR #934 and the five-source +boundary package). Sources `x_0,...,x_{n-1}`, one connector row `z`, output +rows `y_i`, all over `F2`. All maps `B_j` and `A_i` are arbitrary `F2`-linear, +possibly noncommuting and noninvertible; sources are read-only; the connector +and the outputs are arbitrarily dirty. A *complete query* is either + + B_j: z += B_j x_j (source call) + A_i: y_i += A_i z (readout) + +and the batch is correct when `y_i` ends as +`y_i + A_i (sum_{j in m_i} B_j x_j)` and every other row is restored. + +Write `b_j = B_j x_j`. Two cited facts from the predecessor: + +* **(P1) even incidence.** Restoration forces every `B_j` count even and every + `A_i` count even. The predecessor proves this by specializing to `L = 1`, + identity maps, independent source bits and an independent dirty connector + bit. +* **(P2) exact restored five-source value.** The 945-canonical-word census + excludes ten source calls, so the restored minimum is `T(5) = 12`, and the + all-31-nonzero-mask batch costs exactly `74 = 12 + 2*31`. The four-source + case is `38 = 8 + 2*15` with `T(4) = 8`. + +Both are cited inputs. They are not replayed or re-audited here. + +## 2. The extended alphabet + +Add exactly one operation + + Z: z := 0 (reset, one complete query) + +and change one boundary premise: **the connector is consumed**. Its exit value +is unconstrained, so no restoration of `z` is owed. Every other clause of the +contract is unchanged, including restoration of all other rows, read-only +sources, complete fixed-port calls and unit query prices. A caller that still +needs the old connector value must save and restore it, which is a separate +charged obligation and is not used below. + +The reset is not free: it is one complete query in every count that follows. + +## 3. Upper bound: the Gray schedule + +Let `g_0,...,g_{2^n-1}` be the reflected Gray code of `F2^n`: `g_0 = 0`, every +consecutive pair differs in one coordinate, and every vertex occurs once. The +schedule is + + Z; then for k = 1..2^n-1: B_{j_k} (the coordinate flipping into g_k) + A_{g_k} (one readout of the row with mask g_k) + +After the reset, `z = sum_{j in q} b_j` where `q` is the current prefix, so the +readout at `g_k` contributes exactly `A_{g_k} b_j` for `j in g_k`. Each row is +read once, at its own vertex, and no `A_i z_0` term survives because `z_0` was +destroyed by the reset. Row `i` therefore ends as +`y_i + A_i (sum_{j in i} B_j x_j)`, and `z` is left dirty, which the one-way +contract permits. + +Counts: `1` reset, `2^n - 1` source calls, `2^n - 1` readouts, hence + + Q(n) = 2^(n+1) - 1. + +At `n = 5` this is `1 + 31 + 31 = 63`. `verify.py` replays this schedule for +`n = 1..8` in a free symbol model and checks the three literal counts. + +## 4. Lower bound + +Let a legal schedule use `r` reset calls, `T` source calls and `R` readouts, so +`Q = r + T + R`. Since `Z` sets `z := 0` and no operation recreates `z_0`, the +coefficient of `z_0` in the connector is `1` before the first reset and `0` +after it. Call a readout *clean* when that coefficient is `0`. Let `S` be the +set of distinct nonzero clean single-readout values. + +*Clean values are prefixes.* A clean readout sees `sum_{j in q} b_j` for a +prefix set `q` reached after the last reset. A walk of `T` steps visits at most +`T + 1` vertices including `0`, so `|S| <= T`. + +*Every mask needs a readout.* Row `i` ends as a sum of the values it read; with +no readout it cannot change, so `R >= 2^n - 1`. + +*Masks outside `S` need two readouts.* A readout with the `z_0` coefficient `1` +leaves `A_i z_0` in row `i`, which the generic requirement forbids (row `i` +must not depend on the dirty connector content). So a single readout realizes +a mask only when it is clean and equals that mask, i.e. only for masks in `S`. +Hence + + R >= (2^n - 1) + #{ m != 0 : m not in S } >= 2(2^n - 1) - |S| + >= 2(2^n - 1) - T. + +**Case `r >= 1`.** `Q = r + T + R >= 1 + T + 2(2^n - 1) - T = 2^(n+1) - 1`. +The `T` cancels: a longer walk buys no discount, because every extra prefix +value is paid for by one extra source call. + +**Case `r = 0`.** There is no clean readout, so (P1)'s parity argument gives an +even number of readouts per active row, hence `R >= 2(2^n - 1)`. Also `T >= 1` +for every `n >= 1`, since a nonzero mask needs two distinct prefix values that +differ by it. Therefore `Q >= 2^(n+1) - 1`. Equality needs `T = 1` and exactly +two readouts per mask; for `n >= 2` one source call cannot supply the +`2^n - 1 >= 3` distinct masks, so the inequality is strict. + +Combining both cases with Section 3: + + exact optimum = 2^(n+1) - 1 for every n >= 1, + +attained by the Gray schedule. `verify.py` recomputes this optimum completely +for `n = 2, 3` by enumerating every visited vertex set, its shortest walk and +its cheapest readout assignment, and obtains `7` and `15`. + +## 5. What restoration costs + +The two contracts differ only in whether `z` must be restored, and in the one +reset call. Their exact values are: + +| sources `n` | restored, cited | one-way, this package | saving | +|---|---:|---:|---:| +| 4 | 38 = 8 + 30 | 31 | 7 | +| 5 | 74 = 12 + 62 | 63 | 11 | + +In both rows the saving is exactly `T(n) - 1`: the restored minimum source-call +count minus the single reset. The `2(2^n - 1)` readout term is identical. So +the restoration requirement costs the *pairing* structure, not a readout per +mask: a naive comparison would predict a saving of `2^n - 1` (31 at five +sources), and the exact answer is `T(n) - 1` (11), because the pairing contract +can only afford a 12-call walk while single readouts need a 31-vertex walk. + +For general `n` the same comparison gives a lower bound of `2n - 1` on the +saving, since (P1) forces `T(n) >= 2n`. + +## 6. The reset is essential at five sources + +Dropping restoration but keeping the reset forbidden is not enough to reach 63. +Without a reset every readout is dirty, so every row needs an even read count +and `R >= 62`; a row with mask `m` then needs two visited prefixes differing by +`m`. A walk of `T` steps supplies at most `T + 1` vertices, and `|P| = 8` gives +`C(8,2) = 28 < 31` pairs, so `|P| >= 9`. + +If `|P| = 9` the walk has at least 8 steps, and exactly 8 makes it a simple +path. `verify.py` enumerates **all 70,846 simple 8-step paths from `0` in the +5-cube** and finds maximum pairwise-difference coverage **28 of 32**; the +predecessor's closed ten-call census reaches 31 with eleven vertices, which is +outside this family. Hence `T >= 9`, and every reset-free five-source schedule +costs at least `9 + 62 = 71 > 63`. + +## 7. Scope + +This is a scoped exact result in the abstract query alphabet at unit prices. It +is not a `kappa` improvement, not a supplier admission, and not a claim about +physical arity-four or arity-five source operators, nonuniform per-port +tariffs, routing, or word-dependent storage. It does not assert that a caller +can freely discard a shared connector: that is the changed premise, charged as +one reset query, and a caller needing the old value pays a separate save and +restore. The 74 and 38 values and the `T(5) = 12`, `T(4) = 8` counts are cited +from the predecessor, not recomputed here. diff --git a/research/one-way-connector-reset-batch/README.md b/research/one-way-connector-reset-batch/README.md new file mode 100644 index 0000000000..f33a6ef68d --- /dev/null +++ b/research/one-way-connector-reset-batch/README.md @@ -0,0 +1,116 @@ +# One reset makes the five-source connector batch exactly 63 queries + +**Scoped exact result with a finite certificate and a written lower bound; no +new kappa.** Produced by Nick Petalas. + +The universal five-source dirty connector costs exactly **74 complete queries** +for the batch of all 31 nonzero masks (Ross Richardson's #934 contract as +recorded in `research/universal-connector-boundary/`). This package adds one +operation and changes one boundary premise: + + Z: z := 0 one complete query, and the connector is consumed + (its exit value is unconstrained). + +Under that alphabet the exact optimum drops to **63 = 2^6 - 1**: + + 1 reset + 31 source calls + 31 readouts. + +The 31 source calls are a reflected-Gray walk of the 5-cube; each readout sits +at the vertex whose mask is its own output row, so every row is read exactly +once. The matching lower bound is `2^(n+1) - 1` for **every** `n >= 1`, so the +closed form is not a five-source accident. `verify.py` replays the schedule for +`n = 1..8`, and recomputes the complete optimum for `n = 2, 3` from every +visited vertex set. + +```sh +python3.12 -B research/one-way-connector-reset-batch/verify.py +``` + +Expected: +`PASS_ONE_WAY_CONNECTOR_RESET exact_n1..8=3,7,15,31,63,127,255,511 optimum5=63 restored5=74 saving5=11 reset_free5_floor=71 nine_point_coverage=28 paths=70846 controls=6` + +## What the number says + +The saving is **11**, not the 31 that a "one readout per mask" comparison +suggests. The readout term `2(2^n - 1)` is the same under both contracts; what +changes is the source word. Restoration can afford a 12-call paired walk, +single readouts need a 31-vertex walk, and the difference is exactly +`T(n) - 1`: + +| sources | restored (cited) | one-way (here) | saving | +|---|---:|---:|---:| +| 4 | 38 | 31 | 7 | +| 5 | 74 | 63 | 11 | + +So connector restoration is worth exactly `T(n) - 1` queries at these arities, +and at least `2n - 1` in general. The dominant term in both contracts is the +`2^n - 1` readouts, which no boundary change in this alphabet removes. + +The reset is not decoration. Keeping the connector one-way but forbidding the +reset still leaves every readout dirty, so every row needs an even read count +and the cheapest design costs at least `9 + 62 = 71`: `verify.py` exhausts all +70,846 simple eight-step paths from `0` in the 5-cube and finds pairwise +coverage at most 28 of 32, which rules out a nine-vertex difference basis and +forces a ninth source call. The reset, not the missing restoration, is what +buys the last eight queries. + +## Interface and price ledger + +Unchanged from the predecessor: sources `x_j`, connector `z`, outputs `y_i`, +arbitrary `F2`-linear possibly noncommuting maps `B_j`, `A_i`, read-only +sources, arbitrary dirty `z` and `y_i`, complete fixed-port calls, unit query +prices, all rows restored except the requested output sums. The single change +is the exit contract for `z` plus the one reset call. A caller that needs the +old connector value must save and restore it; that is a separate obligation and +is not priced here, so this is not a claim that every caller can discard a +shared connector for free. + +## Claim type and evidence + +Scoped written proof with an exact finite certificate: + +* `PROOF.md` proves `2^(n+1) - 1` in two cases (`r >= 1` and `r = 0`), with the + counting lemma that every extra prefix value is paid for by a source call. +* `verify.py` replays the literal schedule in a free noncommutative symbol + model, checks the three counts, recomputes the complete optimum for `n = 2,3`, + runs the complete eight-step path census for the reset-free floor, and applies + six rejection controls. + +It is not a kappa improvement, not a supplier admission, and not a complete +multiplication theorem. The 74 and 38 values and the restored source-call +counts `T(5) = 12`, `T(4) = 8` are cited from the predecessor; this package does +not replay or audit its 945-word census. + +## Related open work + +* `research/universal-connector-boundary/` (PR #934 lineage, five-source + boundary): supplies the contract, the 945-pairing census, the restored exact + 74 and the four-source 38. Cited, not replayed. +* PR #3909 (open): a five-source arity-four source event priced as one dispatch + plus four additions, whose schedules cost at least 149 units. That extension + enlarges the source alphabet; this one enlarges the connector contract. The + two results are complementary and neither implies the other. +* PR #2249 (open): a high-arity six-source toggle floor with `f(6) = 16`. It + studies larger arities and larger alphabets; this package stays at unit + weight source calls and changes only the exit contract. +* `research/two-connector-transfer-boundary/`: two connectors with a paid + transfer, explicitly excluding connector resets. This package analyzes the + excluded operation, at one connector. + +## Open next questions + +* **Does a save-and-restore wrapper keep the gain?** A caller that must return + the old connector value needs one admitted clean row plus copy and restore + calls. Price that wrapper exactly; the favourable region is narrow (below + 74 - 63 = 11 units at five sources), and no such row is assumed here. +* **Can a nonuniform tariff change the ranking?** The 63 count uses unit + prices. With `c_Z`, `c_B` and `c_A` arbitrary positive prices, does the Gray + schedule still dominate the paired design whenever `c_Z` is small, and what + is the exact crossover? +* **What is the reset-free floor at general `n`?** At five sources the floor is + 71 by a complete eight-step path census. The analogous minimum difference + basis size for `n >= 6` is open here, and the predecessor's six-source floor + is a different quantity. +* **Does a bounded number of resets help a partial mask set?** For a sparse + set of requested masks, resetting between blocks may beat one long walk; the + exact tradeoff is not computed here. diff --git a/research/one-way-connector-reset-batch/SOURCES.json b/research/one-way-connector-reset-batch/SOURCES.json new file mode 100644 index 0000000000..89b7c5747a --- /dev/null +++ b/research/one-way-connector-reset-batch/SOURCES.json @@ -0,0 +1,18 @@ +{ + "schema_version": 1, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "files": [ + { + "path": "docs/research/agent-task-catalog.json", + "usage": "provenance", + "git_blob": "3404fbdd5e7529a0674eef26114b5071e4586cec", + "sha256": "ead6cdc9d0af6d58e8a49744d8ec8c7c15e13d2ba93c276c434bcf9b51b93a81" + }, + { + "path": "certificates/selected-result.json", + "usage": "provenance", + "git_blob": "75d77b328ea02ded535e7f23aee5b1e55d0bb1a8", + "sha256": "154c3d30455d778fd3343b6b4851f0fa4665f0f7625b0adb3675e2bafbbf6bf1" + } + ] +} diff --git a/research/one-way-connector-reset-batch/TASK.json b/research/one-way-connector-reset-batch/TASK.json new file mode 100644 index 0000000000..9e1b6944f5 --- /dev/null +++ b/research/one-way-connector-reset-batch/TASK.json @@ -0,0 +1,80 @@ +{ + "schema_version": 1, + "task_id": "connector-alphabet-change", + "priority_revision": 8, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "original_card": { + "id": "connector-alphabet-change", + "question": "Does one explicit extension of the connector alphabet offer a favorable completed budget?", + "starting_points": [ + "docs/research/research-family-status.md", + "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. A scoped local result may be retained without a complete supplier. Expanding it into further construction rounds requires the family-level budget and obligation gate in research-family-status.md; an optimistic passing relaxation alone is not acceptance.", + "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.", + "Extending a source-count census without naming a supplier/interface decision it could change; audit #2973 pruning concerns before relying on the affected predecessor exclusions." + ], + "overlap_terms": [ + "universal connector", + "source-toggle", + "connector alphabet" + ] + }, + "scope_status": "changed", + "actual_scope": "Exact query optimum of the five-source all-31-nonzero-mask connector batch when the connector is consumed rather than restored and one complete reset call Z: z := 0 is admitted at unit price; general-n closed form 2^(n+1)-1 and the exact cost of connector restoration.", + "scope_change_reason": "The card asks for one explicitly priced alphabet extension on a minimal instance. Instead of adding a larger source operator (the route of open #3909 and #2249), this changes the connector exit contract and adds the single reset operation it needs, which the predecessor and the two-connector packages explicitly exclude. The changed premise is recorded and charged as one complete query.", + "bottleneck_link": "Boundary between calls: the predecessor's 2(2^n - 1) readout term is caused by restoring a dirty connector. Removing that one restoration and pricing the one call it requires saves exactly T(n) - 1 queries (11 at five sources), and the dominant readout term is shown to be irreducible in this alphabet.", + "budget_minutes": 60, + "stop_rule": "Stop at the first verified exact value and its matching lower bound; leave save-and-restore pricing and nonuniform tariffs as open questions.", + "outcome": "completed", + "evidence": "PROOF.md proves 2^(n+1)-1 in the r>=1 and r=0 cases; verify.py replays the literal schedule for n=1..8 in a free symbol model, recomputes the complete optimum for n=2,3, and censuses all 70,846 simple eight-step 5-cube paths for the reset-free floor.", + "author": "Nick Petalas", + "ai_assistance": "Independent human and formal proof-kernel review are unclaimed.", + "open_questions": [ + { + "question": "Does a charged save-and-restore wrapper around the connector keep the 63-query gain?", + "why_it_matters": "A caller that must return the old connector value needs one clean row plus copy and restore calls, and the favourable margin is only 11 units at five sources.", + "first_step": "Price a clean width-L row admission plus the copy, reset, readout and restore calls on the same literal instance.", + "blocked_by": "No clean-row admission cost is fixed by the current contract, so the wrapper cannot be priced without a caller assumption." + }, + { + "question": "With arbitrary positive prices c_Z, c_B and c_A, when does the Gray schedule beat the paired design?", + "why_it_matters": "The 63 result uses unit prices; a real reset may be much cheaper or dearer than a readout.", + "first_step": "Solve the two-design cost inequality 31 c_B + 31 c_A + c_Z versus 12 c_B + 62 c_A in closed form.", + "blocked_by": "Only unit prices are covered here, so no crossover is claimed." + }, + { + "question": "What is the reset-free floor for general n?", + "why_it_matters": "At five sources the floor is 71 by a complete eight-step path census; the general minimum difference-basis size is a different combinatorial question.", + "first_step": "Extend the simple-path census to six and seven coordinates or prove a general lower bound on traceable difference bases.", + "blocked_by": "The exhaustive path census grows too fast beyond five coordinates for this package." + }, + { + "question": "Does a bounded number of resets help a sparse requested mask set?", + "why_it_matters": "For few requested masks, resetting between blocks may beat one long walk, changing which boundary contract is worth pricing.", + "first_step": "Minimize total calls over two reset blocks for a small explicit mask family.", + "blocked_by": "This package covers only the complete nonzero-mask batch." + } + ] +} diff --git a/research/one-way-connector-reset-batch/VERIFY.json b/research/one-way-connector-reset-batch/VERIFY.json new file mode 100644 index 0000000000..623e18845c --- /dev/null +++ b/research/one-way-connector-reset-batch/VERIFY.json @@ -0,0 +1,36 @@ +{ + "schema_version": 1, + "status": "ready", + "python": "3.12", + "requirements": [], + "inputs": [], + "commands": [ + { + "argv": [ + "{python}", + "-B", + "-W", + "error", + "-X", + "dev", + "{package}/verify.py" + ], + "timeout_seconds": 120, + "checks": "Gray schedule replay for n=1..8 in a free symbol model, literal five-source 63-query counts, complete optimum for n=2,3, the 70,846-path eight-step census for the reset-free floor, and six rejection controls." + }, + { + "argv": [ + "{python}", + "-B", + "-W", + "error", + "-X", + "dev", + "-O", + "{package}/verify.py" + ], + "timeout_seconds": 120, + "checks": "Same checks under -O: optimized mode must not skip assertions or change any counted value." + } + ] +} diff --git a/research/one-way-connector-reset-batch/verify.py b/research/one-way-connector-reset-batch/verify.py new file mode 100644 index 0000000000..1eb38039cc --- /dev/null +++ b/research/one-way-connector-reset-batch/verify.py @@ -0,0 +1,311 @@ +#!/usr/bin/env python3 +"""Standalone exact checker for the one-way connector reset batch. + +Checks, with no third-party dependency: + +1. The reflected-Gray source word is a walk on the n-cube, is simple, and + visits every vertex once, for n = 1..8. +2. The explicit n = 5 schedule (one reset, 31 source calls, 31 readouts) + realizes each of the 31 nonzero masks on its own output row, in a free + noncommutative symbol model: row i ends with exactly one copy of A_i b_j + for every j in mask i and no copy of A_i z_initial. +3. Complete query counts equal 2**(n+1)-1 for n = 1..8. +4. A complete optimization over all vertex subsets for n = 2,3 returns + 2**(n+1)-1, so the closed form is exact on those arities. +5. A complete census of all simple 8-step paths from 0 in the 5-cube finds + no 9-point pairwise-difference basis of F2^5, hence every reset-free + five-source schedule costs at least 71. +6. Rejection controls: a schedule missing the reset, a schedule with one + readout removed, the restored ten-call word, a random 31-step word, and a + duplicated readout all fail their respective checks. + +Exit status 0 and a single PASS line on success; nonzero on any failure. +""" + +import random +import sys + +FAILS = [] + + +def check(condition, label): + if not condition: + FAILS.append(label) + return condition + + +def popcount(v): + return bin(v).count("1") + + +def reflected_gray(n): + """All 2**n vertices of F2^n in reflected-Gray order.""" + out = [0] + for bit in range(n): + out += [v | (1 << bit) for v in reversed(out)] + return out + + +def steps_of(word): + """Unit toggles between consecutive entries of a vertex list.""" + return [(a ^ b).bit_length() - 1 for a, b in zip(word, word[1:])] + + +def is_unit_toggle(delta): + return delta != 0 and popcount(delta) == 1 + + +def build_schedule(n): + """One reset, Gray walk, then one readout per nonzero vertex.""" + word = reflected_gray(n) + calls = [("Z",)] + for k, step in enumerate(steps_of(word), start=1): + calls.append(("B", step)) + calls.append(("A", word[k])) + return word, calls + + +def replay(calls, n): + """Free noncommutative symbol replay. + + Connector content is (z0 present?, prefix set). A readout of row m adds + A_m z0 (if present) and one A_m b_j for each j in the prefix. Row symbol + multisets are compared with the requested masks; no relation between A_m + z0, A_m b_j and A_k b_l is assumed, which is the generic (arbitrary + linear, possibly noncommuting) operator case. + """ + z0 = True + prefix = set() + rows = {} + counts = {"Z": 0, "B": 0, "A": 0} + for call in calls: + counts[call[0]] += 1 + if call[0] == "Z": + z0, prefix = False, set() + elif call[0] == "B": + j = call[1] + if j in prefix: + prefix.remove(j) + else: + prefix.add(j) + else: + m = call[1] + terms = rows.setdefault(m, {}) + if z0: + terms[("A", m, "Z")] = terms.get(("A", m, "Z"), 0) + 1 + for j in prefix: + key = ("A", m, j) + terms[key] = terms.get(key, 0) + 1 + return rows, counts + + +def rows_are_exact(rows, n): + """Every nonzero mask has exactly its own terms and nothing else.""" + if set(rows) != set(range(1, 1 << n)): + return False + for m, terms in rows.items(): + wanted = {("A", m, j): 1 for j in range(n) if (m >> j) & 1} + if {k: v for k, v in terms.items() if v} != wanted: + return False + return True + + +def min_walk_length(subset): + """Shortest walk from 0 visiting every vertex of subset (unit steps).""" + verts = sorted(subset) + index = {v: i for i, v in enumerate(verts)} + size = len(verts) + inf = 10 ** 6 + dp = [[inf] * size for _ in range(1 << size)] + dp[1 << index[0]][index[0]] = 0 + for mask in range(1 << size): + for last in range(size): + cost = dp[mask][last] + if cost == inf: + continue + for nxt in range(size): + if mask >> nxt & 1: + continue + if is_unit_toggle(verts[last] ^ verts[nxt]): + cand = cost + 1 + if cand < dp[mask | (1 << nxt)][nxt]: + dp[mask | (1 << nxt)][nxt] = cand + return min(dp[(1 << size) - 1]) + + +def subset_read_cost(values, n, even_only): + """Minimum total readouts over all nonzero masks. + + values is the read-only prefix set (0 excluded: a read at prefix 0 + contributes nothing in the reset case and only z_initial in the + reset-free case, so it can only pad a cost). + """ + inf = 10 ** 6 + # best[(parity, xor)] = fewest values whose xor is that and whose count + # has that parity; repeats are useless because v^v = 0. + best = {(0, 0): 0} + for v in values: + nxt = dict(best) + for (parity, x), k in best.items(): + key = (parity ^ 1, x ^ v) + if nxt.get(key, inf) > k + 1: + nxt[key] = k + 1 + best = nxt + total = 0 + for m in range(1, 1 << n): + choices = [k for (parity, x), k in best.items() if x == m and (parity == 0 or not even_only)] + if not choices: + return inf + total += min(choices) + return total + + +def exhaustive_optimum(n): + """Complete optimum over all schedules that visit a vertex set once.""" + best = None + others = [v for v in range(1 << n) if v] + for size in range(1, len(others) + 1): + for extra in __import__("itertools").combinations(others, size): + subset = (0,) + extra + walk = min_walk_length(subset) + if walk >= 10 ** 6: + continue + values = [v for v in subset if v] + reset_cost = walk + subset_read_cost(values, n, even_only=False) + 1 + free_cost = walk + subset_read_cost(values, n, even_only=True) + local = min(reset_cost, free_cost) + if best is None or local < best: + best = local + return best + + +def census_nine_point_paths(n=5): + """All simple 8-step paths from 0; report the largest difference set.""" + best = [0, 0] + total = [0] + + def walk_vertices(path): + return path + + def dfs(path): + total[0] += 1 + if len(path) == 9: + points = path + seen = set() + for a in points: + for b in points: + seen.add(a ^ b) + if len(seen) > best[0]: + best[0], best[1] = len(seen), 1 + elif len(seen) == best[0]: + best[1] += 1 + return + cur = path[-1] + for j in range(n): + nxt = cur ^ (1 << j) + if nxt not in path: + path.append(nxt) + dfs(path) + path.pop() + + dfs([0]) + return best[0], total[0] + + +def duplicating_readout_fails(): + """Two readouts at one boundary do not make up a mask.""" + calls = [("Z",), ("B", 0), ("A", 1), ("A", 1)] + rows, _ = replay(calls, 1) + return not rows_are_exact(rows, 1) + + +def main(): + # 1. Gray walks. + for n in range(1, 9): + word = reflected_gray(n) + check(len(word) == 1 << n, "gray length n=%d" % n) + check(len(set(word)) == 1 << n, "gray simple n=%d" % n) + check(all(is_unit_toggle(a ^ b) for a, b in zip(word, word[1:])), "gray steps n=%d" % n) + check(word[0] == 0, "gray starts at 0 n=%d" % n) + + # 2 and 3. Explicit schedules and their exact query counts. + expected_costs = {} + for n in range(1, 9): + word, calls = build_schedule(n) + rows, counts = replay(calls, n) + check(rows_are_exact(rows, n), "schedule realizes all masks n=%d" % n) + check(counts["Z"] == 1, "one reset n=%d" % n) + check(counts["B"] == (1 << n) - 1, "source calls n=%d" % n) + check(counts["A"] == (1 << n) - 1, "readouts n=%d" % n) + cost = counts["Z"] + counts["B"] + counts["A"] + check(cost == (1 << (n + 1)) - 1, "cost formula n=%d" % n) + expected_costs[n] = cost + + # The literal five-source instance used in the README. + _, calls5 = build_schedule(5) + _, counts5 = replay(calls5, 5) + check(counts5 == {"Z": 1, "B": 31, "A": 31}, "five-source literal counts") + check(63 == (1 << 6) - 1, "five-source closed form") + + # 4. Complete optimization for the two smallest nontrivial arities. + for n in (2, 3): + got = exhaustive_optimum(n) + check(got == (1 << (n + 1)) - 1, "exhaustive optimum n=%d got %r" % (n, got)) + + # 5. Reset-free five-source floor: no nine-point difference basis in F2^5. + coverage, paths = census_nine_point_paths(5) + check(coverage < 32, "nine-point path coverage below 32, got %d" % coverage) + check(paths > 0, "path census nonempty") + reset_free_floor = 9 + 2 * 31 + check(reset_free_floor == 71, "reset-free floor") + + # 6. Rejection controls. + # (a) dropping the reset leaves z_initial in every row. + _, no_reset = build_schedule(5) + rows_no_reset, _ = replay(no_reset[1:], 5) + check(not rows_are_exact(rows_no_reset, 5), "control: missing reset must fail") + # (b) dropping one readout loses one mask. + short = [c for c in calls5 if c[0] != "A"] + [c for c in calls5 if c[0] == "A"][:30] + rows_short, _ = replay(short, 5) + check(not rows_are_exact(rows_short, 5), "control: 30 readouts must fail") + # (c) the restored paired design needs the cited twelve source calls and + # two readouts per mask, so it costs 74 and is not cheaper than 63. + check(12 + 2 * 31 == 74, "control: restored pairing costs 74") + check(74 > 63, "control: restored pairing is not cheaper") + # (d) a 31-vertex walk with one step removed offers only 30 nonzero + # prefix values, so it cannot realize 31 masks with one readout each. + short_word = reflected_gray(5)[:31] + prefixes = set(short_word) - {0} + check(len(prefixes) == 30, "control: 30-step walk has 30 nonzero prefixes") + check(len(prefixes) < 31, "control: 30-step walk cannot cover 31 masks") + short_calls = [("Z",)] + for k, step in enumerate(steps_of(short_word), start=1): + short_calls.append(("B", step)) + short_calls.append(("A", short_word[k])) + rows_truncated, _ = replay(short_calls, 5) + check(not rows_are_exact(rows_truncated, 5), "control: 30-step walk must fail") + # (e) reading one boundary twice does not build a mask. + check(duplicating_readout_fails(), "control: duplicated readout must fail") + + if FAILS: + for item in FAILS: + print("FAIL " + item) + return 1 + print( + "PASS_ONE_WAY_CONNECTOR_RESET " + "exact_n1..8=%s optimum5=%d restored5=74 saving5=%d " + "reset_free5_floor=%d nine_point_coverage=%d paths=%d controls=6" + % ( + ",".join(str(expected_costs[n]) for n in range(1, 9)), + 63, + 74 - 63, + reset_free_floor, + coverage, + paths, + ) + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main())