diff --git a/research/exact-log-horner/.gitattributes b/research/exact-log-horner/.gitattributes new file mode 100644 index 0000000000..cb2325b7be --- /dev/null +++ b/research/exact-log-horner/.gitattributes @@ -0,0 +1,2 @@ +# Preserve the exact pinned upstream source, including its final blank line. +reference/base_two_moment.py whitespace=-blank-at-eof diff --git a/research/exact-log-horner/CLAIM.json b/research/exact-log-horner/CLAIM.json new file mode 100644 index 0000000000..cb0ccb1c6a --- /dev/null +++ b/research/exact-log-horner/CLAIM.json @@ -0,0 +1,59 @@ +{ + "track": "verification engineering", + "assignment_seed": 89, + "assignment_source": "OS randomness via secrets.randbelow(100)", + "base_commit": "66849e1475c930fd7732b1a0067ffee7e1e95f60", + "scope": "Exact integer-Horner evaluation of the 80-term rational logarithm in base_two_moment.py; no precision reductions or source-engine changes.", + "method": "Homogenize the atanh polynomial with lcm(1,3,...,159), evaluate with integer Horner, retain the identical rational remainder.", + "candidates_considered": [ + { + "task": "cache repeated immutable source hashes", + "decision": "not selected; risks stale-input acceptance and needs broader pipeline profiling" + }, + { + "task": "repair path quoting in costly bit-supplier cold replay", + "decision": "not selected; PR653 already reports the issue and the full script has many affected call sites" + }, + { + "task": "homogeneous integer Horner for exact logarithm intervals", + "decision": "selected; seed 89 mod 3 = 2; narrow algebraic equality and benchmarkable without a supplier rebuild" + } + ], + "coordination": "Open-issue query returned only issue 650 requesting Discussions; no sprint coordination issue found. Local claim only.", + "overlap_checked": [ + "current PR ledger and review through 626", + "open PR metadata through 658", + "PR title search: moment", + "source search: log_bounds and Horner" + ], + "expected_deliverable": "Add-only Apache-2.0 package with exact equivalence derivation, pinned reference, deterministic checks, corruptions and before/after benchmarks.", + "publication": "Original ChatGPT run produced a clean ZIP/patch handoff without a writable fork. Codex subsequently imported and replayed that package in a full, base-pinned checkout on codex/exact-log-horner for a separate PR from yuj1r0/integer-mult-bounds.", + "negative_control_development": "Initial wrong-tail-exponent mutant escaped probes whose reduced numerator was always 1; adding x=9/5 (z=2/7) detects it. Full corrected suite passes.", + "handoff_overlap_refresh": { + "main_head": "66849e1475c930fd7732b1a0067ffee7e1e95f60", + "queries": [ + { + "query": "repo:CrocSwap/integer-mult-bounds \"log_unit\" (all PRs)", + "result": "no matching PRs returned" + }, + { + "query": "repo:CrocSwap/integer-mult-bounds logarithm (open PRs, top 6 by update)", + "returned_prs": [ + 605, + 585, + 573, + 570, + 375, + 92 + ] + } + ], + "interpretation": "The returned relevant PR605/585 are scoped Lean moment/logarithm proofs, not an integer-Horner Python evaluation optimization. No duplicate found in these bounded metadata/source searches; this is not an exhaustive novelty audit." + }, + "submission_result": { + "status": "PASS_EXACT_LOG_HORNER and PASS_PACKAGE_CONTROLS", + "changed_scope": "None: opt-in exact arithmetic kernel; production engines and selected frontier unchanged.", + "fresh_evidence": "SUBMISSION.json", + "overlap_refresh": "Open PR metadata refreshed through #665, bounded Horner search and log_unit search (zero matches). No matching logarithm-kernel optimization found. #662 concerns Clifford helper validation, a different workload. Final pinned-issue query returned none." + } +} diff --git a/research/exact-log-horner/LICENSE b/research/exact-log-horner/LICENSE new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/research/exact-log-horner/LICENSE @@ -0,0 +1,202 @@ + + 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/exact-log-horner/MANIFEST.json b/research/exact-log-horner/MANIFEST.json new file mode 100644 index 0000000000..5be461374c --- /dev/null +++ b/research/exact-log-horner/MANIFEST.json @@ -0,0 +1,22 @@ +{ + ".gitattributes": "0505c14e71ca4c3505f5bd606e6667ee39a9114b71a9188aa868648b021c49bb", + "CLAIM.json": "4270cdc0851ef2a72f4234b866071fb3805761280792316a4788c58bcdfafb42", + "LICENSE": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", + "NOTICE.md": "d9872b4cd2bdcf38ff5f688b33a440cf34b22cc9d45fe1ae7689bb989fad8fc8", + "PROOF.md": "cf0150bc8d6a185dd3d94b817b8bd259100d694a59b1da7dbc90568b4bb97bb7", + "README.md": "fa2ab1ac2957c119f1dcd1037b90854ec88aa187f62e13a0905c2d5a2c33c447", + "SOURCE.json": "cc635c64c33360d9b0c02fd089cf8c2e678cb7752e70d832e742628fc85fcb1d", + "SUBMISSION.json": "b59e8eed2e3230c26e1e90fc0ee791d1f1f8d6f86a51f00b37f1d20313f6a24c", + "evidence/benchmark.json": "8047676315a56701b1c84c873f081ac3ab111c8c7d3525db04104bf8c1d340aa", + "evidence/codex-benchmark.json": "8d3ac463dd872d2501807f743bac3f289c5d87708f60f888c082855a5cccd2d9", + "evidence/codex-optimized.json": "0e70d6b2427408fe0b7ef5d3b577c7c6767db2a782b9f057dafc4154c763f94a", + "evidence/codex-package-controls.json": "dfbbf6c4972028cc5c39b2b32b71c55b1f25066360e4d581e605fd90ff31cc1e", + "evidence/codex-repository-binding.json": "5ef3ba2cbd28e5bee076863194df84596107ed40140d3b0ac33cf64968f24053", + "evidence/isolated-optimized.json": "5df1fe94b1d8d8e1fe234f66360ff8291cc460bf28a86796787b0442784d72d4", + "evidence/package-controls.json": "dfbbf6c4972028cc5c39b2b32b71c55b1f25066360e4d581e605fd90ff31cc1e", + "fixtures.json": "cab28353eff3c0009ad6819ff7d1c67c2ddd54f82c1f9bf2772e0c2f9edb7318", + "log_horner.py": "2ac2759ca07ca9456c85869dc8ebe22363a9056f684b6234dc7df6df1ca93cd8", + "reference/base_two_moment.py": "aee70c242a2f1d225528fabe2002e1564d1dc884797c07d28a831c7878ee9098", + "test_package.py": "0bc6a4ee59ea7d86ca4ddc8700e0f76d2e7f4d7a765fcd315c512a2e14e20d90", + "verify.py": "e0db83f49279ab4715a033f727a59529b82213ba5dde4ef6e601d568fda09e4c" +} diff --git a/research/exact-log-horner/NOTICE.md b/research/exact-log-horner/NOTICE.md new file mode 100644 index 0000000000..f86a40a616 --- /dev/null +++ b/research/exact-log-horner/NOTICE.md @@ -0,0 +1,40 @@ +# Attribution, license and assistance + +This contribution is offered under Apache-2.0. The original rational arithmetic +engine in `reference/base_two_moment.py` is retained **byte for byte** from +CrocSwap/integer-mult-bounds at commit +`66849e1475c930fd7732b1a0067ffee7e1e95f60`, from +`research/five-stage-gen4-banks/base_two_moment.py`. Its Git blob is +`14a90fa0e788217856f070382c9e61bd7c603c61`. The same blob is present at +`research/complex-allcold/engines/base_two_moment.py`. Its original docstring, +imports, constants and checks are preserved. The repository is maintained by +Douglas Colkitt; this contribution does not reassign authorship of that engine. + +The arithmetic fixtures credit Chafik Boukhalfa's #626 owner repair, Jeremy +Kothe's #622/#623 K-triangle/provider work, eumemic's #543 bit supplier, Rohan +Arun's #559 native-complex recurrence correction, and the cumulative contributor +lineage retained in the repository's selected review. Their supplier counts, +physical constructions, original interval engine, surcharge rule and accepted +witness are not new contributions of this package. This package neither +independently reconstructs those suppliers nor takes credit for their bounds. + +The new contribution applies homogeneous integer Horner evaluation to the +existing 80-term logarithm, with a scoped equivalence derivation, tests, +mutation controls and measured timings. Horner evaluation and clearing common +denominators are standard algebraic techniques; no invention or literature +priority claim is made for them. + +Prepared at Tuomo Kiiskinen's request with substantial OpenAI ChatGPT assistance +in the derivation, code, testing, benchmarking, packaging and prose. The +assistant performed the reported local runs. No independent human review, +separate-agent review, remote CI pass, or Lean verification is claimed. + +The subsequent submission pass used OpenAI Codex to inspect the supplied ZIP, +review the code and algebra, verify pinned inputs against a complete checkout, +replay the unchanged implementation and controls on macOS, and prepare the PR. +The original implementation, proof and Linux evidence remain unchanged; fresh +submission receipts are identified separately in SUBMISSION.json. + +The final overlap check also read PR585 and PR605 descriptions. Their scoped +Lean logarithm/moment certificate proofs are prior complementary work; this +package neither imports them nor claims to replace their formal guarantees. diff --git a/research/exact-log-horner/PROOF.md b/research/exact-log-horner/PROOF.md new file mode 100644 index 0000000000..908e16735b --- /dev/null +++ b/research/exact-log-horner/PROOF.md @@ -0,0 +1,116 @@ +# Exact endpoint-preserving integer Horner evaluation + +## 1. Computational setting + +The retained engine prices a finite histogram by enclosing + +\[ + M(s)=\sum_{(t,c)}\frac{tc}{mW}\exp\bigl(s\log(m/t)\bigr). +\] + +Some calls add a separately priced bad-residue surcharge. Counts and the validity +of the physical construction are inputs to this computation, not consequences +of this note. The selected assembly retains the surcharge for the bit supplier +and its conservative complex check, and omits it for the reviewed native +complex check. Those distinctions are unchanged here. + +The engine reduces each logarithm to arguments in [1,2]. Its `log_unit` uses an +80-term rational atanh series. The expensive reference expression separately +constructs 80 rational powers and sums them. We change only how that *same +rational polynomial* is evaluated, leaving its remainder and every downstream +operation unchanged. No input-dependent result cache is introduced. + +## 2. Original enclosure + +For an exact rational x in [1,2], let z=(x-1)/(x+1)=a/b in lowest terms, b>0. +Then 0<=z<=1/3. The original lower and upper endpoints are + +\[ + L_0=2\sum_{j=0}^{79}\frac{z^{2j+1}}{2j+1},\qquad + U_0=L_0+\frac{2z^{161}}{161(1-z^2)}. +\] + +These enclose log(x). In fact, the omitted positive tail is +2 sum_{j>=80} z^(2j+1)/(2j+1), bounded above by replacing every denominator +with 161 and summing a geometric series. At x=1 both endpoints are exactly zero. + +## 3. Homogenized polynomial + +Set + +\[ + D=\operatorname{lcm}(1,3,5,\ldots,159),\qquad c_j=D/(2j+1). +\] + +All c_j are integers. Define the homogeneous integer polynomial + +\[ + N(a,b)=\sum_{j=0}^{79}c_j a^{2j}b^{2(79-j)}. +\] + +Then, by multiplying out each summand, + +\[ + \boxed{L_0=\frac{2aN(a,b)}{Db^{159}}},\qquad + \boxed{U_0-L_0=\frac{2a^{161}}{161b^{159}(b^2-a^2)}}. +\] + +The second identity follows directly from +z^161/(1-z^2)=a^161/[b^159(b^2-a^2)]. It is an equality, not a new approximation. +Every denominator is nonzero throughout the stated domain. + +## 4. Horner recurrence and loop invariant + +Initialize N_79=c_79. For j=78,...,0 evaluate + +\[ + N_j=a^2N_{j+1}+c_jb^{2(79-j)}. +\] + +Induction gives + +\[ + N_j=\sum_{k=j}^{79}c_k a^{2(k-j)}b^{2(79-k)}. +\] + +Thus N_0=N(a,b). In the implementation, `b_power` starts at b^2 and is +multiplied by b^2 after each of the 79 iterations. On exit it equals b^160; +its exact integer quotient by b is b^159. The final `Fraction` constructors +therefore return exactly L_0 and U_0. The zero numerator case requires no +separate shortcut and introduces no division by a. + +This proves endpoint equality for **every exact rational x in [1,2]**. It is a +written algebraic proof of this kernel identity, not a formalized proof and not +a claim inferred from the finite regression grid. + +## 5. Consequences and boundaries + +For Fraction arguments x>=1, the unchanged `log_bounds` range reduction gives +the same k and reduced rational argument. Both its reduced logarithm and its +log(2) enclosure therefore remain identical. Its outward rounding at 10^-30 +is unchanged. The twelve-term exponential and its tail are unchanged, as are +all histogram weights, final outward rounding, and surcharge additions. +Consequently, whenever the original exact-rational moment evaluation is in its +admitted domain, its lower and upper rational outputs remain identical. +Acceptance, rejection, and inconclusive cases based on those outputs are +therefore unchanged; this is stronger than merely keeping the same sign in +six examples. + +The optimized standalone function explicitly rejects floating-point, string, +and other non-exact inputs. It accepts Fraction inputs and exact integer +endpoints 1 and 2. The equivalence claim concerns the original engine's +Fraction-valued arithmetic, not undocumented float behavior. No claim is made +about passing plain large integers to the original `log_bounds`, whose own +`/=` operation can enter floating-point arithmetic; that caller is unmodified. + +The optimization replaces repeated rational powers/additions with 79 integer +Horner updates, two final Fraction constructions, and their final addition. +D and its coefficients are input-independent module constants. Large integer +sizes still depend on the input; empirical speedups are measurements, not a +claimed asymptotic complexity improvement. Import/setup time is excluded from +the reported warmed measurements, and no full replay speedup is established. + +Supplier reconstruction, all 47 outer inequalities, the second rational engine, +source/compiler interfaces, common-label and mutable-basis realization, whole- +call hosting, precision/tape/exact recovery, analytic transfer and the complete +multiplication theorem are outside this contribution. No selected kappa changes. diff --git a/research/exact-log-horner/README.md b/research/exact-log-horner/README.md new file mode 100644 index 0000000000..453b181ab0 --- /dev/null +++ b/research/exact-log-horner/README.md @@ -0,0 +1,177 @@ +# Exact logarithm intervals with integer Horner evaluation + +**Status: verification-engineering contribution; no new kappa.** + +This add-only package evaluates the retained 80-term rational logarithm with +integer Horner arithmetic, preserving its exact lower and upper fractions. +The selected three charged moment pairs run 2.28 times faster in the fresh +macOS submission replay and 2.41 times faster in the original Linux handoff. +The isolated logarithm microbatch runs 10.62 and 12.58 times faster respectively. +These are arithmetic timings, not full frontier-replay timings. + +Base: `66849e1475c930fd7732b1a0067ffee7e1e95f60`. +OS-random assignment seed: **89**, verification engineering. +The selected conditional witness remains +`51110230636731/31250000000000000 = 0.001635527380375392`. +No existing source, supplier, certificate, manifest or `upstream/` file changes. + +## Reproduce + +From the repository or extracted bundle root, with Python 3.10 or later: + +```sh +python3 -B research/exact-log-horner/verify.py --benchmark +``` + +Expected result: `PASS_EXACT_LOG_HORNER`, with 5,872 exact logarithm comparisons, +six charged moment endpoints and eight detected implementation mutations. +Timings vary by environment and are not used to determine success. +Only the Python standard library is required; no network, numerical package, +solver, compiler, or upstream build is needed for this scoped check. + +Optional exact-result receipt and optimized-mode check: + +```sh +python3 -I -O -B research/exact-log-horner/verify.py --output /tmp/exact-log-horner-new-receipt.json +python3 -B research/exact-log-horner/test_package.py +``` + +The output file must not already exist and must be outside this package. +The second command prints `PASS_PACKAGE_CONTROLS` and eight rejected cases. +It checks source/inventory failures in paths containing spaces, both normally +and under optimized Python. Neither command disables failure checks under `-O`. + +## Mechanism and exactness + +Let `z=(x-1)/(x+1)=a/b`, `D=lcm(1,3,...,159)` and +`N=sum((D/(2j+1))*a^(2j)*b^(158-2j), j=0,...,79)`. +The existing lower endpoint is exactly `2*a*N/(D*b^159)` and its unchanged +upper-tail addition is exactly `2*a^161/(161*b^159*(b^2-a^2))`. +The 79 integer Horner updates evaluate N without constructing and summing +80 rational powers. There is no lower precision, shortened series, +input-dependent cache, modified tail, or altered admission decision. + +`PROOF.md` gives the all-rational algebraic identity and loop invariant. +This written proof is not a Lean proof. Finite comparisons corroborate the +implementation; they are not the justification for universal equality. + +The harness loads two private copies of the byte-identical original engine +and substitutes only `log_unit` in one copy. Range reduction, log(2), outward +rounding at 10^-30, twelve-term exponentials, histogram weights and surcharge +pricing remain the original code. This is not an independent reimplementation +of those inherited enclosures. The standalone new function explicitly accepts +exact Fraction inputs and integer endpoints, rejecting non-exact input types. + +## Measured results + +Environment: CPython 3.13.5, Linux x86_64, as recorded in +`evidence/benchmark.json`. Seven repetitions per workload, alternating engine +order, with exact output comparison after every timed pair. Medians: + +| Workload | Original | Integer Horner | Speedup | +|---|---:|---:|---:| +| Logarithm microbatch (20 × 9 exact arguments) | 83.970 ms | 6.675 ms | 12.58× | +| PR626 native-complex accepted/adjacent pair | 23.585 ms | 8.901 ms | 2.65× | +| All three charged accepted/adjacent pairs | 67.830 ms | 28.110 ms | 2.41× | + +The microbatch uses the nine distinct arguments produced by the reference's +strict binary range reduction on the selected profiles, including log(2). +It repeats that set 20 times; it is not a timing for one logarithm. The two +moment workloads price their indicated full intervals including the unchanged +exponentials and final rounding. The combined workload includes native complex, +conservative complex with surcharge, and bit with surcharge. + +Input preparation and module import/setup are excluded. No result cache is +used. The combined measured saving is about 40 milliseconds per six-endpoint +batch here; this does not establish a material reduction in a full replay that +also rebuilds physical suppliers and executes other verification stages. + +## Verification coverage + +The Codex submission replay independently reran the unchanged supplied code +on macOS arm64 / CPython 3.12.8, using the same seven alternating-order +repetitions. [evidence/codex-benchmark.json](evidence/codex-benchmark.json) +contains the raw samples and executed-input hashes: + +| Workload | Original | Integer Horner | Speedup | +|---|---:|---:|---:| +| Logarithm microbatch (20 × 9 exact arguments) | 51.424 ms | 4.840 ms | 10.62× | +| PR626 native-complex accepted/adjacent pair | 14.881 ms | 6.133 ms | 2.43× | +| All three charged accepted/adjacent pairs | 43.783 ms | 19.167 ms | 2.28× | + +Both the normal and isolated optimized submission runs reproduce the original +exact comparison fingerprint below. The eight package corruption checks also +pass. Original Linux evidence remains unchanged; the fresh receipts have +`codex-` names. [SUBMISSION.json](SUBMISSION.json) records the source ZIP and +the complete-checkout verification of all seven pinned repository paths and +the extracted arithmetic fields. No supplier construction was rerun. + +- **5,872 logarithm comparisons:** 1,261 distinct unit rationals with denominator + at most 64; 30 seeded/adversarial rationals up to 256-bit denominators; all + 4,560 child ratios m/t for 2<=m<=96; and 21 power-of-two boundary cases. +- **Six charged moment endpoints:** acceptance at the inherited lower point + and rejection one 10^-24 step above, for native PR626, conservative PR626, + and PR543 bit profiles. Both lower and upper rational outputs match exactly. + Five additional pricing controls run in each engine, covering surcharge + distinctions and an added charged child. +- **Failure detection:** eight numerical implementation mutants; 24 inherited + domain rejection checks; three non-exact-input rejections; and eight + source/inventory corruption cases across normal and optimized Python. + +The normal and isolated optimized full runs have the identical exact comparison +fingerprint `c926bc76b11c982a477174b4c09ea0be2b4c549ae4dcd8215d7ac19deb91202a`. +Two exact integer endpoint checks are also included. Raw evidence binds the +executed reference, replacement, fixture and harness hashes. The manifest binds +all packaged files; it deliberately excludes itself and Python bytecode caches. + +A development probe weakness is recorded in `CLAIM.json`: the first tail-power +mutation escaped arguments whose reduced numerator was always one. Adding +x=9/5, hence z=2/7, detects it. Every reported final mutation passes the corrected +suite. Runtime/syntax failures of mutants do not count as numerical detection. + +## Source binding, coordination and integration boundary + +`SOURCE.json` records source paths, Git blob identities, acquisition scope and +inherited dependencies. The original 1,742-byte reference is authenticated to +Git blob `14a90fa0e788217856f070382c9e61bd7c603c61` and SHA-256 +`aee70c242a2f1d225528fabe2002e1564d1dc884797c07d28a831c7878ee9098`. +The path-local `.gitattributes` preserves the reference's inherited final blank +line without suppressing whitespace checks on authored files. The two profile +fixtures contain explicitly extracted fields, not full original certificate copies. Their counts and physical realizability are inherited +inputs, not proved by this checker. + +`CLAIM.json` records three candidate tasks, the selected scope, the local claim, +prior work and the bounded final overlap check. The main head was refreshed and +still matched the base. No pinned sprint issue was found. Relevant prior work +includes the complementary PR585/605 Lean certificate proofs. This package makes +no exhaustive novelty or priority claim. + +The original ChatGPT environment could not clone GitHub and produced a ZIP +and clean patch handoff from connector-fetched pinned sources. For this +submission, Codex imported the package into a separate full Git worktree at +the same exact base, checked the original source Git blobs and fixture fields +against the repository, and reran its verification and benchmarks. The +implementation, fixtures, proof, reference and original evidence remain +byte-identical to the supplied ZIP. Updated publication prose, fresh receipts +and the resulting package manifest are the submission changes. + +The package deliberately **does not activate the optimization in the selected +pipeline**. That avoids silently invalidating source pins and historical +receipts. Maintainer adoption should separately identify callers, replace the +specific engine copy, update exactly its dependent pins, and run the affected +full replay and repository checks. Those integration checks are not completed +by this standalone tool. + +Not executed here: `make verify`, `make frontier626-verify`, full supplier +reconstruction, the second moment engine, all 47 assembly inequalities, Lean, +or remote CI. The all-size/compiler, common-label/mutable-source, whole-call +hosting, precision/tape/exact-recovery and analytic-transfer obligations remain +unchanged. No new conditional exponent or unconditional theorem is claimed. + +## Attribution + +See `NOTICE.md` and `LICENSE`. The original engine and selected supplier lineage +retain credit. The new implementation, proof, tests and packaging were prepared +at Tuomo Kiiskinen's request with substantial OpenAI ChatGPT assistance. The +subsequent source review, replay and PR preparation used OpenAI Codex. No +independent human or separate-agent review is claimed. diff --git a/research/exact-log-horner/SOURCE.json b/research/exact-log-horner/SOURCE.json new file mode 100644 index 0000000000..941e4e2bb1 --- /dev/null +++ b/research/exact-log-horner/SOURCE.json @@ -0,0 +1,45 @@ +{ + "repository": "https://github.com/CrocSwap/integer-mult-bounds", + "base_commit": "66849e1475c930fd7732b1a0067ffee7e1e95f60", + "source_acquisition": "Direct clone failed because container DNS/network access was unavailable. Selected UTF-8 sources were fetched at exact refs through the connected GitHub tool. The vendored 1742-byte engine was checked against its original Git blob and SHA256. No full clone or repository-wide replay is claimed.", + "reference": { + "path": "research/five-stage-gen4-banks/base_two_moment.py", + "identical_read_path": "research/complex-allcold/engines/base_two_moment.py", + "git_blob_sha1": "14a90fa0e788217856f070382c9e61bd7c603c61", + "sha256": "aee70c242a2f1d225528fabe2002e1564d1dc884797c07d28a831c7878ee9098", + "vendored_path": "reference/base_two_moment.py" + }, + "arithmetic_sources": [ + { + "path": "research/community-k492-audit/pr626/replay/ASSEMBLY.json", + "git_blob_sha1": "2e97b75bd8e74e8aa1b5fb83adcdc461aa07c398", + "acquisition": "Relevant ranges; fixture contains explicitly extracted fields, not a full source copy." + }, + { + "path": "research/e8-bit-r420/EXPECTED.json", + "git_blob_sha1": "b61d859826246e0c3dabbe096e57ad7015eadfd5", + "acquisition": "Relevant ranges; fixture contains explicitly extracted fields, not a full source copy." + }, + { + "path": "research/complex-k492-owner-repair/code/assemble.py", + "git_blob_sha1": "d1674e657ff046f9d55c917723002f270e05c42a", + "acquisition": "Admission context and check_moment/outer-witness sections inspected; whole assembly not executed." + } + ], + "selected_record": { + "path": "certificates/selected-result.json", + "git_blob_sha1": "92a10096dee76479af88a897714b3818d8263141", + "kappa": "51110230636731/31250000000000000", + "status": "unchanged" + }, + "review": { + "path": "docs/research/community-k492-review.md", + "git_blob_sha1": "11efcd07ae2b9d93d355c6adaf773dca70dbce91" + }, + "dependency_policy": "Python 3.10+ standard library; no numerical libraries, compiler, solver, network or additional fetched packages needed for this scoped replay. Exact rational fixture counts are inherited, not established by the checker.", + "submission_replay": { + "acquisition": "Full Git worktree at the identical original base; see SUBMISSION.json", + "binding_receipt": "evidence/codex-repository-binding.json", + "verified": "All seven listed upstream path identities, reference byte equality, both extracted profiles, bit live stock, all three moment endpoints and selected kappa." + } +} diff --git a/research/exact-log-horner/SUBMISSION.json b/research/exact-log-horner/SUBMISSION.json new file mode 100644 index 0000000000..5ea80544b6 --- /dev/null +++ b/research/exact-log-horner/SUBMISSION.json @@ -0,0 +1,38 @@ +{ + "status": "PASS", + "checked_utc": "2026-10-13T03:20:58.128926+00:00", + "original_archive": "exact-log-horner-contribution.zip", + "archive_sha256": "f8626410e23d34015e830b79304c47a58d89fd4ea5276cc0b7dda7b8735d5e81", + "base_commit": "66849e1475c930fd7732b1a0067ffee7e1e95f60", + "branch": "codex/exact-log-horner", + "unchanged_zip_inputs_sha256": { + "log_horner.py": "2ac2759ca07ca9456c85869dc8ebe22363a9056f684b6234dc7df6df1ca93cd8", + "verify.py": "e0db83f49279ab4715a033f727a59529b82213ba5dde4ef6e601d568fda09e4c", + "test_package.py": "0bc6a4ee59ea7d86ca4ddc8700e0f76d2e7f4d7a765fcd315c512a2e14e20d90", + "PROOF.md": "cf0150bc8d6a185dd3d94b817b8bd259100d694a59b1da7dbc90568b4bb97bb7", + "fixtures.json": "cab28353eff3c0009ad6819ff7d1c67c2ddd54f82c1f9bf2772e0c2f9edb7318", + "reference/base_two_moment.py": "aee70c242a2f1d225528fabe2002e1564d1dc884797c07d28a831c7878ee9098", + "evidence/benchmark.json": "8047676315a56701b1c84c873f081ac3ab111c8c7d3525db04104bf8c1d340aa", + "evidence/isolated-optimized.json": "5df1fe94b1d8d8e1fe234f66360ff8291cc460bf28a86796787b0442784d72d4", + "evidence/package-controls.json": "dfbbf6c4972028cc5c39b2b32b71c55b1f25066360e4d581e605fd90ff31cc1e" + }, + "commands": [ + { + "command": "python3 -B research/exact-log-horner/verify.py --benchmark", + "receipt": "evidence/codex-benchmark.json" + }, + { + "command": "python3 -I -O -B research/exact-log-horner/verify.py", + "receipt": "evidence/codex-optimized.json" + }, + { + "command": "python3 -B research/exact-log-horner/test_package.py", + "receipt": "evidence/codex-package-controls.json" + } + ], + "source_binding_receipt": "evidence/codex-repository-binding.json", + "exact_comparison_digest_sha256": "c926bc76b11c982a477174b4c09ea0be2b4c549ae4dcd8215d7ac19deb91202a", + "normal_and_optimized_results_identical": true, + "scope": "Standalone package replay and repository source/fixture binding; production pipeline not modified or activated. No full supplier/assembly/repository-wide/Lean replay or remote CI result claimed.", + "assistance": "Original package prepared with OpenAI ChatGPT assistance; submission review, fresh replay, documentation updates and PR preparation with OpenAI Codex." +} diff --git a/research/exact-log-horner/evidence/benchmark.json b/research/exact-log-horner/evidence/benchmark.json new file mode 100644 index 0000000000..e4c92c4242 --- /dev/null +++ b/research/exact-log-horner/evidence/benchmark.json @@ -0,0 +1,204 @@ +{ + "status": "PASS_EXACT_LOG_HORNER", + "seed": 89, + "base_commit": "66849e1475c930fd7732b1a0067ffee7e1e95f60", + "reference_git_blob_sha1": "14a90fa0e788217856f070382c9e61bd7c603c61", + "executed_input_sha256": { + "verify.py": "e0db83f49279ab4715a033f727a59529b82213ba5dde4ef6e601d568fda09e4c", + "log_horner.py": "2ac2759ca07ca9456c85869dc8ebe22363a9056f684b6234dc7df6df1ca93cd8", + "fixtures.json": "cab28353eff3c0009ad6819ff7d1c67c2ddd54f82c1f9bf2772e0c2f9edb7318", + "reference/base_two_moment.py": "aee70c242a2f1d225528fabe2002e1564d1dc884797c07d28a831c7878ee9098" + }, + "environment": { + "python": "3.13.5 (main, Jul 15 2026, 20:25:40) [GCC 14.2.0]", + "implementation": "CPython", + "platform": "Linux-6.18.44-x86_64-with-glibc2.41", + "machine": "x86_64", + "optimization_level": 0, + "cpu_count": 5 + }, + "verification": { + "groups": { + "unit_grid_denominator_at_most_64": 1261, + "unit_adversarial_and_seeded_large_rationals": 30, + "range_reduction_all_children_m_2_through_96": 4560, + "range_reduction_power_of_two_boundaries": 21, + "charged_moment_endpoints": 6, + "pricing_negative_controls_per_engine": 5, + "inherited_domain_rejections_both_engines": 24, + "new_exact_input_type_rejections": 3, + "exact_integer_endpoints": 2, + "implementation_mutations_detected": 8 + }, + "exact_comparison_digest_sha256": "c926bc76b11c982a477174b4c09ea0be2b4c549ae4dcd8215d7ac19deb91202a", + "moments": [ + { + "name": "complex626_native", + "accept": true, + "surcharge": false, + "interval_minus_one": [ + "-2346073/1000000000000000000000000000000", + "-293259/125000000000000000000000000000" + ] + }, + { + "name": "complex626_native", + "accept": false, + "surcharge": false, + "interval_minus_one": [ + "64931/100000000000000000000000000000", + "649311/1000000000000000000000000000000" + ] + }, + { + "name": "complex626_conservative", + "accept": true, + "surcharge": true, + "interval_minus_one": [ + "-7010240519182780279647/2500000000000000000000000000000000000000000000", + "-5608190415346224223689/2000000000000000000000000000000000000000000000" + ] + }, + { + "name": "complex626_conservative", + "accept": false, + "surcharge": true, + "interval_minus_one": [ + "1912877923638794608283/10000000000000000000000000000000000000000000000", + "76515516945551784337/400000000000000000000000000000000000000000000" + ] + }, + { + "name": "bit543", + "accept": true, + "surcharge": true, + "interval_minus_one": [ + "-1120888283015460284783/2500000000000000000000000000000000000000000000", + "-4483543132061841139029/10000000000000000000000000000000000000000000000" + ] + }, + { + "name": "bit543", + "accept": false, + "surcharge": true, + "interval_minus_one": [ + "13153878434097279887307/5000000000000000000000000000000000000000000000", + "6576941717048639943679/2500000000000000000000000000000000000000000000" + ] + } + ], + "mutations_detected": [ + "drop_last_series_term", + "erase_remainder_bound", + "wrong_homogeneous_denominator", + "wrong_horner_multiplier", + "freeze_denominator_power", + "damage_one_series_coefficient", + "wrong_tail_exponent", + "lossy_float_input_roundtrip" + ] + }, + "verification_seconds": 5.97963986100001, + "benchmark": { + "repeats": 7, + "timer": "perf_counter_ns", + "alternating_order": true, + "input_dependent_caching": false, + "unit_batch_repetitions": 20, + "unit_inputs": [ + "73/64", + "8/7", + "4/3", + "73/48", + "32/21", + "8/5", + "73/40", + "73/37", + "2" + ], + "workloads": { + "log_unit_selected_ratios": { + "seconds": { + "reference": [ + 0.083969698, + 0.083048027, + 0.081204706, + 0.082454541, + 0.087395416, + 0.100910135, + 0.084442356 + ], + "optimized": [ + 0.007430381, + 0.006669717, + 0.006517293, + 0.00669193, + 0.006882802, + 0.006675095, + 0.006503513 + ] + }, + "median_seconds": { + "reference": 0.083969698, + "optimized": 0.006675095 + }, + "speedup": 12.579551002644905 + }, + "complex626_native_endpoint_pair": { + "seconds": { + "reference": [ + 0.024176756, + 0.023808052, + 0.02254703, + 0.023777857, + 0.02299415, + 0.023521558, + 0.023584852 + ], + "optimized": [ + 0.009349324, + 0.008900741, + 0.00878418, + 0.009104292, + 0.009097912, + 0.008691883, + 0.008715618 + ] + }, + "median_seconds": { + "reference": 0.023584852, + "optimized": 0.008900741 + }, + "speedup": 2.6497627557076426 + }, + "selected_three_charged_endpoint_pairs": { + "seconds": { + "reference": [ + 0.067277693, + 0.070151496, + 0.067829588, + 0.069430691, + 0.067617876, + 0.065936663, + 0.069386396 + ], + "optimized": [ + 0.030728399, + 0.02906233, + 0.028104495, + 0.028110434, + 0.028106989, + 0.027575584, + 0.031586917 + ] + }, + "median_seconds": { + "reference": 0.067829588, + "optimized": 0.028110434 + }, + "speedup": 2.4129683661234114 + } + } + }, + "scope": "Exact arithmetic-kernel equivalence and extracted profile pricing only; no full supplier, assembly, repository, CI, or Lean replay. No new kappa." +} diff --git a/research/exact-log-horner/evidence/codex-benchmark.json b/research/exact-log-horner/evidence/codex-benchmark.json new file mode 100644 index 0000000000..b4947eb1ae --- /dev/null +++ b/research/exact-log-horner/evidence/codex-benchmark.json @@ -0,0 +1,204 @@ +{ + "status": "PASS_EXACT_LOG_HORNER", + "seed": 89, + "base_commit": "66849e1475c930fd7732b1a0067ffee7e1e95f60", + "reference_git_blob_sha1": "14a90fa0e788217856f070382c9e61bd7c603c61", + "executed_input_sha256": { + "verify.py": "e0db83f49279ab4715a033f727a59529b82213ba5dde4ef6e601d568fda09e4c", + "log_horner.py": "2ac2759ca07ca9456c85869dc8ebe22363a9056f684b6234dc7df6df1ca93cd8", + "fixtures.json": "cab28353eff3c0009ad6819ff7d1c67c2ddd54f82c1f9bf2772e0c2f9edb7318", + "reference/base_two_moment.py": "aee70c242a2f1d225528fabe2002e1564d1dc884797c07d28a831c7878ee9098" + }, + "environment": { + "python": "3.12.8 (v3.12.8:2dc476bcb91, Dec 3 2024, 14:43:19) [Clang 13.0.0 (clang-1300.0.29.30)]", + "implementation": "CPython", + "platform": "macOS-26.6.2-arm64-arm-64bit", + "machine": "arm64", + "optimization_level": 0, + "cpu_count": 12 + }, + "verification": { + "groups": { + "unit_grid_denominator_at_most_64": 1261, + "unit_adversarial_and_seeded_large_rationals": 30, + "range_reduction_all_children_m_2_through_96": 4560, + "range_reduction_power_of_two_boundaries": 21, + "charged_moment_endpoints": 6, + "pricing_negative_controls_per_engine": 5, + "inherited_domain_rejections_both_engines": 24, + "new_exact_input_type_rejections": 3, + "exact_integer_endpoints": 2, + "implementation_mutations_detected": 8 + }, + "exact_comparison_digest_sha256": "c926bc76b11c982a477174b4c09ea0be2b4c549ae4dcd8215d7ac19deb91202a", + "moments": [ + { + "name": "complex626_native", + "accept": true, + "surcharge": false, + "interval_minus_one": [ + "-2346073/1000000000000000000000000000000", + "-293259/125000000000000000000000000000" + ] + }, + { + "name": "complex626_native", + "accept": false, + "surcharge": false, + "interval_minus_one": [ + "64931/100000000000000000000000000000", + "649311/1000000000000000000000000000000" + ] + }, + { + "name": "complex626_conservative", + "accept": true, + "surcharge": true, + "interval_minus_one": [ + "-7010240519182780279647/2500000000000000000000000000000000000000000000", + "-5608190415346224223689/2000000000000000000000000000000000000000000000" + ] + }, + { + "name": "complex626_conservative", + "accept": false, + "surcharge": true, + "interval_minus_one": [ + "1912877923638794608283/10000000000000000000000000000000000000000000000", + "76515516945551784337/400000000000000000000000000000000000000000000" + ] + }, + { + "name": "bit543", + "accept": true, + "surcharge": true, + "interval_minus_one": [ + "-1120888283015460284783/2500000000000000000000000000000000000000000000", + "-4483543132061841139029/10000000000000000000000000000000000000000000000" + ] + }, + { + "name": "bit543", + "accept": false, + "surcharge": true, + "interval_minus_one": [ + "13153878434097279887307/5000000000000000000000000000000000000000000000", + "6576941717048639943679/2500000000000000000000000000000000000000000000" + ] + } + ], + "mutations_detected": [ + "drop_last_series_term", + "erase_remainder_bound", + "wrong_homogeneous_denominator", + "wrong_horner_multiplier", + "freeze_denominator_power", + "damage_one_series_coefficient", + "wrong_tail_exponent", + "lossy_float_input_roundtrip" + ] + }, + "verification_seconds": 3.7898530419915915, + "benchmark": { + "repeats": 7, + "timer": "perf_counter_ns", + "alternating_order": true, + "input_dependent_caching": false, + "unit_batch_repetitions": 20, + "unit_inputs": [ + "73/64", + "8/7", + "4/3", + "73/48", + "32/21", + "8/5", + "73/40", + "73/37", + "2" + ], + "workloads": { + "log_unit_selected_ratios": { + "seconds": { + "reference": [ + 0.050443166, + 0.050166875, + 0.051424417, + 0.051703667, + 0.051398166, + 0.051908917, + 0.051550041 + ], + "optimized": [ + 0.0046065, + 0.004648125, + 0.004685584, + 0.004961333, + 0.00484025, + 0.004986291, + 0.005216459 + ] + }, + "median_seconds": { + "reference": 0.051424417, + "optimized": 0.00484025 + }, + "speedup": 10.624330768038842 + }, + "complex626_native_endpoint_pair": { + "seconds": { + "reference": [ + 0.015044125, + 0.015151125, + 0.014880583, + 0.014316125, + 0.015104333, + 0.014711959, + 0.014610625 + ], + "optimized": [ + 0.006244084, + 0.005864, + 0.006455375, + 0.006035875, + 0.006132834, + 0.005834833, + 0.006289625 + ] + }, + "median_seconds": { + "reference": 0.014880583, + "optimized": 0.006132834 + }, + "speedup": 2.426379549813349 + }, + "selected_three_charged_endpoint_pairs": { + "seconds": { + "reference": [ + 0.043811083, + 0.043783333, + 0.045112459, + 0.043926333, + 0.04353975, + 0.042711375, + 0.042941209 + ], + "optimized": [ + 0.019233875, + 0.018692833, + 0.019203958, + 0.018923625, + 0.019363708, + 0.019166708, + 0.018678792 + ] + }, + "median_seconds": { + "reference": 0.043783333, + "optimized": 0.019166708 + }, + "speedup": 2.2843428824605665 + } + } + }, + "scope": "Exact arithmetic-kernel equivalence and extracted profile pricing only; no full supplier, assembly, repository, CI, or Lean replay. No new kappa." +} diff --git a/research/exact-log-horner/evidence/codex-optimized.json b/research/exact-log-horner/evidence/codex-optimized.json new file mode 100644 index 0000000000..51c9200b6d --- /dev/null +++ b/research/exact-log-horner/evidence/codex-optimized.json @@ -0,0 +1,103 @@ +{ + "status": "PASS_EXACT_LOG_HORNER", + "seed": 89, + "base_commit": "66849e1475c930fd7732b1a0067ffee7e1e95f60", + "reference_git_blob_sha1": "14a90fa0e788217856f070382c9e61bd7c603c61", + "executed_input_sha256": { + "verify.py": "e0db83f49279ab4715a033f727a59529b82213ba5dde4ef6e601d568fda09e4c", + "log_horner.py": "2ac2759ca07ca9456c85869dc8ebe22363a9056f684b6234dc7df6df1ca93cd8", + "fixtures.json": "cab28353eff3c0009ad6819ff7d1c67c2ddd54f82c1f9bf2772e0c2f9edb7318", + "reference/base_two_moment.py": "aee70c242a2f1d225528fabe2002e1564d1dc884797c07d28a831c7878ee9098" + }, + "environment": { + "python": "3.12.8 (v3.12.8:2dc476bcb91, Dec 3 2024, 14:43:19) [Clang 13.0.0 (clang-1300.0.29.30)]", + "implementation": "CPython", + "platform": "macOS-26.6.2-arm64-arm-64bit", + "machine": "arm64", + "optimization_level": 1, + "cpu_count": 12 + }, + "verification": { + "groups": { + "unit_grid_denominator_at_most_64": 1261, + "unit_adversarial_and_seeded_large_rationals": 30, + "range_reduction_all_children_m_2_through_96": 4560, + "range_reduction_power_of_two_boundaries": 21, + "charged_moment_endpoints": 6, + "pricing_negative_controls_per_engine": 5, + "inherited_domain_rejections_both_engines": 24, + "new_exact_input_type_rejections": 3, + "exact_integer_endpoints": 2, + "implementation_mutations_detected": 8 + }, + "exact_comparison_digest_sha256": "c926bc76b11c982a477174b4c09ea0be2b4c549ae4dcd8215d7ac19deb91202a", + "moments": [ + { + "name": "complex626_native", + "accept": true, + "surcharge": false, + "interval_minus_one": [ + "-2346073/1000000000000000000000000000000", + "-293259/125000000000000000000000000000" + ] + }, + { + "name": "complex626_native", + "accept": false, + "surcharge": false, + "interval_minus_one": [ + "64931/100000000000000000000000000000", + "649311/1000000000000000000000000000000" + ] + }, + { + "name": "complex626_conservative", + "accept": true, + "surcharge": true, + "interval_minus_one": [ + "-7010240519182780279647/2500000000000000000000000000000000000000000000", + "-5608190415346224223689/2000000000000000000000000000000000000000000000" + ] + }, + { + "name": "complex626_conservative", + "accept": false, + "surcharge": true, + "interval_minus_one": [ + "1912877923638794608283/10000000000000000000000000000000000000000000000", + "76515516945551784337/400000000000000000000000000000000000000000000" + ] + }, + { + "name": "bit543", + "accept": true, + "surcharge": true, + "interval_minus_one": [ + "-1120888283015460284783/2500000000000000000000000000000000000000000000", + "-4483543132061841139029/10000000000000000000000000000000000000000000000" + ] + }, + { + "name": "bit543", + "accept": false, + "surcharge": true, + "interval_minus_one": [ + "13153878434097279887307/5000000000000000000000000000000000000000000000", + "6576941717048639943679/2500000000000000000000000000000000000000000000" + ] + } + ], + "mutations_detected": [ + "drop_last_series_term", + "erase_remainder_bound", + "wrong_homogeneous_denominator", + "wrong_horner_multiplier", + "freeze_denominator_power", + "damage_one_series_coefficient", + "wrong_tail_exponent", + "lossy_float_input_roundtrip" + ] + }, + "verification_seconds": 3.790736333001405, + "scope": "Exact arithmetic-kernel equivalence and extracted profile pricing only; no full supplier, assembly, repository, CI, or Lean replay. No new kappa." +} diff --git a/research/exact-log-horner/evidence/codex-package-controls.json b/research/exact-log-horner/evidence/codex-package-controls.json new file mode 100644 index 0000000000..ba11b17009 --- /dev/null +++ b/research/exact-log-horner/evidence/codex-package-controls.json @@ -0,0 +1,46 @@ +{ + "status": "PASS_PACKAGE_CONTROLS", + "rejected": 8, + "cases": [ + { + "case": "changed_reference_with_updated_manifest", + "optimization_level": 0, + "rejection": "reference git blob mismatch" + }, + { + "case": "changed_reference_with_updated_manifest", + "optimization_level": 1, + "rejection": "reference git blob mismatch" + }, + { + "case": "changed_fixture", + "optimization_level": 0, + "rejection": "package hash mismatch: fixtures.json" + }, + { + "case": "changed_fixture", + "optimization_level": 1, + "rejection": "package hash mismatch: fixtures.json" + }, + { + "case": "missing_fixture", + "optimization_level": 0, + "rejection": "package file inventory mismatch" + }, + { + "case": "missing_fixture", + "optimization_level": 1, + "rejection": "package file inventory mismatch" + }, + { + "case": "unexpected_file", + "optimization_level": 0, + "rejection": "package file inventory mismatch" + }, + { + "case": "unexpected_file", + "optimization_level": 1, + "rejection": "package file inventory mismatch" + } + ] +} diff --git a/research/exact-log-horner/evidence/codex-repository-binding.json b/research/exact-log-horner/evidence/codex-repository-binding.json new file mode 100644 index 0000000000..54f9bf5d06 --- /dev/null +++ b/research/exact-log-horner/evidence/codex-repository-binding.json @@ -0,0 +1,50 @@ +{ + "status": "PASS_REPOSITORY_SOURCE_AND_EXTRACTED_FIELDS", + "base_commit": "66849e1475c930fd7732b1a0067ffee7e1e95f60", + "verified_source_files": [ + { + "path": "research/five-stage-gen4-banks/base_two_moment.py", + "git_blob_sha1": "14a90fa0e788217856f070382c9e61bd7c603c61", + "sha256": "aee70c242a2f1d225528fabe2002e1564d1dc884797c07d28a831c7878ee9098" + }, + { + "path": "research/complex-allcold/engines/base_two_moment.py", + "git_blob_sha1": "14a90fa0e788217856f070382c9e61bd7c603c61", + "sha256": "aee70c242a2f1d225528fabe2002e1564d1dc884797c07d28a831c7878ee9098" + }, + { + "path": "research/community-k492-audit/pr626/replay/ASSEMBLY.json", + "git_blob_sha1": "2e97b75bd8e74e8aa1b5fb83adcdc461aa07c398", + "sha256": "6127732e2fcdd470dab349c1c51d03cd9f0787ad0309b1b4a7c811a908028f4e" + }, + { + "path": "research/e8-bit-r420/EXPECTED.json", + "git_blob_sha1": "b61d859826246e0c3dabbe096e57ad7015eadfd5", + "sha256": "06eccee9f6b77e140833df83407e7996dc948c17d49b0779ab171fbe463fd28d" + }, + { + "path": "research/complex-k492-owner-repair/code/assemble.py", + "git_blob_sha1": "d1674e657ff046f9d55c917723002f270e05c42a", + "sha256": "1b1a9024ac910dc9b9d9e30150684e1fa9cb228a4c1c275b75ab04b57fdef1dd" + }, + { + "path": "certificates/selected-result.json", + "git_blob_sha1": "92a10096dee76479af88a897714b3818d8263141", + "sha256": "b3bf402f31a69bde0629936a9b569bed48281568d7b16d5fba120b5311ea1f53" + }, + { + "path": "docs/research/community-k492-review.md", + "git_blob_sha1": "11efcd07ae2b9d93d355c6adaf773dca70dbce91", + "sha256": "3b731d30e80010b15408a289b0b32192700885474c8b36d48ee3320a7a8c5c47" + } + ], + "field_checks": [ + "both complete profiles", + "bit live stock", + "native complex endpoint", + "conservative complex endpoint", + "bit endpoint", + "selected kappa", + "vendored reference byte equality" + ] +} diff --git a/research/exact-log-horner/evidence/isolated-optimized.json b/research/exact-log-horner/evidence/isolated-optimized.json new file mode 100644 index 0000000000..bfae038360 --- /dev/null +++ b/research/exact-log-horner/evidence/isolated-optimized.json @@ -0,0 +1,103 @@ +{ + "status": "PASS_EXACT_LOG_HORNER", + "seed": 89, + "base_commit": "66849e1475c930fd7732b1a0067ffee7e1e95f60", + "reference_git_blob_sha1": "14a90fa0e788217856f070382c9e61bd7c603c61", + "executed_input_sha256": { + "verify.py": "e0db83f49279ab4715a033f727a59529b82213ba5dde4ef6e601d568fda09e4c", + "log_horner.py": "2ac2759ca07ca9456c85869dc8ebe22363a9056f684b6234dc7df6df1ca93cd8", + "fixtures.json": "cab28353eff3c0009ad6819ff7d1c67c2ddd54f82c1f9bf2772e0c2f9edb7318", + "reference/base_two_moment.py": "aee70c242a2f1d225528fabe2002e1564d1dc884797c07d28a831c7878ee9098" + }, + "environment": { + "python": "3.13.5 (main, Jul 15 2026, 20:25:40) [GCC 14.2.0]", + "implementation": "CPython", + "platform": "Linux-6.18.44-x86_64-with-glibc2.41", + "machine": "x86_64", + "optimization_level": 1, + "cpu_count": 5 + }, + "verification": { + "groups": { + "unit_grid_denominator_at_most_64": 1261, + "unit_adversarial_and_seeded_large_rationals": 30, + "range_reduction_all_children_m_2_through_96": 4560, + "range_reduction_power_of_two_boundaries": 21, + "charged_moment_endpoints": 6, + "pricing_negative_controls_per_engine": 5, + "inherited_domain_rejections_both_engines": 24, + "new_exact_input_type_rejections": 3, + "exact_integer_endpoints": 2, + "implementation_mutations_detected": 8 + }, + "exact_comparison_digest_sha256": "c926bc76b11c982a477174b4c09ea0be2b4c549ae4dcd8215d7ac19deb91202a", + "moments": [ + { + "name": "complex626_native", + "accept": true, + "surcharge": false, + "interval_minus_one": [ + "-2346073/1000000000000000000000000000000", + "-293259/125000000000000000000000000000" + ] + }, + { + "name": "complex626_native", + "accept": false, + "surcharge": false, + "interval_minus_one": [ + "64931/100000000000000000000000000000", + "649311/1000000000000000000000000000000" + ] + }, + { + "name": "complex626_conservative", + "accept": true, + "surcharge": true, + "interval_minus_one": [ + "-7010240519182780279647/2500000000000000000000000000000000000000000000", + "-5608190415346224223689/2000000000000000000000000000000000000000000000" + ] + }, + { + "name": "complex626_conservative", + "accept": false, + "surcharge": true, + "interval_minus_one": [ + "1912877923638794608283/10000000000000000000000000000000000000000000000", + "76515516945551784337/400000000000000000000000000000000000000000000" + ] + }, + { + "name": "bit543", + "accept": true, + "surcharge": true, + "interval_minus_one": [ + "-1120888283015460284783/2500000000000000000000000000000000000000000000", + "-4483543132061841139029/10000000000000000000000000000000000000000000000" + ] + }, + { + "name": "bit543", + "accept": false, + "surcharge": true, + "interval_minus_one": [ + "13153878434097279887307/5000000000000000000000000000000000000000000000", + "6576941717048639943679/2500000000000000000000000000000000000000000000" + ] + } + ], + "mutations_detected": [ + "drop_last_series_term", + "erase_remainder_bound", + "wrong_homogeneous_denominator", + "wrong_horner_multiplier", + "freeze_denominator_power", + "damage_one_series_coefficient", + "wrong_tail_exponent", + "lossy_float_input_roundtrip" + ] + }, + "verification_seconds": 5.83721776099992, + "scope": "Exact arithmetic-kernel equivalence and extracted profile pricing only; no full supplier, assembly, repository, CI, or Lean replay. No new kappa." +} diff --git a/research/exact-log-horner/evidence/package-controls.json b/research/exact-log-horner/evidence/package-controls.json new file mode 100644 index 0000000000..ba11b17009 --- /dev/null +++ b/research/exact-log-horner/evidence/package-controls.json @@ -0,0 +1,46 @@ +{ + "status": "PASS_PACKAGE_CONTROLS", + "rejected": 8, + "cases": [ + { + "case": "changed_reference_with_updated_manifest", + "optimization_level": 0, + "rejection": "reference git blob mismatch" + }, + { + "case": "changed_reference_with_updated_manifest", + "optimization_level": 1, + "rejection": "reference git blob mismatch" + }, + { + "case": "changed_fixture", + "optimization_level": 0, + "rejection": "package hash mismatch: fixtures.json" + }, + { + "case": "changed_fixture", + "optimization_level": 1, + "rejection": "package hash mismatch: fixtures.json" + }, + { + "case": "missing_fixture", + "optimization_level": 0, + "rejection": "package file inventory mismatch" + }, + { + "case": "missing_fixture", + "optimization_level": 1, + "rejection": "package file inventory mismatch" + }, + { + "case": "unexpected_file", + "optimization_level": 0, + "rejection": "package file inventory mismatch" + }, + { + "case": "unexpected_file", + "optimization_level": 1, + "rejection": "package file inventory mismatch" + } + ] +} diff --git a/research/exact-log-horner/fixtures.json b/research/exact-log-horner/fixtures.json new file mode 100644 index 0000000000..ce831ea465 --- /dev/null +++ b/research/exact-log-horner/fixtures.json @@ -0,0 +1,35 @@ +{ + "schema": 1, + "base_commit": "66849e1475c930fd7732b1a0067ffee7e1e95f60", + "scope": "Extracted arithmetic inputs, not independently reconstructed supplier counts.", + "selected_kappa": "51110230636731/31250000000000000", + "profiles": { + "complex626": { + "m": 73, + "W": 7168, + "deficit": 2560, + "entries": [[1,181659],[2,30016],[3,31104],[4,11520],[5,5040],[6,576],[8,576],[37,1],[48,2215]], + "source_path": "research/community-k492-audit/pr626/replay/ASSEMBLY.json", + "source_git_blob_sha1": "2e97b75bd8e74e8aa1b5fb83adcdc461aa07c398", + "source_fields": ["complex_profile", "complex_lower", "conservative_complex_lower"], + "dimensions_source": "research/complex-k492-owner-repair/code/assemble.py: check_moment('complex', H, 73, owner['live'], b, 2560, False); docs/research/community-k492-review.md: 7168 live rows" + }, + "bit543": { + "m": 64, + "W": 30720, + "deficit": 9984, + "entries": [[1,380160],[2,426624],[4,32640],[5,34560],[6,15360],[7,23040],[8,2592],[42,3456]], + "source_path": "research/e8-bit-r420/EXPECTED.json", + "source_git_blob_sha1": "b61d859826246e0c3dabbe096e57ad7015eadfd5", + "source_fields": ["nine.profile", "nine.bit.live", "nine.bit_lower"], + "dimensions_source": "research/complex-k492-owner-repair/code/assemble.py: check_moment('bit', bitH, 64, bit['bit']['live'], c, 9984, True)" + } + }, + "cases": [ + {"name":"complex626_native","profile":"complex626","lower":"65528268492323474503/40000000000000000000000","surcharge":false}, + {"name":"complex626_conservative","profile":"complex626","lower":"327641341885943404413/200000000000000000000000","surcharge":true}, + {"name":"bit543","profile":"bit543","lower":"413456747036699736067/250000000000000000000000","surcharge":true} + ], + "next_grid_step": "1/1000000000000000000000000", + "surcharge_rule": "Add moment(m,W,[(1,32*m*m*sum(counts))],saving)/10**16 to each endpoint, exactly as the retained assembly does." +} diff --git a/research/exact-log-horner/log_horner.py b/research/exact-log-horner/log_horner.py new file mode 100644 index 0000000000..09d112baf5 --- /dev/null +++ b/research/exact-log-horner/log_horner.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +"""Exact integer-Horner replacement for the retained 80-term log_unit. + +Apache-2.0. Prepared for Tuomo Kiiskinen with substantial OpenAI ChatGPT +assistance. See NOTICE.md for the original rational-engine attribution. + +This module changes polynomial evaluation, NOT series length, remainder, +precision, rounding, or any supplier admission rule. The intended input is +an exact Fraction in [1, 2]; integer endpoints are accepted exactly as well. +No memoized input-dependent state is used. +""" +from fractions import Fraction +from math import lcm + +TERMS = 80 +_ODDS = tuple(range(1, 2 * TERMS, 2)) +_COMMON = lcm(*_ODDS) +_COEFFICIENTS = tuple(_COMMON // odd for odd in _ODDS) + + +def log_unit(x: Fraction) -> tuple[Fraction, Fraction]: + """Return exactly the original lower/upper fractions for rational x. + + For z=a/b=(x-1)/(x+1), homogenize the 80-term atanh polynomial + over common denominator L*b**159. All loop operations are integer + operations. The original tail is 2*a**161/(161*b**159*(b*b-a*a)). + """ + if not isinstance(x, (Fraction, int)): + raise TypeError("an exact Fraction or integer is required") + if not 1 <= x <= 2: + raise ValueError("logarithm range") + x = Fraction(x) + z = (x - 1) / (x + 1) + a, b = z.numerator, z.denominator + a2, b2 = a * a, b * b + numerator = _COEFFICIENTS[-1] + b_power = b2 + for coefficient in reversed(_COEFFICIENTS[:-1]): + numerator = a2 * numerator + coefficient * b_power + b_power *= b2 + # At loop exit b_power=b**160, including z=0 without a special case. + denominator_power = b_power // b + lower = Fraction(2 * a * numerator, _COMMON * denominator_power) + tail = Fraction(2 * a**161, 161 * denominator_power * (b2 - a2)) + return lower, lower + tail diff --git a/research/exact-log-horner/reference/base_two_moment.py b/research/exact-log-horner/reference/base_two_moment.py new file mode 100644 index 0000000000..14a90fa0e7 --- /dev/null +++ b/research/exact-log-horner/reference/base_two_moment.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +"""Maintainer arithmetic cross-check of the pinned PR39 certificate. + +Uses no producer/checker imports. Counts are inputs, not proved by this script. +80-term rational logarithms and 12-term exponentials independently enclose +the two moments. The accompanying written review addresses their realization. +""" +import argparse +from fractions import Fraction as Q +from hashlib import sha256 +import json +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +GRID = 10**30 + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def log_unit(x): + require(1 <= x <= 2, "logarithm range") + z = (x-1)/(x+1) + lo = 2*sum((z**(2*j+1)/(2*j+1) for j in range(80)), Q(0)) + return lo, lo+2*z**161/(161*(1-z*z)) + + +def log_bounds(x): + k = 0 + while x > 2: + x /= 2 + k += 1 + lo, hi = log_unit(x) + l2, u2 = log_unit(Q(2)) + lo, hi = lo+k*l2, hi+k*u2 + # Outward rational rounding keeps later certificates compact. + return Q((lo*GRID).__floor__(), GRID), Q((hi*GRID).__ceil__(), GRID) + + +def exp_bounds(x): + require(0 <= x < 1, "exponential range") + term = total = Q(1) + for j in range(1, 13): + term *= x/j + total += term + tail = term*x/13/(1-x/14) + return total, total+tail + + +def moment(m, W, entries, saving): + lo = hi = Q(0) + for t, count in entries: + t, count = int(t), int(count) + require(0 < t < m and count > 0, "improper child") + l, u = log_bounds(Q(m, t)) + lower = exp_bounds(saving*l)[0] + upper = exp_bounds(saving*u)[1] + lo += Q(t*count, m*W)*lower + hi += Q(t*count, m*W)*upper + return Q((lo*GRID).__floor__(), GRID), Q((hi*GRID).__ceil__(), GRID) + diff --git a/research/exact-log-horner/test_package.py b/research/exact-log-horner/test_package.py new file mode 100644 index 0000000000..415b8e55fd --- /dev/null +++ b/research/exact-log-horner/test_package.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Exercise fail-closed package/source pins under normal and optimized Python.""" +from pathlib import Path +import hashlib +import json +import shutil +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent + + +def require(condition, message): + if not condition: + raise RuntimeError(message) + + +def main(): + cases = ( + ("changed_reference_with_updated_manifest", "reference git blob mismatch"), + ("changed_fixture", "package hash mismatch: fixtures.json"), + ("missing_fixture", "package file inventory mismatch"), + ("unexpected_file", "package file inventory mismatch"), + ) + receipts = [] + with tempfile.TemporaryDirectory(prefix="exact log controls ") as temp: + root = Path(temp) + for name, reason in cases: + package = root / name + shutil.copytree(HERE, package, ignore=shutil.ignore_patterns("__pycache__")) + if name == "changed_reference_with_updated_manifest": + path = package / "reference/base_two_moment.py" + path.write_bytes(path.read_bytes() + b"# changed\n") + mf = package / "MANIFEST.json" + data = json.loads(mf.read_text()) + data["reference/base_two_moment.py"] = hashlib.sha256(path.read_bytes()).hexdigest() + mf.write_text(json.dumps(data, indent=2) + "\n") + elif name == "changed_fixture": + path = package / "fixtures.json" + path.write_bytes(path.read_bytes() + b" \n") + elif name == "missing_fixture": + (package / "fixtures.json").unlink() + else: + (package / "unlisted.json").write_text("{}\n") + for optimized in (False, True): + command = [sys.executable, "-I", "-B"] + (["-O"] if optimized else []) + command += [str(package / "verify.py")] + result = subprocess.run(command, capture_output=True, text=True, timeout=20) + require(result.returncode == 1, "wrong exit status: " + name) + require(result.stderr.strip() == "FAIL: " + reason, "wrong failure reason: " + name) + require("PASS_EXACT_LOG_HORNER" not in result.stdout, "false success marker") + receipts.append({"case": name, "optimization_level": int(optimized), "rejection": reason}) + print(json.dumps({"status": "PASS_PACKAGE_CONTROLS", "rejected": len(receipts), "cases": receipts}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/research/exact-log-horner/verify.py b/research/exact-log-horner/verify.py new file mode 100644 index 0000000000..dac83a812b --- /dev/null +++ b/research/exact-log-horner/verify.py @@ -0,0 +1,327 @@ +#!/usr/bin/env python3 +"""Check exact equivalence and optionally benchmark the isolated log replacement. + +Python 3.10+, standard library only. No repository files are overwritten. +Checks remain active under -O. No supplier or complete assembly replay is claimed. +""" +from __future__ import annotations + +import argparse +from fractions import Fraction as Q +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import platform +import random +import statistics +import sys +import time +import types + +HERE = Path(__file__).resolve().parent +REFERENCE_BLOB = "14a90fa0e788217856f070382c9e61bd7c603c61" +REFERENCE_SHA256 = "aee70c242a2f1d225528fabe2002e1564d1dc884797c07d28a831c7878ee9098" +SEED = 89 + + +class VerificationError(RuntimeError): + pass + + +def check(condition, message): + if not condition: + raise VerificationError(message) + + +def load(name, path): + spec = importlib.util.spec_from_file_location(name, path) + check(spec is not None and spec.loader is not None, "module loader unavailable") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def source_check(reference_path): + data = reference_path.read_bytes() + blob = hashlib.sha1(b"blob " + str(len(data)).encode() + b"\0" + data).hexdigest() + check(blob == REFERENCE_BLOB, "reference git blob mismatch") + check(hashlib.sha256(data).hexdigest() == REFERENCE_SHA256, "reference SHA256 mismatch") + + +def inventory_check(): + manifest_path = HERE / "MANIFEST.json" + check(manifest_path.is_file(), "missing MANIFEST.json") + manifest = json.loads(manifest_path.read_text()) + actual = {str(p.relative_to(HERE)) for p in HERE.rglob("*") + if p.is_file() and "__pycache__" not in p.parts and p.name != "MANIFEST.json"} + check(actual == set(manifest), "package file inventory mismatch") + for name, wanted in manifest.items(): + check(hashlib.sha256((HERE / name).read_bytes()).hexdigest() == wanted, + "package hash mismatch: " + name) + + +def update_digest(digest, value): + """Canonical integer/fraction encoding without decimal digit-limit changes.""" + value = Q(value) + for n in (value.numerator, value.denominator): + digest.update(b"-" if n < 0 else b"+") + data = abs(n).to_bytes(max(1, (abs(n).bit_length() + 7) // 8), "big") + digest.update(len(data).to_bytes(8, "big")) + digest.update(data) + + +def equal_case(ref, fast, name, x, digest): + wanted = getattr(ref, name)(x) + actual = getattr(fast, name)(x) + check(actual == wanted, name + " exact endpoint mismatch") + check(wanted[0] <= wanted[1], "reversed interval") + update_digest(digest, x) + for endpoint in actual: + update_digest(digest, endpoint) + + +def priced(module, profile, saving, surcharge): + m, W, entries = profile["m"], profile["W"], profile["entries"] + lo, hi = module.moment(m, W, entries, saving) + if surcharge: + count = 32 * m * m * sum(n for _, n in entries) + fl, fu = module.moment(m, W, [(1, count)], saving) + lo += fl / 10**16 + hi += fu / 10**16 + return lo, hi + + +def moment_suite(module, fixture): + out = [] + for case in fixture["cases"]: + profile = fixture["profiles"][case["profile"]] + lower = Q(case["lower"]) + for saving in (lower, lower + Q(fixture["next_grid_step"])): + out.append(priced(module, profile, saving, case["surcharge"])) + return out + + +def rejection_check(call, exc_type, text): + try: + call() + except exc_type as exc: + check(str(exc) == text, "unexpected rejection reason: " + str(exc)) + else: + raise VerificationError("missing rejection: " + text) + + +def mutation_checks(ref, optimized_source): + # Mutate the evaluated implementation, not the expected answers. + changes = { + "drop_last_series_term": ("TERMS = 80", "TERMS = 79"), + "erase_remainder_bound": ("return lower, lower + tail", "return lower, lower"), + "wrong_homogeneous_denominator": ("denominator_power = b_power // b", "denominator_power = b_power"), + "wrong_horner_multiplier": ("numerator = a2 * numerator + coefficient * b_power", "numerator = b2 * numerator + coefficient * b_power"), + "freeze_denominator_power": ("b_power *= b2", "b_power *= 1"), + "damage_one_series_coefficient": ("_COEFFICIENTS = tuple(_COMMON // odd for odd in _ODDS)", "_COEFFICIENTS = tuple(_COMMON // odd + (odd == 75) for odd in _ODDS)"), + "wrong_tail_exponent": ("2 * a**161", "2 * a**159"), + "lossy_float_input_roundtrip": ("x = Fraction(x)", "x = Fraction(float(x))"), + } + probes = (Q(2), Q(7, 5), Q(9, 5), Q(1) + Q(1, 2**80)) + rejected = [] + for name, (old, new) in changes.items(): + check(optimized_source.count(old) == 1, "mutation target missing or ambiguous: " + name) + module = types.ModuleType("mutant_" + name) + exec(compile(optimized_source.replace(old, new), name, "exec"), module.__dict__) + # Every listed mutant must return a numerically wrong interval on a probe; + # syntax/import/runtime exceptions are NOT credited as rejection evidence. + mismatch = any(module.log_unit(x) != ref.log_unit(x) for x in probes) + check(mismatch, "mutation escaped exact comparison: " + name) + rejected.append(name) + return rejected + + +def verify(ref, fast, optimized, fixture): + digest = hashlib.sha256() + groups = {} + unit = sorted({Q(n, d) for d in range(1, 65) for n in range(d, 2 * d + 1)}) + for x in unit: + equal_case(ref, fast, "log_unit", x, digest) + groups["unit_grid_denominator_at_most_64"] = len(unit) + + rng = random.Random(SEED) + difficult = [] + for bits in (17, 53, 80, 127, 256): + tiny = Q(1, 2**bits) + difficult.extend((1 + tiny, 2 - tiny)) + for _ in range(4): + d = rng.getrandbits(bits) | 1 + difficult.append(1 + Q(rng.randrange(d + 1), d)) + for x in difficult: + equal_case(ref, fast, "log_unit", x, digest) + groups["unit_adversarial_and_seeded_large_rationals"] = len(difficult) + + count = 0 + for m in range(2, 97): + for t in range(1, m): + equal_case(ref, fast, "log_bounds", Q(m, t), digest) + count += 1 + groups["range_reduction_all_children_m_2_through_96"] = count + + boundaries = [] + for k in (1, 2, 3, 8, 16, 32, 64): + p = Q(2**k) + boundaries.extend((p, p - Q(1, 2**80), p + Q(1, 2**80))) + for x in boundaries: + equal_case(ref, fast, "log_bounds", x, digest) + groups["range_reduction_power_of_two_boundaries"] = len(boundaries) + + for profile in fixture["profiles"].values(): + m, W, H = profile["m"], profile["W"], profile["entries"] + check(m * W - sum(t * n for t, n in H) == profile["deficit"], "fixture rank mass mismatch") + check(m * m > 2 * max(t for t, _ in H)**2, "fixture halving inequality mismatch") + wanted, actual = moment_suite(ref, fixture), moment_suite(fast, fixture) + check(actual == wanted, "complete charged moment suite differs") + moments = [] + for index, ((lo, hi), case) in enumerate(zip(actual, [c for c in fixture["cases"] for _ in range(2)])): + accept = index % 2 == 0 + check(hi < 1 if accept else lo > 1, "adjacent endpoint decision differs: " + case["name"]) + for v in (lo, hi): + update_digest(digest, v) + moments.append({"name": case["name"], "accept": accept, "surcharge": case["surcharge"], + "interval_minus_one": [str(lo - 1), str(hi - 1)]}) + groups["charged_moment_endpoints"] = len(moments) + + # Controls for the actual physical pricing distinction, not merely agreement. + bit = fixture["cases"][2] + bp = fixture["profiles"][bit["profile"]] + bit_next = Q(bit["lower"]) + Q(fixture["next_grid_step"]) + native = fixture["cases"][0] + cp = fixture["profiles"][native["profile"]] + for module in (ref, fast): + check(priced(module, bp, bit_next, False)[1] < 1, "omitted-bit-surcharge control not reproduced") + check(priced(module, cp, Q(native["lower"]), True)[0] > 1, "conservative-complex-surcharge control not reproduced") + for case in fixture["cases"]: + profile = fixture["profiles"][case["profile"]] + damaged = dict(profile, entries=[[t, n + (t == 1)] for t, n in profile["entries"]]) + check(priced(module, damaged, Q(case["lower"]), case["surcharge"])[0] > 1, + "extra-child mutation was not rejected") + groups["pricing_negative_controls_per_engine"] = 5 + + domain_count = 0 + for module in (ref, fast): + for x in (Q(-1), Q(0), Q(1, 2), Q(2001, 1000)): + rejection_check(lambda: module.log_unit(x), ValueError, "logarithm range") + domain_count += 1 + for x in (Q(-1, 100), Q(1), Q(2)): + rejection_check(lambda: module.exp_bounds(x), ValueError, "exponential range") + domain_count += 1 + for entry in ((0, 1), (73, 1), (74, 1), (1, 0), (1, -1)): + rejection_check(lambda: module.moment(73, 7168, [entry], Q(native["lower"])), ValueError, "improper child") + domain_count += 1 + groups["inherited_domain_rejections_both_engines"] = domain_count + for x in (1.5, "3/2", None): + rejection_check(lambda: optimized.log_unit(x), TypeError, "an exact Fraction or integer is required") + check(optimized.log_unit(1) == ref.log_unit(Q(1)), "integer endpoint 1") + check(optimized.log_unit(2) == ref.log_unit(Q(2)), "integer endpoint 2") + groups["new_exact_input_type_rejections"] = 3 + groups["exact_integer_endpoints"] = 2 + + mutants = mutation_checks(ref, (HERE / "log_horner.py").read_text()) + groups["implementation_mutations_detected"] = len(mutants) + return {"groups": groups, "exact_comparison_digest_sha256": digest.hexdigest(), + "moments": moments, "mutations_detected": mutants} + + +def benchmark(ref, fast, fixture, repeats): + # Same deterministic inputs and same original outer code. No result caches. + # Match the reference's strict x > 2 reduction, including log(2), which + # it evaluates for every ratio. Powers of two therefore reduce to 2. + reduced = {Q(2)} + for profile in fixture["profiles"].values(): + for t, _ in profile["entries"]: + x = Q(profile["m"], t) + while x > 2: + x /= 2 + reduced.add(x) + unit_inputs = sorted(reduced) + check(all(1 <= x <= 2 for x in unit_inputs), "benchmark reduction range") + tasks = { + "log_unit_selected_ratios": lambda m: [m.log_unit(x) for _ in range(20) for x in unit_inputs], + "complex626_native_endpoint_pair": lambda m: [priced(m, fixture["profiles"]["complex626"], z, False) + for z in (Q(fixture["cases"][0]["lower"]), Q(fixture["cases"][0]["lower"]) + Q(fixture["next_grid_step"]))], + "selected_three_charged_endpoint_pairs": lambda m: moment_suite(m, fixture), + } + result = {} + for name, task in tasks.items(): + check(task(ref) == task(fast), "benchmark warmup outputs differ") + samples = {"reference": [], "optimized": []} + for iteration in range(repeats): + order = (("reference", ref), ("optimized", fast)) + if iteration % 2: + order = tuple(reversed(order)) + outputs = [] + for label, module in order: + start = time.perf_counter_ns() + output = task(module) + elapsed = time.perf_counter_ns() - start + samples[label].append(elapsed / 10**9) + outputs.append(output) + check(outputs[0] == outputs[1], "timed outputs differ") + medians = {label: statistics.median(values) for label, values in samples.items()} + result[name] = {"seconds": samples, "median_seconds": medians, + "speedup": medians["reference"] / medians["optimized"]} + return {"repeats": repeats, "timer": "perf_counter_ns", "alternating_order": True, + "input_dependent_caching": False, "unit_batch_repetitions": 20, + "unit_inputs": [str(x) for x in unit_inputs], + "workloads": result} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--benchmark", action="store_true") + parser.add_argument("--repeats", type=int, default=7) + parser.add_argument("--output", type=Path) + args = parser.parse_args() + check(args.repeats >= 3, "at least three benchmark repetitions required") + if args.output is not None: + check(not args.output.exists(), "output already exists") + check(HERE not in args.output.resolve().parents, "output must be outside immutable package") + inventory_check() + reference_path = HERE / "reference" / "base_two_moment.py" + source_check(reference_path) + ref = load("reference_engine", reference_path) + fast = load("optimized_engine", reference_path) + optimized = load("log_horner", HERE / "log_horner.py") + # This private experiment rebinds just one function. No shared import or + # repository file is modified, and all other reference code stays identical. + fast.log_unit = optimized.log_unit + fixture = json.loads((HERE / "fixtures.json").read_text()) + start = time.perf_counter() + report = {"status": "PASS_EXACT_LOG_HORNER", "seed": SEED, + "base_commit": fixture["base_commit"], "reference_git_blob_sha1": REFERENCE_BLOB, + "executed_input_sha256": {name: hashlib.sha256((HERE / name).read_bytes()).hexdigest() + for name in ("verify.py", "log_horner.py", "fixtures.json", "reference/base_two_moment.py")}, + "environment": {"python": sys.version, "implementation": platform.python_implementation(), + "platform": platform.platform(), "machine": platform.machine(), + "optimization_level": sys.flags.optimize, "cpu_count": os.cpu_count()}, + "verification": verify(ref, fast, optimized, fixture)} + report["verification_seconds"] = time.perf_counter() - start + if args.benchmark: + report["benchmark"] = benchmark(ref, fast, fixture, args.repeats) + report["scope"] = "Exact arithmetic-kernel equivalence and extracted profile pricing only; no full supplier, assembly, repository, CI, or Lean replay. No new kappa." + encoded = json.dumps(report, indent=2) + "\n" + if args.output: + args.output.write_text(encoded) + print(report["status"]) + print(json.dumps(report["verification"]["groups"], sort_keys=True)) + if args.benchmark: + for name, row in report["benchmark"]["workloads"].items(): + print(name, "median speedup", format(row["speedup"], ".3f")) + if args.output: + print("receipt:", args.output) + + +if __name__ == "__main__": + try: + main() + except (VerificationError, ValueError, TypeError, OSError, KeyError) as exc: + print("FAIL:", str(exc), file=sys.stderr) + sys.exit(1)