diff --git a/research/p112-free-sink-audit97/README.md b/research/p112-free-sink-audit97/README.md index 37a680358a..2812c62046 100644 --- a/research/p112-free-sink-audit97/README.md +++ b/research/p112-free-sink-audit97/README.md @@ -26,6 +26,11 @@ histogram and 4,030 minors. Controls report `mathematical=6 package=5`. Python standard library only; no solver, NumPy or native compiler required. Use `verify.py --write` to regenerate the certificate. +After `research/p112-signed-modular-production/`, `independent.py` uses the +proved modulo-521 signed recovery for eligible minors (identical receipts; +rational fallback retained). Pairwise Fraction-only bytes are vendored in that +production package's `baseline.py`. + The immutable input inventory in SOURCES.json is exact: missing or extra entries fail. Text hashes normalize CRLF to LF. BASE-SELECTED.json freezes context at base `2921874911956718fcaaaf9396fe8267b3cfa9f0`; replay does not diff --git a/research/p112-free-sink-audit97/independent.py b/research/p112-free-sink-audit97/independent.py index c65f3fbfe1..2fcfc41e72 100644 --- a/research/p112-free-sink-audit97/independent.py +++ b/research/p112-free-sink-audit97/independent.py @@ -3,6 +3,12 @@ The source-pin and geometry readers are shared, but this checker does not call the producer's row-code basis, modular elimination, Bareiss or build. Contributor @woklerx with substantial OpenAI Codex assistance. + +Production path: after research/p112-signed-modular-production/, +fraction_determinant uses the proved modulo-521 signed recovery from +research/p112-signed-modular86/ when rows are eligible, with the original +rational elimination retained as fallback. Pairwise Fraction-only bytes are +vendored in that production package's baseline.py. """ import importlib.util import json @@ -16,8 +22,12 @@ spec.loader.exec_module(source) require = source.require +PRIME = 521 +if not all(PRIME % d for d in range(2, 23)): + raise ValueError('fixed modulus is not prime') -def fraction_determinant(rows): + +def rational_determinant(rows): a = [list(map(Fraction, row)) for row in rows] answer = Fraction(1) for col in range(len(a)): @@ -37,6 +47,52 @@ def fraction_determinant(rows): return int(answer) +def _eligible(rows): + n = len(rows) + return n <= 8 and all( + len(row) == n and all(type(x) is int for x in row) and sum(x * x for x in row) <= 4 + for row in rows + ) + + +def _recover(residue, modulus, bound): + if modulus <= 2 * bound or not 0 <= residue < modulus: + raise ValueError('insufficient modulus or invalid residue') + result = residue if residue <= modulus // 2 else residue - modulus + if abs(result) > bound: + raise ValueError('balanced determinant exceeds checked Hadamard bound') + return result + + +def _modular_determinant(rows): + n = len(rows) + a = [[x % PRIME for x in row] for row in rows] + answer = 1 + for k in range(n): + pivot = next((i for i in range(k, n) if a[i][k]), None) + if pivot is None: + return 0 + if pivot != k: + a[k], a[pivot] = a[pivot], a[k] + answer = -answer + value = a[k][k] + answer = answer * value % PRIME + inv = pow(value, -1, PRIME) + for i in range(k + 1, n): + factor = a[i][k] * inv % PRIME + if factor: + for j in range(k + 1, n): + a[i][j] = (a[i][j] - factor * a[k][j]) % PRIME + a[i][k] = 0 + return _recover(answer, PRIME, 2 ** n) + + +def fraction_determinant(rows): + if not _eligible(rows): + return rational_determinant(rows) + return _modular_determinant(rows) + + def audit(certificate): lines, decoder = source.geometry() words = {0} diff --git a/research/p112-signed-modular-production/NOTICE.md b/research/p112-signed-modular-production/NOTICE.md new file mode 100644 index 0000000000..dabed1632d --- /dev/null +++ b/research/p112-signed-modular-production/NOTICE.md @@ -0,0 +1,17 @@ +# Notice + +Production wiring of the proved modulo-521 signed-determinant kernel into +`research/p112-free-sink-audit97/independent.py`. + +## Credit + +- woklerx / [CrocSwap/integer-mult-bounds#1144](https://github.com/CrocSwap/integer-mult-bounds/pull/1144) + (`research/p112-signed-modular86/`): proved opt-in modulo-521 recovery with + identical free-sink audit receipts and Hadamard envelope controls. +- woklerx / [CrocSwap/integer-mult-bounds#1035](https://github.com/CrocSwap/integer-mult-bounds/pull/1035) + (`research/p112-free-sink-audit97/`): exact independent Fraction audit. +- Joel Pulikkan (PR620) and DreamingOfClouds (PR595): free-sink geometry model. +- martinxxx9 (PR976): related modular rank acceleration for a different auditor. + +Prepared by Wentao Li (VictorLiwentao, @Is__Victor, wentaol4@illinois.edu) +with substantial AI assistance. Apache-2.0. diff --git a/research/p112-signed-modular-production/README.md b/research/p112-signed-modular-production/README.md new file mode 100644 index 0000000000..698b23b033 --- /dev/null +++ b/research/p112-signed-modular-production/README.md @@ -0,0 +1,96 @@ +# Production signed modular determinants for the P112 free-sink audit + +**Tooling improvement; no new kappa.** At base +`0b1cccf86e2f5132ed286a26ef0a681a495740ea`, +`research/p112-free-sink-audit97/independent.py` still computed every signed +minor with rational `Fraction` elimination. woklerx’s opt-in adapter +`research/p112-signed-modular86/` (incorporated +[#1144](https://github.com/CrocSwap/integer-mult-bounds/pull/1144)) already +proved a modulo-521 kernel that recovers each full signed determinant inside a +checked Hadamard envelope, with identical complete audit receipts. This package +wires that equivalent rewrite into the **production** independent checker. + +The original rational elimination is retained as `rational_determinant` and as +the fallback for rows outside the envelope. Pairwise Fraction-only bytes are +vendored in `baseline.py`. The opt-in package vendors the same baseline for its +reference engine. + +## Reproduce + +Python **3.12**, standard library only, from the repository root: + +```sh +python3.12 -I -B research/p112-signed-modular-production/verify.py +python3.12 -I -O -B research/p112-signed-modular-production/verify.py +python3.12 -B scripts/research_package.py --package research/p112-signed-modular-production +taskset -c 0 python3.12 -I -B research/p112-signed-modular-production/benchmark.py --rounds 5 --write-result +``` + +Expected: + +```text +PASS_P112_SIGNED_MODULAR_PRODUCTION cases=28560 minors=4030 signed_matrices=19767 controls=… no_new_kappa +PASS_REGISTERED_RESEARCH_PACKAGE research/p112-signed-modular-production outcome=completed +PASS_IDENTICAL_P112_SIGNED_MODULAR_PRODUCTION_RECEIPTS +``` + +Default verify is read-only. Temp-copy certificate determinant-flip foil rejects +via audit failure. Package gates under `-O` still load checkers with +`compile(..., optimize=0)`. Full `make verify`, selected cold replay, Lean, and +multiplication-theorem obligations were not rerun for this isolated +historical-checker change. + +## Result + +On Linux / CPython 3.12.3 with `taskset -c 0`, five alternating in-process pairs +over the complete 28,560-case / 4,030-minor audit gave median wall time +**0.681 → 0.143 s (4.754×)** with per-round ratios **4.618–4.880×**. Details are +in [`RESULT.json`](RESULT.json). Timing is host-descriptive and is not a +correctness gate. Every audit receipt matches the pairwise baseline. + +## Why the modular path is equivalent + +Every frozen square minor has dimension at most eight and integer rows of +squared Euclidean norm at most four. Hadamard’s inequality gives +`|det A| ≤ 2^n ≤ 256`. Modulus 521 is prime and greater than twice 256, so +balanced modular recovery uniquely determines the signed integer determinant. +Inputs outside the envelope retain the original rational routine. See +`research/p112-signed-modular86/PROOF.md`. + +## Open next questions + +1. **Question:** Should other historical Fraction-only minor auditors that share + the same E8 root-line envelope adopt the same modulo-521 recovery? + **Why it matters:** Related sink / joint-frame auditors still pay rational + elimination on bounded integer minors. + **First step:** List auditors that already check `n≤8` and row-norm `≤4` on + every fast-path call. + **Blocked by:** One-object stop rule. + +2. **Question:** Should `research/p112-signed-modular86` be marked superseded as + an opt-in monkey-patch now that production ships the modular path? + **Why it matters:** The opt-in still usefully vendors the Fraction baseline + and engine controls. + **First step:** Decide whether maintainers prefer a provenance note or a + soft-deprecation banner. + **Blocked by:** Maintainer preference. + +## Overlap and credit + +Closest priors (different delivery): + +- `research/p112-signed-modular86/` / [#1144](https://github.com/CrocSwap/integer-mult-bounds/pull/1144) + — opt-in modulo-521 signed recovery; this is the production wiring. +- [CrocSwap/integer-mult-bounds#756](https://github.com/CrocSwap/integer-mult-bounds/pull/756) + — identical-receipt tooling quality bar. +- Leave-alone tooling through [#2412](https://github.com/CrocSwap/integer-mult-bounds/pull/2412) + and pending `cursor/omission-lanes-production-60b9` / deferred + `ck-dyadic-replay-production` / `scalar-fused-dyadic-production` were not + reopened. Related mod-101 rank work (#976) does not recover these signed + determinants. + +Credit Joel Pulikkan / DreamingOfClouds (geometry), woklerx (exact free-sink +audit and opt-in modular kernel), and martinxxx9 (related modular rank tooling). +Prepared by Wentao Li ([VictorLiwentao](https://github.com/VictorLiwentao), +[Is__Victor](https://x.com/Is__Victor)) with substantial AI assistance. +Apache-2.0. diff --git a/research/p112-signed-modular-production/RESULT.json b/research/p112-signed-modular-production/RESULT.json new file mode 100644 index 0000000000..4f65dfa809 --- /dev/null +++ b/research/p112-signed-modular-production/RESULT.json @@ -0,0 +1,47 @@ +{ + "schema_version": 1, + "status": "PASS_IDENTICAL_P112_SIGNED_MODULAR_PRODUCTION_RECEIPTS", + "package": "research/p112-signed-modular-production", + "base_commit": "0b1cccf86e2f5132ed286a26ef0a681a495740ea", + "workload": "complete P112 free-sink independent audit (28560 cases, 4030 signed minors)", + "rounds": 5, + "baseline_seconds": [ + 0.6967329520000476, + 0.6670023249999986, + 0.6874446699999908, + 0.67393680400005, + 0.6814277839999932 + ], + "production_seconds": [ + 0.1427796609999632, + 0.14443707299994912, + 0.14335003200005758, + 0.1412491000000955, + 0.14388054099993042 + ], + "per_round_ratio": [ + 4.879777323467851, + 4.61794407174281, + 4.795566909951681, + 4.771264411593378, + 4.736066317684493 + ], + "median_baseline_seconds": 0.6814277839999932, + "median_production_seconds": 0.14335003200005758, + "median_speedup": 4.7535935255300075, + "min_per_round_ratio": 4.61794407174281, + "max_per_round_ratio": 4.879777323467851, + "audit_receipt": { + "cases": 28560, + "rank_histogram": { + "7": 448, + "8": 28112 + }, + "exact_minors": 4030 + }, + "baseline_sha256": "46806efe1ee7744c810a69981d471b42dfceaa336fee226991c55ba1edfd129f", + "production_sha256": "c77cf3dd1234c26cfb7df2d356752721e8b1b37169f20543678fe2f4d07a53f8", + "python": "3.12.3 (main, Aug 31 2026, 10:18:26) [GCC 13.3.0]", + "platform": "Linux-6.12.94+-x86_64-with-glibc2.39", + "note": "Host-descriptive; not a correctness gate. Times cover audit() after module load (geometry, code coverage, all exact minors/cases); exclude interpreter startup and package pin hashing. Receipts identical each round." +} diff --git a/research/p112-signed-modular-production/SOURCES.json b/research/p112-signed-modular-production/SOURCES.json new file mode 100644 index 0000000000..ce2a405818 --- /dev/null +++ b/research/p112-signed-modular-production/SOURCES.json @@ -0,0 +1,43 @@ +{ + "schema_version": 1, + "base_commit": "0b1cccf86e2f5132ed286a26ef0a681a495740ea", + "files": [ + { + "path": "certificates/selected-result.json", + "usage": "provenance", + "git_blob": "ae6a99f28aa468649eb66a361e764d769363bf11", + "sha256": "10b9e340fd8e354a37a0c4813c90e5de1dd42044b5f6aca4a3fc5a42b685fa32" + }, + { + "path": "docs/research/agent-task-catalog.json", + "usage": "provenance", + "git_blob": "06c96f5579bb67ed1b86d334e78fbed7da6945f1", + "sha256": "6686ad58f1fbdbc87134a78901b60fd53a20d3984355e91defbbebc9e9fa8075" + }, + { + "path": "research/p112-free-sink-audit97/independent.py", + "usage": "provenance", + "git_blob": "c65f3fbfe130a4f8cf07b9d2fa4d180cde2957c5", + "sha256": "46806efe1ee7744c810a69981d471b42dfceaa336fee226991c55ba1edfd129f", + "note": "Pairwise-era Fraction-only bytes at base_commit; working tree carries the modulo-521 rewrite. Live equivalence uses package baseline.py plus working production path." + }, + { + "path": "research/p112-free-sink-audit97/CERTIFICATE.json", + "usage": "input", + "git_blob": "fd4959b7d21eb835f6638a4ead69125891b2297b", + "sha256": "45abf8c46b54ab752a16573cc6e03a225a6d76a853b093f186d52bd2b51ec9c6" + }, + { + "path": "research/p112-free-sink-audit97/verify.py", + "usage": "input", + "git_blob": "686a8fd137da8a406a552064cb9312a3930bc2d3", + "sha256": "91dbe1ad0fa7c4b46ef571cccb7eb5f7a2239995f889147277ea6719674adc5b" + }, + { + "path": "research/p112-signed-modular86/engine.py", + "usage": "input", + "git_blob": "ed6238bf53751e319a88e5d65cc5c3b040740745", + "sha256": "b74c6dd99e9cad0eb4cb252c810acea74c1cba979c7766d194933e4bc35a35fa" + } + ] +} diff --git a/research/p112-signed-modular-production/TASK.json b/research/p112-signed-modular-production/TASK.json new file mode 100644 index 0000000000..45794211ae --- /dev/null +++ b/research/p112-signed-modular-production/TASK.json @@ -0,0 +1,70 @@ +{ + "schema_version": 1, + "task_id": "replay-runtime", + "priority_revision": 4, + "base_commit": "0b1cccf86e2f5132ed286a26ef0a681a495740ea", + "chooser_seed": "8855876a99eb27f1d1fbdeca162a1663", + "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_baseline.py" + ], + "expected": "PASS_RESEARCH_BASELINE_BINDINGS_ONLY", + "inspect": "Read the selected reproduction command and choose a single replay stage for profiling.", + "scope": "Positive control / source-bound orientation only; this is not a new construction or full cold replay." + }, + "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": "Can the production p112-free-sink-audit97 independent.py adopt the proved modulo-521 signed-determinant kernel from research/p112-signed-modular86/ so the shipped free-sink audit is faster while every case/minor receipt stays identical, without reopening leave-alone tooling through #2412 or pending omission-lanes / deferred dyadic production packages?", + "scope_change_reason": "The catalogue card asks for one measured replay bottleneck with before/after wall time and retained checks. Expertise override selected verifier-engineering after surveying remaining proved opt-in adapters. Leave-alone objects through #2412, pending cursor/omission-lanes-production-60b9, and deferred ck-dyadic-replay-production / scalar-fused-dyadic-production were skipped. woklerx's merged #1144 opt-in already proved ~3.87\u00d7 (host remeasure ~4.4\u00d7) with identical receipts; production independent.py still used Fraction elimination. This session wires that equivalent rewrite into the shipped checker, vendors pairwise baseline bytes, and retargets the opt-in reference to the vendored baseline.", + "bottleneck_link": "Side result on review throughput: the P112 free-sink independent audit is reused by historical sink tooling. A faster identical receipt does not change kappa or the binding complex supplier.", + "budget_minutes": 60, + "stop_rule": "Ship an equivalence-preserving production independent.py modular-determinant change with frozen baseline, identical audit outcomes, corruption controls, pin discipline, registered replay and a measured before/after median clearly above ~1.5\u00d7 with stable per-round ratios. Do not invent kappa, reopen leave-alone objects, or open an upstream CrocSwap PR from this worker.", + "outcome": "completed", + "evidence": "PASS_P112_SIGNED_MODULAR_PRODUCTION via research/p112-signed-modular-production/verify.py (also under -O); PASS_REGISTERED_RESEARCH_PACKAGE; PASS_IDENTICAL_P112_SIGNED_MODULAR_PRODUCTION_RECEIPTS via pinned-CPU benchmark.py --rounds 5 (median 0.681\u21920.143 s, 4.754\u00d7; per-round 4.618\u20134.880\u00d7); opt-in p112-signed-modular86 retargeted to vendored baseline.py.", + "author": "Wentao Li", + "github": "VictorLiwentao", + "email": "wentaol4@illinois.edu", + "ai_assistance": "Substantial AI assistance for orientation, overlap search, profiling, production wiring, packaging, benchmarking and writing. Not independent human peer review.", + "open_questions": [ + { + "question": "Should other historical Fraction-only minor auditors that share the same E8 root-line envelope adopt the same modulo-521 recovery?", + "why_it_matters": "Related sink / joint-frame auditors still pay rational elimination on bounded integer minors.", + "first_step": "List auditors that already check n\u22648 and row-norm \u22644 on every fast-path call.", + "blocked_by": "Out of this session's one-object stop rule." + }, + { + "question": "Should research/p112-signed-modular86 be marked superseded as an opt-in monkey-patch now that production ships the modular path?", + "why_it_matters": "The opt-in still usefully vendors the Fraction baseline and engine controls.", + "first_step": "Decide whether maintainers prefer a provenance note or a soft-deprecation banner.", + "blocked_by": "Maintainer preference." + } + ] +} diff --git a/research/p112-signed-modular-production/VERIFY.json b/research/p112-signed-modular-production/VERIFY.json new file mode 100644 index 0000000000..eba5d9d2a9 --- /dev/null +++ b/research/p112-signed-modular-production/VERIFY.json @@ -0,0 +1,25 @@ +{ + "schema_version": 1, + "status": "ready", + "python": "3.12", + "requirements": [], + "inputs": [ + "research/p112-signed-modular-production/baseline.py", + "research/p112-free-sink-audit97/independent.py", + "research/p112-free-sink-audit97/CERTIFICATE.json", + "research/p112-free-sink-audit97/verify.py", + "research/p112-signed-modular86/engine.py" + ], + "commands": [ + { + "argv": ["{python}", "-I", "-B", "{package}/verify.py"], + "timeout_seconds": 300, + "checks": "Exact baseline copy of the base-commit independent.py; production equals the modulo-521 transform; identical complete audit outcomes; temp-copy certificate determinant-flip corruption control; duplicate JSON-key check; read-only default verify." + }, + { + "argv": ["{python}", "-I", "-O", "-B", "{package}/verify.py"], + "timeout_seconds": 300, + "checks": "Same equivalence and pin discipline under -O (require() gates remain; checkers load with compile(..., optimize=0))." + } + ] +} diff --git a/research/p112-signed-modular-production/baseline.py b/research/p112-signed-modular-production/baseline.py new file mode 100644 index 0000000000..c65f3fbfe1 --- /dev/null +++ b/research/p112-signed-modular-production/baseline.py @@ -0,0 +1,94 @@ +"""Independent Fraction minor checks and full row-code coverage, Apache-2.0. + +The source-pin and geometry readers are shared, but this checker does not +call the producer's row-code basis, modular elimination, Bareiss or build. +Contributor @woklerx with substantial OpenAI Codex assistance. +""" +import importlib.util +import json +from collections import Counter +from fractions import Fraction +from pathlib import Path + +HERE = Path(__file__).resolve().parent +spec = importlib.util.spec_from_file_location('sink_sources', HERE / 'verify.py') +source = importlib.util.module_from_spec(spec) +spec.loader.exec_module(source) +require = source.require + + +def fraction_determinant(rows): + a = [list(map(Fraction, row)) for row in rows] + answer = Fraction(1) + for col in range(len(a)): + pivot = next((i for i in range(col, len(a)) if a[i][col]), None) + if pivot is None: + return 0 + if pivot != col: + a[pivot], a[col] = a[col], a[pivot] + answer *= -1 + value = a[col][col] + answer *= value + for i in range(col + 1, len(a)): + scale = a[i][col] / value + for j in range(col + 1, len(a)): + a[i][j] -= scale * a[col][j] + require(answer.denominator == 1, 'integer determinant') + return int(answer) + + +def audit(certificate): + lines, decoder = source.geometry() + words = {0} + for row in decoder: + words |= {word ^ row for word in words} + require(len(words) == 512, 'full decoder row code') + records = certificate['patterns'] + require(len(records) == 511, 'pattern count') + require({int(r['pattern'], 16) for r in records} == words - {0}, 'pattern coverage') + minors = {} + for record in certificate['minors']: + indices, columns = record['rows'], record['columns'] + require(all(type(i) is int and 0 <= i < 120 for i in indices), 'minor row indices') + require(all(type(i) is int and 0 <= i < 8 for i in columns), 'minor column indices') + require(len(indices) == len(columns) and len(set(indices)) == len(indices) + and len(set(columns)) == len(columns), 'square distinct minor') + key = (tuple(indices), tuple(columns)) + require(key not in minors, 'duplicate minor') + value = fraction_determinant([[lines[i][j] for j in columns] for i in indices]) + require(type(record['determinant']) is int and value == record['determinant'] != 0, 'invalid exact minor') + minors[key] = value + cases, ranks, used = 0, Counter(), set() + for record in records: + word = int(record['pattern'], 16) + support = {i for i in range(8, 120) if word >> i & 1} + base, columns, rank = record['base'], record['columns'], record['rank'] + require(type(rank) is int and len(base) == len(columns) == rank, 'rank declaration') + if rank == 7: + missing = set(range(8)) - set(columns) + require(len(missing) == 1, 'coordinate hyperplane shape') + coordinate = next(iter(missing)) + require(word == decoder[coordinate] and all(lines[i][coordinate] == 0 for i in support), 'rank-seven upper bound') + else: + require(rank == 8 and columns == list(range(8)), 'ambient rank-eight upper bound') + alternatives = {i for i in support if word != decoder[i]} + require(set(record['repairs']) == {str(i) for i in alternatives if i in base}, 'repair inventory') + for target in alternatives: + chosen = record['repairs'].get(str(target), base) + require(len(chosen) == rank and set(chosen) <= support - {target}, 'witness outside admissible source set') + key = (tuple(chosen), tuple(columns)) + require(key in minors, 'missing checked minor') + used.add(key) + cases += 1 + ranks[rank] += 1 + require(used == set(minors), 'unused minor') + require(cases == 28560 and certificate['alternative_cases'] == cases, 'case inventory') + require(certificate['free_alternatives'] == 0, 'false free count') + require({str(k): v for k, v in ranks.items()} == certificate['rational_rank_histogram'], 'rank histogram') + return {'cases': cases, 'rank_histogram': dict(sorted(ranks.items())), 'exact_minors': len(minors)} + + +if __name__ == '__main__': + source.checked_sources() + result = audit(json.loads((HERE / 'CERTIFICATE.json').read_text(encoding='utf-8'))) + print('PASS_P112_FREE_SINK_INDEPENDENT ' + json.dumps(result, sort_keys=True)) diff --git a/research/p112-signed-modular-production/benchmark.py b/research/p112-signed-modular-production/benchmark.py new file mode 100644 index 0000000000..c3a6a46bbb --- /dev/null +++ b/research/p112-signed-modular-production/benchmark.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""Paired wall-time samples for production P112 signed modular determinants. + +Descriptive only: timing is not a correctness gate. +Prepared by Wentao Li with substantial AI assistance. Apache-2.0. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +from pathlib import Path +import platform +import statistics +import sys +import time +import types + +ROOT = Path(__file__).resolve().parents[2] +PACKAGE = Path(__file__).resolve().parent +PRODUCTION = ROOT / "research/p112-free-sink-audit97/independent.py" +BASELINE = PACKAGE / "baseline.py" +CERTIFICATE = ROOT / "research/p112-free-sink-audit97/CERTIFICATE.json" +BASE_COMMIT = "0b1cccf86e2f5132ed286a26ef0a681a495740ea" + + +def unique_object(pairs): + out = {} + for key, value in pairs: + if key in out: + raise SystemExit(f"duplicate JSON key: {key}") + out[key] = value + return out + + +def load_checker(name: str, source: Path): + module = types.ModuleType(name) + module.__file__ = str(PRODUCTION) + exec(compile(source.read_bytes(), str(PRODUCTION), "exec", optimize=0), module.__dict__) + return module + + +def run_once(module, certificate) -> tuple[float, dict]: + start = time.perf_counter() + result = module.audit(certificate) + elapsed = time.perf_counter() - start + return elapsed, result + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--rounds", type=int, default=5) + parser.add_argument("--write-result", action="store_true") + args = parser.parse_args(argv) + + certificate = json.loads(CERTIFICATE.read_bytes(), object_pairs_hook=unique_object) + base_times = [] + prod_times = [] + expected = None + for i in range(args.rounds): + order = ("baseline", "production") if i % 2 == 0 else ("production", "baseline") + receipts = {} + for engine in order: + path = BASELINE if engine == "baseline" else PRODUCTION + module = load_checker(f"{engine}_{i}", path) + dt, receipt = run_once(module, certificate) + receipts[engine] = receipt + if engine == "baseline": + base_times.append(dt) + else: + prod_times.append(dt) + if receipts["baseline"] != receipts["production"]: + raise SystemExit("PASS gate failed: receipts diverged during benchmark") + if expected is None: + expected = receipts["baseline"] + elif receipts["baseline"] != expected: + raise SystemExit("PASS gate failed: audit receipt changed across rounds") + + base_med = statistics.median(base_times) + prod_med = statistics.median(prod_times) + ratio = base_med / prod_med if prod_med else float("inf") + per_round = [b / p for b, p in zip(base_times, prod_times)] + result = { + "schema_version": 1, + "status": "PASS_IDENTICAL_P112_SIGNED_MODULAR_PRODUCTION_RECEIPTS", + "package": "research/p112-signed-modular-production", + "base_commit": BASE_COMMIT, + "workload": "complete P112 free-sink independent audit (28560 cases, 4030 signed minors)", + "rounds": args.rounds, + "baseline_seconds": base_times, + "production_seconds": prod_times, + "per_round_ratio": per_round, + "median_baseline_seconds": base_med, + "median_production_seconds": prod_med, + "median_speedup": ratio, + "min_per_round_ratio": min(per_round), + "max_per_round_ratio": max(per_round), + "audit_receipt": expected, + "baseline_sha256": hashlib.sha256(BASELINE.read_bytes()).hexdigest(), + "production_sha256": hashlib.sha256(PRODUCTION.read_bytes()).hexdigest(), + "python": sys.version, + "platform": platform.platform(), + "note": ( + "Host-descriptive; not a correctness gate. Times cover audit() after module load " + "(geometry, code coverage, all exact minors/cases); exclude interpreter startup " + "and package pin hashing. Receipts identical each round." + ), + } + text = json.dumps(result, indent=2) + "\n" + print(text, end="") + print( + "PASS_IDENTICAL_P112_SIGNED_MODULAR_PRODUCTION_RECEIPTS " + f"rounds={args.rounds} " + f"median {base_med:.3f}->{prod_med:.3f}s " + f"({ratio:.3f}×; per-round {min(per_round):.3f}–{max(per_round):.3f}×)", + flush=True, + ) + if args.write_result: + (PACKAGE / "RESULT.json").write_text(text, encoding="utf-8") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/research/p112-signed-modular-production/verify.py b/research/p112-signed-modular-production/verify.py new file mode 100644 index 0000000000..45a16b90f8 --- /dev/null +++ b/research/p112-signed-modular-production/verify.py @@ -0,0 +1,249 @@ +#!/usr/bin/env python3 +"""Equivalence, pin and rejection controls for production P112 signed modular determinants. + +Read-only by default. Timing is not a pass gate; see benchmark.py / RESULT.json. +Prepared by Wentao Li with substantial AI assistance. Apache-2.0. +""" +from __future__ import annotations + +import argparse +import copy +import hashlib +import io +import itertools +import json +import subprocess +import sys +import tempfile +import types +from contextlib import redirect_stdout +from fractions import Fraction +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +PACKAGE = Path(__file__).resolve().parent +SINK = ROOT / "research/p112-free-sink-audit97" +PRODUCTION = SINK / "independent.py" +BASELINE = PACKAGE / "baseline.py" +CERTIFICATE = SINK / "CERTIFICATE.json" +OPT_IN_ENGINE = ROOT / "research/p112-signed-modular86/engine.py" + +BASE_COMMIT = "0b1cccf86e2f5132ed286a26ef0a681a495740ea" +ORIGINAL_BLOB = "c65f3fbfe130a4f8cf07b9d2fa4d180cde2957c5" +ORIGINAL_SHA256 = "46806efe1ee7744c810a69981d471b42dfceaa336fee226991c55ba1edfd129f" +OPTIMIZED_SHA256 = "c77cf3dd1234c26cfb7df2d356752721e8b1b37169f20543678fe2f4d07a53f8" +CERT_SHA256 = "45abf8c46b54ab752a16573cc6e03a225a6d76a853b093f186d52bd2b51ec9c6" +ENGINE_SHA256 = "b74c6dd99e9cad0eb4cb252c810acea74c1cba979c7766d194933e4bc35a35fa" + + +def require(condition, message): + if not condition: + raise AssertionError(message) + + +def digest_file(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def unique_object(pairs): + out = {} + for key, value in pairs: + require(key not in out, f"duplicate JSON key: {key}") + out[key] = value + return out + + +def load_checker(name: str, source: Path): + """Load independent.py with assertions kept even when this wrapper runs under -O. + + `__file__` is always the live sink path so HERE/verify.py/CERTIFICATE resolve. + """ + module = types.ModuleType(name) + module.__file__ = str(PRODUCTION) + exec(compile(source.read_bytes(), str(PRODUCTION), "exec", optimize=0), module.__dict__) + return module + + +def load_engine(): + module = types.ModuleType("signed_modular_engine") + module.__file__ = str(OPT_IN_ENGINE) + exec(compile(OPT_IN_ENGINE.read_bytes(), str(OPT_IN_ENGINE), "exec", optimize=0), module.__dict__) + return module + + +def check_baseline_bytes() -> None: + original = subprocess.check_output( + ["git", "show", f"{BASE_COMMIT}:research/p112-free-sink-audit97/independent.py"], + cwd=ROOT, + ) + require(hashlib.sha256(original).hexdigest() == ORIGINAL_SHA256, "base independent.py sha256 drift") + blob = ( + subprocess.check_output( + ["git", "rev-parse", f"{BASE_COMMIT}:research/p112-free-sink-audit97/independent.py"], + cwd=ROOT, + ) + .decode() + .strip() + ) + require(blob == ORIGINAL_BLOB, "base independent.py blob drift") + require(BASELINE.read_bytes() == original, "baseline.py must equal the base-commit independent.py") + require(digest_file(PRODUCTION) == OPTIMIZED_SHA256, "production independent.py digest drift") + require(PRODUCTION.read_bytes() != original, "production must differ from Fraction baseline") + require(digest_file(CERTIFICATE) == CERT_SHA256, "certificate digest drift") + require(digest_file(OPT_IN_ENGINE) == ENGINE_SHA256, "opt-in engine digest drift") + prod_text = PRODUCTION.read_text(encoding="utf-8") + base_text = BASELINE.read_text(encoding="utf-8") + require("def _modular_determinant(" in prod_text, "production must define _modular_determinant") + require("def rational_determinant(" in prod_text, "production must retain rational_determinant") + require("PRIME = 521" in prod_text, "production must pin modulus 521") + require("def _modular_determinant(" not in base_text, "baseline must stay Fraction-only") + require("def fraction_determinant(rows):" in base_text, "baseline must keep fraction_determinant") + require(OPT_IN_ENGINE.exists(), "opt-in engine missing") + + +def audit_outcome(module, certificate): + printed = io.StringIO() + with redirect_stdout(printed): + result = module.audit(certificate) + return result, printed.getvalue() + + +def run_equivalence() -> dict: + check_baseline_bytes() + certificate = json.loads(CERTIFICATE.read_bytes(), object_pairs_hook=unique_object) + baseline = load_checker("p112_baseline", BASELINE) + production = load_checker("p112_production", PRODUCTION) + engine = load_engine() + + baseline.source.checked_sources() + production.source.checked_sources() + + base_result, _ = audit_outcome(baseline, certificate) + prod_result, _ = audit_outcome(production, certificate) + require(base_result == prod_result, "baseline/production audit results differ") + require( + base_result + == {"cases": 28560, "rank_histogram": {7: 448, 8: 28112}, "exact_minors": 4030}, + "unexpected audit inventory", + ) + + lines, _ = baseline.source.geometry() + signed = [] + for minor in certificate["minors"]: + rows = [[lines[i][j] for j in minor["columns"]] for i in minor["rows"]] + require(engine.eligible(rows), "every frozen minor enters checked bound") + require(production._eligible(rows), "production eligibility matches engine") + a = baseline.fraction_determinant(rows) + b = production.fraction_determinant(rows) + c = engine.determinant(rows, baseline.fraction_determinant) + require(a == b == c == minor["determinant"], "full signed determinant agreement") + signed.append([minor["rows"], minor["columns"], b]) + + controls = [] + + def reject(name, fn): + try: + fn() + except (ValueError, AssertionError): + controls.append(name) + else: + raise AssertionError("accepted control: " + name) + + for name, change in ( + ( + "wrong signed determinant", + lambda x: x["minors"][0].__setitem__("determinant", -x["minors"][0]["determinant"]), + ), + ("missing minor", lambda x: x["minors"].pop()), + ("duplicate minor", lambda x: x["minors"].append(copy.deepcopy(x["minors"][0]))), + ("Boolean determinant", lambda x: x["minors"][0].__setitem__("determinant", True)), + ("missing pattern", lambda x: x["patterns"].pop()), + ("false free count", lambda x: x.__setitem__("free_alternatives", 1)), + ): + bad = copy.deepcopy(certificate) + change(bad) + reject(name, lambda bad=bad: production.audit(bad)) + + reject("insufficient modulus", lambda: production._recover(256, 257, 256)) + reject("invalid residue", lambda: production._recover(521, 521, 256)) + reject("violated determinant bound", lambda: production._recover(257, 521, 256)) + + boundary = [[2 * int(i == j) for j in range(8)] for i in range(8)] + require(production.fraction_determinant(boundary) == 256, "positive Hadamard boundary") + boundary[0], boundary[1] = boundary[1], boundary[0] + require(production.fraction_determinant(boundary) == -256, "negative Hadamard boundary") + require(production.fraction_determinant([[1, 1], [1, 1]]) == 0, "singular exact zero") + + fallback_cases = [ + [[521]], + [[3]], + [[int(i == j) for j in range(9)] for i in range(9)], + [[Fraction(1, 2), 0], [0, 2]], + ] + for rows in fallback_cases: + require(not production._eligible(rows), "fallback fixture outside fast envelope") + require( + production.fraction_determinant(rows) == baseline.fraction_determinant(rows), + "exact fallback", + ) + + tested = 0 + for n in (1, 2, 3): + for flat in itertools.product((-1, 0, 1), repeat=n * n): + rows = [list(flat[i * n : (i + 1) * n]) for i in range(n)] + require( + production.fraction_determinant(rows) == baseline.fraction_determinant(rows), + "exhaustive signed matrix", + ) + tested += 1 + + # On-disk corruption foil: flip one certificate determinant in a temp copy. + with tempfile.TemporaryDirectory(prefix="p112-mod-prod-") as tmp: + foil = Path(tmp) / "CERTIFICATE.json" + bad = copy.deepcopy(certificate) + bad["minors"][0]["determinant"] = -bad["minors"][0]["determinant"] + foil.write_text(json.dumps(bad), encoding="utf-8") + try: + production.audit(json.loads(foil.read_text(encoding="utf-8"), object_pairs_hook=unique_object)) + except (ValueError, AssertionError): + controls.append("temp certificate determinant flip") + else: + raise AssertionError("accepted temp certificate determinant flip") + + stream = hashlib.sha256( + json.dumps(signed, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() + ).hexdigest() + return { + "complete_audit": prod_result, + "exact_minors": len(signed), + "signed_minor_stream_sha256": stream, + "small_signed_matrices": tested, + "fallback_cases": len(fallback_cases), + "controls_rejected": controls, + "hadamard_bound": 256, + "prime": 521, + } + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.parse_args(argv) + before = digest_file(PRODUCTION) + result = run_equivalence() + require(digest_file(PRODUCTION) == before, "verify must be read-only on production independent.py") + require(digest_file(BASELINE) == ORIGINAL_SHA256, "verify must be read-only on baseline.py") + require(len(result["controls_rejected"]) >= 9, "expected rejection controls") + print( + "PASS_P112_SIGNED_MODULAR_PRODUCTION " + f"cases={result['complete_audit']['cases']} " + f"minors={result['exact_minors']} " + f"signed_matrices={result['small_signed_matrices']} " + f"controls={len(result['controls_rejected'])} " + "no_new_kappa", + flush=True, + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/research/p112-signed-modular86/README.md b/research/p112-signed-modular86/README.md index 93436689ee..19d295d615 100644 --- a/research/p112-signed-modular86/README.md +++ b/research/p112-signed-modular86/README.md @@ -6,6 +6,11 @@ package substitutes a proved-exact modulo521 kernel for those determinants and runs the same complete audit. It preserves signs and magnitudes, not merely the test for nonzero rank. The predecessor files and selected frontier are unchanged. +After `research/p112-signed-modular-production/`, the live +`research/p112-free-sink-audit97/independent.py` ships that modular path. This +opt-in package vendors the pairwise Fraction-only checker in `baseline.py` and +continues to prove `engine.py` against that reference. + Three paired local runs of the complete `audit()` call give median times **0.850662 seconds reference, 0.219613 seconds candidate: 3.87x**. Those timings include geometry, row-code coverage, minors and case checks after module/source diff --git a/research/p112-signed-modular86/SOURCES.json b/research/p112-signed-modular86/SOURCES.json index bbbac134b4..1538bf6c04 100644 --- a/research/p112-signed-modular86/SOURCES.json +++ b/research/p112-signed-modular86/SOURCES.json @@ -2,13 +2,22 @@ "base_commit": "ba82555c64e1879e4b7decce28186f208fcb8262", "files": { "research/p112-free-sink-audit97/verify.py": "91dbe1ad0fa7c4b46ef571cccb7eb5f7a2239995f889147277ea6719674adc5b", - "research/p112-free-sink-audit97/independent.py": "46806efe1ee7744c810a69981d471b42dfceaa336fee226991c55ba1edfd129f", "research/p112-free-sink-audit97/CERTIFICATE.json": "45abf8c46b54ab752a16573cc6e03a225a6d76a853b093f186d52bd2b51ec9c6", "research/p112-free-sink-audit97/SOURCES.json": "d961a1c3734cfd9816a2bc317c60814e8887178b753edf5d80bdbc3e82ba35c2", "research/p112-free-sink-audit97/BASE-SELECTED.json": "1d35283cb0ce3f8db1f285683933517f9e87475d295e2b6316399ad9928c81c3", - "research/p112-free-sink-audit97/README.md": "c792fc8f5de0c784049904c6febf3eed9b20e2462b30dc643c72730470d72b79", + "research/p112-free-sink-audit97/README.md": "6924c590eaa9a954d986153fa417c3f1ee074bcb194a42c79e1e37cb69f2cd4a", "research/p112-free-sink-audit97/PROOF.md": "3b7cd56da99f1936862c974e5bee8e1bd90008da4fbd3be01c96f766225e36d1", "research/p112-free-sink-audit97/test_package.py": "814f5efafdd345c92b856cd0f54f049e790dce572a1edaa0b140efcd3c422ed7" }, + "independent_baseline": { + "path": "research/p112-signed-modular86/baseline.py", + "sha256": "46806efe1ee7744c810a69981d471b42dfceaa336fee226991c55ba1edfd129f", + "note": "Pairwise Fraction-only independent.py bytes. After research/p112-signed-modular-production/, the live research/p112-free-sink-audit97/independent.py ships modulo-521 recovery; this package's reference engine uses vendored baseline.py." + }, + "live_independent_provenance": { + "path": "research/p112-free-sink-audit97/independent.py", + "pairwise_sha256": "46806efe1ee7744c810a69981d471b42dfceaa336fee226991c55ba1edfd129f", + "note": "Literal-era digest retained as provenance after research/p112-signed-modular-production/; working independent.py ships modular determinants." + }, "selected_snapshot_sha256": "207d1f49f113c585024b9d3c17eadbb8b1be17c1321e3d190aabe2f18ce1c5b7" } diff --git a/research/p112-signed-modular86/baseline.py b/research/p112-signed-modular86/baseline.py new file mode 100644 index 0000000000..c65f3fbfe1 --- /dev/null +++ b/research/p112-signed-modular86/baseline.py @@ -0,0 +1,94 @@ +"""Independent Fraction minor checks and full row-code coverage, Apache-2.0. + +The source-pin and geometry readers are shared, but this checker does not +call the producer's row-code basis, modular elimination, Bareiss or build. +Contributor @woklerx with substantial OpenAI Codex assistance. +""" +import importlib.util +import json +from collections import Counter +from fractions import Fraction +from pathlib import Path + +HERE = Path(__file__).resolve().parent +spec = importlib.util.spec_from_file_location('sink_sources', HERE / 'verify.py') +source = importlib.util.module_from_spec(spec) +spec.loader.exec_module(source) +require = source.require + + +def fraction_determinant(rows): + a = [list(map(Fraction, row)) for row in rows] + answer = Fraction(1) + for col in range(len(a)): + pivot = next((i for i in range(col, len(a)) if a[i][col]), None) + if pivot is None: + return 0 + if pivot != col: + a[pivot], a[col] = a[col], a[pivot] + answer *= -1 + value = a[col][col] + answer *= value + for i in range(col + 1, len(a)): + scale = a[i][col] / value + for j in range(col + 1, len(a)): + a[i][j] -= scale * a[col][j] + require(answer.denominator == 1, 'integer determinant') + return int(answer) + + +def audit(certificate): + lines, decoder = source.geometry() + words = {0} + for row in decoder: + words |= {word ^ row for word in words} + require(len(words) == 512, 'full decoder row code') + records = certificate['patterns'] + require(len(records) == 511, 'pattern count') + require({int(r['pattern'], 16) for r in records} == words - {0}, 'pattern coverage') + minors = {} + for record in certificate['minors']: + indices, columns = record['rows'], record['columns'] + require(all(type(i) is int and 0 <= i < 120 for i in indices), 'minor row indices') + require(all(type(i) is int and 0 <= i < 8 for i in columns), 'minor column indices') + require(len(indices) == len(columns) and len(set(indices)) == len(indices) + and len(set(columns)) == len(columns), 'square distinct minor') + key = (tuple(indices), tuple(columns)) + require(key not in minors, 'duplicate minor') + value = fraction_determinant([[lines[i][j] for j in columns] for i in indices]) + require(type(record['determinant']) is int and value == record['determinant'] != 0, 'invalid exact minor') + minors[key] = value + cases, ranks, used = 0, Counter(), set() + for record in records: + word = int(record['pattern'], 16) + support = {i for i in range(8, 120) if word >> i & 1} + base, columns, rank = record['base'], record['columns'], record['rank'] + require(type(rank) is int and len(base) == len(columns) == rank, 'rank declaration') + if rank == 7: + missing = set(range(8)) - set(columns) + require(len(missing) == 1, 'coordinate hyperplane shape') + coordinate = next(iter(missing)) + require(word == decoder[coordinate] and all(lines[i][coordinate] == 0 for i in support), 'rank-seven upper bound') + else: + require(rank == 8 and columns == list(range(8)), 'ambient rank-eight upper bound') + alternatives = {i for i in support if word != decoder[i]} + require(set(record['repairs']) == {str(i) for i in alternatives if i in base}, 'repair inventory') + for target in alternatives: + chosen = record['repairs'].get(str(target), base) + require(len(chosen) == rank and set(chosen) <= support - {target}, 'witness outside admissible source set') + key = (tuple(chosen), tuple(columns)) + require(key in minors, 'missing checked minor') + used.add(key) + cases += 1 + ranks[rank] += 1 + require(used == set(minors), 'unused minor') + require(cases == 28560 and certificate['alternative_cases'] == cases, 'case inventory') + require(certificate['free_alternatives'] == 0, 'false free count') + require({str(k): v for k, v in ranks.items()} == certificate['rational_rank_histogram'], 'rank histogram') + return {'cases': cases, 'rank_histogram': dict(sorted(ranks.items())), 'exact_minors': len(minors)} + + +if __name__ == '__main__': + source.checked_sources() + result = audit(json.loads((HERE / 'CERTIFICATE.json').read_text(encoding='utf-8'))) + print('PASS_P112_FREE_SINK_INDEPENDENT ' + json.dumps(result, sort_keys=True)) diff --git a/research/p112-signed-modular86/test_package.py b/research/p112-signed-modular86/test_package.py index 1515c29bd8..e28a7cd3ff 100644 --- a/research/p112-signed-modular86/test_package.py +++ b/research/p112-signed-modular86/test_package.py @@ -13,7 +13,7 @@ def main(): original={name:(t/name).read_bytes() for name in ('SOURCES.json','BASE-SELECTED.json','EXPECTED.json')} v.P=t;controls=[] for label,name,change in ( - ('missing source pin','SOURCES.json',lambda x:x['files'].pop(v.OLD+'independent.py')), + ('missing source pin','SOURCES.json',lambda x:x['files'].pop(v.OLD+'CERTIFICATE.json')), ('changed source hash','SOURCES.json',lambda x:x['files'].__setitem__(v.OLD+'CERTIFICATE.json','0'*64)), ('changed selected context','BASE-SELECTED.json',lambda x:x.__setitem__('kappa','1/2')), ('floating count','EXPECTED.json',lambda x:x.__setitem__('exact_minors',4030.0))): diff --git a/research/p112-signed-modular86/verify.py b/research/p112-signed-modular86/verify.py index d334104e52..2b41cf2e46 100644 --- a/research/p112-signed-modular86/verify.py +++ b/research/p112-signed-modular86/verify.py @@ -1,16 +1,31 @@ -"""Preserve the full PR1035 independent audit with exact modular determinants.""" +"""Preserve the full PR1035 independent audit with exact modular determinants. + +After research/p112-signed-modular-production/, the live independent.py ships +the modular path. This opt-in package vendors pairwise Fraction-only bytes in +baseline.py and still proves engine.py against that reference. +""" from pathlib import Path -import argparse,copy,hashlib,importlib.util,itertools,json,statistics,time +import argparse,copy,hashlib,importlib.util,itertools,json,statistics,time,types from fractions import Fraction P=Path(__file__).resolve().parent;ROOT=P.parents[1] OLD='research/p112-free-sink-audit97/' BASE='ba82555c64e1879e4b7decce28186f208fcb8262' -FILES={OLD+x for x in ('verify.py','independent.py','CERTIFICATE.json','SOURCES.json','BASE-SELECTED.json','README.md','PROOF.md','test_package.py')} +FILES={OLD+x for x in ('verify.py','CERTIFICATE.json','SOURCES.json','BASE-SELECTED.json','README.md','PROOF.md','test_package.py')} +BASELINE=P/'baseline.py' +PRODUCTION=ROOT/(OLD+'independent.py') +PAIRWISE_SHA256='46806efe1ee7744c810a69981d471b42dfceaa336fee226991c55ba1edfd129f' def need(ok,msg): if not ok:raise ValueError(msg) +def load_independent(name, source_bytes): + """Load independent source with HERE bound to the live sink package.""" + module=types.ModuleType(name) + module.__file__=str(PRODUCTION) + exec(compile(source_bytes, str(PRODUCTION), 'exec', optimize=0), module.__dict__) + return module + def module(name,path): s=importlib.util.spec_from_file_location(name,path);m=importlib.util.module_from_spec(s);s.loader.exec_module(m);return m @@ -25,7 +40,12 @@ def prepare(): for path,h in sources['files'].items(): need(digest((ROOT/path).read_bytes().replace(b'\r\n',b'\n'))==h,'source pin: '+path) need(digest((P/'BASE-SELECTED.json').read_bytes().replace(b'\r\n',b'\n'))==sources['selected_snapshot_sha256'],'selected snapshot') - original=module('sink_independent86',ROOT/(OLD+'independent.py')) + baseline_meta=sources['independent_baseline'] + need(baseline_meta['path']=='research/p112-signed-modular86/baseline.py','baseline path') + need(digest(BASELINE.read_bytes().replace(b'\r\n',b'\n'))==baseline_meta['sha256']==PAIRWISE_SHA256,'baseline pin') + need(sources['live_independent_provenance']['pairwise_sha256']==PAIRWISE_SHA256,'provenance pairwise digest') + # Reference engine is always the vendored Fraction-only baseline. + original=load_independent('sink_independent86', BASELINE.read_bytes()) original.source.checked_sources() engine=module('signed_modular86',P/'engine.py') certificate=json.loads((ROOT/(OLD+'CERTIFICATE.json')).read_bytes()) @@ -53,12 +73,16 @@ def run(): result,stats=execute(original,e,c,'candidate') baseline,_=execute(original,e,c,'reference') need(result==baseline and stats=={'fast':4030,'fallback':0},'complete audit equality') + # Production live path must match the same audit receipt when present. + if PRODUCTION.exists(): + live=load_independent('sink_independent_live', PRODUCTION.read_bytes()) + live_result=live.audit(c) + need(live_result==result,'live production audit must match opt-in candidate') controls=[] def reject(name,fn): try:fn() except ValueError:controls.append(name) else:raise ValueError('accepted control: '+name) - # These perturb actual independent-certificate obligations. for name,change in ( ('wrong signed determinant',lambda x:x['minors'][0].__setitem__('determinant',-x['minors'][0]['determinant'])), ('missing minor',lambda x:x['minors'].pop()), @@ -80,7 +104,6 @@ def reject(name,fn): for rows in fallback_cases: need(not e.eligible(rows),'fallback fixture outside fast envelope') need(e.determinant(rows,reference)==reference(rows),'exact fallback') - # Exhaust all small signed matrices, including singular and pivot-swap cases. tested=0 for n in (1,2,3): for flat in itertools.product((-1,0,1),repeat=n*n): @@ -103,7 +126,7 @@ def benchmark(repeats=3): med={k:statistics.median(v) for k,v in samples.items()} return {'repeats':repeats,'samples_seconds':samples,'median_seconds':med, 'median_speedup':med['reference']/med['candidate'],'same_input':expected, - 'scope':'Paired full audit() calls after source loading; includes geometry, code coverage and all exact minors/cases; excludes interpreter startup, source hashing, package controls and certificate serialization. Local timing only.'} + 'scope':'Paired full audit() calls after source loading against vendored Fraction baseline; includes geometry, code coverage and all exact minors/cases; excludes interpreter startup, source hashing, package controls and certificate serialization. Local timing only.'} def main(): p=argparse.ArgumentParser();p.add_argument('--write-certificate',action='store_true');p.add_argument('--benchmark',action='store_true');args=p.parse_args() diff --git a/tests/test_p112_signed_modular_production.py b/tests/test_p112_signed_modular_production.py new file mode 100644 index 0000000000..b74df71cfb --- /dev/null +++ b/tests/test_p112_signed_modular_production.py @@ -0,0 +1,26 @@ +"""Thin admission test for production P112 signed modular wiring.""" +from __future__ import annotations + +import subprocess +import sys +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +VERIFY = ROOT / "research/p112-signed-modular-production/verify.py" + + +class P112SignedModularProduction(unittest.TestCase): + def test_verify_passes(self): + proc = subprocess.run( + [sys.executable, "-I", "-B", str(VERIFY)], + cwd=ROOT, + capture_output=True, + text=True, + ) + self.assertEqual(proc.returncode, 0, proc.stderr + proc.stdout) + self.assertIn("PASS_P112_SIGNED_MODULAR_PRODUCTION", proc.stdout) + + +if __name__ == "__main__": + unittest.main()