diff --git a/research/p104-token-settled-drops/EXPECTED.json b/research/p104-token-settled-drops/EXPECTED.json new file mode 100644 index 0000000000..2d2a3b1856 --- /dev/null +++ b/research/p104-token-settled-drops/EXPECTED.json @@ -0,0 +1 @@ +{"kappa_26": "0.003649021305394420489213"} diff --git a/research/p104-token-settled-drops/NOTICE b/research/p104-token-settled-drops/NOTICE new file mode 100644 index 0000000000..509591f790 --- /dev/null +++ b/research/p104-token-settled-drops/NOTICE @@ -0,0 +1,13 @@ +Apache-2.0. DreamingOfClouds with Claude Opus 5.5 (Anthropic), via Claude Code. + +data/base-7546-word.json.gz is the unmodified expected/role902-WORD.json.gz of +research/p104-role902-direct-lift at #7546 head +99438c43df7aac1e5dbcc43c1578fcd886c119ec (ToikY, with OpenAI Codex assistance; +Apache-2.0). Credit ToikY for #7546, and for the price engines and replay +lineage; our own #7542 (helper rung merges) sits underneath it, on Clear1nsight's +#7334 and #7314, with Rohan Arun's signed #7113 caller and all contributors +named in those packages. + +The chart convention in chart.py follows the native verifiers retained in this +repository; no code is imported from them. check.py and chart.py adapt the +replay and chart checks of our #7542 package. diff --git a/research/p104-token-settled-drops/README.md b/research/p104-token-settled-drops/README.md new file mode 100644 index 0000000000..9347507863 --- /dev/null +++ b/research/p104-token-settled-drops/README.md @@ -0,0 +1,99 @@ +# Conditional κ = 0.0036490213053944 from token-settled helper drops on #7546 + +This P104 word is the word of ToikY's +[#7546](https://github.com/CrocSwap/integer-mult-bounds/pull/7546) (head +`99438c43df7aac1e5dbcc43c1578fcd886c119ec`, `expected/role902-WORD.json.gz` +SHA256 `6e03624b…cd32`) with two exact edits, each removing one paid rung from +a public chain. #7546 itself builds on our +[#7542](https://github.com/CrocSwap/integer-mult-bounds/pull/7542) and +Clear1nsight's #7334. All 1,569 final rows, all end charts, the 74 owned +lifetimes, the owned MOVEs and the content erased at each owned CLEAR, the +header, the signed #7113 caller data and the coefficient grid are #7546's. + +**Main 134** climbs 0→3 in one MOVE, where #7546 has 0→1→3 (chain 0→3→5→7→8 +instead of 0→1→3→5→7→8). +- The owned read `134 += −2·owned1503 @595` is deleted together with the stop + at chart 595. +- Premix ADDs at the empty frame {0}, where every operand already sits, supply + the helper-token values the read carried. 152 such ADDs are inserted at the + start of the program, for both edits. +- Three correction ADDs at charts 789 and 913 restore row 134 exactly. + +**Main 100** climbs 3→6 in one MOVE, where #7546 has 3→5→6. +- `166 += −½·100 @783` is deleted together with the stop at chart 783. +- One correction `166 += ½·990 @907` restores row 166. + +[data/edits.json](data/edits.json) lists every deleted and inserted event by +#7546 index (6 deleted, 158 inserted; 76,490 → 76,642 events). Each native +word has 154 more ADDs and 2 fewer MOVEs. Its paid histogram changes by +P₁ −2, P₂ −2, P₃ +2; the target histogram is unchanged. + +## Price + +The complete invoice is #7546's with the native delta charged 17 times: +- paid positions 110,468 → 110,434; +- productive positions 22,461; +- rank surplus S = 1,424; +- zero empty-root credits. + +The crossing of Σ(T−P)·r^(1−C) is + +- **κ = 0.0036490213053944204892137903671…**, up from #7546's + 0.0036484112947908453248116499202… (×1.0001672, +0.0167%). + +The repository's own tools certify the claim: +- `scripts/compare_recursive_invoices.py` classifies the change against + #7546 as `uniformly_better` (strict for r^(1−C)). +- `scripts/evaluate_recursive_power.py` gives `new_cost_lower` at + C = 0.0036490213053 (and at #7546's 0.003648411294790) and + `new_cost_higher` at C = 0.0036490213054. + +## Checks + +```sh +python3.12 -B scripts/research_package.py --package research/p104-token-settled-drops +``` + +- `check.py` (standard library) does the following: + - authenticates the vendored #7546 word and rebuilds the new word from it + and the edit list; + - replays both words over the rationals from arbitrary inputs, with the + legality checks listed in its docstring; + - requires the header, every row and end chart, the owned MOVEs, lifetimes, + peak and erased CLEAR contents to equal #7546's, and that only mains 100 + and 134 change their MOVE chains; + - recomputes the census, invoice and κ, and reproduces #7546's crossing; + - runs six rejecting controls (altered premix coefficients, a deleted + correction, a premix at a chart where its operands are absent, the owned + read deleted without the premixes, a tampered invoice). +- `chart.py` checks the two new chart pairs ({0}→rank 3 and rank 3→rank 6, + both nested) on all 512 columns with exact Gaussian dyadic arithmetic. + #7546's own pairs of the same shapes pass the same check, and a non-nested + target and a target without its quadratic phase are rejected. The + phase-free control is only informative for the 3→6 pair. +- `price.py` runs the two repository tools above. + +## Conditional premises and what is not rerun + +The claim has the same conditional status as #7546's: the framework +assumptions `native_all_columns`, `owned_erasure`, `compiler`, +`precision_tape` and `analytic_recovery`, the signed #7113 caller, and the +BIT premise of the base. The gain is small (+0.0167%). + +This package does not rerun #7546's signed caller, outer predicates, +precision/tape counts, or ordinary bill (154 more ADDs per native call). +Header, rows, grid and owned data are identical to #7546's, and the content +erased at every owned CLEAR is identical, which carries the interface over. +The two new chart pairs are checked here. No human has reviewed the package. + +## Open next questions + +**Further stops.** The same premix-and-correct pattern may shorten other +mains' chains. The first step is to apply it to the next chain and run +`check.py` against the new word. See [TASK.json](TASK.json). + +## Credit + +The base word and all retained work are ToikY's #7546 and the authors it +credits, with our #7542 beneath it (see [NOTICE](NOTICE)). DreamingOfClouds +with Claude Opus 5.5 (Anthropic), via Claude Code. Apache-2.0. diff --git a/research/p104-token-settled-drops/SOURCES.json b/research/p104-token-settled-drops/SOURCES.json new file mode 100644 index 0000000000..c484f02b5a --- /dev/null +++ b/research/p104-token-settled-drops/SOURCES.json @@ -0,0 +1,30 @@ +{ + "schema_version": 1, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "files": [ + { + "path": "certificates/selected-result.json", + "usage": "provenance", + "git_blob": "75d77b328ea02ded535e7f23aee5b1e55d0bb1a8", + "sha256": "154c3d30455d778fd3343b6b4851f0fa4665f0f7625b0adb3675e2bafbbf6bf1" + }, + { + "path": "docs/research/agent-task-catalog.json", + "usage": "provenance", + "git_blob": "3404fbdd5e7529a0674eef26114b5071e4586cec", + "sha256": "ead6cdc9d0af6d58e8a49744d8ec8c7c15e13d2ba93c276c434bcf9b51b93a81" + }, + { + "path": "scripts/compare_recursive_invoices.py", + "usage": "input", + "git_blob": "fda2a852e9937e42fe40df0707694465ca7c1b48", + "sha256": "3930c22c11da7bc6042cfeb6e459ecb06e4478430037bee3469d034353855fc6" + }, + { + "path": "scripts/evaluate_recursive_power.py", + "usage": "input", + "git_blob": "ca50f8021fc3238a58fd420383f4619a8d008ace", + "sha256": "52b20f41fd0bb55fa88dccd6015af2ce358917817b9506720f3e60ce681cc3ad" + } + ] +} diff --git a/research/p104-token-settled-drops/TASK.json b/research/p104-token-settled-drops/TASK.json new file mode 100644 index 0000000000..a3b3e74030 --- /dev/null +++ b/research/p104-token-settled-drops/TASK.json @@ -0,0 +1,117 @@ +{ + "schema_version": 1, + "task_id": "p104-side-correction", + "priority_revision": 8, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "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": "refined", + "actual_scope": "Exact #7546 word, public mains 134 and 100: remove the 0->1->3 and 3->5->6 stops by token-settling premix ADDs at the empty frame and exact local corrections, unchanged rows, ownership, header and signed #7113 caller data.", + "scope_change_reason": "The card asks for joint helper bases and causal splits; this is a narrower exact chain shortening on two mains of the current word.", + "bottleneck_link": "Reduces the complete signed paid invoice (34 rank-1 and 34 rank-2 jobs become 34 rank-3 jobs) without changing the productive profile.", + "budget_minutes": 120, + "stop_rule": "One literal word with exact arbitrary-input row equality, legality, new chart pairs, complete invoice and a certified crossing.", + "outcome": "completed", + "evidence": "README.md, data/edits.json, check.py, chart.py, price.py, VERIFY.json.", + "author": "DreamingOfClouds", + "ai_assistance": "Claude Opus 5.5 (Anthropic), via Claude Code.", + "open_questions": [ + { + "question": "Can the same token-settled premix remove further stops in the 134/100-style chains of other mains?", + "why_it_matters": "Each removed stop saves paid positions at unchanged rows and productive profile.", + "first_step": "Apply data/edits.json's pattern to the next main chain and run check.py against data/word.json.gz.", + "blocked_by": "Nothing." + } + ] +} diff --git a/research/p104-token-settled-drops/VERIFY.json b/research/p104-token-settled-drops/VERIFY.json new file mode 100644 index 0000000000..36270c9147 --- /dev/null +++ b/research/p104-token-settled-drops/VERIFY.json @@ -0,0 +1,42 @@ +{ + "schema_version": 1, + "status": "ready", + "python": "3.12", + "requirements": [], + "inputs": [ + "scripts/compare_recursive_invoices.py", + "scripts/evaluate_recursive_power.py" + ], + "commands": [ + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/check.py" + ], + "timeout_seconds": 300, + "checks": "Vendored #7546 word bytes; word = #7546 + edit list; exact arbitrary-input replay and legality of both words; header identical; all 1,569 rows and end charts equal; owned MOVEs, lifetimes, peak and erased CLEAR content unchanged; grid; #7546 crossing reproduced; new invoice and kappa 0.003649021305394420489213...; six rejecting controls. Prints PASS_TOKEN_SETTLED_DROPS_EXACT." + }, + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/chart.py" + ], + "timeout_seconds": 120, + "checks": "Both new chart pairs ({0}->rank 3, rank 3->rank 6) are rank-gap children on all 512 columns (exact Gaussian dyadic); positive controls on #7546 pairs of the same shapes; non-nested and phase-free controls rejected. Prints PASS_NEW_CHART_PAIRS." + }, + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/price.py" + ], + "timeout_seconds": 120, + "checks": "Repository tools: uniformly_better against #7546; new_cost_lower at C=0.0036490213053 and at #7546's 0.003648411294790; new_cost_higher at C=0.0036490213054. Prints PASS_PRICE." + } + ] +} diff --git a/research/p104-token-settled-drops/chart.py b/research/p104-token-settled-drops/chart.py new file mode 100644 index 0000000000..541ec72de9 --- /dev/null +++ b/research/p104-token-settled-drops/chart.py @@ -0,0 +1,202 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""Physical check of the two new chart pairs ({0} to rank 3, and rank 3 to rank 6), with exact Gaussian dyadic arithmetic. + +Standard library only; written for this package. The chart convention is the +one of the native verifiers retained in the repository (for example +research/current-serial-monomial-leaf/vendor/monomial/vendor/selected/native_verify.py, +function `frame`): a frame with basis vectors U of F2^9 is + chart^-1 . C(e_0) ... C(e_{r-1}) . chart, chart = P(G) then D(Q, diag Q), +where G is the transpose of U extended by unit vectors, Q_i = e_i xor +sum_j e_j over the columns c of G^-1, P(G)|x> = |Gx>, +D(Q, l)|x> = i^(sum_{i in x} l_i + 2 sum_{i, and +C(d)|x> = ((1+i)|x> + (1-i)|x xor d>)/2. + +A paid MOVE from chart a to chart b applies frame(a)^-1 then frame(b). For +each of the 512 basis inputs this script computes the output exactly and +requires: support inside x + span(b), exactly 2^g nonzero amplitudes, all +of squared modulus 2^-g, where g = dim b - dim a. For a Clifford operator +this is the statement that it is a rank-g child: monomial . g Fourier +factors . monomial. Controls: the same check on chart pairs that #7546 +already uses with the same dimensions must pass, and a non-nested pair and a +frame with its quadratic phase removed must fail. +""" +import gzip +import json +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +N = 9 + + +def require(cond, label): + if not cond: + raise AssertionError(label) + + +def parity(v): + return bin(v).count('1') & 1 + + +def mul(rows, v): + return sum(parity(row & v) << i for i, row in enumerate(rows)) + + +def transpose(rows): + return tuple(sum(((row >> j) & 1) << i for i, row in enumerate(rows)) for j in range(N)) + + +def invert(rows): + aug = [row | (1 << (N + i)) for i, row in enumerate(rows)] + for j in range(N): + p = next(i for i in range(j, N) if aug[i] >> j & 1) + aug[j], aug[p] = aug[p], aug[j] + for i in range(N): + if i != j and aug[i] >> j & 1: + aug[i] ^= aug[j] + require([row & ((1 << N) - 1) for row in aug] == [1 << i for i in range(N)], 'invertible') + return tuple(row >> N for row in aug) + + +def extend(vectors): + cols, piv = [], {} + for v in list(vectors) + [1 << i for i in range(N)]: + w = v + while w: + j = w.bit_length() - 1 + if j not in piv: + piv[j] = w + cols.append(v) + break + w ^= piv[j] + require(len(cols) == N, 'basis extension') + return tuple(cols) + + +def frame(vectors, with_phase=True): + r = len(vectors) + if r == 0: + return [] + fourier = [('C', 1 << i, 1) for i in range(r)] + if r == N: + return fourier + G = transpose(extend(vectors)) + cols = transpose(invert(G)) + Q = tuple((1 << i) ^ sum(parity(a & b) << j for j, b in enumerate(cols)) for i, a in enumerate(cols)) + lin = tuple((row >> i) & 1 for i, row in enumerate(Q)) + chart = [('P', G)] + ([('D', Q, lin)] if with_phase else []) + inv = [('P', invert(g[1])) if g[0] == 'P' else ('D', g[1], tuple(-x % 4 for x in g[2])) for g in reversed(chart)] + return inv + fourier + chart + + +def inverse_circuit(circ): + out = [] + for g in reversed(circ): + if g[0] == 'P': + out.append(('P', invert(g[1]))) + elif g[0] == 'D': + out.append(('D', g[1], tuple(-x % 4 for x in g[2]))) + else: + out.append(('C', g[1], -g[2])) + return out + + +ROT = (lambda a, b: (a, b), lambda a, b: (-b, a), lambda a, b: (-a, -b), lambda a, b: (b, -a)) + + +def compile_gate(g): + if g[0] == 'P': + return ('P', [mul(g[1], x) for x in range(1 << N)]) + if g[0] == 'D': + Q, lin = g[1], g[2] + ph = [] + for x in range(1 << N): + p = sum(lin[i] for i in range(N) if x >> i & 1) + p += 2 * sum(parity((Q[i] >> (i + 1)) & (x >> (i + 1))) for i in range(N) if x >> i & 1) + ph.append(p % 4) + return ('D', ph) + return g + + +def run(gates, x): + """Exact output for input |x>: amplitudes (a + bi) / 2^den.""" + vec, den = {x: (1, 0)}, 0 + for g in gates: + out = {} + if g[0] == 'C': + d, s = g[1], g[2] + for y, (a, b) in vec.items(): + for t, (p, q) in ((y, (a - s * b, b + s * a)), (y ^ d, (a + s * b, b - s * a))): + u = out.get(t, (0, 0)) + out[t] = (u[0] + p, u[1] + q) + den += 1 + vec = {y: v for y, v in out.items() if v != (0, 0)} + elif g[0] == 'P': + vec = {g[1][y]: v for y, v in vec.items()} + else: + vec = {y: ROT[g[1][y]](*v) for y, v in vec.items()} + return vec, den + + +def child_rank(a, b, phase_b=True): + """Return g if frame(a)^-1 frame(b) is a rank-g child on every column, else raise.""" + gates = [compile_gate(g) for g in inverse_circuit(frame(a)) + frame(b, phase_b)] + sb = {0} + for v in b: + sb |= {s ^ v for s in sb} + g = len(b) - len(a) + require(g >= 0, 'ascending pair') + for x in range(1 << N): + vec, den = run(gates, x) + require(len(vec) == 1 << g, 'column %d support %d != 2^%d' % (x, len(vec), g)) + require(all((y ^ x) in sb for y in vec), 'column %d support inside x + span(b)' % x) + mods = {a_ * a_ + b_ * b_ for a_, b_ in vec.values()} + require(len(mods) == 1, 'column %d equal moduli' % x) + # |amp|^2 = m / 4^den must equal 2^-g. + require(mods.pop() * (1 << g) == 4 ** den, 'column %d modulus 2^-g/2' % x) + return g + + +def main(): + W = json.loads(gzip.decompress((HERE / 'data' / 'word.json.gz').read_bytes())) + B = json.loads(gzip.decompress((HERE / 'data' / 'base-7546-word.json.gz').read_bytes())) + pairs = lambda X: sorted({(tuple(X['frames'][e[2]]), tuple(X['frames'][e[3]])) for e in X['program'] if e[0] == 'MOVE'}) + new = sorted(set(pairs(W)) - set(pairs(B))) + require(len(new) == 2, 'two new pairs') + for a, b in new: + g = child_rank(a, b) + print('PASS new pair %s -> %s: 512 columns, rank %d = dim gap' % (list(a), list(b), g)) + # Positive controls: #7546's own pairs with the same dimensions. + shapes = {(len(a), len(b)) for a, b in new} + seen = {} + for a, b in pairs(B): + k = (len(a), len(b)) + if k in shapes and len(seen.setdefault(k, [])) < 2: + seen[k].append((a, b)) + for k, lst in sorted(seen.items()): + for a, b in lst: + require(child_rank(a, b) == k[1] - k[0], 'control pair') + print('PASS control #7546 pair %d -> %d passes the same check' % k) + # Negative controls on the 3 -> 6 pair: a target not containing the source. + (a36, b36) = [p for p in new if len(p[0]) == 3][0] + other = next(b for a, b in pairs(B) if len(b) == 6 and not set(a36) <= set(b)) + sb = {0} + for v in other: + sb |= {s ^ v for s in sb} + require(not all(v in sb for v in a36), 'control target does not contain the source') + try: + child_rank(a36, other) + raise RuntimeError('non-nested control passed') + except AssertionError as exc: + print('PASS control rejected: 3 -> 6 into a chart not containing the source (%s)' % exc) + try: + child_rank(a36, b36, phase_b=False) + raise RuntimeError('phase control passed') + except AssertionError as exc: + print('PASS control rejected: 3 -> 6 with the target quadratic phase removed (%s)' % exc) + print('PASS_NEW_CHART_PAIRS') + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/research/p104-token-settled-drops/check.py b/research/p104-token-settled-drops/check.py new file mode 100644 index 0000000000..12f36fc43f --- /dev/null +++ b/research/p104-token-settled-drops/check.py @@ -0,0 +1,360 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""Exact replay of the token-settled helper drops against #7546's word. + +Standard library only. Written for this package; it imports no other package. + +1. The vendored #7546 word has the SHA256 of expected/role902-WORD.json.gz + at #7546 head 99438c43df7aac1e5dbcc43c1578fcd886c119ec, and applying the + edit list data/edits.json to it gives data/word.json.gz event for event. +2. Both words are replayed over the rationals from arbitrary inputs (every + public field starts as its own symbol, owned fields start at INIT as 0). + Legality: every ADD/COPY/SCALE operand sits at the event's chart, every + MOVE starts at the register's current chart, public MOVEs strictly ascend + (span inclusion), owned MOVEs are nested and only on live owned fields, + COPY writes a zero field, no SCALE by 0, no self-ADD, every owned field + is cleared at the chart it sits in, and public fields end at `final`. +3. Header identical; all 1,569 rows and end charts equal #7546's; helpers end + at identity, owned rows end empty; owned MOVEs, lifetimes and peak are + unchanged, and the content erased at each owned CLEAR is identical. +4. Only the mains 100 and 134 change their MOVE chains, endpoint-preserving. +5. Census, complete invoice (17 native calls) and kappa are recomputed and + compared with data/invoice-*.json; #7546's crossing is reproduced. +6. Controls: corrupted words and a tampered invoice must be rejected. +""" +import collections +import copy +import decimal +import gzip +import hashlib +import json +import sys +from fractions import Fraction as Q +from pathlib import Path + +HERE = Path(__file__).resolve().parent +DATA = HERE / 'data' +BASE_SHA256 = '6e03624b173b90356e96f845d05fc93153846b863734dc8163ab6c44c602cd32' +CALLS = 17 + + +def require(cond, label): + if not cond: + raise AssertionError(label) + + +def load_gz(path): + return json.loads(gzip.decompress(path.read_bytes())) + + +def span(vectors): + s = {0} + for v in vectors: + require(type(v) is int and 0 < v < 512 and v not in s, 'frame vectors independent in F2^9') + s |= {x ^ v for x in s} + return frozenset(s) + + +def mains(W): + live = set(W['live']) + return live | {r + 112 for r in live} | set(W['hosted']['X2']) | set(W['hosted']['Y2']) + + +def apply_edits(program, E): + require(len(program) == E['base_events'], 'edit list base length') + dele = {} + for i, ev in E['delete']: + require(program[i] == ev, 'deleted event %d matches' % i) + dele[i] = ev + ins = collections.defaultdict(list) + for i, evs in E['insert_before']: + ins[i].extend(evs) + out = [] + for i, ev in enumerate(program): + out.extend(ins.get(i, [])) + if i not in dele: + out.append(ev) + out.extend(ins.get(len(program), [])) + return out + E['append'] + + +def replay(W): + """Exact replay; returns rows, end charts, MOVE chains and owned data. Raises on any illegality.""" + n, N = W['public'], W['public'] + W['owned_fields'] + sp = [span(f) for f in W['frames']] + rows = [{r: Q(1)} if r < n else {} for r in range(N)] + cur = list(W['initial']) + [None] * W['owned_fields'] + alive, chains, owned_moves = set(), collections.defaultdict(list), collections.Counter() + lifetimes, peak = collections.Counter(), 0 + init_chart = {} + stats = dict(max_den_exp=0, odd_den=1, max_num_bits=0) + + def note(q): + d = q.denominator + e = (d & -d).bit_length() - 1 + stats['max_den_exp'] = max(stats['max_den_exp'], e) + odd = d >> e + if odd > 1 and stats['odd_den'] % odd: + stats['odd_den'] = stats['odd_den'] * odd // __import__('math').gcd(stats['odd_den'], odd) + stats['max_num_bits'] = max(stats['max_num_bits'], abs(q.numerator).bit_length()) + + for i, e in enumerate(W['program']): + op, r = e[0], e[1] + require(type(r) is int and 0 <= r < N, '%d register index' % i) + if op == 'MOVE': + a, b, flag = e[2], e[3], e[4] + require(type(flag) is bool and flag == (r >= n), '%d MOVE ownership flag' % i) + require(cur[r] == a, '%d MOVE from the current chart' % i) + if r >= n: + require(r in alive, '%d owned MOVE on a live field' % i) + require(sp[a] < sp[b] or sp[b] < sp[a], '%d owned MOVE nested' % i) + owned_moves[(a, b)] += 1 + else: + require(sp[a] < sp[b], '%d public MOVE strictly ascends' % i) + cur[r] = b + chains[r].append((a, b)) + elif op == 'INIT': + require(r >= n and r not in alive and len(e) == 3, '%d INIT of a dead owned field' % i) + alive.add(r); rows[r] = {}; cur[r] = e[2]; init_chart[r] = e[2] + peak = max(peak, len(alive)) + elif op == 'CLEAR': + require(r >= n and r in alive and cur[r] == e[2], '%d CLEAR at the current chart' % i) + lifetimes[(r, init_chart.pop(r), e[2])] += 1 + alive.discard(r); rows[r] = {}; cur[r] = None + elif op == 'SCALE': + q = Q(e[2]) + require(q != 0, '%d SCALE by zero' % i) + require(cur[r] == e[3] and (r < n or r in alive), '%d SCALE chart' % i) + rows[r] = {k: v * q for k, v in rows[r].items()} + for v in rows[r].values(): + note(v) + elif op in ('ADD', 'COPY'): + s, q, f = e[2], Q(e[3]), e[4] + require(type(s) is int and 0 <= s < N and s != r, '%d operand' % i) + require(q != 0, '%d zero coefficient' % i) + require(cur[r] == f and cur[s] == f, '%d ADD/COPY operands at chart %d' % (i, f)) + for x in (r, s): + require(x < n or x in alive, '%d owned field live' % i) + if op == 'COPY': + require(not rows[r], '%d COPY into a zero field' % i) + R = rows[r] + for k, v in rows[s].items(): + nv = R.get(k, 0) + q * v + if nv: + R[k] = nv + note(nv) + else: + R.pop(k, None) + else: + raise AssertionError('%d unknown op %r' % (i, op)) + require(not alive, 'every owned field cleared') + require(cur[:n] == list(W['final']), 'public fields end at final charts') + return dict(rows=rows, cur=cur, chains=chains, owned_moves=owned_moves, + lifetimes=lifetimes, peak=peak, sp=sp, stats=stats) + + +def census(W, R): + """Per-native paid MOVE ranks and helper targets (the #7546 accounting).""" + dim = [len(f) for f in W['frames']] + paid = collections.Counter(abs(dim[e[3]] - dim[e[2]]) for e in W['program'] if e[0] == 'MOVE') + M, n = mains(W), W['public'] + helpers = collections.Counter(dim[W['final'][r]] - dim[W['initial'][r]] for r in range(n) if r not in M) + rises = collections.Counter(dim[e[3]] - dim[e[2]] for e in W['program'] + if e[0] == 'MOVE' and e[1] >= n and dim[e[3]] > dim[e[2]]) + hist = lambda c: {str(k): v for k, v in sorted(c.items()) if v} + return dict(events=len(W['program']), public=n, helpers=hist(helpers), paid=hist(paid), + lifetimes=sum(R['lifetimes'].values()), owned_peak=R['peak'], rises=hist(rises)) + + +def crossing(T, P, digits=40): + """Root of F(C) = sum (T_r - P_r) r^(1-C) on [0.003, 0.0045] by bisection in 80-digit decimals.""" + D = decimal.Decimal + with decimal.localcontext(decimal.Context(prec=digits + 40)) as ctx: + ranks = sorted({int(r) for r in T} | {int(r) for r in P}) + terms = [(D(T.get(str(r), 0) - P.get(str(r), 0)) * r, D(r).ln()) for r in ranks] + + def F(C): + return sum((c * (-C * l).exp() for c, l in terms), D(0)) + lo, hi = D('0.003'), D('0.0045') + require(F(lo) > 0 > F(hi), 'crossing bracketed') + for _ in range(160): + mid = (lo + hi) / 2 + if F(mid) > 0: + lo = mid + else: + hi = mid + return decimal.Context(prec=digits).create_decimal(lo) + + +def invoice_json(P, T): + return {'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 signed #7113 caller application with 17 native calls'}, + 'paid': {k: P[k] for k in sorted(P, key=int)}, + 'targets': {k: T[k] for k in sorted(T, key=int)}} + + +def clears(W): + """Row content erased at every owned CLEAR, in program order.""" + n = W['public'] + rows = [{r: Q(1)} if r < n else {} for r in range(n + W['owned_fields'])] + out = [] + for e in W['program']: + op, r = e[0], e[1] + if op == 'INIT': + rows[r] = {} + elif op == 'CLEAR': + out.append((r, tuple(sorted(rows[r].items())))) + rows[r] = {} + elif op == 'SCALE': + rows[r] = {k: v * Q(e[2]) for k, v in rows[r].items()} + elif op in ('ADD', 'COPY'): + R = rows[r] + for k, v in rows[e[2]].items(): + nv = R.get(k, 0) + Q(e[3]) * v + if nv: + R[k] = nv + else: + R.pop(k, None) + return out + + +def compare(B, RB, W): + """Everything that must hold between #7546's word B and a candidate W. Returns the candidate replay.""" + require(all(B[k] == W[k] for k in B if k != 'program') and B.keys() == W.keys(), 'header identical') + R = replay(W) + n = W['public'] + bad = [r for r in range(len(R['rows'])) if R['rows'][r] != RB['rows'][r]] + require(not bad, 'all rows equal #7546 (first differing %s)' % bad[:3]) + require(R['cur'] == RB['cur'], 'all end charts equal #7546') + M = mains(W) + require(all(R['rows'][r] == {r: Q(1)} for r in range(n) if r not in M), 'helpers end at identity') + require(all(not R['rows'][r] for r in range(n, len(R['rows']))), 'owned rows end empty') + require(R['owned_moves'] == RB['owned_moves'], 'owned MOVE multiset unchanged') + require(R['lifetimes'] == RB['lifetimes'] and R['peak'] == RB['peak'], 'owned lifetimes and peak unchanged') + require(clears(W) == clears(B), 'content erased at every owned CLEAR identical') + changed = sorted(r for r in set(R['chains']) | set(RB['chains']) if R['chains'][r] != RB['chains'][r]) + require(changed == [100, 134], 'only mains 100 and 134 change chains (got %s)' % changed[:5]) + require(all(r in M for r in changed), 'changed registers are mains') + for r in changed: + old, new = RB['chains'][r], R['chains'][r] + require(old[0][0] == new[0][0] and old[-1][1] == new[-1][1], 'register %d chain endpoints' % r) + return R, changed + + +def main(): + base_raw = (DATA / 'base-7546-word.json.gz').read_bytes() + require(hashlib.sha256(base_raw).hexdigest() == BASE_SHA256, 'vendored #7546 word bytes') + B = json.loads(gzip.decompress(base_raw)) + W = load_gz(DATA / 'word.json.gz') + E = json.loads((DATA / 'edits.json').read_text()) + require(apply_edits(B['program'], E) == W['program'], 'word = #7546 word + edit list') + print('PASS word = #7546 word (%d events) + %d deletions, %d insertions, %d appended events = %d events' + % (len(B['program']), len(E['delete']), sum(len(x[1]) for x in E['insert_before']), + len(E['append']), len(W['program']))) + + RB = replay(B) + R, changed = compare(B, RB, W) + dim = [len(f) for f in W['frames']] + for r in changed: + f = lambda ch: '->'.join([str(dim[ch[0][0]])] + [str(dim[b]) for a, b in ch]) + print('PASS main %d dims %s became %s' % (r, f(RB['chains'][r]), f(R['chains'][r]))) + print('PASS exact replay: legal, all %d rows and end charts equal #7546, helpers identity, owned empty;' + ' owned MOVEs (%d), lifetimes (%d), peak (%d) and erased content (%d CLEARs) unchanged' + % (len(R['rows']), sum(R['owned_moves'].values()), sum(R['lifetimes'].values()), R['peak'], + len(clears(W)))) + + key = lambda W_, i: tuple(W_['frames'][i]) + pairs = lambda W_: {(key(W_, e[2]), key(W_, e[3])) for e in W_['program'] if e[0] == 'MOVE'} + new_pairs = sorted(pairs(W) - pairs(B)) + require(len(new_pairs) == 2, 'two new chart pairs') + for a, b in new_pairs: + require(span(a) < span(b), 'new pair nested') + print('PASS new chart pairs (nested, checked physically by chart.py):', + ', '.join('%d->%d' % (len(a), len(b)) for a, b in new_pairs)) + + def nondyadic(P): + c = 0 + for e in P: + if e[0] in ('ADD', 'COPY', 'SCALE'): + q = Q(e[2] if e[0] == 'SCALE' else e[3]) + c += q.denominator & (q.denominator - 1) != 0 + return c + added = [e for x in E['insert_before'] for e in x[1]] + E['append'] + coeffs = sorted({e[3] for e in added if e[0] == 'ADD'}, key=Q) + require(all(Q(c).denominator & (Q(c).denominator - 1) == 0 for c in coeffs), 'added coefficients dyadic') + require(nondyadic(W['program']) == nondyadic(B['program']), 'odd-denominator event count unchanged') + sb, sw = RB['stats'], R['stats'] + require(sw['max_den_exp'] <= sb['max_den_exp'] and sw['odd_den'] == sb['odd_den'] + and sw['max_num_bits'] <= sb['max_num_bits'], 'intermediate coefficient grid within #7546') + print('PASS intermediate coefficients: 2-adic exponent %d (#7546 %d), odd denominator lcm %d (#7546 %d),' + ' numerator bits %d (#7546 %d)' % (sw['max_den_exp'], sb['max_den_exp'], sw['odd_den'], sb['odd_den'], + sw['max_num_bits'], sb['max_num_bits'])) + ops = lambda P: collections.Counter(e[0] for e in P) + d = ops(W['program']); d.subtract(ops(B['program'])) + print('PASS event delta per native call', {k: v for k, v in sorted(d.items()) if v}) + + cb, cw = census(B, RB), census(W, R) + require(cw['helpers'] == cb['helpers'] and cw['rises'] == cb['rises'], 'helper targets and owned rises unchanged') + dpaid = collections.Counter({int(k): v for k, v in cw['paid'].items()}) + dpaid.subtract({int(k): v for k, v in cb['paid'].items()}) + dpaid = {k: v for k, v in sorted(dpaid.items()) if v} + require(dpaid == {1: -2, 2: -2, 3: 2}, 'native paid delta {1:-2, 2:-2, 3:+2}') + print('PASS native paid delta per call', dpaid) + inv0 = json.loads((DATA / 'invoice-7546.json').read_text()) + P = collections.Counter({int(k): v for k, v in inv0['paid'].items()}) + T = dict(inv0['targets']) + S0 = sum(int(k) * v for k, v in T.items()) - sum(int(k) * v for k, v in inv0['paid'].items()) + paid0 = sum(P.values()) + for k, v in dpaid.items(): + P[k] += CALLS * v + Pn = {str(k): v for k, v in sorted(P.items()) if v} + S = sum(int(k) * v for k, v in T.items()) - sum(int(k) * v for k, v in Pn.items()) + require(S == S0 == 1424, 'rank surplus 1424 unchanged') + require(json.loads((DATA / 'invoice-new.json').read_text()) == invoice_json(Pn, T), 'invoice-new.json matches') + require(json.loads((DATA / 'invoice-zero.json').read_text()) == invoice_json({}, {}), 'zero invoice') + paid1 = sum(Pn.values()) + require((paid0, paid1) == (110468, 110434), 'paid positions') + print('PASS complete invoice: paid positions %d -> %d, productive %d, S = %d' % (paid0, paid1, sum(T.values()), S)) + + k0, k1 = crossing(inv0['targets'], inv0['paid']), crossing(T, Pn) + lo, hi = decimal.Decimal('0.00364841129479084532481164992024'), decimal.Decimal('0.00364841129479084532481164992025') + require(lo <= k0 <= hi, '#7546 published crossing reproduced') + print('PASS kappa #7546 %s (inside the published #7546 enclosure [...992024, ...992025])' % k0) + print('PASS kappa new %s (ratio %s)' % (k1, +decimal.Context(prec=12).divide(k1, k0))) + expected = json.loads((HERE / 'EXPECTED.json').read_text()) + require(str(k1)[:26] == expected['kappa_26'], 'kappa digits as recorded') + + def rejected(label, mutate, base=False): + X = copy.deepcopy(B if base else W) + mutate(X['program']) + try: + if base: + R2 = replay(X) + require(not [r for r in range(len(R2['rows'])) if R2['rows'][r] != RB['rows'][r]], 'rows equal') + else: + compare(B, RB, X) + except AssertionError as exc: + print('PASS control rejected: %s (%s)' % (label, exc)) + return + raise AssertionError('control not rejected: ' + label) + idx = lambda P, ev: P.index(ev) + rejected('premix 134 += -11/2*1030 changed to -9/2', + lambda P: P.__setitem__(idx(P, ['ADD', 134, 1030, '-11/2', 3]), ['ADD', 134, 1030, '-9/2', 3])) + rejected('premix 166 += -2*550 changed to -1', + lambda P: P.__setitem__(idx(P, ['ADD', 166, 550, '-2', 3]), ['ADD', 166, 550, '-1', 3])) + rejected('correction 134 += 1/2*315 @789 deleted', lambda P: P.remove(['ADD', 134, 315, '1/2', 789])) + rejected('premix 134 += -1/2*146 moved to chart 595', + lambda P: P.__setitem__(idx(P, ['ADD', 134, 146, '-1/2', 3]), ['ADD', 134, 146, '-1/2', 595])) + rejected('owned read 134 += -2*owned1503 deleted without the premixes', + lambda P: P.remove(['ADD', 134, 1503, '-2', 595]), base=True) + bad = dict(Pn); bad['3'] -= 1 + require(json.loads((DATA / 'invoice-new.json').read_text()) != invoice_json(bad, T), 'tampered invoice differs') + print('PASS control rejected: invoice with one rank-3 job removed differs from the recomputed one') + print('PASS_TOKEN_SETTLED_DROPS_EXACT') + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/research/p104-token-settled-drops/data/base-7546-word.json.gz b/research/p104-token-settled-drops/data/base-7546-word.json.gz new file mode 100644 index 0000000000..d63f6b195e Binary files /dev/null and b/research/p104-token-settled-drops/data/base-7546-word.json.gz differ diff --git a/research/p104-token-settled-drops/data/edits.json b/research/p104-token-settled-drops/data/edits.json new file mode 100644 index 0000000000..a80a021db0 --- /dev/null +++ b/research/p104-token-settled-drops/data/edits.json @@ -0,0 +1 @@ +{"base_events":76490,"delete":[[39879,["MOVE",134,3,595,false]],[39880,["ADD",134,1503,"-2",595]],[40889,["MOVE",134,595,618,false]],[41827,["MOVE",100,716,783,false]],[41828,["ADD",166,100,"-1/2",783]],[42006,["MOVE",100,783,807,false]]],"insert_before":[[0,[["ADD",134,146,"-1/2",3],["ADD",221,146,"-1/2",3],["ADD",134,230,"-1/2",3],["ADD",221,230,"-1/2",3],["ADD",134,367,"-1/2",3],["ADD",221,367,"-1/2",3],["ADD",134,372,"-5/32",3],["ADD",221,372,"-5/32",3],["ADD",134,471,"1/2",3],["ADD",221,471,"1/2",3],["ADD",134,497,"-5/8",3],["ADD",221,497,"-5/8",3],["ADD",134,521,"1",3],["ADD",221,521,"1",3],["ADD",134,537,"-1/2",3],["ADD",221,537,"-1/2",3],["ADD",134,541,"1/4",3],["ADD",221,541,"1/4",3],["ADD",134,542,"-1/4",3],["ADD",221,542,"-1/4",3],["ADD",134,545,"-1",3],["ADD",221,545,"-1",3],["ADD",134,550,"3",3],["ADD",166,550,"-2",3],["ADD",214,550,"-2",3],["ADD",221,550,"3",3],["ADD",134,553,"-3/4",3],["ADD",221,553,"-3/4",3],["ADD",134,568,"-1/2",3],["ADD",221,568,"-1/2",3],["ADD",134,569,"-1/2",3],["ADD",221,569,"-1/2",3],["ADD",134,575,"-1/2",3],["ADD",221,575,"-1/2",3],["ADD",134,576,"-1/2",3],["ADD",221,576,"-1/2",3],["ADD",134,599,"-1/2",3],["ADD",221,599,"-1/2",3],["ADD",134,655,"-1/8",3],["ADD",221,655,"-1/8",3],["ADD",134,671,"1/2",3],["ADD",166,671,"-1/2",3],["ADD",214,671,"-1/2",3],["ADD",221,671,"1/2",3],["ADD",134,711,"-1/4",3],["ADD",221,711,"-1/4",3],["ADD",134,775,"-1/2",3],["ADD",221,775,"-1/2",3],["ADD",134,917,"1/8",3],["ADD",221,917,"1/8",3],["ADD",166,990,"-1/2",3],["ADD",214,990,"-1/2",3],["ADD",134,999,"-1/4",3],["ADD",221,999,"-1/4",3],["ADD",134,1006,"1/4",3],["ADD",221,1006,"1/4",3],["ADD",134,1008,"-1/2",3],["ADD",221,1008,"-1/2",3],["ADD",134,1013,"-5/2",3],["ADD",221,1013,"-5/2",3],["ADD",134,1016,"-5/4",3],["ADD",221,1016,"-5/4",3],["ADD",134,1030,"-11/2",3],["ADD",221,1030,"-11/2",3],["ADD",134,1032,"-2",3],["ADD",221,1032,"-2",3],["ADD",134,1037,"-9/2",3],["ADD",166,1037,"4",3],["ADD",214,1037,"4",3],["ADD",221,1037,"-9/2",3],["ADD",134,1053,"-3",3],["ADD",166,1053,"2",3],["ADD",214,1053,"2",3],["ADD",221,1053,"-3",3],["ADD",134,1058,"1",3],["ADD",221,1058,"1",3],["ADD",134,1075,"-3/4",3],["ADD",166,1075,"1/2",3],["ADD",214,1075,"1/2",3],["ADD",221,1075,"-3/4",3],["ADD",134,1077,"-1",3],["ADD",166,1077,"2",3],["ADD",214,1077,"2",3],["ADD",221,1077,"-1",3],["ADD",134,1078,"-1/2",3],["ADD",221,1078,"-1/2",3],["ADD",134,1080,"1/2",3],["ADD",221,1080,"1/2",3],["ADD",134,1091,"1",3],["ADD",166,1091,"-1/2",3],["ADD",214,1091,"-1/2",3],["ADD",221,1091,"1",3],["ADD",134,1095,"-6",3],["ADD",166,1095,"4",3],["ADD",214,1095,"4",3],["ADD",221,1095,"-6",3],["ADD",134,1097,"2",3],["ADD",166,1097,"-1",3],["ADD",214,1097,"-1",3],["ADD",221,1097,"2",3],["ADD",134,1110,"-6",3],["ADD",166,1110,"4",3],["ADD",214,1110,"4",3],["ADD",221,1110,"-6",3],["ADD",134,1111,"3",3],["ADD",166,1111,"-2",3],["ADD",214,1111,"-2",3],["ADD",221,1111,"3",3],["ADD",134,1113,"-1",3],["ADD",166,1113,"6",3],["ADD",214,1113,"6",3],["ADD",221,1113,"-1",3],["ADD",134,1116,"-5/4",3],["ADD",166,1116,"-1/2",3],["ADD",214,1116,"-1/2",3],["ADD",221,1116,"-5/4",3],["ADD",134,1127,"1/4",3],["ADD",221,1127,"1/4",3],["ADD",134,1129,"5",3],["ADD",166,1129,"2",3],["ADD",214,1129,"2",3],["ADD",221,1129,"5",3],["ADD",134,1132,"-3/2",3],["ADD",166,1132,"1",3],["ADD",214,1132,"1",3],["ADD",221,1132,"-3/2",3],["ADD",134,1136,"-6",3],["ADD",166,1136,"4",3],["ADD",214,1136,"4",3],["ADD",221,1136,"-6",3],["ADD",166,1143,"-1/2",3],["ADD",214,1143,"-1/2",3],["ADD",134,1171,"-1",3],["ADD",221,1171,"-1",3],["ADD",134,1172,"1/2",3],["ADD",221,1172,"1/2",3],["ADD",134,1207,"1/4",3],["ADD",221,1207,"1/4",3],["ADD",134,1224,"1/4",3],["ADD",221,1224,"1/4",3],["ADD",134,1234,"1",3],["ADD",221,1234,"1",3],["ADD",134,1284,"-5/2",3],["ADD",221,1284,"-5/2",3],["ADD",134,1287,"1/8",3],["ADD",221,1287,"1/8",3],["ADD",134,1466,"1/2",3],["ADD",221,1466,"1/2",3],["ADD",166,1477,"1/2",3],["ADD",214,1477,"1/2",3],["ADD",134,1479,"1/2",3],["ADD",221,1479,"1/2",3]]],[40889,[["MOVE",134,3,618,false]]],[41930,[["ADD",134,315,"1/2",789]]],[42006,[["MOVE",100,716,807,false]]],[43334,[["ADD",166,990,"1/2",907]]],[43373,[["ADD",134,994,"1/2",913],["ADD",134,230,"1/2",913]]]],"append":[]} \ No newline at end of file diff --git a/research/p104-token-settled-drops/data/invoice-7546.json b/research/p104-token-settled-drops/data/invoice-7546.json new file mode 100644 index 0000000000..f496503472 --- /dev/null +++ b/research/p104-token-settled-drops/data/invoice-7546.json @@ -0,0 +1 @@ +{"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 signed #7113 caller application with 17 native calls"}, "paid": {"1": 68367, "2": 14484, "3": 14059, "4": 3791, "5": 5831, "6": 272, "7": 187, "8": 741, "9": 32, "16": 416, "24": 416, "32": 416, "40": 416, "48": 416, "56": 416, "64": 208}, "targets": {"1": 306, "2": 357, "3": 799, "4": 3825, "5": 1360, "6": 731, "7": 323, "8": 544, "9": 10888, "17": 416, "25": 416, "33": 416, "41": 416, "49": 416, "57": 416, "65": 416, "73": 208, "137": 208}} \ No newline at end of file diff --git a/research/p104-token-settled-drops/data/invoice-new.json b/research/p104-token-settled-drops/data/invoice-new.json new file mode 100644 index 0000000000..186e67706c --- /dev/null +++ b/research/p104-token-settled-drops/data/invoice-new.json @@ -0,0 +1 @@ +{"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 signed #7113 caller application with 17 native calls"}, "paid": {"1": 68333, "2": 14450, "3": 14093, "4": 3791, "5": 5831, "6": 272, "7": 187, "8": 741, "9": 32, "16": 416, "24": 416, "32": 416, "40": 416, "48": 416, "56": 416, "64": 208}, "targets": {"1": 306, "2": 357, "3": 799, "4": 3825, "5": 1360, "6": 731, "7": 323, "8": 544, "9": 10888, "17": 416, "25": 416, "33": 416, "41": 416, "49": 416, "57": 416, "65": 416, "73": 208, "137": 208}} \ No newline at end of file diff --git a/research/p104-token-settled-drops/data/invoice-zero.json b/research/p104-token-settled-drops/data/invoice-zero.json new file mode 100644 index 0000000000..6b9ea16bcf --- /dev/null +++ b/research/p104-token-settled-drops/data/invoice-zero.json @@ -0,0 +1 @@ +{"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 signed #7113 caller application with 17 native calls"}, "paid": {}, "targets": {}} \ No newline at end of file diff --git a/research/p104-token-settled-drops/data/word.json.gz b/research/p104-token-settled-drops/data/word.json.gz new file mode 100644 index 0000000000..25ec6e8b3a Binary files /dev/null and b/research/p104-token-settled-drops/data/word.json.gz differ diff --git a/research/p104-token-settled-drops/price.py b/research/p104-token-settled-drops/price.py new file mode 100644 index 0000000000..e701b88d1d --- /dev/null +++ b/research/p104-token-settled-drops/price.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""Certify the price with the repository's own invoice tools. + +Runs scripts/compare_recursive_invoices.py (#7546 invoice against the new +one, concave order) and scripts/evaluate_recursive_power.py (new invoice +against the empty invoice at r^t, t = 1 - C) and requires: + - the new invoice is uniformly better than #7546's for every increasing + concave tariff, strictly for r^(1-C), 0 < C < 1; + - at C = 0.0036490213053 the new paid cost is strictly below the new + targets (F(C) > 0), so the crossing is above the claim; + - at C = 0.0036490213054 it is strictly above (F(C) < 0); + - at #7546's C = 0.003648411294790 the new invoice is strictly favourable. +The invoices themselves are recomputed from the words by check.py. +""" +import json +import subprocess +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +DATA = HERE / 'data' +CLAIM, ABOVE, PR7481 = '0.0036490213053', '0.0036490213054', '0.003648411294790' + + +def tool(name, *args): + out = subprocess.run([sys.executable, '-I', '-B', str(ROOT / 'scripts' / name), *map(str, args)], + capture_output=True, text=True, check=True, timeout=120) + return json.loads(out.stdout) + + +def one_minus(c): + from decimal import Decimal + return str(1 - Decimal(c)) + + +def main(): + old, new, zero = DATA / 'invoice-7546.json', DATA / 'invoice-new.json', DATA / 'invoice-zero.json' + rep = tool('compare_recursive_invoices.py', old, new) + assert rep['classification'] == 'uniformly_better', rep['classification'] + assert rep['power_moment']['new_minus_old_sign'] == 'strictly_negative' + assert rep['delta_paid'] == {'1': -34, '2': -34, '3': 34} and rep['delta_targets'] == {} + print('PASS compare_recursive_invoices #7546 -> new: uniformly_better, paid delta', rep['delta_paid']) + for c, want in ((CLAIM, 'new_cost_lower'), (ABOVE, 'new_cost_higher'), (PR7481, 'new_cost_lower')): + r = tool('evaluate_recursive_power.py', zero, new, '--exponent', one_minus(c), '--bits', 256) + assert r['classification'] == want, (c, r['classification']) + print('PASS evaluate_recursive_power at C = %s (t = %s): %s' % (c, r['exponent'], want)) + print('PASS_PRICE kappa in (%s, %s)' % (CLAIM, ABOVE)) + + +if __name__ == '__main__': + sys.exit(main())