From 08850225adfe88ef13458ed6d8499796ac5cf007 Mon Sep 17 00:00:00 2001 From: Nick Petalas Date: Tue, 3 Nov 2026 09:04:16 +0000 Subject: [PATCH] feat(research): prove a sharp adaptive reserve ratio --- research/sharp-adaptive-reserve/ORIGIN.json | 10 ++ research/sharp-adaptive-reserve/PROOF.md | 125 ++++++++++++++++ research/sharp-adaptive-reserve/README.md | 54 +++++++ research/sharp-adaptive-reserve/SOURCES.json | 18 +++ research/sharp-adaptive-reserve/TASK.json | 75 ++++++++++ research/sharp-adaptive-reserve/VERIFY.json | 32 +++++ .../inputs/example6472.json | 7 + research/sharp-adaptive-reserve/reserve.py | 70 +++++++++ research/sharp-adaptive-reserve/verify.py | 133 ++++++++++++++++++ 9 files changed, 524 insertions(+) create mode 100644 research/sharp-adaptive-reserve/ORIGIN.json create mode 100644 research/sharp-adaptive-reserve/PROOF.md create mode 100644 research/sharp-adaptive-reserve/README.md create mode 100644 research/sharp-adaptive-reserve/SOURCES.json create mode 100644 research/sharp-adaptive-reserve/TASK.json create mode 100644 research/sharp-adaptive-reserve/VERIFY.json create mode 100644 research/sharp-adaptive-reserve/inputs/example6472.json create mode 100644 research/sharp-adaptive-reserve/reserve.py create mode 100644 research/sharp-adaptive-reserve/verify.py diff --git a/research/sharp-adaptive-reserve/ORIGIN.json b/research/sharp-adaptive-reserve/ORIGIN.json new file mode 100644 index 0000000000..34c5c6818a --- /dev/null +++ b/research/sharp-adaptive-reserve/ORIGIN.json @@ -0,0 +1,10 @@ +{ + "source_pr": "https://github.com/CrocSwap/integer-mult-bounds/pull/6472", + "author": "Ali Romman / aliromman", + "repository": "aliromman/integer-mult-bounds", + "commit": "6621e59b773b179a0340627eadbe295eb5254d07", + "path": "research/adaptive-row-bill/example.json", + "retained_path": "inputs/example6472.json", + "sha256": "8819bb327b318bed314cc6cd12781e4ad148a18a4cf77fa749167bc7b1c3c3b4", + "usage": "The four allowed rows only. No predecessor executable or scientific replay is imported." +} diff --git a/research/sharp-adaptive-reserve/PROOF.md b/research/sharp-adaptive-reserve/PROOF.md new file mode 100644 index 0000000000..a9e0a2ada8 --- /dev/null +++ b/research/sharp-adaptive-reserve/PROOF.md @@ -0,0 +1,125 @@ +# Sharp common reserve for the PR6472 example + +This is a scoped mathematical proof, produced by Nick Petalas. +It answers the common-ratio optimization question posed by Ali Romman in +[PR6472](https://github.com/CrocSwap/integer-mult-bounds/pull/6472), exact head +`6621e59b773b179a0340627eadbe295eb5254d07`. That package supplies the menu, +the adaptive row contract, the exact total `u=(5,3)` and its reserve ratio `4/5`. +Those are credited inputs, not new results of this package. + +## Contract and claim + +The two type menus are + +```text +R_1 = {(0,6/5), (1/5,1)} +R_2 = {(2/5,0), (0,1/4)}. +T(x)_i = max_{r in R_i} r x. +``` + +For a positive real weight `w=(x,y)`, let `q(w)` be the smallest number such +that `r w <= q(w) w_i` for every row of type `i`. All four rows are retained. +The new exact optimum is + +```text +min_{w>0} q(w) = lambda = (1+sqrt(41))/10. +``` + +Its minimizing weights have the unique ratio +`x/y=(1+sqrt(41))/4`. Consequently no positive rational weight attains the +minimum. A rational certificate `w=(37,20)` gives `q=137/185 < 4/5`. + +For the finite-depth adaptive unit-toll totals +`x_0=0`, `x_{d+1}=1+T(x_d)`, this certificate gives + +```text +0 <= u-x_d <= (137/185)^d (111/20,3), +max_i (u_i-x_{d,i})/u_i <= (111/100)(137/185)^d. +``` + +These are componentwise inequalities. They imply the relative tolerance +`2^-64` at depth 149. The cited `4/5` reserve bound first implies that +tolerance at depth 199. These are exact cutoffs for the two bounds, not a +claim that the actual nonlinear recurrence first meets tolerance at 149. + +## Lower bound for every positive real weight + +Put `t=x/y>0`. Directly from the four rows, + +```text +q(w) = max(6/(5t), 1/5+1/t, 2t/5, 1/4). +``` + +In particular `q>1/5`, `1/t <= q-1/5` and `t <= 5q/2`. +Multiplying the last two positive inequalities gives +`1 <= (q-1/5)(5q/2)`, hence + +```text +5q^2-q-2 >= 0. +``` + +The polynomial has exactly one positive root, `lambda`, so `q>=lambda`. +This argument quantifies over every positive real weight; the finite +rational-weight checks do not supply this quantifier. + +## Attainment and uniqueness + +Choose `t=(1+sqrt(41))/4=5 lambda/2`. The equation +`5 lambda^2-lambda-2=0` gives +`1/5+1/t=lambda=2t/5`. Also `t>1`, so +`6/(5t) <= 1/5+1/t`; and `1/4=u`. For arbitrary vectors `a,b`, the elementary maximum inequality +and nonnegative rows give + +```text +|T(a)_i-T(b)_i| <= max_{r in R_i} r |a-b|. +``` + +The cited total satisfies `u=1+T(u)`. Starting with `0<=u-x_0=u<=v`, the +displayed inequality proves inductively +`0<=u-x_d<=q^d v` for every integer `d>=0`. Division by `u` gives the +relative bound, since `max_i v_i/u_i=111/100`. + +The new componentwise bound is smaller than the cited bound for every `d>=2`. +It suffices to check +`(111/100)(137/148)^2<1`; larger `d` only decrease this expression. +The exact 64-bit cutoff assertions reduce to four rational comparisons: + +```text +(111/100)(137/185)^149 <= 2^-64 < (111/100)(137/185)^148, +(4/5)^199 <= 2^-64 < (4/5)^198. +``` + +The verifier performs these comparisons with integer-backed fractions. + +## Credit and scope + +Weighted maximum norms, nonnegative matrix theory, and positive-vector +contraction arguments are classical. The selected two coupled rows also +give the classical Perron-root interpretation. No general theorem priority +is claimed. The new contribution is the sharp source-specific reserve +optimization, its rational certificate and the resulting cutoff comparison. +PR6472 retains credit for the row menu, total-bill interface and its proofs. + +This synthetic example does not identify a physical supplier menu. Every +actual caller would still need complete child, adapter and restoration +charges, legal independent row choices, native realization, compiler, +storage, precision/tape and outer applicability. All five selected framework +assumptions remain. There is no new kappa or selected-frontier change. diff --git a/research/sharp-adaptive-reserve/README.md b/research/sharp-adaptive-reserve/README.md new file mode 100644 index 0000000000..80cae873e0 --- /dev/null +++ b/research/sharp-adaptive-reserve/README.md @@ -0,0 +1,54 @@ +# Sharp reserve for an adaptive two-type bill + +Scoped proof with exact finite corroboration, produced by Nick Petalas. + +For the exact synthetic row menu of Ali Romman's [PR6472](https://github.com/CrocSwap/integer-mult-bounds/pull/6472), the optimal common positive-weight contraction ratio is + +```text +lambda = (1+sqrt(41))/10. +``` + +The minimizing weight ratio is uniquely `(1+sqrt(41))/4`, so no positive rational weights attain it. The explicit rational weights `(37,20)` certify ratio `137/185`. Every allowed source row is retained. This answers the source's open common-ratio optimization question; it does not audit or replay the existing total-bill result. + +Using the cited exact total `u=(5,3)`, the new all-depth tail bound is + +```text +0 <= u-x_d <= (137/185)^d (111/20,3). +``` + +It certifies relative error at most `2^-64` at depth 149. The source's `4/5` bound first certifies it at depth 199. These are cutoffs of the two certified bounds; neither is asserted to be the actual first successful depth of the recurrence. The [proof](PROOF.md) establishes the optimum over every positive real weight and the tail inequality for every depth. + +## Reproduce + +From the repository root, use CPython 3.12 and the standard library: + +```sh +/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12 -W error -B research/sharp-adaptive-reserve/verify.py +/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12 -W error -O -B research/sharp-adaptive-reserve/verify.py +/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12 -B scripts/research_package.py --package research/sharp-adaptive-reserve +/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12 -B scripts/check_research_commit.py --package research/sharp-adaptive-reserve --check-source-history +``` + +Another CPython 3.12 interpreter can replace that path. Expected markers are `PASS_SHARP_ADAPTIVE_RESERVE`, `PASS_REGISTERED_RESEARCH_PACKAGE`, and `PASS_RESEARCH_COMMIT_BYTES`. The direct verifier prints a generated receipt bound to all nine package files. An optional `--receipt /absolute/scratch/path.json` writes it outside the package. No receipt is hand-written or required as an input. + +The verifier compares literal source-row products with the reduced ratio formula for all 4,096 integer weight pairs in `1..64` squared. It checks 257 exact nonlinear finite-depth prefixes against a separate two-by-two matrix recurrence, the tail inequalities and minimality of both stated cutoffs. False reserve, invalid precision and source-corruption controls must reject. These finite checks corroborate the written proof; they do not establish its universal quantifiers. + +## Sources and scope + +[ORIGIN.json](ORIGIN.json) identifies the exact PR6472 commit and source file. Its four-row example is retained byte for byte in [inputs/example6472.json](inputs/example6472.json), authenticated before parsing. The package imports no predecessor executable and does not require the pending source commit in local Git history. [SOURCES.json](SOURCES.json) binds the canonical base and historical task catalogue. + +The chosen card is `complex-rank-shape-decoder`, explicitly changed to this analytical side question. Common reserves can control compiler tail cutoffs, but this example is synthetic. The metadata binding baseline passed for selected PR6030. Live handoffs, open and merged PRs, source/formula searches on main, and the bounded overlap cache were checked. Unpublished work, arbitrary historical diffs and uninspected replies remain coverage limits. + +No physical supplier, native word, compiler admission, complete cost invoice, precision/stock/tape result, new kappa or selected-frontier change is supplied. All five selected framework assumptions remain. Selected cold replay, Lean and Docker were not run. Independent human and formal proof-kernel review are unclaimed. + +## Open next questions + +Can a complete source-compatible supplier row menu use optimized reserves to lower a real compiler cutoff? First extract a named caller's complete row menu and required tail tolerance, including all adapters, restoration and extra fees. Actual row legality, native realization, compiler applicability, storage, precision/tape and outer costs remain blockers. Structured fields are in [TASK.json](TASK.json). + +## Attribution + +The new reserve optimization and proof were produced by Nick Petalas. Ali Romman / PR6472 supplies the exact menu, adaptive contract, total `u=(5,3)`, original `4/5` reserve and the explicit next question. Classical weighted norms, nonnegative matrix and Perron theory retain credit; no general literature-priority claim is made. The source package retains its full predecessor attribution, including its fixed-matrix, observed-forcing and synchronized-switching interfaces. None is recertified here. Apache-2.0. + +## Implementation limits + +The retained input is fixed, has two types and four rows, and is hash-checked before parsing. All loops have explicit finite bounds. Cutoff requests accept 1..128 precision bits, search at most 1,025 depths and reject exhaustion. Verification checks use explicit exceptions, so optimized Python preserves every check. Functions remain below 60 physical lines. Python's managed fractions, JSON and hashing allocate dynamically, a rule-3 deviation bounded here by the fixed input, 4,096 weight pairs, 257 prefix depths and at most 1,025 cutoff iterations. This is a finite exact-arithmetic check, not a fixed-memory embedded implementation. The normal and optimized warning-strict registered commands are the diagnostics; no separate Python static analyzer is configured for this package. A future configurable or native implementation must revisit these resource bounds. diff --git a/research/sharp-adaptive-reserve/SOURCES.json b/research/sharp-adaptive-reserve/SOURCES.json new file mode 100644 index 0000000000..594089b9c7 --- /dev/null +++ b/research/sharp-adaptive-reserve/SOURCES.json @@ -0,0 +1,18 @@ +{ + "schema_version": 1, + "base_commit": "7c49fe32c55de02c2c873655c804b16e4c3fef0a", + "files": [ + { + "path": "certificates/selected-result.json", + "usage": "provenance", + "git_blob": "d59b5035e7b4cbaa9d688a1d32dd0d6eb79c466a", + "sha256": "9b8d0eea95b3bf0dfcb7938a732a6439b87a2685dec2a5ab9e525b3b34debbfa" + }, + { + "path": "docs/research/agent-task-catalog.json", + "usage": "provenance", + "git_blob": "3404fbdd5e7529a0674eef26114b5071e4586cec", + "sha256": "ead6cdc9d0af6d58e8a49744d8ec8c7c15e13d2ba93c276c434bcf9b51b93a81" + } + ] +} diff --git a/research/sharp-adaptive-reserve/TASK.json b/research/sharp-adaptive-reserve/TASK.json new file mode 100644 index 0000000000..7336d3d925 --- /dev/null +++ b/research/sharp-adaptive-reserve/TASK.json @@ -0,0 +1,75 @@ +{ + "schema_version": 1, + "task_id": "complex-rank-shape-decoder", + "priority_revision": 8, + "base_commit": "7c49fe32c55de02c2c873655c804b16e4c3fef0a", + "original_card": { + "id": "complex-rank-shape-decoder", + "question": "Can a legal decoder or coframe change improve the full signed moment, including changed helper targets?", + "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", + "docs/research/recursive-invoice-preflight.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": "A source-bound arbitrary-input identity and legal producer/consumer boundary with the complete paid and productive target invoice, including restoration, ownership, native alignment and extra charges. Price under the actual current model; historical ceiling.py assumptions must be established before use. A favorable optimistic relaxation keeps a route open but is not a completed supplier. A scoped local result remains useful; expansion requires the family-level budget gate.", + "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": "Price one complete changed itinerary with both paid and productive histograms. Check #5693/#5698 for overlap and their exact hypotheses before another coframe search. Use the signed invoice preflight where its boundary contract agrees; an inconclusive concave comparison is not a power crossing. Stop if an optimistic complete budget fails at the chosen target or native delivery remains unspecified.", + "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": [ + "coframe", + "signed moment", + "5693", + "5698" + ], + "existing_checks": [ + { + "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": "Optimize the common positive-weight contraction ratio for the exact two-type example of Ali Romman PR6472, and improve its certified finite-depth relative tail cutoff.", + "scope_change_reason": "This is a scoped analytical side result answering PR6472's explicit reserve-ratio open question, rather than a new physical decoder or productive-target itinerary.", + "bottleneck_link": "Common contraction reserves control finite compiler tails. This synthetic row menu is not a selected physical supplier, so the result supplies no native, compiler or outer admission.", + "budget_minutes": 60, + "stop_rule": "Stop after the first proved exact reserve improvement; package its proof and finite corroboration without extending to other menus.", + "outcome": "completed", + "evidence": "PROOF.md; reserve.py; verify.py; generated hash-bound stdout receipt.", + "author": "Nick Petalas", + "ai_assistance": "Independent human and formal proof-kernel review are unclaimed.", + "open_questions": [ + { + "question": "Can a complete source-compatible supplier row menu use an optimized reserve to lower a real compiler tail cutoff?", + "why_it_matters": "The displayed 64-bit cutoff improvement is synthetic until a real caller supplies every row and extra charge.", + "first_step": "Extract one named caller's complete row menu and its required tail tolerance; include adapters, restoration and every additional fee before optimizing weights.", + "blocked_by": "No physical supplier menu, compiler applicability, native realization, storage, precision/tape or outer bill is bound in this package." + } + ] +} diff --git a/research/sharp-adaptive-reserve/VERIFY.json b/research/sharp-adaptive-reserve/VERIFY.json new file mode 100644 index 0000000000..8fb2143a9b --- /dev/null +++ b/research/sharp-adaptive-reserve/VERIFY.json @@ -0,0 +1,32 @@ +{ + "schema_version": 1, + "status": "ready", + "python": "3.12", + "requirements": [], + "inputs": [], + "commands": [ + { + "argv": [ + "{python}", + "-W", + "error", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 120, + "checks": "Exact sharp-ratio polynomial, all four row inequalities, rational reserve, literal finite-depth tails, exact cutoff minimality, invalid certificates and source corruption." + }, + { + "argv": [ + "{python}", + "-W", + "error", + "-O", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 120, + "checks": "Identical complete coverage with Python assertions disabled." + } + ] +} diff --git a/research/sharp-adaptive-reserve/inputs/example6472.json b/research/sharp-adaptive-reserve/inputs/example6472.json new file mode 100644 index 0000000000..79f1b83644 --- /dev/null +++ b/research/sharp-adaptive-reserve/inputs/example6472.json @@ -0,0 +1,7 @@ +{ + "schema": "adaptive-row-bill/v1", + "rows": [ + [[0, "6/5"], ["1/5", 1]], + [["2/5", 0], [0, "1/4"]] + ] +} diff --git a/research/sharp-adaptive-reserve/reserve.py b/research/sharp-adaptive-reserve/reserve.py new file mode 100644 index 0000000000..e5adf25d0b --- /dev/null +++ b/research/sharp-adaptive-reserve/reserve.py @@ -0,0 +1,70 @@ +"""Exact common reserves for the retained two-type row menu.""" + +from fractions import Fraction +from hashlib import sha256 +import json + +Row = tuple[Fraction, Fraction] +Menu = tuple[tuple[Row, ...], tuple[Row, ...]] +Vector = tuple[Fraction, Fraction] +SOURCE_SHA256 = "8819bb327b318bed314cc6cd12781e4ad148a18a4cf77fa749167bc7b1c3c3b4" + + +def require(condition: bool, message: str) -> None: + if not condition: + raise ValueError(message) + + +def parse_menu(data: bytes) -> Menu: + """Authenticate the exact source bytes before parsing their four rows.""" + require(sha256(data).hexdigest() == SOURCE_SHA256, "source hash mismatch") + raw = json.loads(data) + require(raw["schema"] == "adaptive-row-bill/v1", "unexpected schema") + groups = raw["rows"] + require(len(groups) == 2, "expected two types") + parsed = [] + for group in groups: + require(len(group) == 2, "expected two rows per type") + rows = [] + for row in group: + require(len(row) == 2, "expected two coefficients") + a, b = (Fraction(value) for value in row) + require(a >= 0 and b >= 0, "negative row") + rows.append((a, b)) + parsed.append(tuple(rows)) + return parsed[0], parsed[1] + + +def common_ratio(menu: Menu, weight: Vector) -> Fraction: + require(len(weight) == 2 and min(weight) > 0, "positive two-type weight required") + return max( + (row[0] * weight[0] + row[1] * weight[1]) / weight[i] + for i in range(2) + for row in menu[i] + ) + + +def check_certificate(menu: Menu, weight: Vector, ratio: Fraction) -> None: + require(0 <= ratio < 1, "ratio must be in [0,1)") + require(common_ratio(menu, weight) <= ratio, "row exceeds claimed ratio") + + +def next_prefix(menu: Menu, value: Vector) -> Vector: + require(len(value) == 2 and min(value) >= 0, "nonnegative prefix required") + values = tuple( + 1 + max(row[0] * value[0] + row[1] * value[1] for row in group) + for group in menu + ) + return values[0], values[1] + + +def first_cutoff(ratio: Fraction, prefactor: Fraction, bits: int) -> int: + require(0 < ratio < 1 and prefactor >= 1, "invalid tail bound") + require(type(bits) is int and 1 <= bits <= 128, "bits outside 1..128") + threshold = Fraction(1, 2**bits) + tail = prefactor + for depth in range(1025): + if tail <= threshold: + return depth + tail *= ratio + raise ValueError("cutoff exceeds the explicit 1024-depth limit") diff --git a/research/sharp-adaptive-reserve/verify.py b/research/sharp-adaptive-reserve/verify.py new file mode 100644 index 0000000000..e21a906b49 --- /dev/null +++ b/research/sharp-adaptive-reserve/verify.py @@ -0,0 +1,133 @@ +"""Finite corroboration of the new reserve optimization, not a source replay.""" + +import argparse +from fractions import Fraction as F +from hashlib import sha256 +import json +from pathlib import Path + +from reserve import ( + check_certificate, + common_ratio, + first_cutoff, + next_prefix, + parse_menu, + require, +) + +PACKAGE = Path(__file__).resolve().parent +WEIGHT = (F(37), F(20)) +RATIO = F(137, 185) +RESERVE = (F(111, 20), F(3)) +TOTAL = (F(5), F(3)) # Cited PR6472 total, used only as the tail boundary. + + +def polynomial(q: F) -> F: + return 5 * q * q - q - 2 + + +def sharp_ratio_checks(menu) -> dict: + """Rational brackets and all algebraic reductions used in the proof.""" + lower, upper = F(7403124237, 10**10), F(7403124238, 10**10) + require(polynomial(lower) < 0 < polynomial(upper), "wrong root bracket") + require(F(1, 4) < lower < upper < RATIO < F(4, 5), "wrong ratio order") + count = 0 + for x in range(1, 65): + for y in range(1, 65): + q = common_ratio(menu, (F(x), F(y))) + expected = max(F(6 * y, 5 * x), F(1, 5) + F(y, x), + F(2 * x, 5 * y), F(1, 4)) + require(q == expected, "literal row/formula mismatch") + require(polynomial(q) > 0 and q > upper, "sharp lower bound failed") + count += 1 + check_certificate(menu, WEIGHT, RATIO) + require(common_ratio(menu, RESERVE) == RATIO, "reserve scaling changed ratio") + require(min(RESERVE[i] - TOTAL[i] for i in range(2)) >= 0, "boundary too small") + require(F(111, 100) * (RATIO / F(4, 5)) ** 2 < 1, "depth-two comparison failed") + return {"rational_weights": count, "root_bracket": [str(lower), str(upper)]} + + +def prefix_checks(menu) -> dict: + """Literal nonlinear row-max recurrence and an independent matrix recurrence.""" + value, matrix_value = (F(0), F(0)), (F(0), F(0)) + old_cutoff = first_cutoff(F(4, 5), F(1), 64) + cutoff = first_cutoff(RATIO, F(111, 100), 64) + require((old_cutoff, cutoff) == (199, 149), "wrong exact cutoff") + for depth in range(257): + require(value == matrix_value, "literal row choices differ from fixed matrix") + for i in range(2): + error = TOTAL[i] - value[i] + require(0 <= error <= RATIO**depth * RESERVE[i], "new tail bound failed") + value = next_prefix(menu, value) + a, b = matrix_value + matrix_value = (1 + a / 5 + b, 1 + 2 * a / 5) + for q, c, d in ((F(4, 5), F(1), old_cutoff), (RATIO, F(111, 100), cutoff)): + require(c * q**d <= F(1, 2**64) < c * q**(d - 1), "nonminimal cutoff") + return {"prefix_depths": 257, "old_64_bit_cutoff": old_cutoff, + "new_64_bit_cutoff": cutoff} + + +def reject_controls(menu, source: bytes) -> int: + failures = ( + (WEIGHT, F(37, 50)), + (WEIGHT, F(1851, 2500)), + ((F(5), F(3)), RATIO), + ((F(0), F(1)), RATIO), + ((F(-1), F(1)), RATIO), + (WEIGHT, F(1)), + (WEIGHT, F(-1)), + ) + rejected = 0 + for weight, ratio in failures: + try: + check_certificate(menu, weight, ratio) + except ValueError: + rejected += 1 + else: + raise ValueError("false reserve certificate accepted") + for data in (source + b" ", source.replace(b"6/5", b"5/6")): + try: + parse_menu(data) + except ValueError: + rejected += 1 + else: + raise ValueError("source corruption accepted") + for ratio, prefactor, bits in ( + (RATIO, F(1), 0), (RATIO, F(1), 129), (RATIO, F(1), True), + (F(0), F(1), 1), (F(1), F(1), 1), (RATIO, F(1, 2), 1), + (F(9999, 10000), F(1), 128), + ): + try: + first_cutoff(ratio, prefactor, bits) + except ValueError: + rejected += 1 + else: + raise ValueError("invalid or exhausted cutoff request accepted") + return rejected + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--receipt", type=Path, help="write the generated receipt outside the package") + args = parser.parse_args() + if args.receipt is not None: + require(not args.receipt.resolve().is_relative_to(PACKAGE), "receipt must be external") + source = (PACKAGE / "inputs/example6472.json").read_bytes() + menu = parse_menu(source) + result = {"marker": "PASS_SHARP_ADAPTIVE_RESERVE", "claim_type": "scoped proof with finite corroboration", + "optimal_ratio": "(1+sqrt(41))/10", "rational_ratio": str(RATIO), + "weight": [str(x) for x in WEIGHT]} + result.update(sharp_ratio_checks(menu)) + result.update(prefix_checks(menu)) + result["rejection_controls"] = reject_controls(menu, source) + names = ("ORIGIN.json", "PROOF.md", "README.md", "SOURCES.json", "TASK.json", + "VERIFY.json", "reserve.py", "verify.py", "inputs/example6472.json") + result["sha256"] = {name: sha256((PACKAGE / name).read_bytes()).hexdigest() for name in names} + encoded = json.dumps(result, sort_keys=True, indent=2) + "\n" + if args.receipt is not None: + args.receipt.write_text(encoded) + print(encoded, end="") + + +if __name__ == "__main__": + main()