diff --git a/research/h2sem-copyshare-priced/CERTIFICATE.json b/research/h2sem-copyshare-priced/CERTIFICATE.json new file mode 100644 index 0000000000..8a43123fff --- /dev/null +++ b/research/h2sem-copyshare-priced/CERTIFICATE.json @@ -0,0 +1,84 @@ +{ + "status": "PASS_H2SEM_COPYSHARE_PRICED", + "assignment_seed": 42, + "task_id": "bit-helper-contract", + "base_commit": "0b1cccf86e2f5132ed286a26ef0a681a495740ea", + "columns": 661, + "census": { + "operands": 430, + "oriented_pairs": 184470, + "positive_pairs": 41404, + "best_saving": 65, + "best_pair": [ + 277, + 434 + ], + "matching_pairs": 205, + "matching_saving": 6231 + }, + "bills": { + "base": { + "native_ADDs": 24305, + "D_adds": 18085, + "F": 49347, + "B": 1113070, + "local_bits": 93, + "nine_stage_bits": 177 + }, + "single": { + "native_ADDs": 24240, + "D_adds": 18020, + "F": 50535, + "B": 1113070, + "local_bits": 94, + "nine_stage_bits": 177 + }, + "match": { + "native_ADDs": 18074, + "D_adds": 11854, + "F": 75381, + "B": 1196402, + "local_bits": 95, + "nine_stage_bits": 180 + } + }, + "paid_profile": { + "1": 1323, + "2": 1342, + "3": 79, + "4": 44, + "5": 102, + "6": 11, + "7": 19 + }, + "rank_mass": 5129, + "h2sem": { + "shape": true, + "semantic_N_equals_baseline": true, + "syntactic_H2_K": { + "base": { + "H2": true, + "K_equals_D": true + }, + "single": { + "H2": false, + "K_equals_D": false + }, + "match": { + "H2": false, + "K_equals_D": false + } + } + }, + "controls": [ + "unrestored_helper_temp", + "wrong_restore_operand", + "target_feeds_helper", + "source_reads_in_D", + "partial_matching_unrestored", + "mutated_body_changes_N", + "target_temp_plus2_positive" + ], + "kappa_claim": "none", + "new_kappa": false +} diff --git a/research/h2sem-copyshare-priced/CLAIM.md b/research/h2sem-copyshare-priced/CLAIM.md new file mode 100644 index 0000000000..d4d91261b5 --- /dev/null +++ b/research/h2sem-copyshare-priced/CLAIM.md @@ -0,0 +1,19 @@ +# Claim + +**Finite bit construction under H2-sem; no new kappa.** + +Chooser seed `978940692bb73d58cd4b4e07f8514e57`, task `bit-helper-contract`, +scope key `3475f46c8358c6a9211b`, base `0b1cccf86e2f5132ed286a26ef0a681a495740ea`. + +Under the PR1194 H2-sem replacement for syntactic H2/K, the PR848 helper-temp +D wraps on the selected R439 word are fully priced: + +- single pair 277→434: ADDs 24305→24240 (−65); +- seed-42 matching (205 pairs): ADDs 24305→18074 (−6231); + +with identical complete dirty boundary, semantic N unchanged, paid profile +`{1:1323,2:1342,3:79,4:44,5:102,6:11,7:19}` (mass 5129) unchanged, and strict +104/192-bit guards. Syntactic H2/K fail exactly on the wraps. + +This is not a selected-supplier proposal and claims no new kappa. It supplies +the paid invoice that PR1782 left open after interface admission. diff --git a/research/h2sem-copyshare-priced/NOTICE.md b/research/h2sem-copyshare-priced/NOTICE.md new file mode 100644 index 0000000000..4df374b13d --- /dev/null +++ b/research/h2sem-copyshare-priced/NOTICE.md @@ -0,0 +1,16 @@ +# Notice + +This package prices helper-sharing wraps introduced by Aaron Wang in PR848 +(`research/r439-copy-path-sharing-barrier`) under the H2-sem replacement +contract of woklerx in PR1194 +(`research/r439-semantic-d-contract-seed10/PROOF.md`). The selected R439 word +and owner checker belong to DreamingOfClouds (PR589) and eumemic (PR555) +lineage. Open PR1782 (navinor) independently admits the same wraps under +H2-sem without recomputing F/B or the paid profile; that admission is credited +and not vendored. + +Predecessor notices, licenses and source archives are unchanged. New material +in this directory is Apache-2.0. + +Prepared by Wentao Li with substantial AI assistance. +Contributor profiles: GitHub VictorLiwentao; X @Is__Victor. diff --git a/research/h2sem-copyshare-priced/PROOF.md b/research/h2sem-copyshare-priced/PROOF.md new file mode 100644 index 0000000000..e672ef76b5 --- /dev/null +++ b/research/h2sem-copyshare-priced/PROOF.md @@ -0,0 +1,73 @@ +# H2-sem pricing of the PR848 copy-path helper-sharing wraps + +## Contract (imported, not re-derived) + +Use the replacement scalar contract H2-sem of +`research/r439-semantic-d-contract-seed10/PROOF.md` (PR1194): + +1. Every D gate is at the common zero frame and is source-free. +2. No target feeds a source or helper (retained H1 inside D). +3. The complete D operator is exactly `(x,y,h) -> (x, y + N h, h)` for a + specified binary matrix N. + +The old gate-local H2 requires every D gate to write a target. Helper +preparation/restoration writes therefore fail syntactic H2. Under H2-sem they +are legal when the boundary equation holds. Semantic N must equal the raw +helper-response K of A/scatter/B for the interleaved substitution theorem. + +## Objects + +Let W be the selected PR589 R439 word +(`research/e8-bit-p111-tuned/tune/bitE8mut-p111-tuned.json.gz`). Its D section +has 18,085 helper reads and already satisfies syntactic H2/K. + +PR848's wrap for an oriented helper pair `(a,b)` prepends `a ^= b`, rewrites +every D row that contains `a` by symmetric difference with `b`, and appends the +reverse restoration `a ^= b`. The arithmetic source-read saving of one pair is + +`sum_{rows containing a} (1_{b in row} - 1_{b not in row}) - 2`. + +The seed-42 greedy disjoint matching of PR848 selects 205 positive pairs with +total arithmetic saving 6,231; the best single pair is `(277,434)` with saving +65. Both figures are recomputed here. + +## Boundary lemma (dirty inputs) + +Write H for the involution that XORs each selected center by its leaf. The wrap +is chronologically `H; D0; H` where D0 is the rewritten body. Because H = H^{-1} +over F2 and the body applies the conjugated coefficient matrix, the composite +equals the original D map on every F2 input column. Necessity of full helper +restoration is witnessed by deleting a restore gate: some helper basis column +fails to return. Equality of the 661 binary D columns therefore certifies the +H2-sem boundary for every F2-module stream under the common zero-frame reading +(the same coefficient argument as PR1194). + +## Paid invoice + +Only D changes. Register frame paths, COPY ranks and the climb histogram are +unchanged, so the paid recursive profile remains + +`{1:1323, 2:1342, 3:79, 4:44, 5:102, 6:11, 7:19}` + +with rank mass 5,129. Literal COPY/ERASE stream peaks give: + +| word | ADDs | D ADDs | F | B | local bits | nine-stage bits | +|---|---:|---:|---:|---:|---:|---:| +| baseline W | 24,305 | 18,085 | 49,347 | 1,113,070 | 93 | 177 | +| single pair 277→434 | **24,240** | 18,020 | 50,535 | 1,113,070 | 94 | 177 | +| seed-42 matching (205) | **18,074** | 11,854 | 75,381 | 1,196,402 | 95 | 180 | + +Both candidates stay strictly under the inherited 104-bit local and 192-bit +nine-stage guards. Forward/reverse complete-word F2 boundaries equal the +baseline. Inherited H1/H3/H4/H5 and U/J/C remain true; syntactic H2 and +`K_equals_D` are false exactly on the wraps, while semantic N equals the +baseline N (weight 18,085). + +## What this does not claim + +No new kappa: the bit supplier does not bind, and the paid profile is +unchanged. Native C++/Boost replay, hosted supplier emission, all-size +compiler, rounding/tape and analytic transfer are not executed. Matching +optimality is not claimed. PR1782's interface-admission package is complementary: +it established H2-sem legality without recomputing F/B or the paid profile; +this package supplies that invoice. diff --git a/research/h2sem-copyshare-priced/README.md b/research/h2sem-copyshare-priced/README.md new file mode 100644 index 0000000000..1566f074cc --- /dev/null +++ b/research/h2sem-copyshare-priced/README.md @@ -0,0 +1,75 @@ +# Priced H2-sem admission of the PR848 copy-path helper-sharing wraps + +**Priced finite invoice under the H2-sem replacement interface; no new κ.** The +selected frontier, selected bit supplier and `upstream/` are unchanged. The bit +side does not bind. + +PR848 priced helper-temp sharing on the selected R439 word as an arithmetic +source-read upper bound and rejected it under gate-local H2. PR1194 supplies the +replacement contract H2-sem. Open PR1782 checks that the wraps satisfy H2-sem, +but leaves F/B envelopes and the paid profile uncomputed. This package completes +that invoice. + +## Result + +| word | ADDs | D ADDs | F | B | local / nine-stage bits | paid profile | +|---|---:|---:|---:|---:|---|---| +| baseline PR589 | 24,305 | 18,085 | 49,347 | 1,113,070 | 93 / 177 | `{1:1323,…,7:19}` mass 5129 | +| single pair 277→434 | **24,240** (−65) | 18,020 | 50,535 | 1,113,070 | 94 / 177 | unchanged | +| seed-42 matching (205 pairs) | **18,074** (−6,231) | 11,854 | 75,381 | 1,196,402 | 95 / 180 | unchanged | + +Both wraps keep the complete dirty F2 boundary, semantic N equal to the baseline +N, and the inherited 104/192-bit guards. Syntactic H2 and `K_equals_D` fail +exactly on the wraps; H1/H3/H4/H5 and U/J/C remain true. Frame paths and nine +rank-7 COPY ranks are unchanged, so the paid recursive profile is unchanged. + +## Reproduce + +```sh +python3 -I -B research/h2sem-copyshare-priced/verify.py +python3 -I -O -B research/h2sem-copyshare-priced/verify.py +python3.12 scripts/research_package.py --package research/h2sem-copyshare-priced --check-only +python3.12 scripts/research_package.py --package research/h2sem-copyshare-priced +``` + +Expected: + +```text +PASS_H2SEM_COPYSHARE_PRICED single=277->434 adds=24305->24240 matching_pairs=205 adds=24305->18074 profile_mass=5129 columns=661 controls=7 no_new_kappa +``` + +The verifier recomputes the PR848 census, builds both wraps, checks H2-sem shape +and all 661 D columns, replays the full literal COPY/ERASE stream both ways, +recomputes F/B and precision guards, extracts the paid profile from frame-path +climbs plus COPY ranks via the pinned owner checker, and rejects seven controls +(unrestored helper, wrong restore, target→helper feedback, source read in D, +partial matching unrestored, mutated body N, and the +2 target-temp positive). + +## Scope + +- **No new κ.** Paid profile unchanged; bit supplier nonbinding. +- Native C++/Boost, hosted emission, all-size compiler, tape/rounding and + analytic transfer are not run. +- Matching optimality is not claimed. Intermediate envelopes rise even as ADD + counts fall; that trade-off is recorded, not optimized away. +- Complementary to PR1782 (interface admission without this invoice) and PR848 + (H2 barrier). Does not vendor their executables. + +## Open next questions + +1. **Can a different matching lower F while keeping most of the ADD saving?** + The seed-42 matching raises F from 49,347 to 75,381. A first step is to + re-score pairs by a joint (ADD, F) objective on a frozen shortlist. Blocker: + no favorable completed (ADD, F, B) point is known. +2. **Does the single-pair wrap compose with an already H2-sem-legal star D?** + First splice pair 277→434 onto the PR1062/PR1194 candidate and recompute the + full invoice. Blocker: maintained acceptance of H2-sem on the composed word. + +## Credit + +Credit **Aaron Wang / PR848** (pair census, greedy matching, helper-temp wrap), +**woklerx / PR1194** (H2-sem contract), **navinor / PR1782** (interface admission +that left pricing open), **DreamingOfClouds / PR589** and **eumemic / PR555** +(the R439 word and checker lineage). Prepared by Wentao Li with substantial AI +assistance. Apache-2.0. No independent human review or full multiplication +theorem is claimed. diff --git a/research/h2sem-copyshare-priced/SOURCES.json b/research/h2sem-copyshare-priced/SOURCES.json new file mode 100644 index 0000000000..f11faac8ae --- /dev/null +++ b/research/h2sem-copyshare-priced/SOURCES.json @@ -0,0 +1,42 @@ +{ + "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/e8-bit-p111-tuned/code/xcheck_p.py", + "usage": "input", + "git_blob": "184f5dcf94a486cc7db91ca4db5865916bf26009", + "sha256": "af3decc877e27c00001cf56f50c6c09566e8e101297ab34c7860aed96a06d80e" + }, + { + "path": "research/e8-bit-p111-tuned/tune/bitE8mut-p111-tuned.json.gz", + "usage": "input", + "git_blob": "85a4499bf9e4911a705d50567a2c2ef6cf23739a", + "sha256": "e3e301e62bc2b41dbf1ceac0acf3d35824ebeab1848c5a2142d4577b109da52f" + }, + { + "path": "research/r439-copy-path-sharing-barrier/verify.py", + "usage": "input", + "git_blob": "5636566096d20039b3092819b0f4d1a283d66436", + "sha256": "1863b99b132bc5764508a18167303aaff32c815dc73a8693b84fe89a20301c86" + }, + { + "path": "research/r439-semantic-d-contract-seed10/PROOF.md", + "usage": "input", + "git_blob": "2707fdb0d2f34c1c6c4ea41c2a68e44904a3e4fd", + "sha256": "dfbca8c61a92fdf0db8af450dc4466849da37fc296e28b67f357e196e87327db" + } + ] +} diff --git a/research/h2sem-copyshare-priced/TASK.json b/research/h2sem-copyshare-priced/TASK.json new file mode 100644 index 0000000000..ac6a46aba5 --- /dev/null +++ b/research/h2sem-copyshare-priced/TASK.json @@ -0,0 +1,68 @@ +{ + "schema_version": 1, + "task_id": "bit-helper-contract", + "priority_revision": 3, + "base_commit": "0b1cccf86e2f5132ed286a26ef0a681a495740ea", + "chooser_seed": "978940692bb73d58cd4b4e07f8514e57", + "scope_key": "3475f46c8358c6a9211b", + "original_card": { + "id": "bit-helper-contract", + "question": "Can one precisely specified helper-mixing word satisfy a replacement for the inherited H2/K interface?", + "starting_points": [ + "research/r439-bsection-stars-seed01/README.md", + "research/r439-copy-path-sharing-barrier/README.md" + ], + "methods": [ + "Derive a replacement interface lemma and price its implementation.", + "Seek an exact dirty-input or chronological-cut counterexample to the proposed replacement." + ], + "acceptance_gate": "A full boundary contract and paid profile; unchanged scalar counts alone are insufficient.", + "first_step": { + "command": [ + "python3", + "-B", + "research/r439-bsection-stars-seed01/verify.py" + ], + "expected": "PASS_R439_BSECTION_STARS", + "inspect": "Compare the two false H2/K flags with the unchanged paid profile in its README.", + "scope": "Positive control / source-bound orientation only; this is not a new construction or full cold replay." + }, + "first_experiment": "Write one replacement H2/K implication for a single helper-star operation, then try to falsify it on dirty inputs.", + "bottleneck_link": "A legitimate replacement could admit a cheaper bit circuit; scalar savings alone do not alter the selected moment.", + "allowed_variations": [ + "Choose one helper-star or quartet instance; narrow to one boundary implication." + ], + "scope_change_triggers": [ + "Changing only source count or scalar addition count without an interface argument." + ], + "overlap_terms": [ + "H2_D_frame0_targets_from_helpers", + "K_equals_D", + "helper-star" + ] + }, + "scope_status": "refined", + "actual_scope": "Price the PR848 copy-path helper-sharing wraps (single pair 277->434 and seed-42 greedy matching) under the PR1194 H2-sem replacement contract, including full dirty boundary, paid profile, F/B envelopes and precision guards.", + "scope_change_reason": "The card's first experiment asks for one replacement H2/K implication and its price. PR1194 already states H2-sem; PR1782 admits these wraps under it without an invoice. This package supplies the missing paid profile and precision accounting on the exact PR848 objects, which is the acceptance gate.", + "bottleneck_link": "A priced H2-sem-legal D wrap can reduce scalar ADDs on the nonbinding bit side. The paid recursive profile is checked explicitly; unchanged profile means no selected-moment change.", + "budget_minutes": 60, + "stop_rule": "Stop after one complete invoice for the single-pair and matching wraps with dirty controls, or after a falsifying dirty counterexample to H2-sem on those wraps.", + "outcome": "completed", + "evidence": "PASS_H2SEM_COPYSHARE_PRICED: single pair saves 65 ADDs (24305->24240); matching saves 6231 ADDs (24305->18074); paid profile mass 5129 unchanged; guards 94/177 and 95/180; 661 columns; 7 controls.", + "author": "Wentao Li", + "ai_assistance": "Prepared by Wentao Li with substantial AI assistance", + "open_questions": [ + { + "question": "Can a different matching lower F while keeping most of the ADD saving?", + "why_it_matters": "The seed-42 matching raises F from 49347 to 75381; a joint (ADD,F) optimum could improve precision headroom.", + "first_step": "Re-score a frozen shortlist of positive pairs by a joint (ADD, F) objective and recompute one full invoice.", + "blocked_by": "No favorable completed (ADD, F, B) point is known." + }, + { + "question": "Does the single-pair wrap compose with an already H2-sem-legal star D?", + "why_it_matters": "Composition could stack PR848 sharing with PR967/PR1062 star savings under one interface.", + "first_step": "Splice pair 277->434 onto the PR1062 candidate and recompute the full H2-sem invoice.", + "blocked_by": "Maintainer acceptance of H2-sem on the composed word; full re-invoice cost." + } + ] +} diff --git a/research/h2sem-copyshare-priced/VERIFY.json b/research/h2sem-copyshare-priced/VERIFY.json new file mode 100644 index 0000000000..52ee133979 --- /dev/null +++ b/research/h2sem-copyshare-priced/VERIFY.json @@ -0,0 +1,45 @@ +{ + "schema_version": 1, + "status": "ready", + "python": "3.12", + "requirements": [], + "inputs": [ + "research/e8-bit-p111-tuned/tune/bitE8mut-p111-tuned.json.gz", + "research/e8-bit-p111-tuned/code/xcheck_p.py", + "research/r439-copy-path-sharing-barrier/verify.py", + "research/r439-semantic-d-contract-seed10/PROOF.md" + ], + "commands": [ + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 120, + "checks": "Pins, PR848 census, H2-sem shape, 661 D columns, full COPY/ERASE boundary, F/B guards, paid profile, seven controls." + }, + { + "argv": [ + "{python}", + "-I", + "-O", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 120, + "checks": "Identical PASS under -O (assertions not required for need())." + }, + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/test_package.py" + ], + "timeout_seconds": 180, + "checks": "Relocation smoke plus source-pin, certificate and bill corruption controls." + } + ] +} diff --git a/research/h2sem-copyshare-priced/test_package.py b/research/h2sem-copyshare-priced/test_package.py new file mode 100644 index 0000000000..4c3759b32b --- /dev/null +++ b/research/h2sem-copyshare-priced/test_package.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +"""Relocation smoke and corruption controls for h2sem-copyshare-priced.""" +from __future__ import annotations + +import json +import os +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] + + +def need(ok, message): + if not ok: + raise ValueError(message) + + +def run(args, cwd, expect_ok): + env = {k: v for k, v in os.environ.items() if k != "PYTHONOPTIMIZE"} + proc = subprocess.run(args, cwd=cwd, capture_output=True, text=True, env=env) + ok = proc.returncode == 0 and "PASS_H2SEM_COPYSHARE_PRICED" in proc.stdout + if expect_ok: + need(ok, "expected PASS, got code=%s out=%r err=%r" + % (proc.returncode, proc.stdout[-400:], proc.stderr[-400:])) + else: + need(not ok, "corrupt package unexpectedly passed") + return proc + + +def main(): + with tempfile.TemporaryDirectory(prefix="h2sem-copyshare-") as tmp: + tmp = Path(tmp) + # Path with a space exercises relocation robustness. + dest_root = tmp / "repo with spaces" + pkg = dest_root / "research" / "h2sem-copyshare-priced" + pkg.parent.mkdir(parents=True) + + # Minimal checkout: package + declared inputs + SOURCES provenance files. + shutil.copytree(HERE, pkg) + pins = json.loads((HERE / "SOURCES.json").read_text(encoding="utf-8")) + for item in pins["files"]: + src = ROOT / item["path"] + target = dest_root / item["path"] + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(src, target) + + py = sys.executable + run([py, "-I", "-B", str(pkg / "verify.py")], dest_root, True) + + # Corruption 1: mutate a live input pin byte. + word = dest_root / "research/e8-bit-p111-tuned/tune/bitE8mut-p111-tuned.json.gz" + blob = bytearray(word.read_bytes()) + blob[0] ^= 0xFF + word.write_bytes(blob) + run([py, "-I", "-B", str(pkg / "verify.py")], dest_root, False) + shutil.copy2(ROOT / "research/e8-bit-p111-tuned/tune/bitE8mut-p111-tuned.json.gz", word) + + # Corruption 2: mutate certificate bill. + cert = pkg / "CERTIFICATE.json" + data = json.loads(cert.read_text(encoding="utf-8")) + data["bills"]["single"]["native_ADDs"] += 1 + cert.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") + run([py, "-I", "-B", str(pkg / "verify.py")], dest_root, False) + shutil.copy2(HERE / "CERTIFICATE.json", cert) + + # Corruption 3: drop a control label from the frozen certificate. + data = json.loads(cert.read_text(encoding="utf-8")) + data["controls"] = data["controls"][:-1] + cert.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") + run([py, "-I", "-B", str(pkg / "verify.py")], dest_root, False) + shutil.copy2(HERE / "CERTIFICATE.json", cert) + + # Corruption 4: substitute Boolean for an integer receipt. + data = json.loads(cert.read_text(encoding="utf-8")) + data["rank_mass"] = True + cert.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") + run([py, "-I", "-B", str(pkg / "verify.py")], dest_root, False) + + print("PASS_H2SEM_COPYSHARE_PRICED_PACKAGE_CONTROLS relocation=1 corruptions=4") + + +if __name__ == "__main__": + main() diff --git a/research/h2sem-copyshare-priced/verify.py b/research/h2sem-copyshare-priced/verify.py new file mode 100644 index 0000000000..e777965a2a --- /dev/null +++ b/research/h2sem-copyshare-priced/verify.py @@ -0,0 +1,465 @@ +#!/usr/bin/env python3 +"""Price PR848 helper-sharing wraps under the PR1194 H2-sem contract. + +Finite bit construction and paid invoice under a replacement interface; +no new kappa. Apache-2.0. +""" +from __future__ import annotations + +import copy +import gzip +import hashlib +import importlib.util +import itertools +import json +import random +import sys +from collections import Counter +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +WORD = ROOT / "research/e8-bit-p111-tuned/tune/bitE8mut-p111-tuned.json.gz" +CHECKER = ROOT / "research/e8-bit-p111-tuned/code/xcheck_p.py" +SEED = 42 +PROFILE = {1: 1323, 2: 1342, 3: 79, 4: 44, 5: 102, 6: 11, 7: 19} +BASE_BILL = { + "native_ADDs": 24305, + "D_adds": 18085, + "F": 49347, + "B": 1113070, + "local_bits": 93, + "nine_stage_bits": 177, +} +SINGLE_BILL = { + "native_ADDs": 24240, + "D_adds": 18020, + "F": 50535, + "B": 1113070, + "local_bits": 94, + "nine_stage_bits": 177, +} +MATCH_BILL = { + "native_ADDs": 18074, + "D_adds": 11854, + "F": 75381, + "B": 1196402, + "local_bits": 95, + "nine_stage_bits": 180, +} + + +def need(ok, message): + if not ok: + raise ValueError(message) + + +def canonical(value): + return json.dumps(value, sort_keys=True, separators=(",", ":")).encode() + + +def load_word(): + return json.loads(gzip.decompress(WORD.read_bytes())) + + +def load_checker(): + spec = importlib.util.spec_from_file_location("r439_xcheck_priced", CHECKER) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def check_pins(): + pins = json.loads((HERE / "SOURCES.json").read_text(encoding="utf-8")) + need(pins["base_commit"] == "0b1cccf86e2f5132ed286a26ef0a681a495740ea", "unexpected base") + for item in pins["files"]: + digest = hashlib.sha256((ROOT / item["path"]).read_bytes()).hexdigest() + need(digest == item["sha256"], "source pin mismatch: " + item["path"]) + + +def nominate_d(word, seed): + """Exact PR848 oriented-pair census and seed-42 greedy matching.""" + v, ret = word["v"], set(word["ret"]) + rows = [set(g[2]) for g in word["D"]] + pool = sorted(set.union(*rows) - ret - set(range(2 * v))) + need(min(pool) >= 2 * v, "D reads a non-helper") + scored = [] + for a, b in itertools.permutations(pool, 2): + saving = sum((1 if b in row else -1) for row in rows if a in row) - 2 + if saving > 0: + scored.append((saving, a, b)) + random.Random(seed).shuffle(scored) + scored.sort(key=lambda item: -item[0]) + chosen, used, total = [], set(), 0 + for saving, a, b in scored: + if a not in used and b not in used: + chosen.append([a, b]) + used.update((a, b)) + total += saving + return chosen, { + "operands": len(pool), + "oriented_pairs": len(pool) * (len(pool) - 1), + "positive_pairs": len(scored), + "best_saving": scored[0][0], + "best_pair": [scored[0][1], scored[0][2]], + "matching_pairs": len(chosen), + "matching_saving": total, + } + + +def construct_d(word, pairs): + """PR848 helper-temp wrap: prep, rewritten D body, reverse restore.""" + v, ret = word["v"], set(word["ret"]) + rows_pool = set().union(*(set(g[2]) for g in word["D"])) + flat = [r for pair in pairs for r in pair] + need(all(len(pair) == 2 for pair in pairs), "malformed pair") + need(len(flat) == len(set(flat)), "pairs must be disjoint") + need(all(r >= 2 * v and r not in ret for r in flat) and set(flat) <= rows_pool, + "temps must be non-retained D-operand helpers") + pre = [[0, a, [b]] for a, b in pairs] + body = [] + for frame, dst, srcs in word["D"]: + need(frame == 0 and v <= dst < 2 * v, "D gate not frame-zero target write") + row = set(srcs) + for a, b in pairs: + if a in row: + row.symmetric_difference_update({b}) + body.append([frame, dst, sorted(row)]) + result = copy.deepcopy(word) + result["D"] = pre + body + list(reversed(pre)) + return result + + +def stream(w): + out = [("add", d, s) for sec in ("D", "A") for _, d, ss in w[sec] for s in ss] + tmp = 2 * w["v"] + w["R"] + for j, centre in enumerate(w["ret"]): + out.append(("copy", tmp, centre)) + out += [("add", w["v"] + i, tmp) for i, ss in enumerate(w["scatter"]) if j in ss] + out.append(("erase", tmp, centre)) + out += [("add", d, s) for sec in ("B", "C") for _, d, ss in w[sec] for s in ss] + return out + + +def flip(kind): + return {"copy": "erase", "erase": "copy"}.get(kind, kind) + + +def literal_rows(w, reverse=False): + n = 2 * w["v"] + w["R"] + rows = [{i} for i in range(n)] + [set()] + ins = stream(w) + for kind, d, s in (reversed(ins) if reverse else ins): + kind = flip(kind) if reverse else kind + if kind == "add": + rows[d] ^= rows[s] + elif kind == "copy": + need(not rows[d], "copy into a live temporary") + rows[d] = set(rows[s]) + else: + need(rows[d] == rows[s], "erase of a changed copy") + rows[d] = set() + need(not rows[-1], "temporary not erased") + return rows[:-1] + + +def literal_bounds(w): + peaks = [] + for reverse in (False, True): + val = [1] * (2 * w["v"] + w["R"] + 1) + peak = 1 + ins = stream(w) + for kind, d, s in (reversed(ins) if reverse else ins): + kind = flip(kind) if reverse else kind + val[d] = val[d] + val[s] if kind == "add" else (val[s] if kind == "copy" else 0) + peak = max(peak, val[d]) + peaks.append(peak) + F, B = peaks + return { + "native_ADDs": sum(k == "add" for k, _, _ in stream(w)), + "D_adds": sum(len(g[2]) for g in w["D"]), + "F": F, + "B": B, + "local_bits": (64 * F**3 * B**2).bit_length(), + "nine_stage_bits": ((1 << 18) * F**5 * B**4).bit_length(), + } + + +def frame_paths(w): + fs = [frozenset(f) for f in w["frames"]] + ps = [[f] for f in w["start"]] + for sec in "DABC": + for f, d, ss in w[sec]: + for r in (d, *ss): + if ps[r][-1] != f: + need(fs[ps[r][-1]] < fs[f], "illegal frame move") + ps[r].append(f) + for r, f in enumerate(w["final"]): + if ps[r][-1] != f: + need(fs[ps[r][-1]] < fs[f], "illegal final move") + ps[r].append(f) + return ps + + +def semantic_n(gates, v, R): + """Independent bit-column oracle for D; no row-engine import.""" + n = 2 * v + R + flat = [(d, s) for _, d, ss in gates for s in ss] + mask = (1 << v) - 1 + N = [0] * v + for j in range(n): + state = 1 << j + for d, s in flat: + if (state >> s) & 1: + state ^= 1 << d + delta = state ^ (1 << j) + if j < 2 * v: + need(delta == 0, "source/target column changed in D") + else: + need(delta & ~(mask << v) == 0, "helper restoration failed") + for t in range(v): + if (delta >> (v + t)) & 1: + N[t] |= 1 << (j - 2 * v) + return N + + +def h2sem_shape(w): + """H2-sem conditions 1-2: zero-frame, source-free, no target->helper.""" + v = w["v"] + for frame, dst, srcs in w["D"]: + need(frame == 0, "nonzero D frame") + need(dst >= v, "D writes a source") + for s in srcs: + need(s >= v, "D reads a source") + need(not (v <= s < 2 * v and dst >= 2 * v), "target feeds helper") + need(dst != s, "self XOR") + return True + + +def paid_profile(mod, w): + dim, _labels, flow, hyp, con, _parts = mod.check(w) + prof = Counter(dim.fdim[b] - dim.fdim[a] for p in frame_paths(w) for a, b in itertools.pairwise(p)) + prof.update(t["rank"] for t in flow["totals"]) + return { + "profile": {k: prof[k] for k in sorted(prof)}, + "copy_ranks": [t["rank"] for t in flow["totals"]], + "hypotheses": hyp, + "conclusions": con, + } + + +def controls(word, single, matching, base_n, mod): + """Meaningful negative controls; each must fail the stated obligation.""" + rejected = [] + + unrestored = copy.deepcopy(single) + del unrestored["D"][-1] + try: + semantic_n(unrestored["D"], word["v"], word["R"]) + raise ValueError("unrestored helper temp accepted") + except ValueError as exc: + need("helper restoration" in str(exc), "unexpected unrestored failure") + rejected.append("unrestored_helper_temp") + + a, b = matching[0] + other = next(h for h in range(2 * word["v"], 2 * word["v"] + word["R"]) if h not in (a, b)) + wrong_restore = copy.deepcopy(single) + wrong_restore["D"][-1] = [0, a, [other]] + failed = False + try: + semantic_n(wrong_restore["D"], word["v"], word["R"]) + except ValueError as exc: + need("helper restoration" in str(exc), "unexpected wrong-restore failure: " + str(exc)) + failed = True + need(failed, "wrong restore operand accepted") + rejected.append("wrong_restore_operand") + + feedback = copy.deepcopy(word) + # Target feeds helper before D body: violates H2-sem condition 2 / H1. + target, helper = word["D"][0][1], matching[0][1] + feedback["D"] = [[0, helper, [target]]] + [list(g) for g in word["D"]] + [[0, helper, [target]]] + try: + h2sem_shape(feedback) + raise ValueError("target-feedback wrap accepted by H2-sem shape") + except ValueError as exc: + need("target feeds helper" in str(exc), "unexpected feedback failure") + rejected.append("target_feeds_helper") + + source_read = copy.deepcopy(word) + source_read["D"] = [[0, matching[0][0], [0]]] + [list(g) for g in word["D"]] + [[0, matching[0][0], [0]]] + try: + h2sem_shape(source_read) + raise ValueError("source-read wrap accepted by H2-sem shape") + except ValueError as exc: + need("D reads a source" in str(exc), "unexpected source-read failure") + rejected.append("source_reads_in_D") + + # Dropping one matching pair's restore breaks N or restoration. + drop = construct_d(word, matching[:2]) + del drop["D"][-1] + try: + semantic_n(drop["D"], word["v"], word["R"]) + raise ValueError("partial matching unrestored accepted") + except ValueError: + rejected.append("partial_matching_unrestored") + + # Mutate a body gate destination: changes N. + mutated = copy.deepcopy(single) + mutated["D"][1] = [0, mutated["D"][1][1], list(mutated["D"][1][2])] # keep shape + # Flip one source bit in first body gate after prep. + body_idx = 1 # after single prep + dst, srcs = mutated["D"][body_idx][1], list(mutated["D"][body_idx][2]) + need(srcs, "empty body gate") + # Remove one source if present else add a helper. + if len(srcs) > 1: + srcs = srcs[1:] + else: + srcs = srcs + [matching[0][1]] + mutated["D"][body_idx] = [0, dst, sorted(set(srcs))] + n = semantic_n(mutated["D"], word["v"], word["R"]) + need(n != base_n, "body mutation did not change N") + rejected.append("mutated_body_changes_N") + + # Positive control: target-temp +2 wrap remains H2-legal and costs +2. + legal = copy.deepcopy(word) + helper = matching[0][1] + legal["D"] = [[0, target, [helper]]] + [list(g) for g in word["D"]] + [[0, target, [helper]]] + need(semantic_n(legal["D"], word["v"], word["R"]) == base_n, "target-temp changed N") + need(sum(len(g[2]) for g in legal["D"]) - sum(len(g[2]) for g in word["D"]) == 2, + "target-temp cost is not +2") + hyp = mod.Word(legal).interface()[0] + need(hyp["H2_D_frame0_targets_from_helpers"] is True, "target-temp lost syntactic H2") + rejected.append("target_temp_plus2_positive") + + need(len(rejected) == 7, "expected seven controls") + return rejected + + +def main(): + check_pins() + word = load_word() + mod = load_checker() + + # Baseline must pass the inherited interface completely. + _w, _g, _f, hyp0, con0, _p = mod.check(word) + need(all(hyp0.values()) and all(con0.values()), "baseline H1-H5 / U-J-K-C failed") + + matching, census = nominate_d(word, SEED) + need(census["operands"] == 430, "operand census drift") + need(census["oriented_pairs"] == 184470, "oriented-pair census drift") + need(census["positive_pairs"] == 41404, "positive-pair census drift") + need(census["best_pair"] == [277, 434] and census["best_saving"] == 65, "best pair drift") + need(census["matching_pairs"] == 205 and census["matching_saving"] == 6231, "matching drift") + + single = construct_d(word, [census["best_pair"]]) + full = construct_d(word, matching) + + base_n = semantic_n(word["D"], word["v"], word["R"]) + single_n = semantic_n(single["D"], word["v"], word["R"]) + full_n = semantic_n(full["D"], word["v"], word["R"]) + need(single_n == base_n and full_n == base_n, "semantic N changed") + need(sum(bin(x).count("1") for x in base_n) == 18085, "baseline N weight drift") + + h2sem_shape(word) + h2sem_shape(single) + h2sem_shape(full) + + base_paths = frame_paths(word) + need(frame_paths(single) == base_paths and frame_paths(full) == base_paths, + "frame paths changed") + + want = [{i, i - word["v"]} if word["v"] <= i < 2 * word["v"] else {i} + for i in range(2 * word["v"] + word["R"])] + for name, w in (("base", word), ("single", single), ("match", full)): + for reverse in (False, True): + need(literal_rows(w, reverse) == want, + "%s complete boundary (%s)" % (name, "reverse" if reverse else "forward")) + + bills = {} + for name, w, expected in ( + ("base", word, BASE_BILL), + ("single", single, SINGLE_BILL), + ("match", full, MATCH_BILL), + ): + bill = literal_bounds(w) + need(bill == expected, name + " bill mismatch: " + json.dumps(bill)) + need(bill["local_bits"] <= 104 and bill["nine_stage_bits"] <= 192, + name + " precision guard failed") + bills[name] = bill + + need(bills["single"]["native_ADDs"] - bills["base"]["native_ADDs"] == -65, "single ADD delta") + need(bills["match"]["native_ADDs"] - bills["base"]["native_ADDs"] == -6231, "match ADD delta") + + profiles = {} + for name, w, expect_h2, expect_k in ( + ("base", word, True, True), + ("single", single, False, False), + ("match", full, False, False), + ): + own = paid_profile(mod, w) + need(own["profile"] == PROFILE, name + " paid profile changed") + need(sum(r * c for r, c in own["profile"].items()) == 5129, name + " rank mass") + need(own["copy_ranks"] == [7] * 9, name + " COPY ranks") + need(own["hypotheses"]["H2_D_frame0_targets_from_helpers"] is expect_h2, name + " H2") + need(own["conclusions"]["K_equals_D"] is expect_k, name + " K") + for key in ("H1_no_target_feeds_z", "H3_A_z_only_scatter_targets_B_split", + "H4_C_literal_reverse_at_full", "H5_V_identity"): + need(own["hypotheses"][key] is True, name + " " + key) + for key in ("U_block_form", "J_identity", "C_is_U_inverse"): + need(own["conclusions"][key] is True, name + " " + key) + profiles[name] = own["profile"] + + # Non-D fields unchanged. + for w in (single, full): + for key in word: + if key != "D": + need(w[key] == word[key], "non-D field changed: " + key) + + rejected = controls(word, single, matching, base_n, mod) + + report = { + "status": "PASS_H2SEM_COPYSHARE_PRICED", + "assignment_seed": SEED, + "task_id": "bit-helper-contract", + "base_commit": "0b1cccf86e2f5132ed286a26ef0a681a495740ea", + "columns": 2 * word["v"] + word["R"], + "census": census, + "bills": bills, + "paid_profile": {str(k): PROFILE[k] for k in sorted(PROFILE)}, + "rank_mass": 5129, + "h2sem": { + "shape": True, + "semantic_N_equals_baseline": True, + "syntactic_H2_K": { + "base": {"H2": True, "K_equals_D": True}, + "single": {"H2": False, "K_equals_D": False}, + "match": {"H2": False, "K_equals_D": False}, + }, + }, + "controls": rejected, + "kappa_claim": "none", + "new_kappa": False, + } + certificate = HERE / "CERTIFICATE.json" + if certificate.exists(): + need(report == json.loads(certificate.read_text(encoding="utf-8")), + "certificate mismatch") + else: + certificate.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + + print( + "PASS_H2SEM_COPYSHARE_PRICED " + "single=277->434 adds=24305->24240 " + "matching_pairs=205 adds=24305->18074 " + "profile_mass=5129 columns=%d controls=%d no_new_kappa" + % (report["columns"], len(rejected)) + ) + return report + + +if __name__ == "__main__": + try: + main() + except Exception as exc: # noqa: BLE001 - surface exact verifier failure + print("FAIL_H2SEM_COPYSHARE_PRICED:", exc, file=sys.stderr) + raise