From d9d9f7c66bde26375ea79d1357897acc226b906d Mon Sep 17 00:00:00 2001 From: Nick Petalas Date: Tue, 27 Oct 2026 21:17:36 +0000 Subject: [PATCH] feat(research): price local thresholds for the selected invoice at the BIT saving On the authenticated #5599 P104 invoice, the complex bill fails at C=17/5000 by 4.0496 per FULL. One local paid deletion of rank at least five per FULL closes that gap; free helper splitting needs 61 full H9 refinements, and refining every local helper still fails at 1/100. --- .../INPUT.json | 60 +++++ .../INVOICE.json | 44 ++++ .../README.md | 102 ++++++++ .../SOURCES.json | 48 ++++ .../TASK.json | 129 +++++++++++ .../VERIFY.json | 34 +++ .../verify.py | 219 ++++++++++++++++++ 7 files changed, 636 insertions(+) create mode 100644 research/selected-invoice-bit-cap-thresholds/INPUT.json create mode 100644 research/selected-invoice-bit-cap-thresholds/INVOICE.json create mode 100644 research/selected-invoice-bit-cap-thresholds/README.md create mode 100644 research/selected-invoice-bit-cap-thresholds/SOURCES.json create mode 100644 research/selected-invoice-bit-cap-thresholds/TASK.json create mode 100644 research/selected-invoice-bit-cap-thresholds/VERIFY.json create mode 100644 research/selected-invoice-bit-cap-thresholds/verify.py diff --git a/research/selected-invoice-bit-cap-thresholds/INPUT.json b/research/selected-invoice-bit-cap-thresholds/INPUT.json new file mode 100644 index 0000000000..1d4a7a4394 --- /dev/null +++ b/research/selected-invoice-bit-cap-thresholds/INPUT.json @@ -0,0 +1,60 @@ +{ + "base_commit": "19fdb086ea96af9a9f87936a2b888e10af4ed810", + "components": { + "idle_paid": { + "16": 416, + "24": 416, + "32": 416, + "40": 416, + "48": 416, + "56": 416, + "64": 416, + "72": 208 + }, + "local_helpers": { + "1": 2, + "2": 5, + "4": 89, + "5": 11, + "7": 5, + "8": 16, + "9": 412 + }, + "local_paid": { + "1": 2203, + "2": 459, + "3": 493, + "4": 92, + "5": 168, + "6": 18, + "7": 14 + }, + "main_targets": { + "145": 208, + "17": 416, + "25": 416, + "33": 416, + "41": 416, + "49": 416, + "57": 416, + "65": 416, + "73": 208 + }, + "query_paid": { + "1": 1560 + } + }, + "exporter_inputs_sha256": { + "research/p104-helper-subspace-splits/RESULT.json": "1d92e587915052110dfb3aca8890df5afdaf496164efa5a4a52e69ceeb3c70f3", + "research/p104-helper-subspace-splits/WORD.json.gz": "bbb072bced5824a8d9094c49be2fc51fbfdd05fb2b7dab8106e1275053075099", + "research/p104-productive-controller/CONTROLLER.json": "a84f6bbd547379597464e56c420cc665f96bc43a9a1351eed4b7cd0fce3cc4b9" + }, + "full_calls": 18, + "generated_by": "python3 -B scripts/export_selected_invoice.py --evidence EVIDENCE (stdout is the invoice)", + "invoice_file": "INVOICE.json", + "invoice_sha256": "ad826c829c11ae3193736ad2df3310081809ab6cdcd194346065bd97f943e4c1", + "schema": "selected-invoice-bit-cap-input/v1", + "selected_kappa": "62009/20000000", + "selected_record_sha256": "2a0220e866417774606e0f991e41b9c1d26b1f43b97857238cf478dbc7d330b5", + "source_head": "09dd0965711ca7eeb169057a420abab1c9052137" +} diff --git a/research/selected-invoice-bit-cap-thresholds/INVOICE.json b/research/selected-invoice-bit-cap-thresholds/INVOICE.json new file mode 100644 index 0000000000..5ab7fbc69f --- /dev/null +++ b/research/selected-invoice-bit-cap-thresholds/INVOICE.json @@ -0,0 +1,44 @@ +{ + "schema": "integer-mult-recursive-invoice/v1", + "contract": { + "model": "mixed-target-unnormalized-power-v1", + "rank_semantics": "H_r costs r^(1-C); debit surrendered productive fields", + "ambient_rank": 145, + "boundary": "complete unit before the same mixed-target compiler" + }, + "paid": { + "1": 41214, + "2": 8262, + "3": 8874, + "4": 1656, + "5": 3024, + "6": 324, + "7": 252, + "16": 416, + "24": 416, + "32": 416, + "40": 416, + "48": 416, + "56": 416, + "64": 416, + "72": 208 + }, + "targets": { + "1": 36, + "2": 90, + "4": 1602, + "5": 198, + "7": 90, + "8": 288, + "9": 7416, + "17": 416, + "25": 416, + "33": 416, + "41": 416, + "49": 416, + "57": 416, + "65": 416, + "73": 208, + "145": 208 + } +} diff --git a/research/selected-invoice-bit-cap-thresholds/README.md b/research/selected-invoice-bit-cap-thresholds/README.md new file mode 100644 index 0000000000..3f8284945f --- /dev/null +++ b/research/selected-invoice-bit-cap-thresholds/README.md @@ -0,0 +1,102 @@ +# Local thresholds for the selected complex invoice to reach the BIT saving + +**Finite exact certificate on an accounting relaxation. No new κ.** This +result is produced by Nick Petalas. The selected frontier is unchanged. + +The selected #5599 complex supplier binds at `U = 0.0031004563072…`. The +admitted BIT saving is `17/5000`. This package fixes, exactly, how much the +local word of the selected P104 invoice must change before the complex bill +passes at `C = 17/5000`. Every other paid job and target stays fixed. It also +bounds what free local helper splitting can do. + +## Result + +The invoice is the authenticated output of `scripts/export_selected_invoice.py` +at base `19fdb086e`. The packaged `INVOICE.json` is its stdout byte for byte, +and its SHA-256 is the exporter's own `invoice_sha256`. The verifier checks +that every local paid job and local helper target appears exactly 18 times, +once per FULL. Paid work is `18·local + 1560 query + idle`, and targets are +`18·helpers + main`. + +The bill passes at `C` when `Σ T_r r^(1-C) > Σ P_r r^(1-C)`. At `C = 17/5000` +the selected invoice fails by **72.892623830207**, which is +**4.049590212789 per FULL**. + +| Local change per FULL, all else fixed | Passes at 17/5000? | +|---|---| +| delete one paid job of rank 1, 2, 3 or 4 | no; rank 4 gives 3.98 < 4.05 | +| delete one paid job of rank 5, 6 or 7 | yes | +| fewest deletions using only rank ≤ 1 / ≤ 2 / ≤ 3 / ≤ 4 | 5 / 3 / 2 / 2 | +| free full refinement of rank-9 helper targets into rank-1 targets | needs 61 of the 412 | +| free balanced split of rank-9 helpers into 4+5 | needs 194 of the 412 | +| refine every local helper target into rank-1 targets | passes; first crossing in [0.0094772838495, 0.0094772838496] | +| the same, at `C = 1/100` | **fails** | + +For a helper target of rank `r`, every partition into positive ranks has +`Σ p^(1-C) ≤ r` when `0 ≤ C < 1`, with equality for `r` parts of rank one. +So full refinement maximizes the target moment at every `C`. Since that +maximum fails at `C = 1/100`, **no split of local helper targets alone, with +paid work fixed, lets the selected invoice pass at 1/100.** The split counts +are minimal for the same reason. A rank-9 helper gives the largest gain, and +the greedy count is optimal. + +For comparison, #5599 refines thirteen helpers. theon199's #5702 shows that +fifteen fully refined H9 sources fund one added H1 per FULL. Reaching the BIT +saving needs about four times that, which is 61. + +## Claim scope + +This is an optimistic accounting relaxation of the complete signed moment +used by the selected invoice. A deletion or split here is free: no restoration, +native alignment, precision, compiler, stock or outer cost is charged, and no +physical word is supplied. A passing row keeps a route open. It does not make +a supplier. Once complex passes at `17/5000`, the admitted BIT saving binds; +this package does not prove the outer κ. Only the sign at each stated `C` and +the stated root bracket are certified. Uniqueness of the refined crossing is +not claimed beyond the separate failure at `1/100`. + +Every `r^(1-C)` uses Python's correctly rounded decimal `ln` and `exp` at 80 +digits. The total rounding error is far below `1e-50`, and every reported sign +clears `1e-30`. A float evaluation corroborates the deficit. The boundary rows, +including rank 4 versus 5, 4 versus 5 rank-one deletions, 60 versus 61 and +193 versus 194 H9 splits, and the `1/100` failure, are rerun on the actual +changed invoice rather than inferred from the table. + +## Reproduce + +From the repository root with CPython 3.12 and the standard library: + +```sh +python3.12 -I -B -W error research/selected-invoice-bit-cap-thresholds/verify.py +python3.12 -I -O -B -W error research/selected-invoice-bit-cap-thresholds/verify.py +python3.12 -B scripts/research_package.py --package research/selected-invoice-bit-cap-thresholds +python3.12 -B scripts/export_selected_invoice.py | shasum -a 256 +``` + +Each verifier run takes about 0.2 s and prints +`PASS_SELECTED_INVOICE_BIT_CAP_THRESHOLDS`. The last command reproduces the +invoice hash in `INPUT.json` from a full checkout. + +## Open next questions + +1. Which physical window of the selected local word can delete one paid job of + rank 5, 6 or 7, or two of rank 3 or 4, while keeping every target and + restoration? Under this accounting, any one of them lets complex pass at the + admitted BIT saving. The first step is to list the 200 local paid jobs of + rank at least five and their producers and consumers. Closed rewrites of + older words do not transfer automatically. +2. Splitting helper targets alone stops below `1/100`. Which changes to the + paid side or to the main targets, priced with this same moment, would let + the complex side pass at `1/100`? Any target above `.0034` also needs a BIT + improvement. + +## Credit and sources + +The selected P104 word is by Pierre-Loic Doulcet (hexapode), with Ali Romman's +complete caller and helper accounting, Cinna Davis's controller, Jacob Alan +Sussman's productive recursion and zxv's invoice interface. The invoice exporter +is Ali Romman's. theon199's `helper-refinement-budget-s29` (#5702) and +Clear1nsight's #5614 price related helper refinements, and the merged +`productive-lever-reprice` package priced a similar BIT-level gap on the older +#4470 invoice. They are cited, not re-checked. Pins are in +[SOURCES.json](SOURCES.json). Apache-2.0. diff --git a/research/selected-invoice-bit-cap-thresholds/SOURCES.json b/research/selected-invoice-bit-cap-thresholds/SOURCES.json new file mode 100644 index 0000000000..8b654ebba8 --- /dev/null +++ b/research/selected-invoice-bit-cap-thresholds/SOURCES.json @@ -0,0 +1,48 @@ +{ + "schema_version": 1, + "base_commit": "19fdb086ea96af9a9f87936a2b888e10af4ed810", + "files": [ + { + "path": "certificates/selected-result.json", + "usage": "provenance", + "git_blob": "581f8d87008354eb5b869f7ed9de1317ad837ce8", + "sha256": "2a0220e866417774606e0f991e41b9c1d26b1f43b97857238cf478dbc7d330b5" + }, + { + "path": "docs/research/agent-task-catalog.json", + "usage": "provenance", + "git_blob": "3404fbdd5e7529a0674eef26114b5071e4586cec", + "sha256": "ead6cdc9d0af6d58e8a49744d8ec8c7c15e13d2ba93c276c434bcf9b51b93a81" + }, + { + "path": "scripts/export_selected_invoice.py", + "usage": "provenance", + "git_blob": "00224b1bc549b0bab3f87d62cf739e907f04bfe3", + "sha256": "a76767b8d02efa722a61ce3461e530246fd0d6785c376d6e58893b452f966013" + }, + { + "path": "research/p104-helper-subspace-splits/RESULT.json", + "usage": "provenance", + "git_blob": "35f75c8555193c6e845cd52cc562ca23fd5924cb", + "sha256": "1d92e587915052110dfb3aca8890df5afdaf496164efa5a4a52e69ceeb3c70f3" + }, + { + "path": "research/p104-productive-controller/CONTROLLER.json", + "usage": "provenance", + "git_blob": "cc539db709cf7a6c42872c4380902736ad453af3", + "sha256": "a84f6bbd547379597464e56c420cc665f96bc43a9a1351eed4b7cd0fce3cc4b9" + }, + { + "path": "research/helper-refinement-budget-s29/README.md", + "usage": "provenance", + "git_blob": "e7b173fb96da2f45fa49ae49979486611cb13065", + "sha256": "87b0376c0156d1e87ae8a6e048b94806cbf9e718207fcd6de5798b720e639dd7" + }, + { + "path": "research/productive-lever-reprice/README.md", + "usage": "provenance", + "git_blob": "4cb841dfb4399edcbf1394b918d0d038257b0b89", + "sha256": "57d2e2252eaf8844b7946f54aea5ecd386855d3220723acb350bfd34b2ab51d6" + } + ] +} diff --git a/research/selected-invoice-bit-cap-thresholds/TASK.json b/research/selected-invoice-bit-cap-thresholds/TASK.json new file mode 100644 index 0000000000..6ff92caf25 --- /dev/null +++ b/research/selected-invoice-bit-cap-thresholds/TASK.json @@ -0,0 +1,129 @@ +{ + "schema_version": 1, + "task_id": "p104-side-correction", + "priority_revision": 8, + "base_commit": "19fdb086ea96af9a9f87936a2b888e10af4ed810", + "original_card": { + "id": "p104-side-correction", + "question": "Can joint helper bases and a legal causal split improve the complete P104 productive/paid invoice?", + "starting_points": [ + "docs/research/current-priorities.md", + "docs/research/research-family-status.md", + "certificates/selected-result.json", + "docs/research/pr-intake-evidence/pr5599-completion/PROOF-REVIEW.md", + "research/p104-helper-subspace-splits/README.md", + "research/dyadic-helper-channel-capacity/README.md" + ], + "methods": [ + "Construct and independently check one source-bound instance of the stated first experiment.", + "Seek an exact counterexample or target-specific complete-budget obstruction to that same proposed change." + ], + "acceptance_gate": "An exact arbitrary-input identity, source/target frame availability and restoration at the chosen cut, plus the complete channel+correction+idle/hosting bill or an explicit favorable bound. The native channel alone is not a supplier. A scoped local result may be retained without a complete supplier. Expanding it into further construction rounds requires the family-level budget and obligation gate in research-family-status.md; an optimistic passing relaxation alone is not acceptance.", + "first_step": { + "command": [ + "python3", + "-B", + "scripts/research_selected_baseline.py" + ], + "expected": "PASS_RESEARCH_BASELINE_BINDINGS_ONLY", + "inspect": "Read revision 8, the selected review and live exact-source handoffs. Then follow this card's bounded first_experiment.", + "scope": "Source-bound orientation only, not a supplier replay or theorem proof." + }, + "first_experiment": "Start with the selected #5599 emitted word and review pending #5718 distinct input/output bases plus #5717/#5719 coverage before claiming work. Pick one uncovered source word, helper group and cut region. Prove the arbitrary-input relation and legal entry/exit corrections, then compare full target and paid profiles. Reject if completion, owned lifetimes or consumer costs repay the gain. A static pairing rank alone is not a physical split.", + "bottleneck_link": "Judge the actual current supplier contract and complete signed target/paid bill; frozen-profile ceilings require an applicability proof.", + "allowed_variations": [ + "One exact source head, helper/cut region or quantified proposition and changed hypothesis; check live handoffs first. Different seeds are not different scopes." + ], + "scope_change_triggers": [ + "Changing source head, helper/cut domain, operation alphabet or caller boundary without recording the new scope.", + "Treating an archived proposal or local numerical pass as complete supplier admission." + ], + "overlap_terms": [ + "P104", + "helper basis", + "helper split", + "5718", + "dyadic capacity" + ], + "existing_checks": [ + { + "scope": "PR #4133: literal-slot defect", + "evidence": "research/p104-literal-slot-defect/README.md", + "remaining": "Independently validate the stated scope or change its producer/consumer premise and pay the complete boundary.", + "status": "author-checked", + "source_commit": "88666f1dee93fbd85b31fd5d6f91a219e111b5f4", + "selected_record_sha256": "bb2eaa58647b353f88d0aec2eafb9d30df1be53589231b23e12ceef3e4bad129" + }, + { + "scope": "PR #4136: uniform commutation gap", + "evidence": "research/p104-uniform-commutation-gap/README.md", + "remaining": "Independently validate the stated scope or change its producer/consumer premise and pay the complete boundary.", + "status": "author-checked", + "source_commit": "281ce601a8be9db470de630759179c23e1dfaa88", + "selected_record_sha256": "bb2eaa58647b353f88d0aec2eafb9d30df1be53589231b23e12ceef3e4bad129" + }, + { + "scope": "PR #4140: uniform encoding gap", + "evidence": "research/p104-uniform-encoding-gap/README.md", + "remaining": "Independently validate the stated scope or change its producer/consumer premise and pay the complete boundary.", + "status": "author-checked", + "source_commit": "de25c6525aa866962309df5d107b32d55e6e5628", + "selected_record_sha256": "bb2eaa58647b353f88d0aec2eafb9d30df1be53589231b23e12ceef3e4bad129" + }, + { + "scope": "PR #4153: source-chart shortcut exhausts its optimistic allowance", + "evidence": "research/p104-source-chart-shortcut/README.md", + "remaining": "Independently validate the stated scope or change its producer/consumer premise and pay the complete boundary.", + "status": "author-checked", + "source_commit": "9123241fea53df77e51ffe30d9aca1625d4bf3a8", + "selected_record_sha256": "bb2eaa58647b353f88d0aec2eafb9d30df1be53589231b23e12ceef3e4bad129" + }, + { + "scope": "PR #4154: fiber-tag seam mismatch", + "evidence": "research/p104-fiber-tag-seam/README.md", + "remaining": "Independently validate the stated scope or change its producer/consumer premise and pay the complete boundary.", + "status": "author-checked", + "source_commit": "4ffcdaee5d6255a9cea1fe53a5424435068089d0", + "selected_record_sha256": "bb2eaa58647b353f88d0aec2eafb9d30df1be53589231b23e12ceef3e4bad129" + }, + { + "scope": "Selected PR5599: complete helper-subspace construction and independent caller replay; five framework assumptions remain.", + "evidence": "docs/research/pr-intake-evidence/pr5599-completion/PROOF-REVIEW.md", + "remaining": "The next experiment must identify uncovered source-specific work. Successor archive intake does not transfer this admission.", + "status": "reviewed", + "source_commit": "09dd0965711ca7eeb169057a420abab1c9052137", + "selected_record_sha256": "2a0220e866417774606e0f991e41b9c1d26b1f43b97857238cf478dbc7d330b5" + } + ] + }, + "scope_status": "changed", + "actual_scope": "Exact accounting thresholds on the authenticated selected #5599 P104 invoice: the per-FULL deficit at C=17/5000, the fewest local paid deletions and free local helper splits that pass there, and the raw ceiling of free local helper refinement.", + "scope_change_reason": "The donation assignment asks for original frontier work. Before a helper group or causal cut is built, this prices how much local change the binding complex invoice needs before the admitted BIT saving binds instead.", + "bottleneck_link": "Complex binds at U=0.0031004563; the admitted BIT saving is 17/5000. This fixes the exact local per-FULL gap between them and shows that local helper refinement alone cannot pass at 1/100.", + "budget_minutes": 60, + "stop_rule": "Ship the first exact threshold table with changed-invoice controls; do not search constructions.", + "outcome": "completed", + "evidence": "verify.py authenticates the exported invoice bytes, checks the 18-fold local replication, evaluates every moment with correctly rounded 80-digit decimal ln/exp, and reruns each boundary case on the actual changed invoice.", + "author": "Nick Petalas", + "ai_assistance": "Independent human and formal proof-kernel review are unclaimed.", + "open_questions": [ + { + "question": "Which physical local window can delete one paid rank-5, rank-6 or rank-7 job, or two rank-3/rank-4 jobs, while keeping every target and restoration?", + "why_it_matters": "Under this accounting, any one such deletion per FULL lets complex pass at the admitted BIT saving, after which BIT binds.", + "first_step": "List the 168+18+14 local paid jobs of rank at least five in the selected word and their producers and consumers.", + "blocked_by": "Earlier closed local rewrites of older words do not transfer automatically; no candidate window is checked here." + }, + { + "question": "Can combined helper refinement and paid change raise both suppliers past 1/100?", + "why_it_matters": "Refining every local helper target alone fails at 1/100 with all paid work fixed, so a target near 0.01 needs paid or controller change on the complex side as well as BIT.", + "first_step": "Price the main-target and idle-paid families with the same exact moment at C=1/100.", + "blocked_by": "No changed controller or main-target contract is supplied." + } + ], + "claim_type": "finite exact certificate", + "claim_url": "https://github.com/CrocSwap/integer-mult-bounds/discussions/1166#discussioncomment-19227727", + "question_source": { + "origin": "original", + "note": "Original accounting question on the selected #5599 invoice." + } +} diff --git a/research/selected-invoice-bit-cap-thresholds/VERIFY.json b/research/selected-invoice-bit-cap-thresholds/VERIFY.json new file mode 100644 index 0000000000..b51441d396 --- /dev/null +++ b/research/selected-invoice-bit-cap-thresholds/VERIFY.json @@ -0,0 +1,34 @@ +{ + "schema_version": 1, + "status": "ready", + "python": "3.12", + "requirements": [], + "inputs": [], + "commands": [ + { + "argv": [ + "{python}", + "-I", + "-B", + "-W", + "error", + "{package}/verify.py" + ], + "timeout_seconds": 120, + "checks": "Authenticated selected invoice, 18-fold replication, exact moment thresholds and changed-invoice boundary controls." + }, + { + "argv": [ + "{python}", + "-I", + "-O", + "-B", + "-W", + "error", + "{package}/verify.py" + ], + "timeout_seconds": 120, + "checks": "The same exact arithmetic with assertions disabled." + } + ] +} diff --git a/research/selected-invoice-bit-cap-thresholds/verify.py b/research/selected-invoice-bit-cap-thresholds/verify.py new file mode 100644 index 0000000000..ca507ab8f8 --- /dev/null +++ b/research/selected-invoice-bit-cap-thresholds/verify.py @@ -0,0 +1,219 @@ +"""Exact local thresholds for the selected P104 invoice to pass at C = 17/5000. + +The invoice passes at saving C when its productive target moment exceeds its +paid moment, sum T_r r^(1-C) > sum P_r r^(1-C). Every r^(1-C) is evaluated +with correctly rounded decimal ln/exp at PREC digits; the accumulated error +is far below ERROR_BOUND, and every reported sign clears it. +""" + +import hashlib +import json +import math +import sys +from decimal import Decimal, getcontext +from fractions import Fraction +from pathlib import Path + +PREC = 80 +ERROR_BOUND = Decimal("1e-50") +SIGN_FLOOR = Decimal("1e-30") +BIT_CAP = Fraction(17, 5000) +SELECTED_KAPPA = Fraction(62009, 20000000) +HERE = Path(__file__).resolve().parent +MARKER = "PASS_SELECTED_INVOICE_BIT_CAP_THRESHOLDS" + +getcontext().prec = PREC + + +def dec(q): + return Decimal(q.numerator) / Decimal(q.denominator) + + +def power(rank, c): + if rank == 1: + return Decimal(1) + return (dec(1 - c) * Decimal(rank).ln()).exp() + + +def moment(targets, paid, c): + total = sum((n * power(r, c) for r, n in targets.items()), Decimal(0)) + return total - sum((n * power(r, c) for r, n in paid.items()), Decimal(0)) + + +def certified_sign(value): + if abs(value) <= SIGN_FLOOR: + raise SystemExit(f"FAIL: undecided sign {value}") + return 1 if value > 0 else -1 + + +def int_keys(table): + return {int(r): n for r, n in table.items()} + + +def load(): + meta = json.loads((HERE / "INPUT.json").read_text()) + raw = (HERE / meta["invoice_file"]).read_bytes() + if hashlib.sha256(raw).hexdigest() != meta["invoice_sha256"]: + raise SystemExit("FAIL: invoice bytes differ from the exporter hash") + invoice = json.loads(raw) + parts = {k: int_keys(v) for k, v in meta["components"].items()} + return meta, int_keys(invoice["paid"]), int_keys(invoice["targets"]), parts + + +def check_replication(paid, targets, parts, full): + """Paid = full*local + query + idle; targets = full*helpers + main.""" + want_paid, want_targets = {}, {} + for r, n in parts["local_paid"].items(): + want_paid[r] = want_paid.get(r, 0) + full * n + for name in ("query_paid", "idle_paid"): + for r, n in parts[name].items(): + want_paid[r] = want_paid.get(r, 0) + n + for r, n in parts["local_helpers"].items(): + want_targets[r] = want_targets.get(r, 0) + full * n + for r, n in parts["main_targets"].items(): + want_targets[r] = want_targets.get(r, 0) + n + if want_paid != paid or want_targets != targets: + raise SystemExit("FAIL: invoice is not the declared 18-fold local replication") + + +def bisect_root(targets, paid, lo, hi, width): + if certified_sign(moment(targets, paid, lo)) != 1: + raise SystemExit("FAIL: lower root bracket does not pass") + if certified_sign(moment(targets, paid, hi)) != -1: + raise SystemExit("FAIL: upper root bracket does not fail") + while hi - lo > width: + mid = (lo + hi) / 2 + if certified_sign(moment(targets, paid, mid)) == 1: + lo = mid + else: + hi = mid + return lo, hi + + +def min_deletions(local_paid, max_rank, need): + """Fewest local paid deletions of rank <= max_rank whose per-FULL mass exceeds need.""" + total, count = Decimal(0), 0 + for r in sorted((r for r in local_paid if r <= max_rank), reverse=True): + for _ in range(local_paid[r]): + total += power(r, BIT_CAP) + count += 1 + if total > need + SIGN_FLOOR: + return count, total + return None, total + + +def split_gain(rank, parts): + return sum(power(p, BIT_CAP) for p in parts) - power(rank, BIT_CAP) + + +def min_splits(helpers, need, gain_of): + """Fewest local helper targets split (each once, by gain_of) to exceed need.""" + gains = sorted(((gain_of(r), r) for r, n in helpers.items() for _ in range(n)), reverse=True) + total = Decimal(0) + for count, (gain, _) in enumerate(gains, start=1): + total += gain + if total > need + SIGN_FLOOR: + return count, total + return None, total + + +def main(): + meta, paid, targets, parts = load() + full = meta["full_calls"] + check_replication(paid, targets, parts, full) + if meta["selected_kappa"] != f"{SELECTED_KAPPA.numerator}/{SELECTED_KAPPA.denominator}": + raise SystemExit("FAIL: selected kappa changed") + + root = bisect_root(targets, paid, Fraction(31, 10000), Fraction(311, 100000), Fraction(1, 10**13)) + deficit = -moment(targets, paid, BIT_CAP) + if certified_sign(deficit) != 1: + raise SystemExit("FAIL: selected invoice already passes at 17/5000") + need = deficit / full + + single = {r: certified_sign(power(r, BIT_CAP) - need) == 1 for r in range(1, 8)} + deletions = {} + for s in range(1, 8): + deletions[s], _ = min_deletions(parts["local_paid"], s, need) + + refine = {r: split_gain(r, [1] * r) for r in parts["local_helpers"]} + binary = {r: split_gain(r, [r // 2, r - r // 2]) if r > 1 else Decimal(0) for r in parts["local_helpers"]} + full_count, full_mass = min_splits(parts["local_helpers"], need, lambda r: refine[r]) + bin_count, bin_mass = min_splits(parts["local_helpers"], need, lambda r: binary[r]) + + refined_targets = dict(parts["main_targets"]) + rank_mass = sum(r * n for r, n in parts["local_helpers"].items()) + refined_targets[1] = refined_targets.get(1, 0) + full * rank_mass + ceiling = bisect_root(refined_targets, paid, Fraction(1, 1000), Fraction(1, 10), Fraction(1, 10**13)) + + controls = run_controls(paid, targets, parts, full, need) + controls["all_helpers_refined_at_1_100"] = certified_sign(moment(refined_targets, paid, Fraction(1, 100))) + if controls["all_helpers_refined_at_1_100"] != -1: + raise SystemExit("FAIL: refined invoice passes at 1/100") + controls["h9_refinements"] = h9_split_control(paid, targets, full, full_count, [1] * 9) + controls["h9_binary_splits"] = h9_split_control(paid, targets, full, bin_count, [4, 5]) + result = { + "marker": MARKER, + "selected_root_bracket": [str(x) for x in root], + "selected_root_decimal": [f"{float(x):.13f}" for x in root], + "deficit_at_17_5000": f"{deficit:.12f}", + "deficit_per_full": f"{need:.12f}", + "full_calls": full, + "single_local_paid_deletion_passes": single, + "min_local_paid_deletions_with_rank_at_most": deletions, + "full_refinement_gain_per_helper": {r: f"{g:.12f}" for r, g in sorted(refine.items())}, + "balanced_binary_gain_per_helper": {r: f"{g:.12f}" for r, g in sorted(binary.items())}, + "min_full_helper_refinements": full_count, + "min_balanced_binary_splits": bin_count, + "all_helpers_refined_root_bracket": [f"{float(x):.13f}" for x in ceiling], + "controls": controls, + "float_corroboration": float_corroboration(paid, targets, need), + } + print(json.dumps(result, indent=1, sort_keys=True)) + print(MARKER) + + +def float_corroboration(paid, targets, need): + a = 1 - float(BIT_CAP) + m = sum(n * r**a for r, n in targets.items()) - sum(n * r**a for r, n in paid.items()) + if not math.isclose(-m / 18, float(need), rel_tol=1e-9): + raise SystemExit("FAIL: float and decimal deficits disagree") + return f"{-m:.9f}" + + +def h9_split_control(paid, targets, full, count, pieces): + """Split count local H9 targets into pieces; count passes and count-1 fails.""" + signs = [] + for k in (count - 1, count): + t = dict(targets) + t[9] -= full * k + for piece in pieces: + t[piece] = t.get(piece, 0) + full * k + signs.append(certified_sign(moment(t, paid, BIT_CAP))) + if signs != [-1, 1]: + raise SystemExit(f"FAIL: H9 split control {pieces} {signs}") + return {str(count - 1): signs[0], str(count): signs[1]} + + +def run_controls(paid, targets, parts, full, need): + """Rerun the actual changed invoices for the boundary cases.""" + out = {} + for rank, expect in ((4, -1), (5, 1)): + p = dict(paid) + p[rank] -= full + out[f"delete_one_local_rank_{rank}"] = certified_sign(moment(targets, p, BIT_CAP)) + if out[f"delete_one_local_rank_{rank}"] != expect: + raise SystemExit(f"FAIL: control rank {rank}") + for k, expect in ((4, -1), (5, 1)): + p = dict(paid) + p[1] -= full * k + out[f"delete_{k}_local_rank_1"] = certified_sign(moment(targets, p, BIT_CAP)) + if out[f"delete_{k}_local_rank_1"] != expect: + raise SystemExit(f"FAIL: control {k} rank-one deletions") + out["selected_passes_at_selected_kappa"] = certified_sign(moment(targets, paid, SELECTED_KAPPA)) + if out["selected_passes_at_selected_kappa"] != 1: + raise SystemExit("FAIL: selected invoice does not pass at selected kappa") + return out + + +if __name__ == "__main__": + sys.exit(main())