diff --git a/research/complex-x4-compensation-pairs/CLAIM.json b/research/complex-x4-compensation-pairs/CLAIM.json new file mode 100644 index 0000000000..46114ec219 --- /dev/null +++ b/research/complex-x4-compensation-pairs/CLAIM.json @@ -0,0 +1,29 @@ +{ + "track": "complex supplier", + "assignment_seed": 39, + "randomness": "Python secrets.randbelow(100), operating-system randomness", + "base_commit": "f567884aeb8851b6e794af1184119a3bfbe1e631", + "started_utc": "2026-10-13T10:43:23Z", + "expected_finish_utc": "2026-10-13T11:23:23Z", + "object": "PR799 selected X4 word, zero-frame arbitrary-helper compensation", + "method": "Exhaust signed unit target-pair row shears; choose one deterministic seed-39 disjoint greedy pass; emit and price preparation, factored compensation and inverse target basis", + "deliverable": "One finite scalar circuit improvement or scoped negative result, exact all-column replay, complete primitive prices, source pins and mutation controls; no new kappa", + "candidates": [ + "copy/unit coefficient lowering on X4: small direct transfer of PR696", + "restored target-pair factoring of actual X4 compensation: chosen", + "restored helper-pair factoring of X4: larger restoration/interface burden" + ], + "prior_work": "PR749, Sricharan Vagvala, d76c276a9f77df270982a61be7e53219316faf55: target pairs on earlier JP8; method credited, implementation not imported", + "overlap_check": "GitHub open issue search returned only #650, no sprint coordination issue; targeted all-state PR searches for compensation+gauge44 and X4+compensation found #645 and #881, neither this circuit improvement. Reviewed #864 frame exclusion, #876 full pair/triple exchange search, #787 coefficient composition and #807 CK helper pairs.", + "coordination": "Local claim because no coordination issue exists", + "constraints": "Only this new research directory; upstream and selected frontier unchanged; subordinate worker restricted to provenance and independent scalar verification", + "result": { + "status": "Completed finite circuit construction; no new kappa", + "finished_utc": "2026-10-13T11:15:01Z", + "compensation_additions": "6320 -> 3276, including preparation and restoration", + "saved_real_primitives_per_orientation": 33800, + "validation": "Exact primitive replay on 728 logical plus 9 private columns, both orientations; independent integer/dyadic endpoint check; 9 package tests normal and optimized; selected-record check and 5 existing tests passed", + "unresolved": "Typed supplier integration, refreshed bindings and global assembly admission; inherited theorem obligations remain", + "pull_request": "https://github.com/CrocSwap/integer-mult-bounds/pull/901" + } +} diff --git a/research/complex-x4-compensation-pairs/LICENSE b/research/complex-x4-compensation-pairs/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/research/complex-x4-compensation-pairs/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/complex-x4-compensation-pairs/NOTICE.md b/research/complex-x4-compensation-pairs/NOTICE.md new file mode 100644 index 0000000000..1e0e8fcd00 --- /dev/null +++ b/research/complex-x4-compensation-pairs/NOTICE.md @@ -0,0 +1,21 @@ +# Attribution + +New experiment, exact circuit recipe, primitive replay, integer checker, +controls and packaging prepared for ToikY with substantial OpenAI Codex +assistance. One delegated Codex agent wrote the integer checker and performed +a bounded code review. This is not independent human peer review. + +The restored target-pair mechanism is credited to Sricharan Vagvala +(@theon199), PR749 at d76c276a9f77df270982a61be7e53219316faf55, following +Scott Woolsey Biggart's PR713 and the concurrent PR716 target-basis work. +No predecessor implementation is imported or claimed as new. + +Inputs are the selected PR799 emitted construction by Jeremy Kothe, retaining +Chafik Boukhalfa's PR741 frames and icekylinx's gauge44 source work. The +construction/compiler ancestry includes DreamingOfClouds, Dominik Scholz, +Dugongue, eumemic, Rohan Arun and other credited predecessors. Original +gauge44, SW4 and upstream notices are preserved in UPSTREAM-NOTICES.md. +Douglas Colkitt's accepted replay archive provides the source artifacts. + +Apache-2.0 applies. LICENSE is copied unchanged from the source package. +All inherited assumptions and source-specific AI disclosures remain intact. diff --git a/research/complex-x4-compensation-pairs/README.md b/research/complex-x4-compensation-pairs/README.md new file mode 100644 index 0000000000..47dfea7693 --- /dev/null +++ b/research/complex-x4-compensation-pairs/README.md @@ -0,0 +1,161 @@ +# Restored target pairs in the selected X4 compensation + +**Finite complex-supplier circuit construction; no new κ.** On the selected +PR799 X4 word, 56 disjoint signed-unit target pairs reduce the fully paid +zero-frame compensation from **6,320 to 3,276 additions**, including preparation +and restoration. The full emitted programs save **33,800 real-component +primitives per orientation** under the unchanged binary-Horner lowering. + +| Full emitted scalar program | Original | Candidate | +| --- | ---: | ---: | +| Scalar macros, either orientation | 19,197 | 16,153 | +| Forward real-component primitives | 193,162 | 159,362 | +| Inverse-transpose real-component primitives | 193,210 | 159,410 | +| Forward positive-prefix bound | 6,812,058,044,968,180,837 / 256 | unchanged | +| Reverse positive-prefix bound | 48,299,247,699,832,632,898,063 / 16 | 48,299,247,845,619,250,997,475 / 16 | +| Forward / reverse prefix bits | 55 / 72 | 55 / 72 | + +The paid child profile remains +`{1:2548, 2:338, 3:430, 4:194, 5:56, 8:8}`. Every non-scalar event is preserved +in order, including phases, climbs, centre boundaries and residual wrappers. +The accepted conditional κ remains **0.001661634653669567**. This scalar saving +alone changes no recurrence exponent and is not a measured runtime improvement. + +## Reproduce + +Python 3.10 or newer, standard library only, no network or optimizer: + +```sh +python3 -I -B research/complex-x4-compensation-pairs/verify.py +python3 -I -B research/complex-x4-compensation-pairs/test_package.py +``` + +Expected main marker: + +```text +PASS_X4_COMPENSATION_PAIRS pairs=56 compensation=6320->3276 saved_real=33800 columns=728+9 orientations=2 no_new_kappa +``` + +The second command passes nine focused tests. Both also work under `-O`. +To export both literal candidate event programs, add `--out /fresh/directory` +to the first command. Verification regenerates and compares every result field; +the output directory must not exist. Normal replay takes approximately six +seconds on the author's environment; this is reproduction guidance only. + +## Circuit and complete local cost + +At the compensation boundary the old operation is `y += C h`, where all 112 +targets are arbitrary and all 504 helpers may contain dirt. `experiment.py` +re-derives C from the actual `A + cut + B` map followed by the actual target +precondition; it compares every coefficient with the selected canonical input. +There are 6,320 nonzero coefficients. + +For a selected pair `(t,u,s)`, `s` is ±1. Let T be the target shear +`y_t += s y_u`. Replace the compensation by the literal schedule + +1. prepare every disjoint T; +2. accumulate `(T C) h` into the prepared targets; +3. restore every target with T⁻¹ in reverse order. + +Only row t changes: `C_t` becomes `C_t + s C_u`. Thus the endpoint is exactly +`T⁻¹(T y + T C h) = y + C h` over the rationals and complexes, with arbitrary +initial y and h. The 56 pairs are disjoint, so these transforms commute; no +helper is written, no private array is added, and every target is restored to +its original basis before the next retained event. The reverse program uses +the inverse transpose of every scalar macro in chronological order. Its +composition is the inverse transpose of the same complete endpoint. + +All replacement gates are at frame zero. Every touched target has bottom start +frame. Every touched helper has bottom start and FULL end; no entering or +cold-ended helper is touched before its wrapper. Both basis changes occur +before `entry_adapters`. Consequently the complete state and existing frame +schedule at that boundary are identical to the original. The subsequent +scalar, frame, cone, phase, centre and wrapper interfaces are inherited from +the exact source-pinned selected construction. + +For a reduced nonzero dyadic coefficient `q = ±a / 2^d`, the retained lowering +charges + +`2 (3 + floor(log2(a)) + popcount(a) + d)` + +real-component primitives. These are the initial coefficient-stream CLEAR, +every source access, Horner doubling, halving, signed target accumulation and +final CLEAR, on both real and imaginary components. A signed-unit target shear +costs eight, so preparation and restoration cost **16 per pair**, all included. +No coefficient sharing or copy/unit discounts from other pending PRs are added. +All old centre copies/clears and every retained scalar macro remain paid. + +The primitive replay gives exact endpoints on all **728 logical input columns +plus nine arbitrary private-input columns** in both orientations. The inherited +eight centre registers and coefficient stream are erased with charged CLEARs; +they are not claimed to restore arbitrary private dirt. All 504 public dirty +helpers are restored. Positive envelopes include every coefficient-work +intermediate. The reverse envelope grows slightly, while the 55/72-bit budgets +remain below the inherited local 192-bit allowance. A global precision or +invoice replay is not claimed. + +## Search domain and independent evidence + +OS assignment seed **39** chooses the complex-supplier track. Exhaustive scoring +covers all **24,864** ordered distinct target pairs with signs ±1; **2,978** have +positive fully paid saving. A single seeded shuffle followed by descending +gain and greedy disjoint selection yields the 56-pair recipe. The stopping +rule is completion of this census and one greedy pass. This proves neither +optimal pair matching nor optimal general compensation. Larger coefficients, +overlapping bases, helper bases and broader circuit classes were not searched. + +`RECIPE.json` records every selected pair and score, and binds the complete +score census. `RESULT.json` records full programs' semantic hashes, exact +prices, prefixes, profiles and endpoint digests. `independent.py` imports no +constructor, retained auditor or experiment code: it replays sparse integer +numerator rows with common dyadic denominators. It checks the original and +candidate logical words on all 728 columns in both orientations, as well as +the complete compensation boundary with arbitrary target inputs. + +Negative controls reject missing preparation/restoration, sign and coefficient +errors, dirty-helper writes, dropped private-stream clears, overlapping pairs, +unpaid basis costs, corrupted sources (even after repairing the outer manifest) +and corrupted results. The missing-preparation control **passes a helper-only +column check but fails the arbitrary-target check**. Recompression, JSON +reformatting and standalone optimized relocation are positive controls. + +## Provenance, limits and credit + +Exact base: `f567884aeb8851b6e794af1184119a3bfbe1e631`. `SOURCES.json` pins the +immutable accepted replay archive and all proof-relevant input JSON fields. +The three inputs are unchanged `native/local/` members of +`research/community-frontier799-audit/integrated799-replay.tar.gz`; their +canonical word and ordered program hashes match PR799's published local pins. +Gzip packaging is not a mathematical equality criterion. + +The source is Jeremy Kothe's **PR799** (`80e6463157cfc80b85af09e7e2f14748fe2dac60`) +on Chafik Boukhalfa's **PR741** (`e516b1463606840a15f80aac1995d64ce0092e89`), +icekylinx's gauge44 and the retained cold/entrance/owner/compiler ancestry. +**Sricharan Vagvala's PR749** (`d76c276a9f77df270982a61be7e53219316faf55`) +supplied the restored rational target-pair mechanism on the earlier JP8 word; +its implementation is not imported. That PR credits the binary target-basis +work in **PR713/PR716**. This contribution applies the credited mechanism to +the actual selected X4 matrix and emitted programs, supplies a new complete +pair census, and adds an integer-based full logical replay. No priority for +the mechanism is claimed. PR787 coefficient composition and PR807 CK helper +pairs concern different inputs/circuit blocks. PR864 frame-only optimality +does not exclude changes to this scalar block. + +Concurrent **Philipp (@mightyOil), PR883** +(`b31a870a3842b37f6ab97767c506ce91783632a2`) fuses X4's original 168 +precondition macros. Here those macros are retained byte-for-byte; the changed +block is the subsequent 6,320-addition helper compensation. Its code and +784-primitive saving are not consumed, and no combined saving is asserted. + +Only this research directory is added. Production integration still requires +a typed alternative-compensation step and refreshed source/program bindings, +global hosting, invoice and assembly admission. All-size/compiler, +common-label/mutable-source realization, whole-call hosting, precision/tape, +analytic transfer and bit H1–H5 remain inherited hypotheses. No full supplier +cold replay, whole-repository suite, hosted CI, Lean multiplication theorem, +or independent human review is claimed. See `VALIDATION.md` for checks and +development corrections. The selected frontier and `upstream/` are unchanged. + +Prepared for **ToikY** with substantial **OpenAI Codex assistance**, including +one bounded delegated implementation and review of the integer checker. +Apache-2.0; predecessor notices and license are retained alongside this note. diff --git a/research/complex-x4-compensation-pairs/RECIPE.json b/research/complex-x4-compensation-pairs/RECIPE.json new file mode 100644 index 0000000000..543d952041 --- /dev/null +++ b/research/complex-x4-compensation-pairs/RECIPE.json @@ -0,0 +1,347 @@ +{ + "seed": 39, + "pairs": [ + [ + 114, + 184, + -1, + 744 + ], + [ + 191, + 137, + -1, + 728 + ], + [ + 126, + 127, + -1, + 696 + ], + [ + 217, + 164, + -1, + 696 + ], + [ + 160, + 210, + -1, + 684 + ], + [ + 161, + 146, + -1, + 684 + ], + [ + 162, + 221, + -1, + 668 + ], + [ + 172, + 196, + -1, + 668 + ], + [ + 213, + 166, + -1, + 666 + ], + [ + 115, + 178, + -1, + 664 + ], + [ + 218, + 165, + -1, + 664 + ], + [ + 153, + 154, + -1, + 664 + ], + [ + 131, + 214, + -1, + 664 + ], + [ + 179, + 192, + -1, + 650 + ], + [ + 118, + 194, + -1, + 644 + ], + [ + 140, + 187, + -1, + 644 + ], + [ + 185, + 195, + -1, + 644 + ], + [ + 144, + 136, + -1, + 644 + ], + [ + 121, + 201, + -1, + 632 + ], + [ + 211, + 156, + -1, + 632 + ], + [ + 173, + 206, + -1, + 632 + ], + [ + 158, + 159, + -1, + 618 + ], + [ + 181, + 209, + -1, + 616 + ], + [ + 188, + 112, + -1, + 614 + ], + [ + 197, + 147, + -1, + 612 + ], + [ + 113, + 198, + -1, + 612 + ], + [ + 171, + 142, + -1, + 604 + ], + [ + 170, + 205, + -1, + 604 + ], + [ + 180, + 117, + -1, + 602 + ], + [ + 125, + 190, + -1, + 600 + ], + [ + 130, + 152, + -1, + 600 + ], + [ + 207, + 120, + -1, + 600 + ], + [ + 167, + 151, + -1, + 586 + ], + [ + 200, + 138, + -1, + 586 + ], + [ + 135, + 145, + -1, + 580 + ], + [ + 134, + 220, + -1, + 580 + ], + [ + 219, + 157, + -1, + 580 + ], + [ + 186, + 141, + -1, + 580 + ], + [ + 124, + 212, + -1, + 578 + ], + [ + 168, + 150, + -1, + 576 + ], + [ + 128, + 155, + -1, + 568 + ], + [ + 182, + 183, + -1, + 568 + ], + [ + 139, + 193, + -1, + 566 + ], + [ + 149, + 132, + -1, + 566 + ], + [ + 208, + 176, + -1, + 552 + ], + [ + 116, + 177, + -1, + 538 + ], + [ + 163, + 216, + -1, + 536 + ], + [ + 148, + 133, + -1, + 534 + ], + [ + 199, + 119, + -1, + 534 + ], + [ + 222, + 223, + -1, + 522 + ], + [ + 202, + 122, + -1, + 520 + ], + [ + 215, + 129, + -1, + 512 + ], + [ + 204, + 169, + -1, + 502 + ], + [ + 189, + 143, + -1, + 498 + ], + [ + 123, + 203, + -1, + 488 + ], + [ + 175, + 174, + -1, + 456 + ] + ], + "search": { + "domain": 24864, + "profitable": 2978, + "scores_sha256": "91e47752f8b2e1872805d6f89f10b709387f633749b101ec4ba3eab57354401b", + "stopping_rule": "all ordered target pairs, signs -1/+1; one greedy pass" + } +} diff --git a/research/complex-x4-compensation-pairs/RESULT.json b/research/complex-x4-compensation-pairs/RESULT.json new file mode 100644 index 0000000000..5ad71ea010 --- /dev/null +++ b/research/complex-x4-compensation-pairs/RESULT.json @@ -0,0 +1,122 @@ +{ + "status": "PASS_X4_COMPENSATION_PAIRS", + "base_commit": "f567884aeb8851b6e794af1184119a3bfbe1e631", + "selected_kappa_unchanged": "1661634653669567/1000000000000000000", + "seed": 39, + "pairs": 56, + "search": { + "domain": 24864, + "profitable": 2978, + "scores_sha256": "91e47752f8b2e1872805d6f89f10b709387f633749b101ec4ba3eab57354401b", + "stopping_rule": "all ordered target pairs, signs -1/+1; one greedy pass" + }, + "compensation_adds_before": 6320, + "compensation_adds_after": 3276, + "compensation_boundary": { + "status": "PASS_INDEPENDENT_ALL_COLUMN_COMPENSATION", + "checked_columns": 728, + "max_numerator_bits": 3, + "endpoint_sha256": "b956a0889d4580d638d48d5a29796e5e443cdee4102b00a9a87bd3adb94d3946" + }, + "orientations": { + "forward": { + "baseline": { + "real_component_primitives": 193162, + "scalar_macros": 19197, + "prefix_l1": "6812058044968180837/256", + "prefix_bits": 55, + "paid_profile": { + "1": 2548, + "2": 338, + "3": 430, + "4": 194, + "5": 56, + "8": 8 + }, + "checked_columns": 737, + "private_input_contract": "eight centres and coefficient stream are erased by charged CLEARs", + "program_sha256": "076a2d428f97abb30473df05110998efbe5ac809885bae4ceb1b8bd81329a1e6" + }, + "candidate": { + "real_component_primitives": 159362, + "scalar_macros": 16153, + "prefix_l1": "6812058044968180837/256", + "prefix_bits": 55, + "paid_profile": { + "1": 2548, + "2": 338, + "3": 430, + "4": 194, + "5": 56, + "8": 8 + }, + "checked_columns": 737, + "private_input_contract": "eight centres and coefficient stream are erased by charged CLEARs", + "program_sha256": "e84b603ebcc0b8e60cf96405629a0b8c298d2a8d9098109f6b3235d952fa48a4" + }, + "saved_real_primitives": 33800, + "independent_baseline": { + "status": "PASS_INDEPENDENT_ALL_COLUMN_FORWARD", + "checked_columns": 728, + "max_numerator_bits": 20, + "endpoint_sha256": "5cea0ab5ede77348dd9257a6d62209cd39338d17e571779279b7d08f19fd514d" + }, + "independent_candidate": { + "status": "PASS_INDEPENDENT_ALL_COLUMN_FORWARD", + "checked_columns": 728, + "max_numerator_bits": 20, + "endpoint_sha256": "5cea0ab5ede77348dd9257a6d62209cd39338d17e571779279b7d08f19fd514d" + } + }, + "backward": { + "baseline": { + "real_component_primitives": 193210, + "scalar_macros": 19197, + "prefix_l1": "48299247699832632898063/16", + "prefix_bits": 72, + "paid_profile": { + "1": 2548, + "2": 338, + "3": 430, + "4": 194, + "5": 56, + "8": 8 + }, + "checked_columns": 737, + "private_input_contract": "eight centres and coefficient stream are erased by charged CLEARs", + "program_sha256": "7915679ee305927463d19725360cc15132dd21ede18897d09a935dca1df0d55d" + }, + "candidate": { + "real_component_primitives": 159410, + "scalar_macros": 16153, + "prefix_l1": "48299247845619250997475/16", + "prefix_bits": 72, + "paid_profile": { + "1": 2548, + "2": 338, + "3": 430, + "4": 194, + "5": 56, + "8": 8 + }, + "checked_columns": 737, + "private_input_contract": "eight centres and coefficient stream are erased by charged CLEARs", + "program_sha256": "87d62d9b7a76d0e2d592cf30916b589ebf3a8eac490e76d99b0f175d74bae0f3" + }, + "saved_real_primitives": 33800, + "independent_baseline": { + "status": "PASS_INDEPENDENT_ALL_COLUMN_DUAL", + "checked_columns": 728, + "max_numerator_bits": 20, + "endpoint_sha256": "3aaef3b50e9ddb37b6357841d2389a9fde40d3ff87711864385e0041bac8c8ac" + }, + "independent_candidate": { + "status": "PASS_INDEPENDENT_ALL_COLUMN_DUAL", + "checked_columns": 728, + "max_numerator_bits": 20, + "endpoint_sha256": "3aaef3b50e9ddb37b6357841d2389a9fde40d3ff87711864385e0041bac8c8ac" + } + } + }, + "scope": "Finite scalar circuit; exact all-column and primitive-prefix replays. No global invoice, supplier compilation or new kappa." +} diff --git a/research/complex-x4-compensation-pairs/SOURCES.json b/research/complex-x4-compensation-pairs/SOURCES.json new file mode 100644 index 0000000000..1ec0330d01 --- /dev/null +++ b/research/complex-x4-compensation-pairs/SOURCES.json @@ -0,0 +1,27 @@ +{ + "base_commit": "f567884aeb8851b6e794af1184119a3bfbe1e631", + "source_pr799_head": "80e6463157cfc80b85af09e7e2f14748fe2dac60", + "source_pr741_head": "e516b1463606840a15f80aac1995d64ce0092e89", + "selected_record_sha256": "9873519224e2db72d6a8c926f51e3e75129671e467948c6f6b03744f8bcfc699", + "archive": { + "path": "research/community-frontier799-audit/integrated799-replay.tar.gz", + "sha256": "70dfdfcf2ff95352c6020ee9dfca6dca9032b33c10daed3f3dc574c014f4e2cb" + }, + "input_semantic_sha256": { + "CANONICAL-WORD.json.gz": "1c0e9da767d4418f70016af599e4a447a3f7777acabe930318459c0fbbd260aa", + "LOCAL-CHECKS.json": "4cca9475a0d9a93041696c570cbc8d91a40be76e63196a670256ce7e79521580", + "LOCAL-PROGRAMS.json.gz": "223c2bb27ad68a4e9468c3ddaece1899d577b661190922fdd25f5976052c4cab" + }, + "extracted_members": { + "CANONICAL-WORD.json.gz": "native/local/CANONICAL-WORD.json.gz", + "LOCAL-PROGRAMS.json.gz": "native/local/LOCAL-PROGRAMS.json.gz", + "LOCAL-CHECKS.json": "native/local/LOCAL-CHECKS.json" + }, + "prior_method": { + "pr": 749, + "author": "Sricharan Vagvala (@theon199)", + "head": "d76c276a9f77df270982a61be7e53219316faf55", + "imported_implementation": false + }, + "comparison_rule": "All proof-relevant JSON fields are canonically hashed; gzip recompression is permitted. Archive hash pins the immutable source archive; it is not a regenerated-container equality test." +} diff --git a/research/complex-x4-compensation-pairs/UPSTREAM-NOTICES.md b/research/complex-x4-compensation-pairs/UPSTREAM-NOTICES.md new file mode 100644 index 0000000000..9bc57dab79 --- /dev/null +++ b/research/complex-x4-compensation-pairs/UPSTREAM-NOTICES.md @@ -0,0 +1,77 @@ +# Preserved predecessor notices + +Historical source notices below retain their original scope. + +## Original research/gauge44-frames-x/NOTICE.md + +# Gauge44 attribution and scope + +New contributions by icekylinx, with OpenAI GPT-6 Astra assistance. +Local review and packaging used OpenAI Codex. Apache-2.0 applies; +the license is included. The full original PR635 notice is preserved as +UPSTREAM-NOTICE.md and construction/UPSTREAM-NOTICE.md. + +The new contribution is the changed source-branch gauge and retired-row +completion, source-carried coordinate totals, exact 44-cold-end realization, +and explicit all72 whole-family assignment using concave capacity matching +with integer majorization certificates. The center-carrier generalization +retains the exact ordered common frames and complete native local contract. +Independent local, price, interface and owner fixed-point checks are included. + +The construction retains the credited PR635 K-triangle and porting machinery, +earlier joint-prefix/HPE/frame ancestry and icekylinx's prior factory work. +#645 used the same cited PR543 bit supplier as PR635. This package (research/gauge44-frames-x) cites the merged PR589 bit supplier instead, with a derived rank-mass deficit (PROOF-NOTE-BIT.md); #645's retained PR543-based evidence is historical. It builds #645's word without K-triangles (PartialK) and stacks earlier community jp8 layers on it (G44Stack), adds the p6n ends (NoTriReopen), entrance promotions (BlockInvert) a read-set exchange (BRoute), chafreaky's #741 frames and JointXF's joint exchange; see README. All-size, realization, +hosting, precision/tape, analytic-transfer and bit H1-H5 assumptions remain +conditional. No upstream license, credit, source pin or AI disclosure is +replaced by this notice. + +PR641 and PR642 were checked as concurrent reported frontier comparisons. +Their endpoints and owner maps are not included here. See CONSTRUCTION.md, +hosting/PROOF.md, independent/ and README.md for the exact contribution scope. + +## Original research/complex-sw4-frame8/NOTICE.md + +# Eight B-frame changes: attribution + +New frame search, recipe, controls, owner reconstruction and standalone packaging by chafreaky with substantial OpenAI Codex assistance. Apache-2.0 applies. + +This work retains PR699's BRoute SW4 read exchanges and minimal four-promotion recipe; PR676's NoTriReopen p6n ends, ColdWitness driver and Q6Reviewer controls; PR664's BlockInvert promotion machinery; our PR685/PR660 integer owner methods; and the earlier PR659, PR635, gauge, joint-prefix, HPE, phase, global-admission and bit-supplier lineages. Original notices are retained in UPSTREAM-NOTICE.md, construction/ and provenance/. See PROVENANCE.md for source commits, authors and verification boundaries. + +The original gauge44 notice is retained under provenance/upstream-pr699/NOTICE.md. Its historical contribution statements do not describe the new frame-only change. All-size realization, hosting, precision/tape, analytic transfer and bit-interface assumptions remain conditional. + +## Original research/gauge44-frames-x/UPSTREAM-NOTICE.md + +# Attribution and scope + +Four verified provider types are offered to every call: PR571's prefix word with twelve multi-cut cold kernels (PR568's unchanged constructor), the same word with forty width-five entrance promotions (PR569's unchanged frame constructor) before those kernels, PR575's plain joint-prefix provider, and PR568's eight-cold provider. A window MILP with an exact per-pattern model chooses the dispatch and a literal owner map. PR583's six source-bound kernel frame coalescences (its unchanged constructor and negative controls) are applied to every PR571-prefix provider word (ck and atm3), followed by two further coalescences that each first move one addition past two commuting additions (package code/build_gate_moves.py, extending PR583's constructor); a final hyperplane_end step (package code/build_hpe.py) then runs 46 single-gate cleanups h -= p right after part B at the dim-8 join U of their registers, so 46 width-8 entering helpers per call end at U with width 7; each such gate commutes with every earlier cleanup gate on its registers (for 8 of them the partner's one earlier gate x -= p only reads p), and the reordered program is replayed exactly. A window MILP (exact windows, RINS around an LP vertex) gives the dispatch ck 45 / atm3 21 / jp8 6 and the literal owner map. + +Pinned external sources (unchanged; `verify.py` checks their manifests and every file it uses): +- PR568 (`research/complex-multicold`, commit `71c99ac935a33bb7b59a1b4a7af8725a939b0b90`). +- PR571 (`research/structural-gain`, commit `b7bdc5a8de18fcf418cfb9c7d83a2b1097a5e4a3`). +- PR569 (`research/larger-gain`, commit `897213a855b7fb8a1b8b0e552a2f5c42e6c1b326`). +- PR575 (`research/complex-joint-prefix`, commit `eac6f7e378ab622dac50a2fd4b7ef6eab014de44`). +- PR583 (`research/kernel-frame-coalescing`, commit `89be768f0157f5a3d8e4db69cf1748768605eac9`). + +Provider construction is described as typed steps in `data/SPEC.json` (`build`); `verify.py` runs only allowlisted step types with their paired omission audits and checks every input and output content hash. `code/` holds the spec-driven global admission scripts adapted from PR571's `frontier-composition/global-code/` (OpenAI Codex assisted, Apache-2.0): every expected value is read from `data/SPEC.json` and compared only after independent recomputation. `code/generated_identity.py` and `code/generated_identity_controls.py`, and the decompressed-content artifact identities in the bind, audit, invoice, assembly and phase-timing scripts, are taken unchanged from PR586 by chafreaky (`research/promoted-kernel-coalescing`, commit `4846fee5b06af770e9b3a10c36200f673d656725`, OpenAI Codex assisted, Apache-2.0), including its proof-content and reference/metadata mutation controls; the normalization of descriptive width metadata after frame changes follows the same PR. + +In PR601, the owner map was nominated by a HiGHS window MILP (adapted from PR569's `global/nominate_width7.py`) with lazy cross-time Hall cuts; this package's re-solved map is described below. Neither is an admission dependency. + +DreamingOfClouds with Claude Opus 5.5 (Anthropic), via Claude Code. (The PR601 package this one starts from states: "Prepared by Claude Code (Anthropic) research agents.") Apache-2.0 applies; LICENSE is included. All notices, licenses, source pins and AI disclosures of the pinned sources and their ancestry are retained in those packages and are not replaced by this notice. All inherited conditional assumptions remain conditional. + +**This package (complex-571-cold14, DreamingOfClouds).** It starts from PR601 (jeremykothe2, `research/complex-571-hpem46`, commit `529ab7dcb59d5ea7a5798e9e06cf5b3aee8a1550`). Everything above is kept unchanged except the following: +- every provider chain (ck, atm3, jp8) gains the typed step `cold_end` (`code/build_cold_end.py`, `code/cold_end_controls.py`; recipes `data/recipes/*-cold_end.json.gz`); +- the generalised native chain and the global admission scripts accept cold helpers that end below FULL (with `0:U` wrappers), a refactored exact cleanup, and check the wrapper order; +- `data/PLAN.json` / `data/OWNERS.json.gz` (dispatch and literal owner map) come from a relocate/swap/ejection-chain/provider-flip annealing search started from PR601's map, refined by an exact pattern-restricted owner model (CP-SAT) with a literal edge-colouring expansion (not an admission dependency); +- `data/SPEC.json` holds the expected values, recorded by a discovery run and then checked by a strict run. + +The cold-end construction (a row-plus-column cone condition for low-frame ends, a rank-0 dirt-spread premix and multi-gate lower-frame cleanup) builds on PR591 / PR592 / PR593 / PR601 (jeremykothe2) and our PR599 (Lean: multi-gate and cold hyperplane-end tails). DreamingOfClouds with Claude Opus 5.5 (Anthropic), via Claude Code. Build on this at your own risk. + +**This package (complex-571-cold14-b3, jeremykothe2).** It is PR604's `complex-571-cold14` (DreamingOfClouds) with ColdBeyond's second cold end per block (two new `cold_end` A-gate primitives, `PROOF-NOTE.md`), ColdSupply's E1 entering pair and reviewed controls, a free dispatch (jp8 ×60, atm3 ×12) and a literal owner map from an exact per-time-Hall window MIP. All other construction, code, controls and proofs are PR604's and earlier contributors', unchanged. + +**This package (complex-571-cold14-k492).** It is complex-571-cold14-b3 with these changes: +- **K-triangle base words.** The leaver-read K-triangle skeleton atom and its read schedule (`data/TRI-SCHEDULE.json`) are by AtomScout, a Claude Code research agent. `code/construct_k_triangle.py` is PR531's `code/construct_504.py` (icekylinx, OpenAI Codex / GPT assisted, Apache-2.0; pinned source `direct_delivery`) extended with that atom. +- **Ported chains.** The PR604/B3 chains are ported stage by stage onto the K-triangle words by `code/build_port_stage.py` (Port480, a Claude Code research agent). `code/build_frame_regroup.py` extends PR583's `build_frames.py` (chafreaky). +- **Helper count R.** The generalisation of the global scripts to the provider helper count R is by GlobalR (a Claude Code research agent), with AtomReviewer's fixes (PROOF-NOTE-R.md). +- **Owner map.** The owner map, the cold_end recipes on the K-triangle words and the package assembly are by Stack492, Port480 and ColdBeyond (Claude Code research agents). + +Build on this at your own risk. diff --git a/research/complex-x4-compensation-pairs/VALIDATION.md b/research/complex-x4-compensation-pairs/VALIDATION.md new file mode 100644 index 0000000000..6ed16695bf --- /dev/null +++ b/research/complex-x4-compensation-pairs/VALIDATION.md @@ -0,0 +1,86 @@ +# Validation receipt + +Checked 2026-10-13 on macOS arm64 with bundled CPython **3.12.14**. +Only the new package is added to base +`f567884aeb8851b6e794af1184119a3bfbe1e631`. + +Passing commands (normal and optimized receipts agree exactly): + +```sh +python3 -I -B research/complex-x4-compensation-pairs/verify.py --out /tmp/x4-seed39-first-replay +python3 -I -O -B research/complex-x4-compensation-pairs/verify.py --out /tmp/x4-seed39-optimized-replay +python3 -I -B research/complex-x4-compensation-pairs/test_package.py +python3 -I -O -B research/complex-x4-compensation-pairs/test_package.py +make selected-record-check +python3 -B -m unittest discover -s tests -p test_selected_result.py -v +``` + +The output directories above must be fresh. The first recorded run used +`--record` to create RESULT.json; subsequent runs compare every field. +Actual execution used the desktop's bundled Python executable, without an +installation or new dependency. The system Python 3.9.6 is below this package's +documented Python 3.10 minimum. + +Results: + +- Complete 24,864-score census reproduced; 2,978 profitable candidates; + seed-39 greedy pass reproduces all 56 disjoint selected pairs. +- All 728 arbitrary logical input columns pass for baseline/candidate, + forward/inverse-transpose, in the independent integer engine. +- Both literal primitive programs pass 728 logical plus nine private-input + columns, including charged coefficient/centre erasure and dirty-helper + restoration. Full costs and exact positive prefix bounds match RESULT.json. +- Nine focused tests pass normally and under optimized Python. These include + six boundary corruptions, the omitted-preparation/helper-only countercontrol, + both missing-restoration orientations, both dropped private CLEARs, + overlapping/unpaid recipes, eight independent admission controls and every + actual coefficient's numeric lowering boundary. +- Package tests accept recompressed/reformatted JSON and standalone optimized + relocation with spaces. They reject changed sources, repaired outer source + manifests and changed stored result prices. Exported candidate program + hashes agree with the directly constructed programs. +- The selected-record integrity command and its five existing regression + tests pass. The selected certificate, source packages, proof supplements and + upstream inputs remain unchanged. + +A delegated read-only review independently ran the optimized nine-test suite, +checked the algebra, prices, private-input contract and receipt scope, and +reported no material defect. This is an AI-assisted review, not independent +human or proof-assistant verification. + +## Development corrections + +The first comparison used the untransported raw word against transported +canonical registers; exact equality failed despite matching 6,320 coefficients. +The final experiment derives its matrix directly from the pinned **canonical +selected X4** word and matches every compensation gate after sorting target +and helper indices. Historical `evidence/local` is a predecessor and is not +the input to this package. + +The initial integer checker rejected legitimate scale gates with denominator +`-1`, used by the retained inverse convention. It now normalizes denominator +sign before dyadic validation, still rejects zero denominators, and includes +a negative-denominator cancellation control. Full replays subsequently pass. +These were implementation/admission failures, not mathematical counterexamples +to the selected construction. + +## Verification limits + +This contribution supplies a complete finite scalar and frame-boundary +substitution with explicit lowering and local prefix evidence. It does not +modify the selected compiler or source-bound supplier wrappers. No fresh +Clifford/phase construction, global owner admission, complete global invoice, +47-constraint outer assembly, full supplier cold replay, repository-wide +`make verify`, hosted CI or Lean multiplication theorem was run or is claimed. +The broad Make target regenerates unrelated historical artifacts and replays +unchanged suppliers; scoped checks above cover this isolated research package. +The global integration and inherited hypotheses listed in README remain open. + +Final overlap refresh at **2026-10-13 11:03 UTC**, through PR897, found no PR for this X4 +compensation construction. Targeted all-state searches returned #881 +(independent word verification) and #869 (different B deliveries), with the +earlier credited #749 on JP8. PR883's complete metadata was inspected: its +changed 168-macro target precondition is retained here, while this contribution +changes only the following helper compensation. Its head and attribution are +credited in README. No pending implementation is consumed or combined saving +claimed. A fresh `git fetch origin` confirmed main still equals the exact base. diff --git a/research/complex-x4-compensation-pairs/experiment.py b/research/complex-x4-compensation-pairs/experiment.py new file mode 100644 index 0000000000..91c4349ac8 --- /dev/null +++ b/research/complex-x4-compensation-pairs/experiment.py @@ -0,0 +1,263 @@ +"""Bounded signed-unit target-pair experiment on the pinned selected X4 word. + +Prepared for ToikY with substantial OpenAI Codex assistance. Apache-2.0. +The mechanism follows Sricharan Vagvala's PR749; its code is not imported. +""" +import copy +import gzip +import hashlib +import json +import random +from collections import Counter +from fractions import Fraction as Q +from pathlib import Path + +HERE = Path(__file__).resolve().parent + + +def require(value, label): + if not value: + raise RuntimeError(label) + + +def digest(value): + return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(',', ':')).encode()).hexdigest() + + +def read(path): + raw = Path(path).read_bytes() + return json.loads(gzip.decompress(raw) if str(path).endswith('.gz') else raw) + + +def apply(gate, rows, dual=False): + if gate[0] == 'add': + t, s = gate[1:3] + q = Q(gate[3], gate[4]) + if dual: + t, s, q = s, t, -q + require(t != s, 'self add') + for k, x in list(rows[s].items()): + z = rows[t].get(k, Q(0)) + q*x + if z: + rows[t][k] = z + else: + rows[t].pop(k, None) + elif gate[0] == 'scale': + t = gate[1] + q = Q(gate[2], gate[3]) + if dual: + q = 1/q + rows[t] = {k: q*x for k, x in rows[t].items()} + else: + raise RuntimeError('unknown logical gate') + + +def compensation(word): + v, n = word['v'], 2*word['v']+word['R'] + raw = [{i: Q(1)} for i in range(n)] + for gate in word['A']+word['cut']+word['B']: + apply(gate, raw) + dirt = [{} for _ in range(n)] + for t in range(v, 2*v): + dirt[t] = {k: x for k, x in raw[t].items() if k >= 2*v} + for gate in word['precondition']: + require(gate[-1] == 0, 'nonzero precondition frame') + apply(gate, dirt) + return {t: {k: -x for k, x in dirt[t].items()} for t in range(v, 2*v)} + + +def add(t, s, q, frame=0): + q = Q(q) + require(t != s and q != 0, 'invalid generated add') + return ['add', t, s, q.numerator, q.denominator, frame] + + +def row_gates(matrix): + return [add(t, s, q) for t, row in sorted(matrix.items()) for s, q in sorted(row.items()) if q] + + +def scalar_cost(gate): + if gate[0] in ('clear', 'copy'): + return 2 + q = Q(gate[3], gate[4]) if gate[0] == 'add' else Q(gate[2], gate[3]) + a, b = abs(q.numerator), q.denominator + require(a > 0 and b & (b-1) == 0, 'invalid dyadic scalar') + if gate[0] == 'scale': + require(a & (a-1) == 0, 'nonunit scale') + return 2*(abs(a.bit_length()-b.bit_length()) + int(q < 0)) + return 2*(3+a.bit_length()-1+a.bit_count()+b.bit_length()-1) + + +def row_cost(row): + return sum(scalar_cost(add(-1, s, q)) for s, q in row.items() if q) + + +def combine(a, b, sign): + row = dict(a) + for k, x in b.items(): + y = row.get(k, Q(0))+sign*x + if y: + row[k] = y + else: + row.pop(k, None) + return row + + +def search(matrix, seed=39): + # Complete enumeration; one seeded disjoint greedy pass, no optimality claim. + scores = [] + for t in sorted(matrix): + before = row_cost(matrix[t]) + for u in sorted(matrix): + if t == u: + continue + for sign in (-1, 1): + changed = combine(matrix[t], matrix[u], sign) + after = row_cost(changed)+2*scalar_cost(add(t, u, sign)) + scores.append([before-after, t, u, sign]) + shuffled = list(scores) + random.Random(seed).shuffle(shuffled) + shuffled.sort(key=lambda x: -x[0]) + selected, used = [], set() + for gain, t, u, sign in shuffled: + if gain > 0 and not used.intersection((t, u)): + selected.append([t, u, sign, gain]) + used.update((t, u)) + require(selected, 'no profitable signed-unit target pair') + return selected, dict(domain=len(scores), profitable=sum(s[0] > 0 for s in scores), + scores_sha256=digest(scores), stopping_rule='all ordered target pairs, signs -1/+1; one greedy pass') + + +def factored(matrix, selected): + transformed = copy.deepcopy(matrix) + used = set() + for t, u, sign, gain in selected: + require(sign in (-1, 1) and t in matrix and u in matrix and t != u, 'invalid recipe') + require(not used.intersection((t, u)), 'overlapping target pairs') + used.update((t, u)) + transformed[t] = combine(matrix[t], matrix[u], sign) + require(gain == row_cost(matrix[t])-row_cost(transformed[t])-2*scalar_cost(add(t, u, sign)), 'recipe gain') + prep = [add(t, u, sign) for t, u, sign, _ in selected] + restore = [add(t, u, -sign) for t, u, sign, _ in reversed(selected)] + return prep+row_gates(transformed)+restore + + +def dual(gate): + result = list(gate) + if result[0] == 'add': + result[1], result[2], result[3] = result[2], result[1], -result[3] + else: + result[2], result[3] = result[3], result[2] + return result + + +def scalar_event(gate, backward=False): + e = dual(gate) if backward else gate + if e[0] == 'add': + scalar = ['add', ['L', e[1]], ['L', e[2]], e[3], e[4]] + else: + scalar = ['scale', ['L', e[1]], e[2], e[3]] + return ['scalar', scalar, 0] + + +def splice(program, canonical, replacement, backward=False): + require(program[0] == ['phase', 'zero_frame_precondition'], 'initial phase') + end = program.index(['phase', 'entry_adapters']) + original = canonical['precondition']+canonical['compensation'] + require(program[1:end] == [scalar_event(e, backward) for e in original], 'baseline compensation boundary') + start = 1+len(canonical['precondition']) + return program[:start]+[scalar_event(e, backward) for e in replacement]+program[end:] + + +def lower(scalar): + """Literal one-real-component primitive word, including all private work. + + w is the inherited private coefficient stream. It is cleared before and + after each add; each access/double/half/update/clear is an instruction. + """ + tag, t = scalar[0], tuple(scalar[1]) + if tag == 'clear': + return [('clear', t)] + if tag == 'copy': + return [('copy', t, tuple(scalar[2]))] + q = Q(scalar[3], scalar[4]) if tag == 'add' else Q(scalar[2], scalar[3]) + a, b = abs(q.numerator), q.denominator + require(a and b & (b-1) == 0, 'lowering dyadic') + if tag == 'scale': + require(a & (a-1) == 0, 'lowering unit scale') + power = a.bit_length()-b.bit_length() + result = [('scale', t, Q(2) if power > 0 else Q(1, 2)) for _ in range(abs(power))] + if q < 0: + result.append(('scale', t, Q(-1))) + return result + require(tag == 'add', 'unknown lowering') + s, w = tuple(scalar[2]), ('W', 0) + result = [('clear', w)] + for i, bit in enumerate(bin(a)[2:]): + if i: + result.append(('scale', w, Q(2))) + if bit == '1': + result.append(('add', w, s, Q(1))) + result.extend(('scale', w, Q(1, 2)) for _ in range(b.bit_length()-1)) + result.extend([('add', t, w, Q(1 if q > 0 else -1)), ('clear', w)]) + require(2*len(result) == scalar_cost(scalar), 'lowering price') + return result + + +def replay_emitted(events, n, v, backward=False): + """Exact all-column macro replay and positive primitive-prefix enclosure.""" + # Arbitrary inputs for all eight private centres and the coefficient stream + # are included. Their inherited CLEAR contract erases them, not restores dirt. + keys = [('L', i) for i in range(n)]+[('C', i) for i in range(8)]+[('W', 0)] + state = {key: {i: Q(1)} for i, key in enumerate(keys)} + bound = {key: Q(1) for key in keys} + peak = Q(1) + paid = Counter() + count = macros = 0 + for event in events: + if event[0] in ('climb', 'center'): + paid[event[5] if event[0] == 'climb' else event[4]] += 1 + continue + if event[0] != 'scalar': + continue + scalar = event[1] + macros += 1 + for primitive in lower(scalar): + count += 2 # identical real and imaginary component instructions + tag, t = primitive[:2] + if tag == 'clear': + bound[t] = Q(0) + state[t] = {} + elif tag == 'copy': + bound[t] = bound[primitive[2]] + state[t] = dict(state[primitive[2]]) + elif tag == 'scale': + bound[t] *= abs(primitive[2]) + state[t] = {k: primitive[2]*x for k, x in state[t].items()} + else: + bound[t] += abs(primitive[3])*bound[primitive[2]] + for k, x in list(state[primitive[2]].items()): + z = state[t].get(k, Q(0))+primitive[3]*x + if z: + state[t][k] = z + else: + state[t].pop(k, None) + peak = max(peak, bound[t]) + for i in range(n): + expected = {i: Q(1)} + if backward and i < v: + expected[i+v] = Q(-1) + elif not backward and v <= i < 2*v: + expected[i-v] = Q(1) + require(state['L', i] == expected, 'emitted endpoint '+str(i)) + require(all(not state[k] for k in keys[n:]), 'private centre/stream erasure') + bits = peak.numerator.bit_length()-peak.denominator.bit_length()+1 + return dict(real_component_primitives=count, scalar_macros=macros, + prefix_l1=str(peak), prefix_bits=bits, + paid_profile=dict(sorted(paid.items())), checked_columns=n+9, + private_input_contract='eight centres and coefficient stream are erased by charged CLEARs', + program_sha256=digest(events)) + + +def logical_program(word, replacement): + return word['precondition']+replacement+word['A']+word['cut']+word['B']+word['tail']+word['cleanup'] diff --git a/research/complex-x4-compensation-pairs/independent.py b/research/complex-x4-compensation-pairs/independent.py new file mode 100644 index 0000000000..3a6c2f9461 --- /dev/null +++ b/research/complex-x4-compensation-pairs/independent.py @@ -0,0 +1,191 @@ +"""Independent exact scalar replay using integer rows and dyadic denominators. + +No constructor, retained auditor, or search implementation is imported. Every +register starts with its own independent input column, including dirty helpers. +Prepared with substantial OpenAI Codex assistance; Apache-2.0. +""" + +import hashlib +import json +from fractions import Fraction + + +def _require(condition, message): + if not condition: + raise RuntimeError(message) + + +def _power(value): + _require(type(value) is int and value > 0 and value & (value - 1) == 0, + "denominator is not a positive power of two") + return value.bit_length() - 1 + + +def _normalize(row, denominator_power): + """Remove common factors of two, without introducing negative powers.""" + if not row: + return {}, 0 + if denominator_power: + shift = min(denominator_power, + min((abs(value) & -abs(value)).bit_length() - 1 + for value in row.values())) + if shift: + row = {column: value >> shift for column, value in row.items()} + denominator_power -= shift + return row, denominator_power + + +def _run(program, n, dual): + _require(type(n) is int and n > 0, "invalid register count") + rows = [({register: 1}, 0) for register in range(n)] + largest = 1 + for index, gate in enumerate(program): + _require(isinstance(gate, (list, tuple)) and gate, + "malformed gate at %d" % index) + op = gate[0] + _require(op in ("add", "scale"), "unknown operation at %d" % index) + _require(len(gate) == (6 if op == "add" else 5), + "malformed %s gate at %d" % (op, index)) + target = gate[1] + registers = [target, gate[2]] if op == "add" else [target] + _require(all(type(r) is int and 0 <= r < n for r in registers), + "register out of range at %d" % index) + numerator, denominator = gate[3:5] if op == "add" else gate[2:4] + _require(type(numerator) is int, "noninteger numerator at %d" % index) + _require(type(denominator) is int and denominator != 0, + "invalid denominator at %d" % index) + if denominator < 0: + numerator, denominator = -numerator, -denominator + power = _power(denominator) + if op == "add": + source = gate[2] + _require(source != target, "self-add at %d" % index) + if dual: + target, source, numerator = source, target, -numerator + target_row, target_power = rows[target] + source_row, source_power = rows[source] + if not numerator or not source_row: + continue + common_power = max(target_power, source_power + power) + new_row = {column: value << (common_power - target_power) + for column, value in target_row.items()} + source_shift = common_power - source_power - power + for column, value in source_row.items(): + result = new_row.get(column, 0) + numerator * (value << source_shift) + if result: + new_row[column] = result + else: + new_row.pop(column, None) + rows[target] = _normalize(new_row, common_power) + else: + _require(numerator != 0, "zero scale at %d" % index) + absolute = abs(numerator) + _require(absolute & (absolute - 1) == 0, + "scale is not a signed binary unit at %d" % index) + if dual: + numerator, power = (-1 if numerator < 0 else 1) << power, absolute.bit_length() - 1 + row, old_power = rows[target] + rows[target] = _normalize({column: numerator * value + for column, value in row.items()}, old_power + power) + largest = max(largest, max((abs(value).bit_length() + for value in rows[target][0].values()), default=0)) + return rows, largest + + +def _endpoint(rows, expected, largest, label): + for register, (actual, denominator_power) in enumerate(rows): + wanted = expected(register) + scale = 1 << denominator_power + _require(set(actual) == set(wanted) and + all(Fraction(value, scale) == wanted[column] + for column, value in actual.items()), + "%s endpoint mismatch at register %d" % (label, register)) + canonical = [[power, sorted(row.items())] for row, power in rows] + return dict(status="PASS_INDEPENDENT_ALL_COLUMN_" + label, + checked_columns=len(rows), max_numerator_bits=largest, + endpoint_sha256=hashlib.sha256(json.dumps( + canonical, separators=(",", ":")).encode()).hexdigest()) + + +def check(program, n, dual=False, v=112): + """Check the complete forward shear or chronological inverse transpose. + + ``v=112`` is the selected X4 port count. A smaller explicit ``v`` is useful + for independent controls. Every source, target, and helper input is checked. + """ + _require(type(n) is int and n > 0, "invalid register count") + _require(type(v) is int and v > 0 and n >= 2 * v, "invalid port count") + rows, largest = _run(program, n, dual) + + def expected(register): + row = {register: 1} + if dual and register < v: + row[v + register] = -1 + elif not dual and v <= register < 2 * v: + row[register - v] = 1 + return row + + return _endpoint(rows, expected, largest, "DUAL" if dual else "FORWARD") + + +def check_compensation(program, C, v, n): + """Check ``target += C * helper`` with arbitrary target and helper dirt. + + C is a mapping from target register to a mapping from helper register to an + exact rational coefficient. A list of row mappings indexed by target-v is + also accepted. All other registers must retain their independent inputs. + """ + _require(type(n) is int and n > 0, "invalid register count") + _require(type(v) is int and v > 0 and n >= 2 * v, "invalid port count") + if isinstance(C, (list, tuple)): + _require(len(C) == v, "compensation matrix row count") + C = {v + index: row for index, row in enumerate(C)} + _require(isinstance(C, dict), "compensation must be a row mapping") + wanted = {} + for target, row in C.items(): + _require(type(target) is int and v <= target < 2 * v, + "compensation target out of range") + _require(isinstance(row, dict), "compensation row is not a mapping") + wanted[target] = {} + for source, value in row.items(): + _require(type(source) is int and 2 * v <= source < n, + "compensation helper out of range") + value = Fraction(*value) if isinstance(value, (list, tuple)) else Fraction(value) + _power(value.denominator) + if value: + wanted[target][source] = value + rows, largest = _run(program, n, False) + return _endpoint(rows, lambda register: {register: 1, **wanted.get(register, {})}, + largest, "COMPENSATION") + + +def self_test(): + """Exercise noncommuting dirty-helper cancellation and rejection controls.""" + program = [["add", 2, 0, 1, 2, []], ["add", 1, 2, 2, 1, []], + ["add", 2, 0, -1, 2, []], ["add", 1, 2, -2, 1, []], + ["scale", 2, -2, 1, []], ["scale", 2, -1, 2, []], + ["scale", 2, 1, -1, []], ["scale", 2, -1, 1, []], + ["add", 2, 0, 3, 4, []], ["add", 2, 0, -3, 4, []]] + check(program, 3, v=1) + check(program, 3, dual=True, v=1) + block = [["add", 1, 2, 3, 4, []]] + check_compensation(block, {1: {2: Fraction(3, 4)}}, 1, 3) + controls = [program[:3], [["add", 0, 0, 1, 1, []]], + [["scale", 2, 0, 1, []]], [["scale", 2, 3, 1, []]], + [["scale", 2, 1, 3, []]], [["scale", 2, 1, 0, []]], + [["add", 3, 0, 1, 1, []]]] + for control in controls: + try: + check(control, 3, v=1) + except RuntimeError: + continue + raise RuntimeError("negative self-test accepted") + try: + check_compensation([], {1: {2: Fraction(3, 4)}}, 1, 3) + except RuntimeError: + return dict(status="PASS_INDEPENDENT_SELF_TEST", rejected_controls=len(controls) + 1) + raise RuntimeError("compensation control accepted") + + +if __name__ == "__main__": + print(json.dumps(self_test(), sort_keys=True)) diff --git a/research/complex-x4-compensation-pairs/inputs/CANONICAL-WORD.json.gz b/research/complex-x4-compensation-pairs/inputs/CANONICAL-WORD.json.gz new file mode 100644 index 0000000000..416757e153 Binary files /dev/null and b/research/complex-x4-compensation-pairs/inputs/CANONICAL-WORD.json.gz differ diff --git a/research/complex-x4-compensation-pairs/inputs/LOCAL-CHECKS.json b/research/complex-x4-compensation-pairs/inputs/LOCAL-CHECKS.json new file mode 100644 index 0000000000..1c8b6b8dd4 --- /dev/null +++ b/research/complex-x4-compensation-pairs/inputs/LOCAL-CHECKS.json @@ -0,0 +1,36 @@ +{ + "forward": { + "sha256": "076a2d428f97abb30473df05110998efbe5ac809885bae4ceb1b8bd81329a1e6", + "events": 24399, + "scalar_macros": 19197, + "real_component_primitive_bound": 193162, + "paid_profile": { + "1": 2548, + "2": 338, + "3": 430, + "4": 194, + "5": 56, + "8": 8 + }, + "all_columns": 728, + "private_centers_cleared": true, + "private_coefficient_stream_cleared_after_each_macro": true + }, + "backward": { + "sha256": "7915679ee305927463d19725360cc15132dd21ede18897d09a935dca1df0d55d", + "events": 24399, + "scalar_macros": 19197, + "real_component_primitive_bound": 193210, + "paid_profile": { + "1": 2548, + "2": 338, + "3": 430, + "4": 194, + "5": 56, + "8": 8 + }, + "all_columns": 728, + "private_centers_cleared": true, + "private_coefficient_stream_cleared_after_each_macro": true + } +} diff --git a/research/complex-x4-compensation-pairs/inputs/LOCAL-PROGRAMS.json.gz b/research/complex-x4-compensation-pairs/inputs/LOCAL-PROGRAMS.json.gz new file mode 100644 index 0000000000..f3cb79ae40 Binary files /dev/null and b/research/complex-x4-compensation-pairs/inputs/LOCAL-PROGRAMS.json.gz differ diff --git a/research/complex-x4-compensation-pairs/test_package.py b/research/complex-x4-compensation-pairs/test_package.py new file mode 100644 index 0000000000..00de142640 --- /dev/null +++ b/research/complex-x4-compensation-pairs/test_package.py @@ -0,0 +1,139 @@ +"""Mathematical and package controls; every rejection uses the production checker.""" +import copy +import gzip +import json +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import experiment as E +import independent as I +import verify as V + + +class Controls(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.c, cls.programs, cls.checks, cls.C, cls.recipe, cls.block, cls.changed = V.build(rerun_search=False) + + def test_missing_preparation_only_helper_test_is_insufficient(self): + missing = self.block[56:] + actual, _ = I._run(missing, 728, False) + # A check confined to helper inputs incorrectly accepts omitted prep. + for t, row in self.C.items(): + numerator, power = actual[t] + observed = {k: E.Q(x, 1 << power) for k, x in numerator.items() if k >= 224} + self.assertEqual(observed, row) + with self.assertRaisesRegex(RuntimeError, 'endpoint mismatch'): + I.check_compensation(missing, self.C, 112, 728) + + def test_compensation_mutations(self): + controls = {'omit_restore': self.block[:-56], + 'wrong_prep_sign': copy.deepcopy(self.block), + 'wrong_restore_sign': copy.deepcopy(self.block), + 'dropped_coefficient': self.block[:56]+self.block[57:], + 'wrong_coefficient': copy.deepcopy(self.block), + 'dirty_helper_write': self.block+[E.add(224, 112, 1)]} + controls['wrong_prep_sign'][0][3] *= -1 + controls['wrong_restore_sign'][-1][3] *= -1 + controls['wrong_coefficient'][56][3] *= 2 + for label, block in controls.items(): + with self.subTest(label=label), self.assertRaisesRegex(RuntimeError, 'endpoint mismatch'): + I.check_compensation(block, self.C, 112, 728) + + def test_complete_program_detects_missing_restore_in_both_orientations(self): + program = E.logical_program(self.c, self.block[:-56]) + for back in (False, True): + with self.subTest(back=back), self.assertRaisesRegex(RuntimeError, 'endpoint mismatch'): + I.check(program, 728, dual=back) + + def test_private_stream_clears_are_paid_and_required(self): + original = E.lower + for omitted in ('first', 'last'): + def broken(scalar): + result = original(scalar) + if scalar[0] == 'add': + return result[1:] if omitted == 'first' else result[:-1] + return result + with self.subTest(omitted=omitted), patch.object(E, 'lower', broken), self.assertRaises(RuntimeError): + E.replay_emitted(self.changed['forward'], 728, 112) + + def test_recipe_overlap_and_unpaid_gain_reject(self): + pairs = self.recipe['pairs'] + with self.assertRaisesRegex(RuntimeError, 'overlapping'): + E.factored(self.C, pairs+[pairs[0]]) + unpaid = copy.deepcopy(pairs) + unpaid[0][3] += 16 + with self.assertRaisesRegex(RuntimeError, 'recipe gain'): + E.factored(self.C, unpaid) + + def test_independent_noncommuting_and_admission_controls(self): + self.assertEqual(I.self_test()['rejected_controls'], 8) + + def test_every_literal_coefficient_lowering_has_exact_boundary(self): + # Independent one-column numeric execution; arbitrary initial work=7 + # must be erased and initial target=11 must be preserved plus q*source. + cases = {E.Q(e[1][3], e[1][4]) for p in self.changed.values() + for e in p if e[0] == 'scalar' and e[1][0] == 'add'} + for q in cases: + values = {('L', 0): E.Q(11), ('L', 1): E.Q(13), ('W', 0): E.Q(7)} + scalar = ['add', ['L', 0], ['L', 1], q.numerator, q.denominator] + for primitive in E.lower(scalar): + tag, target = primitive[:2] + if tag == 'clear': values[target] = E.Q(0) + elif tag == 'scale': values[target] *= primitive[2] + elif tag == 'copy': values[target] = values[primitive[2]] + else: values[target] += primitive[3]*values[primitive[2]] + self.assertEqual(values[('L', 0)], 11+13*q) + self.assertEqual(values[('L', 1)], 13) + self.assertEqual(values[('W', 0)], 0) + + def test_semantic_source_pins_and_recompression(self): + with tempfile.TemporaryDirectory(prefix='x4 source controls ') as directory: + root = Path(directory)/'package' + shutil.copytree(E.HERE, root) + for name in ('CANONICAL-WORD.json.gz', 'LOCAL-PROGRAMS.json.gz'): + p = root/'inputs'/name + p.write_bytes(gzip.compress(json.dumps(E.read(p), indent=1).encode(), mtime=1234)) + V.inputs(root) # positive: changed formatting and gzip bytes + name = 'CANONICAL-WORD.json.gz' + p = root/'inputs'/name + c = E.read(p) + c['h'] = 10 + p.write_bytes(gzip.compress(json.dumps(c).encode())) + with self.assertRaisesRegex(RuntimeError, 'source digest'): + V.inputs(root) + # Repairing the editable outer manifest cannot bypass source pins. + manifest = E.read(root/'SOURCES.json') + manifest['input_semantic_sha256'][name] = E.digest(c) + (root/'SOURCES.json').write_text(json.dumps(manifest)) + with self.assertRaisesRegex(RuntimeError, 'selected canonical source pin'): + V.inputs(root) + + def test_standalone_optimized_relocation_and_output(self): + with tempfile.TemporaryDirectory(prefix='x4 standalone controls ') as directory: + root = Path(directory)/'package with spaces' + shutil.copytree(E.HERE, root) + result = subprocess.run([sys.executable, '-I', '-O', '-B', str(root/'verify.py'), + '--out', str(Path(directory)/'fresh output')], + cwd=directory, capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stdout+result.stderr) + output = E.read(Path(directory)/'fresh output/CANDIDATE-PROGRAMS.json.gz') + self.assertEqual({k: E.digest(v) for k, v in output.items()}, + {k: E.digest(v) for k, v in self.changed.items()}) + receipt = E.read(root/'RESULT.json') + receipt['orientations']['forward']['saved_real_primitives'] += 1 + (root/'RESULT.json').write_text(json.dumps(receipt)) + rejected = subprocess.run([sys.executable, '-I', '-O', '-B', str(root/'verify.py')], + cwd=directory, capture_output=True, text=True) + self.assertNotEqual(rejected.returncode, 0) + self.assertIn('saved result mismatch', rejected.stderr) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/research/complex-x4-compensation-pairs/verify.py b/research/complex-x4-compensation-pairs/verify.py new file mode 100644 index 0000000000..93365e8558 --- /dev/null +++ b/research/complex-x4-compensation-pairs/verify.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +"""Reproduce the X4 finite compensation circuit and all exact prices (no kappa).""" +import argparse +import gzip +import hashlib +import json +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import experiment as E +import independent as I + +CANONICAL = '1c0e9da767d4418f70016af599e4a447a3f7777acabe930318459c0fbbd260aa' +PROGRAMS = {'forward': '076a2d428f97abb30473df05110998efbe5ac809885bae4ceb1b8bd81329a1e6', + 'backward': '7915679ee305927463d19725360cc15132dd21ede18897d09a935dca1df0d55d'} +PROFILE = {1: 2548, 2: 338, 3: 430, 4: 194, 5: 56, 8: 8} + + +def inputs(root=E.HERE): + manifest = E.read(root/'SOURCES.json') + for name, expected in manifest['input_semantic_sha256'].items(): + E.require(E.digest(E.read(root/'inputs'/name)) == expected, 'source digest '+name) + canonical = E.read(root/'inputs/CANONICAL-WORD.json.gz') + programs = E.read(root/'inputs/LOCAL-PROGRAMS.json.gz') + checks = E.read(root/'inputs/LOCAL-CHECKS.json') + E.require(E.digest(canonical) == CANONICAL, 'selected canonical source pin') + E.require((canonical['v'], canonical['R'], canonical['h']) == (112, 504, 9), 'geometry') + E.require({int(k): v for k, v in canonical['local_profile'].items()} == PROFILE, 'paid profile') + for name, expected in PROGRAMS.items(): + E.require(E.digest(programs[name]) == expected == checks[name]['sha256'], 'selected program '+name) + return canonical, programs, checks + + +def build(root=E.HERE, rerun_search=True): + c, programs, checks = inputs(root) + C = E.compensation(c) + E.require(E.row_gates(C) == sorted(c['compensation'], key=lambda g: g[1:3]), 'derived full compensation') + recipe = E.read(root/'RECIPE.json') + E.require(recipe['seed'] == 39, 'assignment seed') + if rerun_search: + pairs, search = E.search(C, seed=39) + E.require(recipe == dict(seed=39, pairs=pairs, search=search), 'search/recipe reproduction') + replacement = E.factored(C, recipe['pairs']) + # Only targets and ordinary bottom-start / FULL-ended helpers are touched. + for gate in replacement: + for r in gate[1:3]: + E.require(c['start'][r] == 0, 'nonzero start frame') + if r >= 224: + E.require(c['final'][r] == 1, 'cold/entering helper touch') + E.require(gate[-1] == 0, 'nonzero replacement frame') + changed = {name: E.splice(events, c, replacement, name == 'backward') + for name, events in programs.items()} + for name in programs: + E.require([e for e in programs[name] if e[0] != 'scalar'] == + [e for e in changed[name] if e[0] != 'scalar'], 'non-scalar event drift') + return c, programs, checks, C, recipe, replacement, changed + + +def run(root=E.HERE, out=None): + c, programs, checks, C, recipe, replacement, changed = build(root) + n, v = 2*c['v']+c['R'], c['v'] + block_check = I.check_compensation(replacement, C, v, n) + rows = {} + for name in ('forward', 'backward'): + back = name == 'backward' + before = E.replay_emitted(programs[name], n, v, back) + after = E.replay_emitted(changed[name], n, v, back) + E.require(before['real_component_primitives'] == checks[name]['real_component_primitive_bound'], 'baseline price') + E.require(before['scalar_macros'] == checks[name]['scalar_macros'], 'baseline macro count') + E.require(before['paid_profile'] == after['paid_profile'] == PROFILE, 'child profile') + E.require(after['prefix_bits'] == before['prefix_bits'] and after['prefix_bits'] < 192, 'inherited local guard') + actual_gain = before['real_component_primitives']-after['real_component_primitives'] + E.require(actual_gain == sum(p[3] for p in recipe['pairs']) > 0, 'complete price gain') + old_logical = I.check(E.logical_program(c, c['compensation']), n, dual=back, v=v) + new_logical = I.check(E.logical_program(c, replacement), n, dual=back, v=v) + E.require(old_logical['endpoint_sha256'] == new_logical['endpoint_sha256'], 'independent endpoint') + rows[name] = dict(baseline=before, candidate=after, saved_real_primitives=actual_gain, + independent_baseline=old_logical, independent_candidate=new_logical) + result = dict(status='PASS_X4_COMPENSATION_PAIRS', base_commit='f567884aeb8851b6e794af1184119a3bfbe1e631', + selected_kappa_unchanged='1661634653669567/1000000000000000000', seed=39, + pairs=len(recipe['pairs']), search=recipe['search'], + compensation_adds_before=len(c['compensation']), compensation_adds_after=len(replacement), + compensation_boundary=block_check, orientations=rows, + scope='Finite scalar circuit; exact all-column and primitive-prefix replays. No global invoice, supplier compilation or new kappa.') + if out is not None: + out = Path(out) + E.require(not out.exists(), 'output directory must be new') + out.mkdir(parents=True) + (out/'CANDIDATE-PROGRAMS.json.gz').write_bytes(gzip.compress( + json.dumps(changed, sort_keys=True, separators=(',', ':')).encode(), mtime=0)) + (out/'RESULT.json').write_text(json.dumps(result, indent=2)+'\n') + return result + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument('--out', type=Path, help='optional fresh directory for the literal candidate programs') + ap.add_argument('--record', action='store_true', help='write the reproducible RESULT.json after all checks') + args = ap.parse_args() + result = run(out=args.out) + normalized = json.loads(json.dumps(result)) + if args.record: + (E.HERE/'RESULT.json').write_text(json.dumps(result, indent=2)+'\n') + else: + E.require(normalized == E.read(E.HERE/'RESULT.json'), 'saved result mismatch') + print('PASS_X4_COMPENSATION_PAIRS pairs=%d compensation=%d->%d saved_real=33800 columns=728+9 orientations=2 no_new_kappa' % + (result['pairs'], result['compensation_adds_before'], result['compensation_adds_after'])) + + +if __name__ == '__main__': + main()