diff --git a/research/literal-canonical-rotation-switch/INDEPENDENT-RESULT.json b/research/literal-canonical-rotation-switch/INDEPENDENT-RESULT.json new file mode 100644 index 0000000000..d47cc939f8 --- /dev/null +++ b/research/literal-canonical-rotation-switch/INDEPENDENT-RESULT.json @@ -0,0 +1,124 @@ +{ + "all_locations_static_validation": true, + "claims": "finite independent replay; universal result rests on separately reviewed proof", + "clean_rejection_controls": [ + { + "history": 31, + "name": "height_zero", + "steps": 146 + }, + { + "history": 85, + "name": "size_zero", + "steps": 1117 + }, + { + "history": 85, + "name": "size_above_cube", + "steps": 1147 + }, + { + "history": 85, + "name": "offset_equals_size", + "steps": 1201 + }, + { + "history": 85, + "name": "row_above_last", + "steps": 1309 + }, + { + "history": 85, + "name": "wire_above_cube", + "steps": 1255 + }, + { + "history": 29, + "name": "height_empty", + "steps": 128 + }, + { + "history": 33, + "name": "height_noncanonical", + "steps": 164 + }, + { + "history": 29, + "name": "height_end_symbol", + "steps": 128 + }, + { + "history": 77, + "name": "row_end_symbol", + "steps": 834 + }, + { + "history": 72, + "name": "size_short", + "steps": 732 + }, + { + "history": 77, + "name": "offset_long", + "steps": 823 + } + ], + "full_depth_half_turns": [ + { + "h": 13, + "history": 199, + "loops": 13, + "outcome": "DONE", + "steps": 13751 + }, + { + "h": 37, + "history": 467, + "loops": 37, + "outcome": "DONE", + "steps": 84501 + }, + { + "h": 97, + "history": 1129, + "loops": 97, + "outcome": "DONE", + "steps": 523316 + } + ], + "graph_sha256": "320daab199a5528d1e7c273c719b6787c01629ff6160cb01fb9c959e87c7b1d8", + "interpreter": "independent single sparse map with negative translated owner origins", + "largest_normal_run_steps": 523316, + "locations": 2096, + "normal_graph_complete_steps": 4507530, + "normal_graph_dynamic_locations": 1930, + "oracle": "independent parity-union-find canonical coloring and full route verification", + "outside_abi_control": "missing permanent LEFT leaves promised owner window; outside ABI", + "required_h5_s17_j6_queries": 544, + "required_row_sha256": "bc0ab563e6d8fdfa24ee89b50dbe3f9a3a6f23681f491e883c6b5aeef07d4104", + "returning_child_parity_mutant": { + "arguments": [ + 3, + 5, + 1, + 1, + 5 + ], + "changed_locations": [ + 1242, + 1325, + 1419, + 1512 + ], + "correct": 1, + "heads_and_private_state_restored": true, + "history": 85, + "returned": 0, + "steps": 1625 + }, + "small_networks": 49, + "small_queries": 1566, + "source_sha256": "89fe721a2920943dbc58eefe7f855ac1573e653e8af3b029c9c2ef838fdeac40", + "status": "PASS", + "tapes": 14 +} diff --git a/research/literal-canonical-rotation-switch/LICENSE b/research/literal-canonical-rotation-switch/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/research/literal-canonical-rotation-switch/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/research/literal-canonical-rotation-switch/NOTICE.md b/research/literal-canonical-rotation-switch/NOTICE.md new file mode 100644 index 0000000000..86f6b001dc --- /dev/null +++ b/research/literal-canonical-rotation-switch/NOTICE.md @@ -0,0 +1,21 @@ +# Attribution and scope + +Prepared for Jerry Chen / @CubeJerry with substantial OpenAI assistance. +Apache-2.0. No independent human or formal-kernel acceptance is claimed. + +Nick Petalas, CrocSwap/integer-mult-bounds#7504 at +4eece58f5cebdb70a92d65447974f1c02383f60b, supplied the direct canonical +padded-rotation predicate, endpoint formulas and exact child closure. +His unmodified proof, source manifest and evaluator are retained. These +mathematical results and arithmetic complexity are credited prior work. + +Cinna Davis / 1337isnot1337 #4100 supplied the original deterministic Beneš +compiler and padded rotation. Its canonical check_batched_crt.py and NOTICE +remain unmodified. ToikY #4192 supplied generic arena lowering; JoyboyBrian +#5092/#5496 and successors supplied the encoded ROM/current-row context. +#7388's live CRT caller and #7390's sort fusion remain separate work. + +The new contribution is the2096-location,14-tape graph, its format/domain +validation, owned-Boolean/cleanup/guard contracts, complete scan costs and +historical-backing bound. No predecessor formula is claimed anew. No full +caller or selected assumption is discharged and no new kappa is claimed. diff --git a/research/literal-canonical-rotation-switch/PLAN.md b/research/literal-canonical-rotation-switch/PLAN.md new file mode 100644 index 0000000000..eda84a43e1 --- /dev/null +++ b/research/literal-canonical-rotation-switch/PLAN.md @@ -0,0 +1,62 @@ +# Literal direct-switch plan and optimistic complete budget + +Base e54523517d0f03e58352e647c403a5af3e525a57. +Exact arithmetic predecessor: Nick Petalas #7504, +4eece58f5cebdb70a92d65447974f1c02383f60b. Formula/child closure are credited. + +## Scope and proposed ABI + +One fixed finite graph on14 tape roles. Five borrowed records encode h,s,a,j,x; +output is one separate owned Boolean; eight private roles hold an initial +height countdown, unary width, s,a,j,x,last-row and one temporary. All input +heads begin at first body cells with supplied LEFT guards. h is positive +canonical LSB-first binary terminated by blank. The other four numbers are +exactly h+1 LSB-first bits followed by blank (zero padding is part of this +explicit ABI). Their unused high bits are validated by mathematical domain +checks, not interpreted as signs. Inputs are preserved byte-for-byte. + +The graph creates/retires its private guards on supplied blank disjoint +windows, constructs its own h+1-cell width guide, validates every domain, +follows at most h literal child steps and clears/returns all private and +borrowed roles on success. The owned output remains one bit at its original +owner/head. Current CRT offset production and serialization into this ABI +remain caller obligations. No ROM, runtime callback or host integer acts +inside the graph. A finite malformed encoding rejects; no infinite-stream +recognition or enclosing caller rollback is claimed. + +## Complete optimistic bill before coding + +With W=h+1, setup constructs the unary width using O(h log(h+1)) bit steps, +then reads/validates/copies O(h) bits. Every direct-query iteration uses a +constant number of complete W-cell comparisons, shifts, +/-1 steps and +head returns. At most h iterations give O(h^2) complete steps. Initial +private writes, final erasure and all returns are O(h). Eight fixed private +roles have O(h) total active bits; historical backing retains their full +visited spans. A conservative explicit constant will be proved from the +emitted loop bodies, not fitted to execution timings. + +For Q queries at identical physical origins, the full proposed workload is + + T_produce/serialize + Q*C*(h+3)^2 + T_consume/retire, + +with O(h) reusable private backing and inherited history retained. Repeated +point queries do not become free. No repeated workload or caller price is +assumed from the one-bit lemma. + +For a supplied retained ROM, write its complete build cost as B and its +actual query/movement/restoration bill as sum R_q. Its workload is + + T_produce/serialize_ROM + B + sum R_q + T_dispose. + +Direct queries improve this total only after the corresponding inequality +is established for the same actual query sequence. In the optimistic +resident/streaming ROM comparison, R_q may be constant and build is amortized; +then sufficiently many repeated queries can favor the ROM. All offsets at +h5,s17,j6 comprise544 bits: asking for all544 individually pays544 quadratic +point-query bills. No speedup over building and scanning those544 retained +bits is asserted. A single query avoids exponential-size table production, +which is the meaningful missing physical-predicate premise here, not a +complete-system asymptotic improvement. + +Stop if the literal proof requires runtime host arithmetic or exceeds +O(h^2) steps/O(h) work; no larger caller integration or kappa claim. diff --git a/research/literal-canonical-rotation-switch/PR-BODY.md b/research/literal-canonical-rotation-switch/PR-BODY.md new file mode 100644 index 0000000000..d9bd299250 --- /dev/null +++ b/research/literal-canonical-rotation-switch/PR-BODY.md @@ -0,0 +1,66 @@ +## What changes and why it matters + +Nick Petalas's #7504 proves how to query a bit of the precise canonical +padded-rotation Beneš network without constructing its ROM. Its first open +question asks for a literal fixed-tape implementation with encoded inputs, +an owned Boolean return, preservation and complete costs. This package +implements that interface. + +## Exact result + +On the explicit binary ABI, one input-independent program has2096 locations +and14 tapes. For every legal h,s,a,j,x it returns the original canonical +row-j bit at the **current wire address x**, with complete time at most +`1024(h+3)^2` and additional historical backing at most`16(h+4)` cells. +It preserves five borrowed descriptors, returns every head, clears eight +private bodies and retires their guards, leaving one owned output bit. +Domain and length validation precede identity shortcuts. The graph uses +only fixed-symbol reads/writes, unit moves, fixed jumps and halts. + +The formulas and child closure belong to #7504. The new result is their +literal physical lowering and ownership/cost proof. The original #4100 +canonical compiler supplies expected table bits independently of the new graph. + +## Verification and reproduction + +Base: `e54523517d0f03e58352e647c403a5af3e525a57`. Exact source commits, +Git blobs and SHA256 pins are in SOURCE-PINS.json. Originals/notices remain +unchanged. Normal and optimized warning-strict primary results agree. + +```sh +python3 -B scripts/research_package.py --package research/literal-canonical-rotation-switch +``` + +Primary checks include1566 queries covering49 full networks through h3, +all544 h5,s17,j6 entries,13 malformed/domain rejections, three detected +child/parity graph mutants, an owner-alias rejection and full-depth cases +through h129. Every call checks borrowed bytes, heads, private capacity, +guards, exteriors and historical spans. Universal correctness rests on the +written induction and emitted-loop counts, not these finite fixtures. + +## Limits and kappa status + +**No new kappa. All five selected foundational assumptions remain.** +The supplied binary ABI and initialized disjoint working windows are explicit. +Current CRT offset production, serialization, source transport, current-wire +payload updates and the full exceptional-key caller are not installed. +Repeated queries retain their complete quadratic bill and require comparison +against amortized ROM reuse. The544 separately supplied fixtures are not an +uninterrupted caller or a global speedup claim. + +## Credit and AI assistance + +Prepared for @CubeJerry with substantial OpenAI assistance. Credit Nick +Petalas #7504 for the arithmetic construction, Cinna Davis / 1337isnot1337 +#4100 for the canonical compiler, ToikY #4192 and JoyboyBrian's ROM/current-row +lineage. #7388 and #7390 remain distinct caller/sort work. Original notices +and Apache-2.0 license are retained. No independent human or formal-kernel +acceptance is claimed. Full proof, receipts and open interfaces are packaged. + +## Independent review + +A separate reviewer reproduced universal arithmetic, cleanup, source-loop time and history bounds, then checked the frozen graph through an independent sparse interpreter and parity-union-find canonical-network oracle. All1566 small and544 required row queries pass. A child-parity mutant returns a wrong bit while restoring every head and private cell. Normal/optimized receipts agree. REVIEW.md, INDEPENDENT-RESULT.json and SOURCE-CHECK.json contain the exact evidence. This is model-assisted review, not human or formal-kernel acceptance. + +## Publication checks + +All four canonical registered commands, exact six-file origin comparisons, committed bytes/modes, whitespace and official export/input integrity checks passed. The full-history check is unavailable in the shallow checkout; no pass is claimed. PUBLICATION-CHECKS.json records exact local evidence. No hosted CI or independent human/formal acceptance is claimed. diff --git a/research/literal-canonical-rotation-switch/PR-TITLE.txt b/research/literal-canonical-rotation-switch/PR-TITLE.txt new file mode 100644 index 0000000000..64258a2ee7 --- /dev/null +++ b/research/literal-canonical-rotation-switch/PR-TITLE.txt @@ -0,0 +1 @@ +Implement canonical padded-rotation switch queries as a restored fourteen-tape program with quadratic bit cost diff --git a/research/literal-canonical-rotation-switch/PROOF.md b/research/literal-canonical-rotation-switch/PROOF.md new file mode 100644 index 0000000000..b886214a59 --- /dev/null +++ b/research/literal-canonical-rotation-switch/PROOF.md @@ -0,0 +1,268 @@ +# A literal canonical padded-rotation switch predicate + +## 1. Claim, source and credited arithmetic + +Canonical base: e54523517d0f03e58352e647c403a5af3e525a57. Nick Petalas's +[#7504](https://github.com/CrocSwap/integer-mult-bounds/pull/7504), exact head +4eece58f5cebdb70a92d65447974f1c02383f60b, proves the arithmetic formulas and +child closure for Cinna Davis's #4100 canonical Beneš compiler. Its proof +and evaluator are retained byte-for-byte. The canonical compiler SHA256 is +681e2e3d71fa74c8b9b326f3860104fd9d89590a222e26ae6ee718d1fd40ff2e. +Those formulas and their canonical orientation are credited prior results. + +For h>=1, N=2^h, 1<=s<=N, 0<=a0, s<=2^h, aS rejects. The credited child theorem +proves A<=S. Since this branch has prior A>0, S>=2 and the child modulus is +positive. J decreases once, R twice and X is halved. The invariant now holds +at eta-1 and the requested canonical bit is unchanged. At most h loop +entrances occur. This induction proves all-height correctness independently +of finite fixtures. No recursion stack or whole permutation is produced. + +The caller still owes the current-wire payload update between queries. +This predicate does not silently advance x or convert original-token labels. + +## 5. Complete instruction and historical-backing bounds + +Every R/W/M/J/H costs one; labels have no action. For at most W-bit records, +direct counts of the emitted loops give these safe complete bounds: + +| Macro | Instructions including returns | +| --- | ---: | +| Rewind from relative position <=W+1 |3W+6| +| Zero test including destination jump |6W+5| +| Increment/decrement |7W+5| +| Zero a number |7W+4| +| Copy a number and return both heads |11W+7| +| Right shift |9W+2| +| Left shift |7W+5| +| Compare and branch |11W+10| + +For example comparison uses two reads, two moves and one jump per bit, +then two frontier reads, two full rewinds and its destination jump. Right +shift has six transitions per following-bit transfer, plus its first move, +high zero and return. These counts include scanning erased spans to return. + +The canonical height has ell<=h=1`. + +Every branch and arithmetic macro was traced in the emitted construction. +The low-to-high comparison correctly lets the highest unequal digit replace +its previous comparison state. Right shifts read a successor before writing +its predecessor; carry and borrow are single control bits. No arithmetic +operation requires a decoded runtime integer or random-access operation. +All emitted reads have five fixed-symbol targets, all moves are unit moves, +all writes are fixed symbols and no graph write addresses borrowed ports0..4. + +The loop invariant is the stated smaller padded-rotation instance +`(eta,S,A,J,X)` with `R=2eta-2`. Its first and last row cases match the exact +predecessor formulas, including the first padded wire. Interior selection +reads the *current* low wire bit. It computes + +``` +S' = floor(S/2) + [S odd and (X mod2)=(A mod2)], +Apre = floor(A/2) + (X mod2)(A mod2), +``` + +and replaces equality `Apre=S'` by zero. The credited closure theorem gives +`Apre<=S'`; the preceding `A>0` test guarantees `S>=2`, hence `S'>=1`. +There is no implicit division by a zero child modulus. Updating J, R and X +reduces eta by one and preserves all domain inequalities. This proves at +most h loop entrances. It also establishes that x means a current wire +address, not an original input-token label. + +All input/output heads are rewound. Each private word is erased through its +END, the head traverses the erased span, and the installed LEFT is erased +before return. The review checked both success and rejection continuations. +The latter does not promise recovery from missing/interior LEFT, aliased +owners, arbitrary bank corruption or an unterminated stream. Those exclusions +are part of the stated physical ABI, not hidden assumptions in the theorem. + +## Independently counted complete bill + +Direct counting of the literal macro bodies reproduces the bounds below; +these are not fitted to execution times. A rewind starting at relative k +uses exactly `3k+3` instructions. The following W-bit bounds include returns +and their stated branch dispatches. + +| Macro | Bound | +| --- | ---: | +| Rewind from position at most W+1 | `3W+6` | +| Zero test with destination jump | `6W+5` | +| Increment or decrement | `7W+5` | +| Zero word | `7W+4` | +| Copy word and return both heads | `11W+7` | +| Right shift | `9W+2` | +| Left shift | `7W+5` | +| Comparison and branch | `11W+10` | + +For ell=`bit_length(h)`, the setup decomposes into guard/output checks, +height copy, width countdown, six numeric initializations, four field copies, +last-row construction, temporary high-bit construction and validation. Its +sum is at most `h(13ell+13)+28ell+180W+189`, hence the claimed +`h(13W+13)+208W+189`. The longest interior route is bounded by `109W+77`; +`128(W+1)` safely covers every loop entrance, including its terminal output +write. Cleanup is bounded by `98W+179`. Therefore the full bill is at most + +``` +141h^2+588h+674 <= 1024(h+3)^2. +``` + +No input serialization, producer, consumer or transport outside entry/return +is silently included in this point-service statement. Those remain caller +obligations exactly as the package says. + +The successful runs also admit the sharper exact span count +`11h+2ell+48`: height contributes `ell+2`, the four fixed fields contribute +`4(W+2)`, output contributes3, countdown contributes `ell+3`, and the width +plus six numeric owners contribute `7(W+3)`. This is below the claimed +`16(h+4)` increment. Historical backing remains charged after erasure. +Reusing the same origins takes the per-owner interval union; moving an +origin requires separately charged transport. + +## Independent execution and failure detection + +`independent_check.py` uses one sparse dictionary keyed by owner and logical +position. Every owner has a distinct negative origin, permanent/private +guards are distinguished, and opaque exterior sentinels are placed just +outside the legal windows. Every physical move, including moves over erased +cells, updates historical extrema. Whole sparse state and all heads are +compared after return; all five borrowed ports must have zero writes. +The six permanent guards must remain untouched and the eight private guard +write sequences must be exactly `[LEFT,blank]`. + +The expected-bit oracle independently solves the canonical input/output-pair +color constraints with parity union-find. It orients each component by its +least wire, derives child permutations and recurses. This differs from the +source compiler's traversal and from the direct-query arithmetic evaluator. +The oracle checks each row is constant across its switched pair and routes +every wire through the entire resulting network to its specified endpoint. +Canonical color uniqueness after fixing each component's least wire explains +why this constructs the required canonical orientation. + +Executed coverage: + +- All1566 queries of all49 networks through height3. +- All544 queries with `h=5,s=17,j=6`, ranging over every offset and wire. + The independently computed byte-bit hash is + `bc0ab563e6d8fdfa24ee89b50dbe3f9a3a6f23681f491e883c6b5aeef07d4104`. +- Half-turns at heights13,37,97 reach exactly h loop entrances. Their + expected one-bit middle-row answer follows by recursive halving of a + dyadic half turn, without building an exponential reference network. +- Twelve binary/domain/END faults reject with the full stated cleanup. +- One emitted-table child-parity mutation swaps the 0/1 destinations at + locations1242,1325,1419,1512. At `(h,s,a,j,x)=(3,5,1,1,5)` it returns0 + instead of the independently required1 while restoring all heads, guards + and private storage. The test therefore detects a semantic error in a + successfully returning program. +- Removing the height's permanent LEFT crosses the promised owner window. + This explicitly records the failure boundary; no clean rejection is + claimed for this outside-ABI input. + +Normal-graph replay uses4,507,530 transitions and dynamically visits1930 of +the2096 locations. Every graph location passes static instruction checks; +the universal macro and induction review covers the claim beyond finite +execution. No assertion of complete dynamic branch coverage is made. + +## Scope, next obligation and reproduction + +This is an explicit missing physical point-query service under its supplied +ABI. All five foundational assumptions remain, and there is no new kappa. +The source-faithful next lemma is a priced adapter from an actual caller's +physical height/rotation/row/current-wire records into this W-bit ABI, +together with output use/retirement and the caller's actual repeated-query +sequence. It must include current-wire updates and transport; the standalone +predicate does not establish that a retained ROM loses on a whole workload. + +Portable, read-only replay from a package containing the frozen `switch.py`: + +``` +python -B independent_check.py . +python -B -O independent_check.py . +``` + +The reviewer also ran the normal command against a separately saved emitted +graph and the optimized command against the authenticated constructor. Both +must print the same JSON as `INDEPENDENT-RESULT.json`; no artifact is written +implicitly. The graph fallback is only needed for the reviewer's separate +workspace. The published package can use its already pinned constructor. diff --git a/research/literal-canonical-rotation-switch/SOURCE-CHECK.json b/research/literal-canonical-rotation-switch/SOURCE-CHECK.json new file mode 100644 index 0000000000..47398f3897 --- /dev/null +++ b/research/literal-canonical-rotation-switch/SOURCE-CHECK.json @@ -0,0 +1,59 @@ +{ + "pins": [ + { + "bytes": 11520, + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "method": "git show exact canonical commit:path", + "path": "research/unconditional-batched-crt/check_batched_crt.py", + "repository": "CrocSwap/integer-mult-bounds", + "sha256": "681e2e3d71fa74c8b9b326f3860104fd9d89590a222e26ae6ee718d1fd40ff2e", + "status": "PASS" + }, + { + "bytes": 2380, + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "method": "git show exact canonical commit:path", + "path": "research/unconditional-batched-crt/NOTICE.md", + "repository": "CrocSwap/integer-mult-bounds", + "sha256": "924109837e71c52392191710d49c9deb42780878d1094f0b01e8690dbe799461", + "status": "PASS" + }, + { + "bytes": 11357, + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "method": "git show exact canonical commit:path", + "path": "LICENSE", + "repository": "CrocSwap/integer-mult-bounds", + "sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4", + "status": "PASS" + }, + { + "bytes": 10374, + "commit": "4eece58f5cebdb70a92d65447974f1c02383f60b", + "method": "independent GitHub exact-commit fetch", + "path": "research/canonical-rotation-switch-query/PROOF.md", + "repository": "petalas/integer-mult-bounds", + "sha256": "cd886b0ed8a49153babd2a49887da0abf819902461268bf48f0a1cb6d427bdb1", + "status": "PASS" + }, + { + "bytes": 1582, + "commit": "4eece58f5cebdb70a92d65447974f1c02383f60b", + "method": "independent GitHub exact-commit fetch", + "path": "research/canonical-rotation-switch-query/SOURCES.json", + "repository": "petalas/integer-mult-bounds", + "sha256": "7918c49ade0b407275cf59469b8d455f1a89e594c899c041d5e3ceb7a01b27cb", + "status": "PASS" + }, + { + "bytes": 2329, + "commit": "4eece58f5cebdb70a92d65447974f1c02383f60b", + "method": "independent GitHub exact-commit fetch", + "path": "research/canonical-rotation-switch-query/rotation_query.py", + "repository": "petalas/integer-mult-bounds", + "sha256": "f38e6a92be46a620d1a8faca9b013fcb44e55dfad329735a30ceb64a413f5cc2", + "status": "PASS" + } + ], + "status": "PASS" +} diff --git a/research/literal-canonical-rotation-switch/SOURCE-ORIGIN-CHECK.json b/research/literal-canonical-rotation-switch/SOURCE-ORIGIN-CHECK.json new file mode 100644 index 0000000000..09f93637c5 --- /dev/null +++ b/research/literal-canonical-rotation-switch/SOURCE-ORIGIN-CHECK.json @@ -0,0 +1,47 @@ +{ + "status": "PASS_EXACT_SOURCE_ORIGINS", + "files": [ + { + "local": "inputs/check_batched_crt.py", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/unconditional-batched-crt/check_batched_crt.py", + "sha256": "681e2e3d71fa74c8b9b326f3860104fd9d89590a222e26ae6ee718d1fd40ff2e", + "match": true + }, + { + "local": "inputs/canonical-NOTICE.md", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/unconditional-batched-crt/NOTICE.md", + "sha256": "924109837e71c52392191710d49c9deb42780878d1094f0b01e8690dbe799461", + "match": true + }, + { + "local": "LICENSE", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "LICENSE", + "sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4", + "match": true + }, + { + "local": "inputs/7504-PROOF.md", + "commit": "4eece58f5cebdb70a92d65447974f1c02383f60b", + "path": "research/canonical-rotation-switch-query/PROOF.md", + "sha256": "cd886b0ed8a49153babd2a49887da0abf819902461268bf48f0a1cb6d427bdb1", + "match": true + }, + { + "local": "inputs/7504-SOURCES.json", + "commit": "4eece58f5cebdb70a92d65447974f1c02383f60b", + "path": "research/canonical-rotation-switch-query/SOURCES.json", + "sha256": "7918c49ade0b407275cf59469b8d455f1a89e594c899c041d5e3ceb7a01b27cb", + "match": true + }, + { + "local": "inputs/rotation_query.py", + "commit": "4eece58f5cebdb70a92d65447974f1c02383f60b", + "path": "research/canonical-rotation-switch-query/rotation_query.py", + "sha256": "f38e6a92be46a620d1a8faca9b013fcb44e55dfad329735a30ceb64a413f5cc2", + "match": true + } + ] +} diff --git a/research/literal-canonical-rotation-switch/SOURCE-PINS.json b/research/literal-canonical-rotation-switch/SOURCE-PINS.json new file mode 100644 index 0000000000..84504a1fb4 --- /dev/null +++ b/research/literal-canonical-rotation-switch/SOURCE-PINS.json @@ -0,0 +1,59 @@ +{ + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "files": [ + { + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/unconditional-batched-crt/check_batched_crt.py", + "local": "inputs/check_batched_crt.py", + "bytes": 11520, + "sha256": "681e2e3d71fa74c8b9b326f3860104fd9d89590a222e26ae6ee718d1fd40ff2e", + "git_blob": "1cf78abccd5e06beecc3ed21ba55f7c03b65fdbc" + }, + { + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/unconditional-batched-crt/NOTICE.md", + "local": "inputs/canonical-NOTICE.md", + "bytes": 2380, + "sha256": "924109837e71c52392191710d49c9deb42780878d1094f0b01e8690dbe799461", + "git_blob": "886a8fdee275f01b459cbd68ae2815dc9269502f" + }, + { + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "LICENSE", + "local": "LICENSE", + "bytes": 11357, + "sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4", + "git_blob": "261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64" + }, + { + "repository": "petalas/integer-mult-bounds", + "commit": "4eece58f5cebdb70a92d65447974f1c02383f60b", + "path": "research/canonical-rotation-switch-query/PROOF.md", + "local": "inputs/7504-PROOF.md", + "bytes": 10374, + "sha256": "cd886b0ed8a49153babd2a49887da0abf819902461268bf48f0a1cb6d427bdb1", + "git_blob": "80a8295201d5aea4e37016075ed8df10eca44656" + }, + { + "repository": "petalas/integer-mult-bounds", + "commit": "4eece58f5cebdb70a92d65447974f1c02383f60b", + "path": "research/canonical-rotation-switch-query/SOURCES.json", + "local": "inputs/7504-SOURCES.json", + "bytes": 1582, + "sha256": "7918c49ade0b407275cf59469b8d455f1a89e594c899c041d5e3ceb7a01b27cb", + "git_blob": "a505d408948ebe669e2dd422540c2f35aaf47698" + }, + { + "repository": "petalas/integer-mult-bounds", + "commit": "4eece58f5cebdb70a92d65447974f1c02383f60b", + "path": "research/canonical-rotation-switch-query/rotation_query.py", + "local": "inputs/rotation_query.py", + "bytes": 2329, + "sha256": "f38e6a92be46a620d1a8faca9b013fcb44e55dfad329735a30ceb64a413f5cc2", + "git_blob": "d9501b0425b432ff9d2a49b0a4514d7ff9914969" + } + ] +} diff --git a/research/literal-canonical-rotation-switch/SOURCES.json b/research/literal-canonical-rotation-switch/SOURCES.json new file mode 100644 index 0000000000..89b7c5747a --- /dev/null +++ b/research/literal-canonical-rotation-switch/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/literal-canonical-rotation-switch/TASK.json b/research/literal-canonical-rotation-switch/TASK.json new file mode 100644 index 0000000000..3500a6d92c --- /dev/null +++ b/research/literal-canonical-rotation-switch/TASK.json @@ -0,0 +1,90 @@ +{ + "schema_version": 1, + "task_id": "uniform-transfer-audit", + "priority_revision": 8, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "original_card": { + "id": "uniform-transfer-audit", + "question": "Can one of the selected record's five inherited assumptions be proved at its actual caller?", + "starting_points": [ + "docs/research/current-priorities.md", + "docs/research/research-family-status.md", + "certificates/selected-result.json", + "docs/research/pr-intake-evidence/pr5599-completion/PROOF-REVIEW.md" + ], + "methods": [ + "Construct and independently check one source-bound instance of the stated first experiment.", + "Seek an exact counterexample or target-specific complete-budget obstruction to that same proposed change." + ], + "acceptance_gate": "Identify the proposition and what would change downstream; do not equate a finite replay with a universal proof.", + "first_step": { + "command": [ + "python3", + "-B", + "scripts/research_selected_baseline.py" + ], + "expected": "PASS_RESEARCH_BASELINE_BINDINGS_ONLY", + "inspect": "Read revision 8, the selected review and live exact-source handoffs. Then follow this card's bounded first_experiment.", + "scope": "Source-bound orientation only, not a supplier replay or theorem proof." + }, + "first_experiment": "Choose one assumption ID (native_all_columns, owned_erasure, compiler, precision_tape, analytic_recovery), one quantified implication and exact dependency closure. Check current handoffs, including #5625 row reentry and #5707 root-prefix lowering, without treating their partial scope as the whole theorem. Prove or falsify that implication with a caller-bound argument; stop at the chosen obligation. Finite tests or root digits do not discharge an all-size statement.", + "bottleneck_link": "Judge the actual current supplier contract and complete signed target/paid bill; frozen-profile ceilings require an applicability proof.", + "allowed_variations": [ + "One exact source head, helper/cut region or quantified proposition and changed hypothesis; check live handoffs first. Different seeds are not different scopes." + ], + "scope_change_triggers": [ + "Changing source head, helper/cut domain, operation alphabet or caller boundary without recording the new scope.", + "Treating an archived proposal or local numerical pass as complete supplier admission." + ], + "overlap_terms": [ + "native_all_columns", + "owned_erasure", + "compiler", + "precision_tape", + "analytic_recovery" + ], + "existing_checks": [ + { + "scope": "PR #4100: proposed unconditional construction and finite checks, without independent acceptance.", + "evidence": "research/unconditional-batched-crt/README.md", + "remaining": "Independent proof audit of one caller-bound all-size implication; all other premises remain explicit.", + "status": "author-checked", + "source_commit": "337d04939571a637aeab54a0f58f54fde811663a", + "selected_record_sha256": "bb2eaa58647b353f88d0aec2eafb9d30df1be53589231b23e12ceef3e4bad129" + }, + { + "scope": "Selected PR5599: complete helper-subspace construction and independent caller replay; five framework assumptions remain.", + "evidence": "docs/research/pr-intake-evidence/pr5599-completion/PROOF-REVIEW.md", + "remaining": "The next experiment must identify uncovered source-specific work. Successor archive intake does not transfer this admission.", + "status": "reviewed", + "source_commit": "09dd0965711ca7eeb169057a420abab1c9052137", + "selected_record_sha256": "2a0220e866417774606e0f991e41b9c1d26b1f43b97857238cf478dbc7d330b5" + } + ] + }, + "scope_status": "refined", + "actual_scope": "Literal fixed-tape canonical padded-rotation switch predicate from #7504: five preserved descriptors, one owned Boolean, quadratic full time and linear working/history bound.", + "scope_change_reason": "The context-bound audit was already resolved by merged #6901. Root reallocated this worker to the explicit first physical-predicate open question of #7504.", + "bottleneck_link": "Arithmetic bit-query formulas lack literal tape, owned return and restoration. This package supplies that physical primitive under an explicit binary ABI.", + "budget_minutes": 90, + "stop_rule": "Stop at the predicate and honest repeated-workload bill; do not infer CRT offset production, complete caller or kappa improvement.", + "outcome": "completed", + "evidence": "PROOF.md, switch.py, hardware.py, verify.py, SOURCE-PINS.json, RESULT.json, REVIEW.md and INDEPENDENT-RESULT.json", + "author": "Jerry Chen / @CubeJerry", + "ai_assistance": "Substantial OpenAI assistance in research, implementation, proof, independent model-assisted review and publication packaging.", + "result_summary": "Uniform fixed2096-location14-tape predicate with complete time/history proof, canonical source binding and independent execution/oracle review. No new kappa or full assumption discharge.", + "open_questions": [ + { + "question": "Bind actual current CRT descriptors and consume the literal Boolean under a paid physical caller.", + "why_it_matters": "The point service currently enters through supplied descriptors and cannot establish caller source/transport/consumer closure by itself.", + "first_step": "Read exact current source and numerical lease, convert into the fixed-word ABI, consume output in the current-wire path and retire all copies.", + "blocked_by": "Actual source acquisition, physical header conversion, row/current-wire invariant and complete caller bill remain outside this package." + }, + { + "question": "Determine when direct queries improve a complete repeated workload over a resident ROM.", + "why_it_matters": "Avoiding ROM construction does not automatically beat amortized reuse.", + "first_step": "Compare identical query sequences including construction, transport, query return, reuse and disposal.", + "blocked_by": "No matched complete admitted caller tariff or reuse model is supplied." + } + ] +} diff --git a/research/literal-canonical-rotation-switch/VERIFY.json b/research/literal-canonical-rotation-switch/VERIFY.json new file mode 100644 index 0000000000..346342df7c --- /dev/null +++ b/research/literal-canonical-rotation-switch/VERIFY.json @@ -0,0 +1,68 @@ +{ + "schema_version": 1, + "status": "ready", + "python": "3.12", + "requirements": [], + "inputs": [ + "research/literal-canonical-rotation-switch/inputs/check_batched_crt.py", + "research/literal-canonical-rotation-switch/inputs/canonical-NOTICE.md", + "research/literal-canonical-rotation-switch/LICENSE", + "research/literal-canonical-rotation-switch/inputs/7504-PROOF.md", + "research/literal-canonical-rotation-switch/inputs/7504-SOURCES.json", + "research/literal-canonical-rotation-switch/inputs/rotation_query.py" + ], + "commands": [ + { + "argv": [ + "{python}", + "-I", + "-W", + "error", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 120, + "checks": "Canonical source, literal graph,544 key queries, all owners/guards/heads/retirement/history, malformed-domain rejection and semantic mutations." + }, + { + "argv": [ + "{python}", + "-I", + "-W", + "error", + "-B", + "-O", + "{package}/verify.py" + ], + "timeout_seconds": 120, + "checks": "Canonical source, literal graph,544 key queries, all owners/guards/heads/retirement/history, malformed-domain rejection and semantic mutations; optimized." + }, + { + "argv": [ + "{python}", + "-I", + "-W", + "error", + "-B", + "{package}/independent_check.py", + "{package}" + ], + "timeout_seconds": 60, + "checks": "Independent sparse interpreter and canonical parity-union-find oracle; all1566 small and544 required queries; full-depth and clean-rejection controls; physically returning wrong-answer mutation." + }, + { + "argv": [ + "{python}", + "-I", + "-W", + "error", + "-B", + "-O", + "{package}/independent_check.py", + "{package}" + ], + "timeout_seconds": 60, + "checks": "Independent sparse interpreter and canonical parity-union-find oracle; all1566 small and544 required queries; full-depth and clean-rejection controls; physically returning wrong-answer mutation." + } + ] +} diff --git a/research/literal-canonical-rotation-switch/hardware.py b/research/literal-canonical-rotation-switch/hardware.py new file mode 100644 index 0000000000..a8c259b6c9 --- /dev/null +++ b/research/literal-canonical-rotation-switch/hardware.py @@ -0,0 +1,85 @@ +"""Bounded verifier hardware. No fixture integer reaches a runtime operand. +Prepared for @CubeJerry with OpenAI assistance. Apache-2.0. +""" +B,L,E=2,3,4 +class Tape: + def __init__(self,body=(),origin=3,private=False,capacity=None): + self.origin=self.head=origin + span=len(body) if capacity is None else capacity+1 + if span=1<>i)&1 for i in range(width)] + +def fixture(h,s,a,j,x,overrides=None): + if h<0: raise ValueError('fixture h domain') + width=h+1 + bodies=[bits(h,max(1,h.bit_length())),bits(s,width),bits(a,width),bits(j,width),bits(x,width)] + if overrides: + for key,value in overrides.items(): bodies[key]=list(value) + tapes=[Tape(body,origin=3+i%4) for i,body in enumerate(bodies)] + tapes.append(Tape((),origin=4,capacity=1)) + # Capacity includes current blank frontier and guard retirement. + tapes.extend(Tape((),origin=3+i%5,private=True,capacity=max(h+2,len(bodies[0])+1)) for i in range(8)) + return tapes + +def check_return(tapes,before,outcome,expected=None): + if any(t.head!=t.origin for t in tapes): raise ValueError('head return') + for t,old in zip(tapes[:5],before[:5]): + if t.cells!=old or t.writes: raise ValueError('borrowed descriptor changed') + if outcome=='DONE': + old=list(before[5]);old[tapes[5].origin]=expected + if tapes[5].cells!=old or tapes[5].writes!=1: raise ValueError('owned Boolean output') + elif outcome=='REJECT': + if tapes[5].cells!=before[5] or tapes[5].writes: raise ValueError('rejected output modified') + else: raise ValueError('unknown outcome') + for t,old in zip(tapes[6:],before[6:]): + if t.cells!=old: raise ValueError('private capacity or exterior not restored') + if t.guard_writes!=[L,B]: raise ValueError('private guard lifetime') + if any(t.low= 5 and ins[2] in range(5), "borrowed/nonfixed write") + elif op == "M": + need(ins[2] in (-1, 1), "nonunit motion") + elif op == "J": + need(0 <= ins[1] < len(code), "jump target") + else: + need(ins[1] in ("DONE", "REJECT"), "unknown halt") + return code, labels + +def canonical_network(permutation): + """Canonical colors from input/output pair constraints, not source DFS.""" + n = len(permutation) + need(n >= 2 and n & (n - 1) == 0, "dyadic oracle domain") + need(sorted(permutation) == list(range(n)), "oracle permutation") + if n == 2: + return [(0, (permutation[0], permutation[0]))] + parent, parity = list(range(n)), [0] * n + def find(x): + value = 0 + while parent[x] != x: + value ^= parity[x] + x = parent[x] + return x, value + def constrain(x, y): + rx, px = find(x) + ry, py = find(y) + if rx == ry: + need(px ^ py == 1, "odd canonical coloring cycle") + else: + parent[ry] = rx + parity[ry] = px ^ py ^ 1 + for x in range(0, n, 2): + constrain(x, x + 1) + pairs = [[] for _ in range(n // 2)] + for x, image in enumerate(permutation): + pairs[image // 2].append(x) + for pair in pairs: + need(len(pair) == 2, "output pair degree") + constrain(*pair) + anchors, color = {}, [] + for x in range(n): + root, value = find(x) + if root not in anchors: + anchors[root] = value + color.append(value ^ anchors[root]) + first = tuple(color[x] ^ (x & 1) for x in range(n)) + last = [0] * n + children = [[None] * (n // 2) for _ in range(2)] + for x, image in enumerate(permutation): + last[image] = color[x] ^ (image & 1) + need(children[color[x]][x // 2] is None, "child input collision") + children[color[x]][x // 2] = image // 2 + left, right = [canonical_network(child) for child in children] + result = [(0, first)] + for a, b in zip(left, right): + need(a[0] == b[0], "child axis mismatch") + result.append((a[0] + 1, tuple((a, b)[x & 1][1][x // 2] for x in range(n)))) + result.append((0, tuple(last))) + for axis, table in result: + need(all(table[x] == table[x ^ (1 << axis)] for x in range(n)), + "oracle control depends on switched bit") + for start in range(n): + current = start + for axis, table in result: + current ^= table[current] << axis + need(current == permutation[start], "independent network endpoint") + return result + +def rotation_network(h, s, a): + n = 1 << h + return canonical_network([(x + a) % s if x < s else x for x in range(n)]) + +def word(value, width): + need(0 <= value < 1 << width, "fixture integer outside width") + return [(value // (1 << i)) % 2 for i in range(width)] + +class FrameViolation(RuntimeError): + pass + +def execute(code, labels, h, s, a, j, x, expected, override=None, missing_guard=False): + """One sparse map, literal instructions, translated negative owner origins.""" + origins = [-37 - 19 * role for role in range(14)] + height = word(h, max(1, h.bit_length())) + bodies = {0: height, 1: word(s, h + 1), 2: word(a, h + 1), + 3: word(j, h + 1), 4: word(x, h + 1)} + bodies.update(override or {}) + maximum = [len(bodies[t]) for t in range(5)] + [1] + maximum += [max(h + 2, len(bodies[0]) + 1)] * 8 + memory = {} + for role in range(14): + origin = origins[role] + memory[role, origin - 2] = 41 + memory[role, origin + maximum[role] + 1] = 43 + if role < 6: + memory[role, origin - 1] = LEFT + for role, body in bodies.items(): + for offset, symbol in enumerate(body): + if symbol != B: + memory[role, origins[role] + offset] = symbol + if missing_guard: + del memory[0, origins[0] - 1] + initial = memory.copy() + heads = origins.copy() + low, high = origins.copy(), origins.copy() + writes = [0] * 14 + guard_writes = [[] for _ in range(14)] + opcounts, visited = Counter(), set() + pc = steps = loops = 0 + limit = 1024 * (h + 3) ** 2 + while True: + need(steps < limit, "explicit step bill exceeded") + need(0 <= pc < len(code), "program counter escaped fixed graph") + visited.add(pc) + if pc == labels["query_loop"]: + loops += 1 + instruction = code[pc] + op = instruction[0] + opcounts[op] += 1 + steps += 1 + pc += 1 + if op in ("R", "W", "M"): + role = instruction[1] + if not origins[role] - 1 <= heads[role] <= origins[role] + maximum[role]: + raise FrameViolation("owner boundary crossed") + if op == "R": + symbol = memory.get((role, heads[role]), B) + if symbol not in instruction[2]: + raise FrameViolation("opaque exterior read") + pc = instruction[2][symbol] + elif op == "W": + symbol = instruction[2] + writes[role] += 1 + if heads[role] == origins[role] - 1: + guard_writes[role].append(symbol) + key = role, heads[role] + if symbol == B: + memory.pop(key, None) + else: + memory[key] = symbol + elif op == "M": + heads[role] += instruction[2] + low[role] = min(low[role], heads[role]) + high[role] = max(high[role], heads[role]) + if not origins[role] - 1 <= heads[role] <= origins[role] + maximum[role]: + raise FrameViolation("unit move crossed owner boundary") + elif op == "J": + pc = instruction[1] + elif op == "H": + outcome = instruction[1] + break + else: + raise RuntimeError("nonliteral opcode") + need(heads == origins, "not every physical head returned") + need(all(count == 0 for count in writes[:5]), "borrowed input was written") + need(all(not history for history in guard_writes[:6]), "permanent guard modified") + need(all(history == [LEFT, B] for history in guard_writes[6:]), + "private guard not installed then erased exactly once") + intended = initial.copy() + if expected is None: + need(outcome == "REJECT" and writes[5] == 0, "malformed/domain input accepted") + else: + need(outcome == "DONE" and writes[5] == 1, "valid query failed") + intended[5, origins[5]] = expected + need(loops <= h, "child descent exceeds height") + need(memory == intended, "full sparse owner state differs from specified return") + history = sum(b - a + 1 for a, b in zip(low, high)) + if expected is not None: + need(history == 11 * h + 2 * h.bit_length() + 48, + "exact successful owner history changed") + need(history < 16 * (h + 4), "linear history cap exceeded") + return {"steps": steps, "history": history, "loops": loops, + "outcome": outcome, "visited": visited, "opcounts": dict(opcounts)} + +def main(): + directory = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).resolve().parent + code, labels = load_graph(directory) + union = set() + calls = networks = total_steps = max_steps = 0 + def record(run): + nonlocal total_steps, max_steps + union.update(run["visited"]) + total_steps += run["steps"] + max_steps = max(max_steps, run["steps"]) + for h in range(1, 4): + for s in range(1, (1 << h) + 1): + for a in range(s): + oracle = rotation_network(h, s, a) + networks += 1 + for j, (_, row) in enumerate(oracle): + for x, bit in enumerate(row): + record(execute(code, labels, h, s, a, j, x, bit)) + calls += 1 + need((networks, calls) == (49, 1566), "small domain coverage changed") + key_bits = bytearray() + for a in range(17): + row = rotation_network(5, 17, a)[6][1] + for x, bit in enumerate(row): + record(execute(code, labels, 5, 17, a, 6, x, bit)) + key_bits.append(bit) + key_digest = sha256(key_bits).hexdigest() + need(len(key_bits) == 544 and key_digest == + "bc0ab563e6d8fdfa24ee89b50dbe3f9a3a6f23681f491e883c6b5aeef07d4104", + "required independently colored row fingerprint differs") + # A half turn preserves each lower input bit, recursively remains a half + # turn, and swaps only the final axis. No exponential network is built. + deep = [] + for h in (13, 37, 97): + run = execute(code, labels, h, 1 << h, 1 << (h - 1), h - 1, + (1 << h) - 1, 1) + record(run) + need(run["loops"] == h, "half-turn fixture did not reach full depth") + deep.append({k: v for k, v in run.items() if k not in ("visited", "opcounts")} | {"h": h}) + malformed = [ + ("height_zero", (0, 1, 0, 0, 0), None), + ("size_zero", (3, 0, 0, 0, 0), None), + ("size_above_cube", (3, 9, 0, 0, 0), None), + ("offset_equals_size", (3, 5, 5, 0, 0), None), + ("row_above_last", (3, 5, 1, 5, 0), None), + ("wire_above_cube", (3, 5, 1, 0, 8), None), + ("height_empty", (3, 5, 1, 0, 0), {0: []}), + ("height_noncanonical", (3, 5, 1, 0, 0), {0: [1, 0]}), + ("height_end_symbol", (3, 5, 1, 0, 0), {0: [END]}), + ("row_end_symbol", (3, 5, 1, 0, 0), {3: [END, 0, 0, 0]}), + ("size_short", (3, 5, 1, 0, 0), {1: [1, 0, 1]}), + ("offset_long", (3, 5, 1, 0, 0), {2: [1, 0, 0, 0, 0]}), + ] + rejected = [] + for name, arguments, override in malformed: + run = execute(code, labels, *arguments, None, override=override) + record(run) + rejected.append({"name": name, "steps": run["steps"], "history": run["history"]}) + # Mutate the *emitted table*, independently of the author's mutation API. + mutant = list(code) + changed = [] + for pc in range(labels["interior"], labels["child_reduce"]): + ins = mutant[pc] + if ins[0] == "R" and ins[1] == 11: + branches = dict(ins[2]) + branches[0], branches[1] = branches[1], branches[0] + mutant[pc] = ("R", 11, branches) + changed.append(pc) + need(len(changed) == 4, "child-parity mutation missed fixed branches") + args = (3, 5, 1, 1, 5) + expected = rotation_network(*args[:3])[args[3]][1][args[4]] + need(expected == 1, "independent mutation witness changed") + wrong = execute(mutant, labels, *args, 0) + need(wrong["outcome"] == "DONE", "mutant is not a returning semantic failure") + try: + execute(code, labels, 3, 5, 1, 1, 5, 1, missing_guard=True) + except FrameViolation: + outside = "missing permanent LEFT leaves promised owner window; outside ABI" + else: + raise RuntimeError("outside-ABI missing-guard control was silently accepted") + result = { + "status": "PASS", "source_sha256": SOURCE_SHA, + "graph_sha256": GRAPH_SHA, "locations": len(code), "tapes": 14, + "interpreter": "independent single sparse map with negative translated owner origins", + "oracle": "independent parity-union-find canonical coloring and full route verification", + "small_networks": networks, "small_queries": calls, + "required_h5_s17_j6_queries": len(key_bits), "required_row_sha256": key_digest, + "full_depth_half_turns": deep, "clean_rejection_controls": rejected, + "returning_child_parity_mutant": {"arguments": args, "correct": expected, + "returned": 0, "changed_locations": changed, "steps": wrong["steps"], + "history": wrong["history"], "heads_and_private_state_restored": True}, + "outside_abi_control": outside, + "all_locations_static_validation": True, + "normal_graph_dynamic_locations": len(union), + "normal_graph_complete_steps": total_steps, + "largest_normal_run_steps": max_steps, + "claims": "finite independent replay; universal result rests on separately reviewed proof", + } + print(json.dumps(result, indent=2, sort_keys=True)) + +if __name__ == "__main__": + main() diff --git a/research/literal-canonical-rotation-switch/inputs/7504-PROOF.md b/research/literal-canonical-rotation-switch/inputs/7504-PROOF.md new file mode 100644 index 0000000000..80a8295201 --- /dev/null +++ b/research/literal-canonical-rotation-switch/inputs/7504-PROOF.md @@ -0,0 +1,238 @@ +# Direct canonical switch queries for padded rotations + +This scoped written proof gives a new arithmetic construction of the precise +deterministic tables in Cinna Davis's #4100 `check_batched_crt.py:benes`. +The source is pinned at canonical main +`e54523517d0f03e58352e647c403a5af3e525a57` in SOURCES.json. Its generic +permutation-routing theorem is a cited premise. No predecessor replay is a +deliverable of this package. This contribution was produced by Nick Petalas. + +## 1. Domain and result + +Let `N=2^h`, `h>=1`, `1<=s<=N`, and `0<=a1`, the first row is + +``` +F(x) = [s and a are odd] [floor(x/2)=floor(s/2)]. (1) +``` + +The last row is + +``` +L(x) = [a is odd] [x (h-1,s_(x mod 2),a_(x mod 2),j-1,floor(x/2)). (4) +``` + +At `h=1`, the only row has constant bit `a`. If `a=0`, the entire network +is identity. Equations (1)-(4) compute one canonical bit by at most `h` +iterations, with `O(h^2)` elementary bit operations and `O(h)` working bits. +These are bounds for bounded-integer arithmetic, not a physical tape bill. + +## 2. Canonical component colors + +The source colors the graph with the two perfect matchings + +``` +A(x)=x xor 1, B(x)=P^{-1}(P(x) xor 1). +``` + +It starts each uncolored component at its least vertex with color zero. +For an even-cycle component, fixing that first color uniquely determines +all colors. DFS neighbor order therefore does not affect the result. The +source's endpoint rows are + +``` +F(x)=color(x) xor (x mod 2), +L(y)=color(P^{-1}(y)) xor (y mod 2). (5) +``` + +Call `A` pairs with coincident `B` edges doubled pairs. Every doubled pair +whose least endpoint is even has colors equal to address parity. +Write `s=2m+epsilon`, `a=2b+delta`. + +If `s` and `a` are both even, all components are doubled pairs. If `s` is +even and `a` is odd, the active interval `[0,s-1]` forms one alternating +cycle: its `B` edges are `(1,2),(3,4),...,(s-3,s-2),(s-1,0)`. +All remaining components are doubled pairs. Both cases give +`color(x)=x mod 2` everywhere. The size-two cycle may itself be doubled. + +Suppose `s` is odd and `a` is even. The component containing the first +padded vertex `s` is the interval `[s-a-1,s]`. Its edges alternate along +successive vertices, with one closing `B` edge between the interval's +endpoints. Its least vertex `s-a-1` is even. Every other component is a +doubled pair. Again `color(x)=x mod 2` everywhere. For `a=0` the named +interval is just the doubled pair `(s-1,s)`. + +Finally suppose `s` and `a` are odd. Put `t=s-a`, which is even and at +least two. The exceptional component has vertices + +``` +0,1,...,t-1, s, s-1. +``` + +There are alternating consecutive edges on `[0,t-1]`, the `B` edges +`(t-1,s)` and `(s-1,0)`, and the `A` edge `(s-1,s)`. +Starting at zero gives parity colors on `[0,t-1]`, color zero at `s`, +and color one at `s-1`. All other components are doubled pairs. Hence + +``` +color(x) = (x mod 2) xor [x in {s-1,s}]. (6) +``` + +These descriptions follow directly by substituting the rotation and its +inverse into `B`; they list all edges because each vertex has one `A` +neighbor and one `B` neighbor. In particular they also identify each +component's least vertex and settle the source's orientation convention. +Substitution in the first equation of (5) proves (1). + +## 3. The last row + +For `y=a`, and `y+s-a` when `y=s` the inverse is `y`. + +When `s` is even, the active inverse changes parity exactly when `a` is +odd, giving the first line of (2). When `s` is odd and `a` even, precisely +`y= 2 and size & (size - 1) == 0, "dyadic network size") + need(sorted(permutation) == list(range(size)), "permutation") + if size == 2: + return [(0, (permutation[0],) * 2)] + inverse = [0] * size + for x, y in enumerate(permutation): + inverse[y] = x + color = [-1] * size + for initial in range(size): + if color[initial] >= 0: + continue + color[initial] = 0 + stack = [initial] + while stack: + x = stack.pop() + for other in (x ^ 1, inverse[permutation[x] ^ 1]): + if color[other] < 0: + color[other] = color[x] ^ 1 + stack.append(other) + need(color[other] == color[x] ^ 1, "even cycle coloring") + first = tuple(color[x] ^ (x & 1) for x in range(size)) + last = tuple(color[inverse[y]] ^ (y & 1) for y in range(size)) + children = [] + for c in (0, 1): + child = [None] * (size // 2) + for x in range(size): + if color[x] == c: + child[x // 2] = permutation[x] // 2 + children.append(benes(child)) + result = [(0, first)] + for left, right in zip(*children): + need(left[0] == right[0], "common network schedule") + table = tuple((left, right)[x & 1][1][x // 2] for x in range(size)) + result.append((left[0] + 1, table)) + result.append((0, last)) + return result + + +def run_network(layers, value): + for bit, table in layers: + value ^= table[value] << bit + return value + + +def rotation(size, modulus, offset): + return tuple((x + offset) % modulus if x < modulus else x for x in range(size)) + + +def decode_group(values, moduli): + """Recover the integer from locally scaled CRT residues.""" + product = math.prod(moduli) + answer = 0 + prefix = 1 + for value, modulus in zip(values, moduli): + complement = product // modulus + residue = value * prefix % modulus + answer += residue * complement * pow(complement, -1, modulus) + prefix *= modulus + return answer % product + + +def balanced(values, moduli, reverse=False, compiled=False): + count = len(moduli) + need(count > 0 and count & (count - 1) == 0, "power-of-two axis count") + state = list(values) + levels = list(range(1, count.bit_length())) + for level in reversed(levels) if reverse else levels: + width = 1 << level + half = width // 2 + for start in range(0, count, width): + middle = start + half + valid = all(state[i] < moduli[i] for i in range(start, middle)) + lower = decode_group(state[start:middle], moduli[start:middle]) if valid else 0 + prefix = math.prod(moduli[start:middle]) + for i in range(middle, start + width): + offset = lower * pow(prefix, -1, moduli[i]) % moduli[i] + if reverse: + offset = -offset % moduli[i] + if compiled: + size = 1 << (moduli[i] - 1).bit_length() + state[i] = run_network(benes(rotation(size, moduli[i], offset)), state[i]) + elif state[i] < moduli[i]: + state[i] = (state[i] + offset) % moduli[i] + prefix *= moduli[i] + return tuple(state) + + +def direct(values, moduli): + prefix = 1 + integer = 0 + prefixes = [] + for value, modulus in zip(values, moduli): + prefixes.append(prefix) + integer += value * prefix + prefix *= modulus + return tuple(integer * pow(prefix, -1, modulus) % modulus + for prefix, modulus in zip(prefixes, moduli)) + + +def primitive_f(u, t, y, bits, positions, ybits, control_bits): + radix = 1 << bits + control_mask = (1 << control_bits) - 1 + ymask = (1 << ybits) - 1 + z = [(u >> (bits * i)) & 1 for i in range(len(positions))] + digits = [(t >> (bits * i)) & (radix - 1) for i in range(len(positions))] + y = (y + sum(2 * bit * digit * (1 << pos) + for bit, digit, pos in zip(z, digits, positions))) & ymask + t = (t + sum(((y >> pos) & 1) << (bits * i) + for i, pos in enumerate(positions))) & control_mask + digits = [(t >> (bits * i)) & (radix - 1) for i in range(len(positions))] + y = (y + sum(bit * (1 - 2 * digit) * (1 << pos) + for bit, digit, pos in zip(z, digits, positions))) & ymask + t = (t - sum((((y >> pos) & 1) ^ z[i]) << (bits * i) + for i, pos in enumerate(positions))) & control_mask + return u, t, y + + +def compact(u, t, y, source, bits=2, positions=(0,), ybits=6, control_bits=2): + need(control_bits >= bits * len(positions), "control field capacity") + mask = (1 << control_bits) - 1 + u, t, y = primitive_f(u, t, y, bits, positions, ybits, control_bits) + u = (u + sum(value << (bits * i) for i, value in enumerate(source(y)))) & mask + u, t, y = primitive_f(u, t, y, bits, positions, ybits, control_bits) + u = (u - sum(value << (bits * i) for i, value in enumerate(source(y)))) & mask + return u, t, y + + +def good(u, t, y, bits=2, positions=(0,), guard=6): + radix = 1 << bits + return all(((u >> (bits * i)) & (radix - 1)) != radix - 1 + and ((t >> (bits * i)) & (radix - 1)) != radix - 1 + and 2 * radix <= ((y >> (pos + 1)) & ((1 << (guard - 1)) - 1)) + < (1 << (guard - 1)) - 2 * radix + for i, pos in enumerate(positions)) + + +def linear_guard(u, t, y, bits=2, positions=(0,), guard=6, + control_bits=2, ybits=6): + """Bit-by-bit guard predicate; source functions are never evaluated.""" + steps = 0 + accepted = True + for word in (u, t): + for digit in range(len(positions)): + all_ones = True + for bit in range(bits): + all_ones = all_ones and bool((word >> (digit * bits + bit)) & 1) + steps += 1 + accepted = accepted and not all_ones + for pos in positions: + lower = 2 * (1 << bits) + upper = (1 << (guard - 1)) - lower + comparison = [0, 0] + for bit in range(guard - 2, -1, -1): + value = (y >> (pos + 1 + bit)) & 1 + for index, bound in enumerate((lower, upper)): + if comparison[index] == 0: + comparison[index] = value - ((bound >> bit) & 1) + steps += 2 + accepted = accepted and comparison[0] >= 0 and comparison[1] < 0 + need(steps <= 2 * control_bits + 2 * ybits, "linear tested-bit budget") + return accepted + + +def check(): + network_count = address_count = 0 + for bits in range(1, 7): + size = 1 << bits + for modulus in range(max(2, size // 2), size): + for offset in range(modulus): + permutation = rotation(size, modulus, offset) + layers = benes(permutation) + need(len(layers) == 2 * bits - 1, "network depth") + for bit, table in layers: + need(all(table[x] == table[x ^ (1 << bit)] for x in range(size)), + "switch control omits its target bit") + need(tuple(run_network(layers, x) for x in range(size)) == permutation, + "all-column modular rotation") + network_count += 1 + address_count += size + crt_addresses = valid_addresses = 0 + for moduli in ((3,), (3, 5), (3, 5, 7, 11)): + sizes = [1 << (s - 1).bit_length() for s in moduli] + seen = set() + for source in itertools.product(*(range(size) for size in sizes)): + target = balanced(source, moduli) + need(target not in seen, "padded CRT injection") + seen.add(target) + need(balanced(target, moduli, reverse=True) == source, "padded CRT inverse") + valid = all(x < s for x, s in zip(source, moduli)) + need(valid == all(x < s for x, s in zip(target, moduli)), "padding invariance") + if valid: + need(target == direct(source, moduli), "scaled CRT endpoint") + valid_addresses += 1 + need(balanced(source, moduli, compiled=True) == target, "compiled CRT endpoint") + crt_addresses += 1 + compact_cases = good_cases = repair_cases = 0 + functions = [lambda y: (0,), lambda y: (1,), lambda y: ((y >> 2) & 1,), + lambda y: ((y >> 1).bit_count() & 1,), + lambda y: ((((y >> 1) & 1) & ((y >> 4) & 1)),)] + for source_function, control_bits in itertools.product(functions, (2, 4)): + actual = {} + ideal = {} + for u, t, y in itertools.product(range(1 << control_bits), + range(1 << control_bits), range(64)): + start = (u, t, y) + end = compact(*start, source_function, control_bits=control_bits) + wanted = (u, t, y ^ source_function(y)[0]) + need(end not in actual, "actual gadget bijection") + need(wanted not in ideal, "ideal switch bijection") + actual[end] = start + ideal[wanted] = start + is_good = good(*start) + need(linear_guard(*start, control_bits=control_bits) == is_good, + "linear guard agrees with interval predicate") + need(good(*end) == is_good and good(*wanted) == is_good, "good/bad invariance") + if is_good: + need(end == wanted, "compact endpoint on good addresses") + good_cases += 1 + compact_cases += 1 + # Each arbitrary dirty input column follows S, then T S^-1 on bad holes. + for end, start in actual.items(): + u, t, y = start + repaired = (u, t, y ^ source_function(y)[0]) if not good(*end) else end + need(ideal[repaired] == start, "sparse correction column") + repair_cases += not good(*end) + multi_cases = 0 + def source_pair(y): + return (y >> 3) & 1, (y & ~65).bit_count() & 1 + for u, t in ((0, 0), (0, 15), (5, 5), (10, 10), (15, 0), (15, 15)): + for y in range(1 << 12): + start = (u, t, y) + end = compact(*start, source_pair, positions=(0, 6), ybits=12, control_bits=4) + f0, f1 = source_pair(y) + wanted = (u, t, y ^ f0 ^ (f1 << 6)) + is_good = good(*start, positions=(0, 6)) + need(linear_guard(*start, positions=(0, 6), control_bits=4, ybits=12) == is_good, + "two-target linear guard") + need(good(*end, positions=(0, 6)) == is_good, "two-target guard invariance") + if is_good: + need(end == wanted, "two-target compact endpoint") + multi_cases += 1 + return dict(status="PASS_FINITE_BATCHED_CRT_CONTROLS", network_count=network_count, + network_addresses=address_count, crt_addresses=crt_addresses, + valid_crt_addresses=valid_addresses, compact_addresses=compact_cases, + good_addresses=good_cases, repaired_bad_addresses=repair_cases, + two_target_addresses=multi_cases, linear_guard_verified=True, + machine_cost_verified=False, multiplication_kappa_claimed=False) + + +if __name__ == "__main__": + print(json.dumps(check(), sort_keys=True, indent=2)) diff --git a/research/literal-canonical-rotation-switch/inputs/rotation_query.py b/research/literal-canonical-rotation-switch/inputs/rotation_query.py new file mode 100644 index 0000000000..d9501b0425 --- /dev/null +++ b/research/literal-canonical-rotation-switch/inputs/rotation_query.py @@ -0,0 +1,56 @@ +"""Direct canonical Beneš switch queries for padded modular rotations. + +Produced by Nick Petalas. Apache-2.0. See PROOF.md for the exact source rule. +""" + + +def require(condition: bool, message: str) -> None: + if not condition: + raise ValueError(message) + + +def endpoint_bit(modulus: int, offset: int, address: int, last: bool) -> int: + """Internal endpoint formula; the public query validates the domain.""" + if not last: + return int((modulus & offset & 1) and address // 2 == modulus // 2) + if modulus % 2 == 0: + return int(offset % 2 == 1 and address < modulus) + if offset % 2 == 0: + return int(address < offset) + return int(offset - 1 <= address <= modulus) + + +def child_parameters(modulus: int, offset: int, branch: int) -> tuple[int, int]: + """Internal recurrence, including an empty identity child.""" + child_modulus = modulus // 2 + int(modulus % 2 == 1 and branch == offset % 2) + raw_offset = offset // 2 + branch * (offset % 2) + child_offset = 0 if raw_offset == child_modulus else raw_offset + return child_modulus, child_offset + + +def switch_bit(h: int, modulus: int, offset: int, layer: int, address: int) -> int: + """Return a bit of precisely the source's deterministic network. + + The conceptual domain is every h >= 1. The executable caps h at 4096 + to bound interpreter allocation and work. No permutation or ROM is built. + """ + require(all(type(value) is int for value in (h, modulus, offset, layer, address)), + "integer parameters") + require(1 <= h <= 4096, "1 <= h <= 4096") + require(1 <= modulus <= 1 << h, "modulus in occupied address domain") + require(0 <= offset < modulus, "canonical offset") + require(0 <= layer < 2 * h - 1, "network layer") + require(0 <= address < 1 << h, "network address") + for _ in range(h): + if offset == 0: + return 0 + if h == 1: + return offset + if layer == 0 or layer == 2 * h - 2: + return endpoint_bit(modulus, offset, address, layer != 0) + modulus, offset = child_parameters(modulus, offset, address & 1) + require(0 <= offset < modulus, "nonidentity child has positive modulus") + h -= 1 + layer -= 1 + address //= 2 + raise ArithmeticError("unreachable after one descent per address bit") diff --git a/research/literal-canonical-rotation-switch/switch.py b/research/literal-canonical-rotation-switch/switch.py new file mode 100644 index 0000000000..18a09d3401 --- /dev/null +++ b/research/literal-canonical-rotation-switch/switch.py @@ -0,0 +1,225 @@ +"""Literal fixed-tape canonical padded-rotation switch predicate. + +Prepared for @CubeJerry with OpenAI assistance. Apache-2.0. +The mathematical formulas and child closure are Nick Petalas's #7504. +Python loops below expand fixed graph macros only, never runtime data. +""" +from hashlib import sha256 +import json + +B,L,E=2,3,4 +SYMBOLS=(0,1,B,L,E) +H_IN,S_IN,A_IN,J_IN,X_IN,OUT=range(6) +COUNT,WIDTH,S,A,J,X,LAST,TEMP=range(6,14) +PRIVATE=tuple(range(6,14)); NUMBERS=(S,A,J,X,LAST,TEMP) +TAPES=14 + +class Builder: + def __init__(self): self.code=[]; self.labels={}; self.counter=0 + def fresh(self,prefix='q'): + self.counter+=1; return prefix+'_'+str(self.counter) + def mark(self,label): + if label in self.labels: raise ValueError('duplicate label '+label) + self.labels[label]=len(self.code) + def op(self,*instruction): self.code.append(instruction) + def read(self,tape,branches): + self.op('R',tape,{s:branches.get(s,'reject') for s in SYMBOLS}) + def jump(self,label): self.op('J',label) + def finish(self): + out=[] + for ins in self.code: + if ins[0]=='R': out.append(('R',ins[1],{s:self.labels[t] for s,t in ins[2].items()})) + elif ins[0]=='J': out.append(('J',self.labels[ins[1]])) + else: out.append(ins) + return tuple(out) + + def rewind(self,t): + loop=self.fresh('rewind'); back=self.fresh('back'); done=self.fresh('home') + self.op('M',t,-1); self.mark(loop) + self.read(t,{0:back,1:back,B:back,E:back,L:done}) + self.mark(back); self.op('M',t,-1); self.jump(loop) + self.mark(done); self.op('M',t,1) + + def zero_test(self,t,yes,no): + loop=self.fresh('zero'); adv=self.fresh('zadv'); z=self.fresh('iszero'); nz=self.fresh('nonzero') + self.mark(loop); self.read(t,{0:adv,1:nz,E:z}) + self.mark(adv); self.op('M',t,1); self.jump(loop) + self.mark(z); self.rewind(t); self.jump(yes) + self.mark(nz); self.rewind(t); self.jump(no) + + def decrement(self,t): + loop=self.fresh('dec'); zero=self.fresh('borrow'); one=self.fresh('borrow_done') + self.mark(loop); self.read(t,{0:zero,1:one}) + self.mark(zero); self.op('W',t,1); self.op('M',t,1); self.jump(loop) + self.mark(one); self.op('W',t,0); self.rewind(t) + + def increment(self,t): + loop=self.fresh('inc'); one=self.fresh('carry'); zero=self.fresh('carry_done') + self.mark(loop); self.read(t,{0:zero,1:one}) + self.mark(one); self.op('W',t,0); self.op('M',t,1); self.jump(loop) + self.mark(zero); self.op('W',t,1); self.rewind(t) + + def zero_word(self,t): + loop=self.fresh('clear_number'); bit=self.fresh('digit'); done=self.fresh('number_zero') + self.mark(loop); self.read(t,{0:bit,1:bit,E:done}) + self.mark(bit); self.op('W',t,0); self.op('M',t,1); self.jump(loop) + self.mark(done); self.rewind(t) + + def copy_word(self,source,target): + loop=self.fresh('copy'); z=self.fresh('copy0'); o=self.fresh('copy1'); done=self.fresh('copied') + self.mark(loop); self.read(source,{0:z,1:o,E:done}) + for bit,label in ((0,z),(1,o)): + self.mark(label); self.op('W',target,bit) + self.op('M',source,1); self.op('M',target,1); self.jump(loop) + self.mark(done); self.rewind(source); self.rewind(target) + + def shift_right(self,t): + loop=self.fresh('half'); z=self.fresh('half0'); o=self.fresh('half1'); done=self.fresh('half_done') + self.op('M',t,1); self.mark(loop); self.read(t,{0:z,1:o,E:done}) + for bit,label in ((0,z),(1,o)): + self.mark(label); self.op('M',t,-1); self.op('W',t,bit) + self.op('M',t,1); self.op('M',t,1); self.jump(loop) + self.mark(done); self.op('M',t,-1); self.op('W',t,0); self.op('M',t,1); self.rewind(t) + + def shift_left(self,t): + loops=[self.fresh('double0'),self.fresh('double1')]; done=self.fresh('double_done') + self.jump(loops[0]) + for carry in (0,1): + self.mark(loops[carry]); writes=[self.fresh('double_digit'),self.fresh('double_digit')] + self.read(t,{0:writes[0],1:writes[1],E:done if carry==0 else 'reject'}) + for old in (0,1): + self.mark(writes[old]); self.op('W',t,carry); self.op('M',t,1); self.jump(loops[old]) + self.mark(done); self.rewind(t) + + def compare(self,t,u,lt,eq,gt,skip=0): + loops=[self.fresh('cmp_lt'),self.fresh('cmp_eq'),self.fresh('cmp_gt')] + for _ in range(skip): self.op('M',t,1); self.op('M',u,1) + self.jump(loops[1]) + for state in range(3): + t0=self.fresh('cmp_t0'); t1=self.fresh('cmp_t1'); end=self.fresh('cmp_end') + pairs={(a,b):self.fresh('cmp_pair') for a in (0,1) for b in (0,1)} + done=self.fresh('cmp_done') + self.mark(loops[state]); self.read(t,{0:t0,1:t1,E:end}) + self.mark(t0); self.read(u,{0:pairs[0,0],1:pairs[0,1]}) + self.mark(t1); self.read(u,{0:pairs[1,0],1:pairs[1,1]}) + for (a,b),label in pairs.items(): + self.mark(label); self.op('M',t,1); self.op('M',u,1) + self.jump(loops[state if a==b else (0 if a=5,'fixed writes/no borrowed write') + count=networks=0; max_steps=0; max_history=0; totals={'steps':0,'reads':0,'writes':0,'moves':0} + for h in range(1,4): + n=1<