diff --git a/research/p440-decoded-pulse-replay/BENCHMARK.json b/research/p440-decoded-pulse-replay/BENCHMARK.json new file mode 100644 index 0000000000..cf8a2987f5 --- /dev/null +++ b/research/p440-decoded-pulse-replay/BENCHMARK.json @@ -0,0 +1,50 @@ +{ + "errors": 0, + "executable": "/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12", + "output_sha256": "326ee2369ed29383546225442e25d321af863233a19ca8772d4115a98351a8cb", + "platform": "macOS-27.0.1-arm64-arm-64bit", + "processor": "arm", + "python": "3.12.15 (main, Oct 14 2026, 00:55:37) [Clang 23.1.3 ]", + "reduction_percent": 15.90996246516788, + "samples_seconds": { + "baseline": [ + 5.824649709044024, + 5.885767083847895, + 5.675675584003329, + 5.892942500067875, + 5.941731208004057 + ], + "prepared": [ + 5.2083180418703705, + 4.884200790897012, + 4.952405916061252, + 4.796745708910748, + 4.949343750020489 + ] + }, + "seconds_saved": 0.9364233338274062, + "source_sha256": { + "SOURCES.json": "8a91cacee994531ace01574ebbe947197e6fdc6fb36112d898215e8e782ce214", + "benchmark.py": "3e41d47100a0c3eb14427b75166be9d0ae21eac1dfccc355eaa3136a4388b027", + "fast.py": "d86bc00ec132aa9f9061f3744108603135499cc93d2c8ad63a2758c7b808cbe7" + }, + "status": "PASS_COMPLETE_P440_TIMING", + "successful_complete_callers": 10, + "summary": { + "baseline": { + "median_seconds": 5.885767083847895, + "range_seconds": [ + 5.675675584003329, + 5.941731208004057 + ] + }, + "prepared": { + "median_seconds": 4.949343750020489, + "range_seconds": [ + 4.796745708910748, + 5.2083180418703705 + ] + } + }, + "workload": "unchanged PR1431 independent.main including all controls" +} diff --git a/research/p440-decoded-pulse-replay/README.md b/research/p440-decoded-pulse-replay/README.md new file mode 100644 index 0000000000..4a42195746 --- /dev/null +++ b/research/p440-decoded-pulse-replay/README.md @@ -0,0 +1,152 @@ +# Decode-once execution of the complete pivot-440 replay + +This contribution was produced by Nick Petalas. Apache-2.0. + +Scoped exact implementation improvement with a local performance measurement. +The complete PR1431 independent forward-pulse replay takes **15.91% less wall +time** in the recorded five-pair comparison. Its median falls from 5.886 s to +4.949 s. Every timed process completes the original caller and checks its saved +mathematical receipt. All ten stdout hashes agree. No new mathematical +obstruction, construction or kappa is claimed. + +The new opt-in command is [fast.py](fast.py). The frozen +[predecessor package](../complex-p440-window-shocks/README.md) is unchanged. +Hanson Sun's PR1431 supplies the mathematics, enumeration and independent +caller. This contribution changes how its fixed gates execute. + +## Exact change and retained coverage + +The original pulse interpreter reconstructs the same rational coefficient +each time it visits a gate. The new interpreter prepares one exact `Fraction` +per gate, retains every original gate field, and appends that coefficient. +It preserves the original state recurrence, every gate visit, every pulse cut, +zero removal and operation order. The complete original `main` still runs. +Preparation and source loading are inside the timed process. + +For one prepared gate, its saved coefficient equals the source's `amount(g)` +by construction. Starting with equal states, both interpreters add the same +pulses before a cut. Both then perform the same add or scale using that exact +coefficient and remove precisely the zero coordinates. Induction over all cuts, +including the terminal pulse cut, proves equal returned states. No sign, +integrality or nonzero-state hypothesis is needed. The window enumerator reads +only original fields, so its domain, order and response serialization agree. +This proof concerns the fixed interpreter contract, not the predecessor's +mathematical obstruction theorem. + +The complete source caller retains 2,757 nonzero windows, one zero window, +1,611 projective directions, all 5,177,758 classified span cases and the full +704-column dirty-input identity. It also retains the missing-close, +wrong-coefficient and omitted-fourth-window rejection controls. The source +checks the full window and direction digests and compares its complete result +with `INDEPENDENT.json`; comparing stdout alone is not the equality test. + +The new verifier additionally compares both interpreters on every word of +length zero through two from a 17-gate alphabet, three initial states and +every pulse cut. It rejects changed source bytes, an unknown gate, a zero +denominator and both gate-capacity violations. The normal and optimized +registered commands execute both complete callers, including all source +controls. The generated stdout receipt binds all eight package files. + +## Measurement + +[BENCHMARK.json](BENCHMARK.json) is the unedited generated timing receipt. +[benchmark.py](benchmark.py) runs five alternating baseline/prepared pairs in +fresh CPython processes. Both sides load the same source and execute the same +complete independent caller. Every subprocess must exit successfully, emit no +stderr and produce the matching success output. The receipt binds the source +manifest, implementation and harness hashes. Timing is opt-in; CI checks its +source bindings and correctness without imposing a machine-dependent speed +threshold. + +| Complete independent caller | Median | Observed range | +| --- | ---: | ---: | +| Original gate decoding | 5.886 s | 5.676 to 5.942 s | +| Prepared coefficients | 4.949 s | 4.797 to 5.208 s | + +Environment was CPython 3.12.15 on macOS 27.0.1 arm64. The machine reports +18 logical CPUs; the pre-run load averages were 2.61, 2.50 and 1.92. Other +research processes can run concurrently, so the samples alternate and the +claim is local to this measurement. The ranges do not overlap. There were +ten successful complete callers and zero errors. + +A separate instrumented profile put 21.961 of 22.601 seconds in +`direct_windows`, chiefly its 2,760 `run` calls. It observed 5,419,435 +`amount` calls. Profiling overhead is excluded from reported timings. Rational +state arithmetic and full gate traversal remain; the change does not remove +their cost. No timing claim covers the primary verifier, predecessor test +suite, other pivots or a full supplier replay. + +## Reproduce + +From the repository root, with the CPython 3.12 standard library: + +```sh +/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12 -I -W error -B research/p440-decoded-pulse-replay/fast.py +/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12 -I -W error -B research/p440-decoded-pulse-replay/verify.py +/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12 -I -O -W error -B research/p440-decoded-pulse-replay/verify.py +/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12 -B scripts/research_package.py --package research/p440-decoded-pulse-replay +/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12 -B scripts/check_research_commit.py --package research/p440-decoded-pulse-replay --check-source-history +``` + +Add `--baseline` to `fast.py` to run the unmodified interpreter. Run +`benchmark.py` with the same interpreter and flags to print a fresh timing +receipt. Another CPython 3.12 installation can replace the absolute path. +Use a scratch path outside the checkout for redirected output. + +The repository runner authenticates all four declared live inputs in +[SOURCES.json](SOURCES.json). Direct execution authenticates the interpreter +bytes and runs the source's word-hash and complete saved-receipt checks. +The selected record and original task catalogue are historical provenance. +The research base is `2485805a6d47f36ea83ddde6327d453ac82d44dc`, priority +revision 8. The selected-binding positive control passed; selected conditional +kappa stays `781451/250000000`. + +## Bounds and limitations + +This is one opt-in execution adapter, with no changes to shared code or frozen +sources. It does not discharge native, compiler, ownership, precision/tape or +analytic-recovery assumptions. No complete multiplication theorem follows. +Independent human and formal proof-kernel review are unclaimed. Lean, Docker, +selected supplier cold replay and a separate static analyzer were not run. + +New functions are under 60 lines. Preparation and execution accept at most +8,192 gates; the actual pulse sequences have 1,963 gates. The source word has +1,844 B gates and 6,800 cleanup gates, of which the caller selects 119. The +private interpreter receives only prepared source gates or the finite control +domain. Its state has at most 704 coordinates on the actual word. No recursion, +network access or file writes occur in the implementation or verifier. +Subprocess timeouts are 120 seconds and every return code is checked. + +Managed Python allocation is a bounded deviation from static memory allocation. +The fixed gate and coordinate domains bound live collections. Executing +authenticated source bytes and rebinding two names in one private module is a +bounded deviation from avoiding dynamic execution and dispatch. This preserves +the predecessor's complete caller without copying or editing it and bypasses +bytecode-cache reads. The changed-source control exercises that boundary. +The five immediately executed rejection callbacks are a bounded dispatch +deviation. Warning-strict normal and optimized runs and in-memory syntax checks +provide diagnostics. A larger domain, shared module or concurrent use of one +module instance requires a new contract; this package supplies none. + +## Open next questions + +- Can sparse zero-state handling reduce the remaining exact pulse cost? Begin + with a profile of the prepared complete caller and cancellation, scale-zero, + dirty-state and pulse-boundary tests. No such shortcut is supplied here. +- Should a maintained successor adopt this prepared execution? Begin with one + explicit caller and retain all four pinned inputs and full receipt checks. + The frozen source integration and broader workload measurements remain open. + +Structured relevance, first steps and blockers are in [TASK.json](TASK.json). + +## Credit + +Credit Hanson Sun / bbMisk for [PR1431](https://github.com/CrocSwap/integer-mult-bounds/pull/1431), +its exact window theorem, source interpreter, independent integer-rank caller +and saved receipts. `run` adapts that interpreter by saving each coefficient; +the new adapter, differential controls, harness and measurements are produced +by Nick Petalas. Marius-Paul Dumitrean / PR1337, Rohan Arun / PR1297, Jeremy +Kothe / PR1274 and the retained construction lineage keep their credit. Source +[notices](../complex-p440-window-shocks/NOTICE.md) and licenses remain applicable +and unchanged. Their mathematical results are predecessors, not new results of +this contribution. diff --git a/research/p440-decoded-pulse-replay/SOURCES.json b/research/p440-decoded-pulse-replay/SOURCES.json new file mode 100644 index 0000000000..8f7ddffebf --- /dev/null +++ b/research/p440-decoded-pulse-replay/SOURCES.json @@ -0,0 +1,42 @@ +{ + "schema_version": 1, + "base_commit": "2485805a6d47f36ea83ddde6327d453ac82d44dc", + "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" + }, + { + "path": "research/complex-p440-window-shocks/CERTIFICATE.json", + "usage": "input", + "git_blob": "755a9d42ad3e38f56f45de440373cad0ca722bab", + "sha256": "a1191a61c67c59b427248df99f0c54ca5a65ff02b2f8cf696d2d5fe56bacb06f" + }, + { + "path": "research/complex-p440-window-shocks/INDEPENDENT.json", + "usage": "input", + "git_blob": "0188ad39a2cb6a01624f7f16c8f4811cc30b8e51", + "sha256": "f740d76bcea452096b26166a06cf5f02ea370b377797c8d4615bf693af7d58ea" + }, + { + "path": "research/complex-p440-window-shocks/independent.py", + "usage": "input", + "git_blob": "220a634050fc4fef1195ca7edb792e753a0ee805", + "sha256": "f9013193a4e46aa045071f768c2815780b5a8051ff1158cd0ec917415ed1f941" + }, + { + "path": "research/complex-p440-window-shocks/inputs/BASE-WORD.json.gz", + "usage": "input", + "git_blob": "eacf8c773cb50637f93a762342b3b5f0853fe29a", + "sha256": "e8e6e78ff7422275c38324499e1f33fb2ecd30de9503aef2b8f1ee80d8c4df8e" + } + ] +} diff --git a/research/p440-decoded-pulse-replay/TASK.json b/research/p440-decoded-pulse-replay/TASK.json new file mode 100644 index 0000000000..f788ed8961 --- /dev/null +++ b/research/p440-decoded-pulse-replay/TASK.json @@ -0,0 +1,81 @@ +{ + "schema_version": 1, + "task_id": "replay-runtime", + "priority_revision": 8, + "base_commit": "2485805a6d47f36ea83ddde6327d453ac82d44dc", + "original_card": { + "id": "replay-runtime", + "question": "Can one measured replay bottleneck be sped up without dropping coverage?", + "starting_points": [ + "scripts/run_isolated_tests.py", + "scripts/verify_replay_coverage.py", + "certificates/selected-result.json" + ], + "methods": [ + "Profile one isolated replay and optimize the measured bottleneck.", + "Design source-bound reuse with explicit dependency invalidation and negative controls." + ], + "acceptance_gate": "Report before/after wall time on the same fixture, retained checks and invalidation behavior.", + "first_step": { + "command": [ + "python3", + "-B", + "scripts/research_selected_baseline.py" + ], + "expected": "PASS_RESEARCH_BASELINE_BINDINGS_ONLY", + "inspect": "Resolve the current selected review, separate complex/ordinary BIT/admitted BIT/outer budgets, and compare the card against live handoffs before starting. Historical ceilings require exact source/model equivalence.", + "scope": "Source-binding orientation only; not a scientific replay or all-size proof. Materialize selected inputs if this checkout is sparse." + }, + "first_experiment": "Measure one unchanged fixture, preserve check coverage, and test one optimization with invalidation controls.", + "bottleneck_link": "Faster trustworthy replays increase review throughput and let mechanism candidates be checked sooner.", + "allowed_variations": [ + "Profile one stage or design one source-bound cache boundary." + ], + "scope_change_triggers": [ + "Skipping coverage or comparing different fixtures to claim speedup." + ], + "overlap_terms": [ + "replay runtime", + "cache invalidation", + "isolated tests" + ] + }, + "scope_status": "refined", + "actual_scope": "Decode-once exact gates for the complete PR1431 pivot-440 independent forward-pulse replay, with unchanged mathematical predicates and measured full-caller wall time.", + "scope_change_reason": "The runtime card is narrowed to one complete independent caller. The predecessor obstruction is cited and retained, not independently audited as the deliverable.", + "bottleneck_link": "The complex supplier depends on exact dirty-helper and restoration checks. Reducing complete replay friction makes those checks cheaper without claiming a better paid moment or kappa.", + "budget_minutes": 60, + "stop_rule": "Stop after the first complete-caller improvement that exceeds timing noise and passes exact differential and invalidation controls. Do not optimize another mechanism or extend the mathematical census.", + "outcome": "completed", + "evidence": "BENCHMARK.json records ten successful complete callers in alternating fresh processes with equal output hashes. verify.py checks the exact pulse recurrence, source invalidation, and both complete callers against the retained receipts.", + "author": "Nick Petalas", + "ai_assistance": "Independent human and formal proof-kernel review are unclaimed.", + "open_questions": [ + { + "question": "Can exact sparse-state zero handling reduce the remaining pulse propagation cost while preserving every source operation and pulse cut?", + "why_it_matters": "Fraction arithmetic and the full gate traversal remain the dominant work after decoding is removed.", + "first_step": "Profile the prepared complete caller and test any zero shortcut against cancellation, scale-zero, dirty-state and pulse-boundary cases.", + "blocked_by": "No such shortcut is implemented or measured here." + }, + { + "question": "Should this prepared execution replace the source command in a separately maintained successor?", + "why_it_matters": "The frozen source is unchanged and the faster command is currently opt-in.", + "first_step": "Choose an explicit maintained caller and retain all four source dependencies and the complete saved-receipt checks.", + "blocked_by": "No source-package integration or broader workload timing is supplied." + } + ], + "claim_url": "https://github.com/CrocSwap/integer-mult-bounds/discussions/1166#discussioncomment-19294840", + "predecessor": { + "pr": 1431, + "author": "Hanson Sun / bbMisk", + "path": "research/complex-p440-window-shocks", + "relation": "Implementation performance contribution; no new mathematical obstruction." + }, + "publication_context": { + "upstream_main": "2485805a6d47f36ea83ddde6327d453ac82d44dc", + "priority_revision": 8, + "selected_kappa": "781451/250000000", + "overlap_coverage": "333 open PRs and 6059 Discussion records with complete remote pagination; 91 of 8722 local HEAD notes searched, supplemented by targeted all-main README and merged-PR searches. Unpublished work and arbitrary historical diffs remain outside coverage.", + "selected_binding_control": "PASS_RESEARCH_BASELINE_BINDINGS_ONLY" + } +} diff --git a/research/p440-decoded-pulse-replay/VERIFY.json b/research/p440-decoded-pulse-replay/VERIFY.json new file mode 100644 index 0000000000..b6219bba10 --- /dev/null +++ b/research/p440-decoded-pulse-replay/VERIFY.json @@ -0,0 +1,39 @@ +{ + "schema_version": 1, + "status": "ready", + "python": "3.12", + "requirements": [], + "inputs": [ + "research/complex-p440-window-shocks/CERTIFICATE.json", + "research/complex-p440-window-shocks/INDEPENDENT.json", + "research/complex-p440-window-shocks/independent.py", + "research/complex-p440-window-shocks/inputs/BASE-WORD.json.gz" + ], + "commands": [ + { + "argv": [ + "{python}", + "-I", + "-W", + "error", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 180, + "checks": "Exact differential pulse recurrence, changed-source and boundary rejection, both unchanged complete callers and saved receipts." + }, + { + "argv": [ + "{python}", + "-I", + "-O", + "-W", + "error", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 180, + "checks": "The same complete exact and rejection checks under optimized Python, including optimized child interpreters." + } + ] +} diff --git a/research/p440-decoded-pulse-replay/benchmark.py b/research/p440-decoded-pulse-replay/benchmark.py new file mode 100644 index 0000000000..9fba523178 --- /dev/null +++ b/research/p440-decoded-pulse-replay/benchmark.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""Time fresh complete baseline/changed callers in alternating order.""" + +import hashlib +import json +from pathlib import Path +import platform +import statistics +import subprocess +import sys +import time + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] + + +def main(): + samples = {"baseline": [], "prepared": []} + output_hashes = set() + for _ in range(5): + for mode in samples: + command = [sys.executable, "-I", "-W", "error", "-B", str(HERE / "fast.py")] + if mode == "baseline": + command.append("--baseline") + start = time.perf_counter() + result = subprocess.run(command, cwd=ROOT, capture_output=True, + timeout=120, check=True) + elapsed = time.perf_counter() - start + if result.stderr or not result.stdout.startswith(b"PASS_INDEPENDENT_P440_"): + raise ValueError("complete caller did not succeed cleanly") + samples[mode].append(elapsed) + output_hashes.add(hashlib.sha256(result.stdout).hexdigest()) + if len(output_hashes) != 1: + raise ValueError("complete caller outputs differ") + summary = {mode: {"median_seconds": statistics.median(values), + "range_seconds": [min(values), max(values)]} + for mode, values in samples.items()} + names = ["fast.py", "benchmark.py", "SOURCES.json"] + hashes = {name: hashlib.sha256((HERE / name).read_bytes()).hexdigest() for name in names} + baseline = summary["baseline"]["median_seconds"] + prepared = summary["prepared"]["median_seconds"] + print(json.dumps({"status": "PASS_COMPLETE_P440_TIMING", "samples_seconds": samples, + "summary": summary, "seconds_saved": baseline - prepared, + "reduction_percent": 100 * (baseline - prepared) / baseline, + "successful_complete_callers": 10, "errors": 0, + "output_sha256": next(iter(output_hashes)), "source_sha256": hashes, + "python": sys.version, "platform": platform.platform(), + "processor": platform.processor(), "executable": sys.executable, + "workload": "unchanged PR1431 independent.main including all controls"}, + indent=2, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/research/p440-decoded-pulse-replay/fast.py b/research/p440-decoded-pulse-replay/fast.py new file mode 100644 index 0000000000..638a848d60 --- /dev/null +++ b/research/p440-decoded-pulse-replay/fast.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""Decode each fixed gate once before PR1431's complete forward-pulse replay. + +Produced by Nick Petalas. The pulse interpreter adapts Hanson Sun's PR1431 +independent.py; that source and its complete caller remain unchanged. +""" + +import argparse +from fractions import Fraction +import hashlib +from pathlib import Path +import sys +from types import ModuleType + +HERE = Path(__file__).resolve().parent +SOURCE = HERE.parent / "complex-p440-window-shocks" / "independent.py" +SOURCE_SHA256 = "f9013193a4e46aa045071f768c2815780b5a8051ff1158cd0ec917415ed1f941" + + +def load_source(raw=None): + """Execute authenticated source bytes, without reading a bytecode cache.""" + data = SOURCE.read_bytes() if raw is None else raw + if hashlib.sha256(data).hexdigest() != SOURCE_SHA256: + raise ValueError("retained interpreter source hash mismatch") + module = ModuleType("p440_retained_independent") + module.__file__ = str(SOURCE) + exec(compile(data, str(SOURCE), "exec"), module.__dict__) + return module + + +def prepare(gates): + """Retain original fields and append the immutable exact coefficient.""" + if len(gates) > 8192: + raise ValueError("gate count exceeds the prepared replay contract") + out = [] + for gate in gates: + if gate is None: + out.append(None) + elif gate[0] == "add" and len(gate) in (5, 6): + out.append((*gate, Fraction(gate[3], gate[4]))) + elif gate[0] == "scale" and len(gate) in (4, 5): + out.append((*gate, Fraction(gate[2], gate[3]))) + else: + raise ValueError("invalid gate") + return tuple(out) + + +def run(gates, initial, pulses=None): + """The source's state recurrence with a coefficient read, not a decode.""" + if len(gates) > 8192: + raise ValueError("gate count exceeds the prepared replay contract") + state = dict(initial) + pulses = pulses or {} + for index in range(len(gates) + 1): + for donor, change in pulses.get(index, []): + state[donor] = state.get(donor, 0) + change + if not state[donor]: + del state[donor] + if index == len(gates) or gates[index] is None: + continue + gate = gates[index] + value = state.get(gate[1], 0) + coefficient = gate[-1] + value = (value + coefficient * state.get(gate[2], 0) + if gate[0] == "add" else coefficient * value) + if value: + state[gate[1]] = value + else: + state.pop(gate[1], None) + return state + + +def install(module): + """Bind a private caller instance; no source file or shared module changes.""" + original = module.direct_windows + + def direct_windows(word): + prepared = dict(word) + prepared["B"] = list(prepare(word["B"])) + prepared["cleanup"] = list(prepare(word["cleanup"])) + return original(prepared) + + module.run = run + module.direct_windows = direct_windows + return module + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--baseline", action="store_true") + args = parser.parse_args() + module = load_source() + if not args.baseline: + install(module) + sys.argv = [str(SOURCE)] + module.main() + + +if __name__ == "__main__": + main() diff --git a/research/p440-decoded-pulse-replay/verify.py b/research/p440-decoded-pulse-replay/verify.py new file mode 100644 index 0000000000..8b2c815963 --- /dev/null +++ b/research/p440-decoded-pulse-replay/verify.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""Exact differential controls and unchanged complete-caller execution.""" + +from fractions import Fraction +import hashlib +import importlib.util +from itertools import product +import json +from pathlib import Path +import subprocess +import sys + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] + + +def load_fast(): + path = HERE / "fast.py" + spec = importlib.util.spec_from_file_location("p440_prepared", path) + module = importlib.util.module_from_spec(spec) + exec(compile(path.read_bytes(), str(path), "exec"), module.__dict__) + return module + + +def require(ok, reason): + if not ok: + raise ValueError(reason) + + +def differential_controls(fast): + source = fast.load_source() + gates = [None] + for target in range(2): + for coefficient in (Fraction(-2), Fraction(-1, 2), Fraction(0), Fraction(1, 2), Fraction(2)): + gates.append(["add", target, 1 - target, coefficient.numerator, + coefficient.denominator, [7]]) + for coefficient in (-1, 0, 2): + gates.append(["scale", target, coefficient, 1, [7]]) + cases = 0 + for length in range(3): + for word in product(gates, repeat=length): + prepared = fast.prepare(word) + for initial in ({}, {0: Fraction(1, 3)}, {0: Fraction(-2), 1: Fraction(3, 2)}): + for cut in range(length + 1): + pulses = {cut: [(0, Fraction(1, 2)), (1, Fraction(-1, 3))]} + expected = source.run(word, initial, pulses) + require(fast.run(prepared, initial, pulses) == expected, "pulse recurrence differs") + cases += 1 + return cases + + +def rejection_controls(fast): + controls = [lambda: fast.load_source(fast.SOURCE.read_bytes() + b"\n"), + lambda: fast.prepare([["other", 0, 1, 1]]), + lambda: fast.prepare([["add", 0, 1, 1, 0]]), + lambda: fast.prepare([None] * 8193), + lambda: fast.run([None] * 8193, {})] + for control in controls: + try: + control() + except (ValueError, ZeroDivisionError): + continue + raise ValueError("source or gate boundary mutation was accepted") + return len(controls) + + +def complete_callers(): + outputs = [] + for baseline in (True, False): + command = [sys.executable, "-I", "-W", "error", "-B", str(HERE / "fast.py")] + if sys.flags.optimize: + command.insert(1, "-O") + if baseline: + command.append("--baseline") + result = subprocess.run(command, cwd=ROOT, capture_output=True, timeout=120, check=True) + require(not result.stderr, "complete caller emitted diagnostics") + require(result.stdout.startswith(b"PASS_INDEPENDENT_P440_"), "missing complete success") + outputs.append(result.stdout) + require(outputs[0] == outputs[1], "complete caller output differs") + return hashlib.sha256(outputs[0]).hexdigest() + + +def check_benchmark(output): + receipt = json.loads((HERE / "BENCHMARK.json").read_text()) + require(receipt["output_sha256"] == output, "timed caller output differs") + require(receipt["errors"] == 0 and receipt["successful_complete_callers"] == 10, + "timing receipt did not complete every caller") + for name, expected in receipt["source_sha256"].items(): + require(name in ("fast.py", "benchmark.py", "SOURCES.json"), "unknown timing source") + require(hashlib.sha256((HERE / name).read_bytes()).hexdigest() == expected, + "timing source changed") + require(set(receipt["source_sha256"]) == {"fast.py", "benchmark.py", "SOURCES.json"}, + "timing source coverage missing") + for values in receipt["samples_seconds"].values(): + require(len(values) == 5 and all(0 < value < 120 for value in values), + "invalid complete-caller timing samples") + + +def main(): + fast = load_fast() + cases = differential_controls(fast) + controls = rejection_controls(fast) + output = complete_callers() + check_benchmark(output) + names = ["README.md", "TASK.json", "SOURCES.json", "VERIFY.json", "fast.py", + "verify.py", "benchmark.py", "BENCHMARK.json"] + hashes = {name: hashlib.sha256((HERE / name).read_bytes()).hexdigest() for name in names} + print(json.dumps({"status": "PASS_P440_PREPARED_REPLAY", "differential_cases": cases, + "rejection_controls": controls, "complete_callers": 2, + "output_sha256": output, "package_sha256": hashes}, sort_keys=True)) + + +if __name__ == "__main__": + main()