From a16a511a2abdd4576e7fbb7fc4c69455e6ae08ec Mon Sep 17 00:00:00 2001 From: Dylan Roy <249851642+d6g8k5htny-coder@users.noreply.github.com> Date: Thu, 15 Oct 2026 18:55:24 -0500 Subject: [PATCH 1/4] experiments: freeze Reactor A finite amplitude control Engineering-only deterministic control under the RTW-REACTOR-A-FREEZE-20261015 pickup. No sampler, theorem conclusion, campaign result, or scientific-status change. --- .github/workflows/reactor-v0-controls.yml | 36 +++++ experiments/reactor_v0/README.md | 44 ++++++ experiments/reactor_v0/closure.json | 13 ++ experiments/reactor_v0/control.json | 13 ++ experiments/reactor_v0/evaluator.py | 55 +++++++ experiments/reactor_v0/exact_helpers.py | 99 +++++++++++++ experiments/reactor_v0/fixture.json | 7 + experiments/reactor_v0/mutation_harness.py | 91 ++++++++++++ experiments/reactor_v0/run_control.py | 29 ++++ experiments/reactor_v0/source_manifest.json | 27 ++++ experiments/reactor_v0/test_reactor_v0.py | 103 +++++++++++++ experiments/reactor_v0/validator.py | 154 ++++++++++++++++++++ 12 files changed, 671 insertions(+) create mode 100644 .github/workflows/reactor-v0-controls.yml create mode 100644 experiments/reactor_v0/README.md create mode 100644 experiments/reactor_v0/closure.json create mode 100644 experiments/reactor_v0/control.json create mode 100644 experiments/reactor_v0/evaluator.py create mode 100644 experiments/reactor_v0/exact_helpers.py create mode 100644 experiments/reactor_v0/fixture.json create mode 100644 experiments/reactor_v0/mutation_harness.py create mode 100644 experiments/reactor_v0/run_control.py create mode 100644 experiments/reactor_v0/source_manifest.json create mode 100644 experiments/reactor_v0/test_reactor_v0.py create mode 100644 experiments/reactor_v0/validator.py diff --git a/.github/workflows/reactor-v0-controls.yml b/.github/workflows/reactor-v0-controls.yml new file mode 100644 index 000000000..7f29d53a5 --- /dev/null +++ b/.github/workflows/reactor-v0-controls.yml @@ -0,0 +1,36 @@ +name: reactor-v0-controls + +on: + pull_request: + paths: + - 'experiments/reactor_v0/**' + - '.github/workflows/reactor-v0-controls.yml' + push: + branches: [main] + paths: + - 'experiments/reactor_v0/**' + - '.github/workflows/reactor-v0-controls.yml' + +permissions: + contents: read + +jobs: + finite-control: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.11' + - name: Normal tests and control + run: | + python3 -B -m unittest discover -s experiments/reactor_v0 -p 'test_*.py' -v + python3 -B experiments/reactor_v0/mutation_harness.py + python3 -B experiments/reactor_v0/run_control.py + - name: Optimized tests and control + run: | + python3 -B -O -m unittest discover -s experiments/reactor_v0 -p 'test_*.py' -v + python3 -B -O experiments/reactor_v0/mutation_harness.py + python3 -B -O experiments/reactor_v0/run_control.py + - name: Frozen run stage is read-only + run: git diff --exit-code -- experiments/reactor_v0 .github/workflows/reactor-v0-controls.yml diff --git a/experiments/reactor_v0/README.md b/experiments/reactor_v0/README.md new file mode 100644 index 000000000..3ac5e5b47 --- /dev/null +++ b/experiments/reactor_v0/README.md @@ -0,0 +1,44 @@ +# Reactor v0 — finite amplitude-transform control freeze + +This directory freezes one deterministic, engineering-only regression control. +It does **not** sample a random field, run a campaign, consume a Gaussian or +asymptotic theorem conclusion, alter a scientific status, or execute Reactor B. + +The 4×4 periodic integer grid in `fixture.json` has positive finite ordinary +superlevel H0 bars `[[1, 0], [8, 0]]` and essential birth `27`. The essential +class is excluded. For the declared whole-field amplitude law parameters +`alpha = 2/3`, `a = 2`, and `t = 1/4`, the exact exposed regression control is + +```text +sum_i min((t / (a * lifetime_i))**alpha, 1) = 1/4 + 1/16 = 5/16. +``` + +Only rational powers whose required rational roots are exact are supported; +other inputs raise `ValueError`. Positive finite-bar selection uses the +inclusive rule `birth - death <= t` in the grid's input units. Expected answers +are exposed regression controls, not blind discoveries. + +`source_manifest.json` allowlists the two open parent proof commits and records +raw-byte SHA-256 separately from Git blob membership. Both entries explicitly +say that no theorem conclusion is consumed. `closure.json` pins every consumed +helper, fixture, test, validator, runner, mutation harness, README, manifest, +and path-scoped workflow by raw SHA-256; it intentionally cannot hash itself. + +Run the complete frozen controls from the repository root: + +```sh +python3 -B -m unittest discover -s experiments/reactor_v0 -p 'test_*.py' -v +python3 -B -O -m unittest discover -s experiments/reactor_v0 -p 'test_*.py' -v +python3 -B experiments/reactor_v0/mutation_harness.py +python3 -B -O experiments/reactor_v0/mutation_harness.py +python3 -B experiments/reactor_v0/run_control.py +python3 -B -O experiments/reactor_v0/run_control.py +``` + +The workflow has read-only repository permissions, is triggered only by this +directory or its own workflow file, and ends with a clean-worktree check so the +run stage cannot silently edit the evaluator, tests, or any other tracked input. + +Canonical coordination: [Reactor A pickup](https://github.com/d6g8k5htny-coder/main/issues/419#issuecomment-6204609205), +[owner mandate](https://github.com/d6g8k5htny-coder/main/blob/b665307520948308a53d190d7341bf301df3b3a2/governance/OWNER_MANDATE_20261015.md), +and [standing delegation](https://github.com/d6g8k5htny-coder/main/blob/main/governance/OP-AUTONOMY-20260923-v2.1.md). diff --git a/experiments/reactor_v0/closure.json b/experiments/reactor_v0/closure.json new file mode 100644 index 000000000..6dfb58000 --- /dev/null +++ b/experiments/reactor_v0/closure.json @@ -0,0 +1,13 @@ +{ + ".github/workflows/reactor-v0-controls.yml": "64507243afbe7af49ff6be3d4ad07da45bc0608a0b60fbac3e36b93d8b0ebcb8", + "experiments/reactor_v0/README.md": "2a50cb3efb4b14338e1cad20e0f09c26778a21a4683d75708fb6b80356dc8e3a", + "experiments/reactor_v0/control.json": "ad7066c7f8b7073edb5da910250f714f969bae2e164646a4c8c7cecffa9b43a1", + "experiments/reactor_v0/evaluator.py": "92fe4dd24be870c1651b59a2e9f2a110a8b008d99f6c601efb60e11a6922c5dd", + "experiments/reactor_v0/exact_helpers.py": "2569978f248a28b3754dad8d6ba4d80b47febf338a7db925f17f53723145cb61", + "experiments/reactor_v0/fixture.json": "8fd0ffb74fc98ccb022c0f4652922bd2881dae11ef11902b7d4e79235b7f94ea", + "experiments/reactor_v0/mutation_harness.py": "0acb0a4300cb04eae12c3001c178eb32aac78ec8ae06de4c387cd48c11d09556", + "experiments/reactor_v0/run_control.py": "6af0e3ab778dbe980860fb4d7d78d83f00bd67844c882ad72876b94d050854e3", + "experiments/reactor_v0/source_manifest.json": "86c55b140acc6cf8219915f16df995085eafd95c61c249a6cde29b73a83f9c8d", + "experiments/reactor_v0/test_reactor_v0.py": "eb53592024f9cdb47ec253e564749fe174e4e7997f85ac700b2a97d904bf29e4", + "experiments/reactor_v0/validator.py": "b7fc075db19457b50a42c2295f7fbf39d045176c72577f86aff5ad0a5613b3af" +} diff --git a/experiments/reactor_v0/control.json b/experiments/reactor_v0/control.json new file mode 100644 index 000000000..52b867310 --- /dev/null +++ b/experiments/reactor_v0/control.json @@ -0,0 +1,13 @@ +{ + "alpha": {"denominator": 3, "numerator": 2}, + "amplitude_scale": {"denominator": 1, "numerator": 2}, + "campaign_status": "B_UNRESOLVED_NO_RUN", + "closure": "closure.json", + "expected_control": {"denominator": 16, "numerator": 5}, + "fixture": "fixture.json", + "schema_version": 1, + "scientific_status_effect": "NONE", + "scope": "ENGINEERING_ONLY_FINITE_AMPLITUDE_TRANSFORM_CONTROL", + "sources": "source_manifest.json", + "threshold": {"denominator": 4, "numerator": 1} +} diff --git a/experiments/reactor_v0/evaluator.py b/experiments/reactor_v0/evaluator.py new file mode 100644 index 000000000..b25a6332a --- /dev/null +++ b/experiments/reactor_v0/evaluator.py @@ -0,0 +1,55 @@ +"""Finite amplitude-transform regression control; no sampler or theorem use.""" + +from fractions import Fraction + +from exact_helpers import exact_periodic_h0, rational_power_exact + + +def short_bar_lifetimes(barcode, threshold): + """Select positive finite bars with inclusive lifetime threshold.""" + if type(threshold) is not Fraction or threshold < 0: + raise ValueError("nonnegative exact Fraction threshold required") + intervals = barcode.get("intervals") + if type(intervals) is not list: + raise ValueError("finite intervals list required") + lifetimes = [] + for pair in intervals: + if (type(pair) is not list or len(pair) != 2 or + any(type(endpoint) is not int for endpoint in pair)): + raise ValueError("strict integer finite-bar endpoints required") + lifetime = pair[0] - pair[1] + if lifetime <= 0: + raise ValueError("positive finite bars required") + if Fraction(lifetime) <= threshold: + lifetimes.append(lifetime) + return tuple(lifetimes) + + +def _fraction(document): + return Fraction(document["numerator"], document["denominator"]) + + +def evaluate_package(package): + fixture = package["fixture"] + control = package["control"] + barcode = exact_periodic_h0(fixture["values"], fixture["grid_side"]) + if barcode != fixture["expected_barcode"]: + raise ValueError("exact barcode differs from frozen regression fixture") + threshold = _fraction(control["threshold"]) + alpha = _fraction(control["alpha"]) + amplitude_scale = _fraction(control["amplitude_scale"]) + finite_lifetimes = tuple(birth - death for birth, death in barcode["intervals"]) + # The finite transform integrates each declared positive finite lifetime. + terms = [] + for lifetime in finite_lifetimes: + base = threshold / (amplitude_scale * lifetime) + terms.append(min(rational_power_exact(base, alpha), Fraction(1))) + expected = sum(terms, Fraction(0)) + if expected != _fraction(control["expected_control"]): + raise ValueError("declared expected control differs from exact evaluation") + return { + "finite_bars": tuple(tuple(pair) for pair in barcode["intervals"]), + "essential_birth": barcode["essential"][0], + "included_lifetimes": finite_lifetimes, + "expected_short_bar_count": expected, + } diff --git a/experiments/reactor_v0/exact_helpers.py b/experiments/reactor_v0/exact_helpers.py new file mode 100644 index 000000000..59d19cbb2 --- /dev/null +++ b/experiments/reactor_v0/exact_helpers.py @@ -0,0 +1,99 @@ +"""Copied exact helpers consumed by the Reactor A finite control only.""" + +from array import array +from fractions import Fraction + + +def _require(condition, message): + if not condition: + raise ValueError(message) + + +def exact_periodic_h0(values, side): + """Return positive finite superlevel H0 bars and the essential birth. + + This is the consumed union-find core of ``periodic_h0/exact_h0.py``. + Endpoints remain in strict integer input units and axis edges wrap. + """ + _require(type(side) is int and side >= 3, "integer grid side >= 3 required") + _require(type(values) in (list, tuple) and len(values) == side * side, + "flat square list or tuple required") + _require(all(type(value) is int for value in values), + "strict integer samples required") + count = len(values) + parent = array("i", [-1]) * count + sizes = array("I", [0]) * count + eldest = array("I", [0]) * count + order = sorted(range(count), key=values.__getitem__, reverse=True) + records = [] + + def root(index): + while parent[index] != index: + parent[index] = parent[parent[index]] + index = parent[index] + return index + + for vertex in order: + parent[vertex] = vertex + sizes[vertex] = 1 + eldest[vertex] = vertex + row, column = divmod(vertex, side) + neighbors = ( + ((row - 1) % side) * side + column, + ((row + 1) % side) * side + column, + row * side + (column - 1) % side, + row * side + (column + 1) % side, + ) + for neighbor in neighbors: + if parent[neighbor] < 0: + continue + left, right = root(vertex), root(neighbor) + if left == right: + continue + survivor, dying = eldest[left], eldest[right] + if (values[survivor] < values[dying] or + (values[survivor] == values[dying] and survivor > dying)): + survivor, dying = dying, survivor + birth, death = values[dying], values[vertex] + if birth > death: + records.append((birth, death, dying)) + if sizes[left] < sizes[right]: + left, right = right, left + parent[right] = left + sizes[left] += sizes[right] + eldest[left] = survivor + records.sort() + essential_vertex = eldest[root(0)] + return { + "intervals": [[birth, death] for birth, death, _ in records], + "essential": [values[essential_vertex]], + } + + +def _integer_root_exact(value, order): + _require(type(value) is int and value >= 0, "nonnegative integer radicand required") + _require(type(order) is int and order > 0, "positive integer root order required") + low, high = 0, value + 1 + while low + 1 < high: + middle = (low + high) // 2 + if middle ** order <= value: + low = middle + else: + high = middle + if low ** order != value: + raise ValueError("rational root is not exact; exact control refused") + return low + + +def rational_power_exact(value, exponent): + """Return ``value**exponent`` only when the rational root is exact.""" + _require(type(value) in (int, Fraction) and value >= 0, + "nonnegative exact rational base required") + _require(type(exponent) is Fraction and exponent > 0, + "positive Fraction exponent required") + value = Fraction(value) + root = Fraction( + _integer_root_exact(value.numerator, exponent.denominator), + _integer_root_exact(value.denominator, exponent.denominator), + ) + return root ** exponent.numerator diff --git a/experiments/reactor_v0/fixture.json b/experiments/reactor_v0/fixture.json new file mode 100644 index 000000000..7e847e005 --- /dev/null +++ b/experiments/reactor_v0/fixture.json @@ -0,0 +1,7 @@ +{ + "exclusions": ["essential_class"], + "expected_barcode": {"essential": [27], "intervals": [[1, 0], [8, 0]]}, + "grid_side": 4, + "schema_version": 1, + "values": [27, 0, 8, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0] +} diff --git a/experiments/reactor_v0/mutation_harness.py b/experiments/reactor_v0/mutation_harness.py new file mode 100644 index 000000000..75d47128b --- /dev/null +++ b/experiments/reactor_v0/mutation_harness.py @@ -0,0 +1,91 @@ +"""Kill seeded one-point mutations of the strict package validator.""" + +import copy +import json +from pathlib import Path +import subprocess +import sys +import tempfile + + +HERE = Path(__file__).resolve().parent +VALIDATOR = HERE / "validator.py" + + +MUTANTS = { + "allow_missing_field": ( + "set(document) == expected", + "set(document) <= expected", + "missing", + ), + "allow_scientific_status_promotion": ( + 'document["scientific_status_effect"] == "NONE"', + 'document["scientific_status_effect"] in ("NONE", "ACCEPTED")', + "status", + ), + "allow_theorem_consumption": ( + 'source["theorem_conclusion_consumed"] is False', + 'source["theorem_conclusion_consumed"] in (False, True)', + "theorem", + ), + "allow_incomplete_closure": ( + "set(closure) == REQUIRED_CLOSURE", + "set(closure) <= REQUIRED_CLOSURE", + "closure", + ), +} + + +PROBE = r'''import copy, importlib.util, json, pathlib, sys +spec = importlib.util.spec_from_file_location("mutated_validator", sys.argv[1]) +module = importlib.util.module_from_spec(spec) +spec.loader.exec_module(module) +here = pathlib.Path(sys.argv[2]) +kind = sys.argv[3] +control = json.loads((here / "control.json").read_text()) +sources = json.loads((here / "source_manifest.json").read_text()) +try: + if kind == "missing": + del control["scientific_status_effect"] + module.validate_document(control) + elif kind == "status": + control["scientific_status_effect"] = "ACCEPTED" + module.validate_document(control) + elif kind == "theorem": + sources["sources"][0]["theorem_conclusion_consumed"] = True + module._validate_sources(sources) + elif kind == "closure": + module.verify_closure(here, {}) + else: + raise RuntimeError("unknown probe") +except ValueError: + raise SystemExit(0) +raise SystemExit(1) +''' + + +def run(): + source = VALIDATOR.read_text(encoding="utf-8") + killed = [] + for name, (old, new, probe) in MUTANTS.items(): + if source.count(old) != 1: + raise RuntimeError(name + " mutation point is not unique") + mutated = source.replace(old, new, 1) + with tempfile.TemporaryDirectory(prefix="reactor-v0-mutant-") as temporary: + path = Path(temporary) / "validator.py" + path.write_text(mutated, encoding="utf-8") + completed = subprocess.run( + [sys.executable, "-O", "-B", "-c", PROBE, str(path), str(HERE), probe], + text=True, + capture_output=True, + check=False, + ) + if completed.returncode != 0: + killed.append(name) + else: + raise RuntimeError(name + " survived its negative probe") + return killed + + +if __name__ == "__main__": + print(json.dumps({"killed": run()}, sort_keys=True)) diff --git a/experiments/reactor_v0/run_control.py b/experiments/reactor_v0/run_control.py new file mode 100644 index 000000000..6430a901d --- /dev/null +++ b/experiments/reactor_v0/run_control.py @@ -0,0 +1,29 @@ +"""Validate and run the frozen deterministic Reactor A control.""" + +from fractions import Fraction +import json +from pathlib import Path + +from evaluator import evaluate_package +from validator import load_and_validate + + +def _render(value): + if type(value) is Fraction: + return str(value) + if type(value) is tuple: + return [_render(item) for item in value] + return value + + +if __name__ == "__main__": + directory = Path(__file__).resolve().parent + package = load_and_validate(directory) + result = {key: _render(value) for key, value in evaluate_package(package).items()} + result.update({ + "scope": package["control"]["scope"], + "scientific_status_effect": package["control"]["scientific_status_effect"], + "campaign_status": package["control"]["campaign_status"], + "validated": True, + }) + print(json.dumps(result, sort_keys=True, indent=2)) diff --git a/experiments/reactor_v0/source_manifest.json b/experiments/reactor_v0/source_manifest.json new file mode 100644 index 000000000..7780809a1 --- /dev/null +++ b/experiments/reactor_v0/source_manifest.json @@ -0,0 +1,27 @@ +{ + "schema_version": 1, + "sources": [ + { + "byte_length": 42478, + "commit": "88ff9223e57bf38c7fc33cb3559a88793a7b5087", + "git_blob_sha": "72c8964740731a50c461d7d2b2eb2599fdfdc16d", + "path": "experiments/universality/spectral_gaussian_admission/PROOF.md", + "pull_request": 330, + "raw_sha256": "6c0f34cb318d337b3b8c2c306f3b965f5e5a9d2fe38d5e001b8044de74b7f225", + "repository": "d6g8k5htny-coder/main", + "source_status": "OPEN_UNMERGED_AT_FREEZE", + "theorem_conclusion_consumed": false + }, + { + "byte_length": 37461, + "commit": "6bd133d591e43e75a9292463bb4bfde7a34984dc", + "git_blob_sha": "5a8b9c525277dcdabdedc372d2ae2f0f39a0cc54", + "path": "experiments/universality/spectral_amplitude_crossover/PROOF.md", + "pull_request": 334, + "raw_sha256": "aeea6b55a1876c357d9beeeb5a96ee54a5b17b53c6138e2993c454f1117f65d5", + "repository": "d6g8k5htny-coder/main", + "source_status": "OPEN_UNMERGED_AT_FREEZE", + "theorem_conclusion_consumed": false + } + ] +} diff --git a/experiments/reactor_v0/test_reactor_v0.py b/experiments/reactor_v0/test_reactor_v0.py new file mode 100644 index 000000000..438916e3f --- /dev/null +++ b/experiments/reactor_v0/test_reactor_v0.py @@ -0,0 +1,103 @@ +import copy +import json +import os +from fractions import Fraction +from pathlib import Path +import subprocess +import sys +import unittest + + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +if str(HERE) not in sys.path: + sys.path.insert(0, str(HERE)) + + +class ReactorFreezeTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + from evaluator import evaluate_package + from validator import load_and_validate + + cls.evaluate_package = staticmethod(evaluate_package) + cls.load_and_validate = staticmethod(load_and_validate) + cls.package = load_and_validate(HERE) + + def test_exposed_control_is_exact_five_sixteenths(self): + result = self.evaluate_package(self.package) + self.assertEqual(result["expected_short_bar_count"], Fraction(5, 16)) + self.assertEqual(result["finite_bars"], ((1, 0), (8, 0))) + self.assertEqual(result["essential_birth"], 27) + self.assertEqual(result["included_lifetimes"], (1, 8)) + + def test_tampered_expected_control_is_rejected(self): + package = copy.deepcopy(self.package) + package["control"]["expected_control"] = {"numerator": 1, "denominator": 2} + with self.assertRaisesRegex(ValueError, "declared expected control"): + self.evaluate_package(package) + + def test_threshold_is_inclusive_and_essential_class_is_excluded(self): + from evaluator import short_bar_lifetimes + + barcode = {"intervals": [[3, 1], [8, 0]], "essential": [27]} + self.assertEqual(short_bar_lifetimes(barcode, Fraction(2)), (2,)) + + def test_unsupported_exact_root_is_refused(self): + from exact_helpers import rational_power_exact + + with self.assertRaisesRegex(ValueError, "rational root"): + rational_power_exact(Fraction(1, 2), Fraction(2, 3)) + + def test_schema_rejects_missing_extra_wrong_type_and_status_effect(self): + from validator import validate_document + + good = json.loads((HERE / "control.json").read_text(encoding="utf-8")) + mutations = [] + missing = copy.deepcopy(good) + del missing["scientific_status_effect"] + mutations.append(missing) + extra = copy.deepcopy(good) + extra["unexpected"] = False + mutations.append(extra) + wrong_type = copy.deepcopy(good) + wrong_type["threshold"] = 1.0 + mutations.append(wrong_type) + wrong_status = copy.deepcopy(good) + wrong_status["scientific_status_effect"] = "ACCEPTED" + mutations.append(wrong_status) + for document in mutations: + with self.subTest(document=document), self.assertRaises(ValueError): + validate_document(document) + + def test_source_manifest_separates_raw_hash_from_git_membership(self): + sources = self.package["sources"] + self.assertEqual(len(sources), 2) + for source in sources: + self.assertEqual(source["repository"], "d6g8k5htny-coder/main") + self.assertEqual(len(source["commit"]), 40) + self.assertEqual(len(source["raw_sha256"]), 64) + self.assertEqual(len(source["git_blob_sha"]), 40) + self.assertFalse(source["theorem_conclusion_consumed"]) + + def test_consumed_closure_hashes_match_exact_bytes(self): + from validator import verify_closure + + self.assertTrue(verify_closure(HERE, self.package["closure"])) + + def test_optimized_child_process_runs_validator_and_evaluator(self): + completed = subprocess.run( + [sys.executable, "-O", "-B", str(HERE / "run_control.py")], + cwd=ROOT, + text=True, + capture_output=True, + check=False, + ) + self.assertEqual(completed.returncode, 0, completed.stderr) + payload = json.loads(completed.stdout) + self.assertEqual(payload["expected_short_bar_count"], "5/16") + self.assertTrue(payload["validated"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/reactor_v0/validator.py b/experiments/reactor_v0/validator.py new file mode 100644 index 000000000..adfc61391 --- /dev/null +++ b/experiments/reactor_v0/validator.py @@ -0,0 +1,154 @@ +"""Strict validator for the Reactor A freeze package.""" + +import hashlib +import json +from pathlib import Path + + +CONTROL_KEYS = { + "schema_version", "scope", "scientific_status_effect", "fixture", + "sources", "closure", "alpha", "amplitude_scale", "threshold", + "expected_control", "campaign_status", +} +SOURCE_KEYS = { + "repository", "commit", "path", "byte_length", "raw_sha256", + "git_blob_sha", "pull_request", "theorem_conclusion_consumed", + "source_status", +} +RATIONAL_KEYS = {"numerator", "denominator"} +REQUIRED_CLOSURE = { + ".github/workflows/reactor-v0-controls.yml", + "experiments/reactor_v0/README.md", + "experiments/reactor_v0/control.json", + "experiments/reactor_v0/source_manifest.json", + "experiments/reactor_v0/fixture.json", + "experiments/reactor_v0/exact_helpers.py", + "experiments/reactor_v0/evaluator.py", + "experiments/reactor_v0/validator.py", + "experiments/reactor_v0/run_control.py", + "experiments/reactor_v0/test_reactor_v0.py", + "experiments/reactor_v0/mutation_harness.py", +} + + +def _require(condition, message): + if not condition: + raise ValueError(message) + + +def _object(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError("duplicate JSON key: " + key) + result[key] = value + return result + + +def _load_json(path): + try: + return json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=_object) + except (json.JSONDecodeError, UnicodeDecodeError) as error: + raise ValueError("invalid UTF-8 JSON: " + str(path)) from error + + +def _strict_keys(document, expected, name): + _require(type(document) is dict and set(document) == expected, + name + " has missing or extra fields") + + +def _rational(document, name): + _strict_keys(document, RATIONAL_KEYS, name) + _require(type(document["numerator"]) is int and + type(document["denominator"]) is int and + document["denominator"] > 0, name + " must be an exact rational") + + +def validate_document(document): + _strict_keys(document, CONTROL_KEYS, "control") + _require(document["schema_version"] == 1 and type(document["schema_version"]) is int, + "unsupported control schema") + _require(document["scope"] == "ENGINEERING_ONLY_FINITE_AMPLITUDE_TRANSFORM_CONTROL", + "unexpected control scope") + _require(document["scientific_status_effect"] == "NONE", + "scientific_status_effect must be NONE") + _require(document["campaign_status"] == "B_UNRESOLVED_NO_RUN", + "campaign B must remain UNRESOLVED/no-run") + for key in ("fixture", "sources", "closure"): + _require(type(document[key]) is str and document[key] and "/" not in document[key], + key + " must be a local filename") + for key in ("alpha", "amplitude_scale", "threshold", "expected_control"): + _rational(document[key], key) + return True + + +def _validate_fixture(document): + expected = {"schema_version", "grid_side", "values", "expected_barcode", "exclusions"} + _strict_keys(document, expected, "fixture") + _require(document["schema_version"] == 1 and type(document["schema_version"]) is int, + "unsupported fixture schema") + side = document["grid_side"] + values = document["values"] + _require(type(side) is int and side == 4, "exact 4x4 fixture required") + _require(type(values) is list and len(values) == 16 and + all(type(value) is int for value in values), "strict 4x4 integer values required") + _require(document["expected_barcode"] == {"intervals": [[1, 0], [8, 0]], "essential": [27]}, + "unexpected exposed barcode oracle") + _require(document["exclusions"] == ["essential_class"], + "essential class must be excluded") + + +def _validate_sources(document): + _require(type(document) is dict and set(document) == {"schema_version", "sources"}, + "source manifest has missing or extra fields") + _require(document["schema_version"] == 1 and type(document["schema_version"]) is int, + "unsupported source manifest schema") + sources = document["sources"] + _require(type(sources) is list and len(sources) == 2, "exactly two parent sources required") + for source in sources: + _strict_keys(source, SOURCE_KEYS, "source") + _require(source["repository"] == "d6g8k5htny-coder/main", "unexpected source repository") + _require(type(source["commit"]) is str and len(source["commit"]) == 40, + "full source commit required") + _require(type(source["path"]) is str and source["path"].endswith("/PROOF.md"), + "proof source path required") + _require(type(source["byte_length"]) is int and source["byte_length"] > 0, + "positive source byte length required") + _require(type(source["raw_sha256"]) is str and len(source["raw_sha256"]) == 64, + "raw SHA-256 required") + _require(type(source["git_blob_sha"]) is str and len(source["git_blob_sha"]) == 40, + "Git blob membership identity required separately") + _require(type(source["pull_request"]) is int and source["pull_request"] in (330, 334), + "parent PR allowlist mismatch") + _require(source["theorem_conclusion_consumed"] is False, + "A may consume no theorem conclusion") + _require(source["source_status"] == "OPEN_UNMERGED_AT_FREEZE", + "source status must remain explicit") + return sources + + +def verify_closure(package_directory, closure): + repository_root = Path(package_directory).resolve().parents[1] + _require(type(closure) is dict and set(closure) == REQUIRED_CLOSURE, + "consumed closure path set mismatch") + for relative, digest in closure.items(): + _require(type(digest) is str and len(digest) == 64, + "closure SHA-256 must be 64 lowercase hex characters") + path = repository_root / relative + _require(path.is_file(), "missing closure path: " + relative) + actual = hashlib.sha256(path.read_bytes()).hexdigest() + _require(actual == digest, "closure hash mismatch: " + relative) + return True + + +def load_and_validate(package_directory): + directory = Path(package_directory).resolve() + control = _load_json(directory / "control.json") + validate_document(control) + fixture = _load_json(directory / control["fixture"]) + _validate_fixture(fixture) + source_manifest = _load_json(directory / control["sources"]) + sources = _validate_sources(source_manifest) + closure = _load_json(directory / control["closure"]) + verify_closure(directory, closure) + return {"control": control, "fixture": fixture, "sources": sources, "closure": closure} From d1fdf077435190831314b5960807ef2c195e2f41 Mon Sep 17 00:00:00 2001 From: Dylan Roy <249851642+d6g8k5htny-coder@users.noreply.github.com> Date: Thu, 15 Oct 2026 20:09:28 -0500 Subject: [PATCH 2/4] fix: close Reactor A review findings Bind exact parent source objects, harden negative and freeze controls, add amplitude scaling coverage, and clarify counted-event semantics. Engineering-only; no campaign run or scientific-status change. --- .github/workflows/reactor-v0-controls.yml | 73 +++++- experiments/reactor_v0/README.md | 8 +- experiments/reactor_v0/closure.json | 10 +- experiments/reactor_v0/mutation_harness.py | 45 ++-- experiments/reactor_v0/test_reactor_v0.py | 273 +++++++++++++++++++++ experiments/reactor_v0/validator.py | 115 ++++++++- 6 files changed, 486 insertions(+), 38 deletions(-) diff --git a/.github/workflows/reactor-v0-controls.yml b/.github/workflows/reactor-v0-controls.yml index 7f29d53a5..ea0bef9b8 100644 --- a/.github/workflows/reactor-v0-controls.yml +++ b/.github/workflows/reactor-v0-controls.yml @@ -17,11 +17,75 @@ permissions: jobs: finite-control: runs-on: ubuntu-latest + timeout-minutes: 10 + env: + REACTOR_VERIFY_SOURCES: '1' steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 with: python-version: '3.11' + - name: Fetch and bind exact parent source objects + run: | + git fetch --no-tags --depth=1 origin \ + 88ff9223e57bf38c7fc33cb3559a88793a7b5087 \ + 6bd133d591e43e75a9292463bb4bfde7a34984dc + - name: Preserve an existing frozen closure + if: github.event_name == 'pull_request' + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + run: | + python3 -B - <<'PY' + import hashlib + import json + from pathlib import Path + import os + import subprocess + + closure_path = "experiments/reactor_v0/closure.json" + closure_file = Path(closure_path) + package = Path("experiments/reactor_v0") + package_entries = list(package.rglob("*")) + if (closure_file.is_symlink() or package.is_symlink() or + any(path.is_symlink() for path in package_entries)): + raise SystemExit("frozen package may not contain symlinks") + base = os.environ["BASE_SHA"] + prior = subprocess.run( + ["git", "show", base + ":" + closure_path], + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + check=False, + ) + if prior.returncode != 0: + print("Base has no Reactor A freeze; introduction is permitted.") + raise SystemExit(0) + current = closure_file.read_bytes() + if current != prior.stdout: + raise SystemExit("frozen closure.json differs from pull-request base") + closure = json.loads(prior.stdout) + expected_package = { + Path(path).relative_to("experiments/reactor_v0").as_posix() + for path in closure + if path.startswith("experiments/reactor_v0/") + } | {"closure.json"} + actual_package = { + path.relative_to(package).as_posix() + for path in package_entries + if not path.is_dir() + } + if actual_package != expected_package: + raise SystemExit("frozen package file set differs from pull-request base") + for relative, expected in closure.items(): + path = Path(relative) + if path.is_symlink(): + raise SystemExit("frozen closure member may not be a symlink: " + relative) + actual = hashlib.sha256(path.read_bytes()).hexdigest() + if actual != expected: + raise SystemExit("frozen byte mismatch: " + relative) + PY - name: Normal tests and control run: | python3 -B -m unittest discover -s experiments/reactor_v0 -p 'test_*.py' -v @@ -33,4 +97,7 @@ jobs: python3 -B -O experiments/reactor_v0/mutation_harness.py python3 -B -O experiments/reactor_v0/run_control.py - name: Frozen run stage is read-only - run: git diff --exit-code -- experiments/reactor_v0 .github/workflows/reactor-v0-controls.yml + run: | + git diff --exit-code -- experiments/reactor_v0 .github/workflows/reactor-v0-controls.yml + test -z "$(git status --porcelain --untracked-files=all --ignored -- \ + experiments/reactor_v0 .github/workflows/reactor-v0-controls.yml)" diff --git a/experiments/reactor_v0/README.md b/experiments/reactor_v0/README.md index 3ac5e5b47..184ab0c56 100644 --- a/experiments/reactor_v0/README.md +++ b/experiments/reactor_v0/README.md @@ -14,9 +14,11 @@ sum_i min((t / (a * lifetime_i))**alpha, 1) = 1/4 + 1/16 = 5/16. ``` Only rational powers whose required rational roots are exact are supported; -other inputs raise `ValueError`. Positive finite-bar selection uses the -inclusive rule `birth - death <= t` in the grid's input units. Expected answers -are exposed regression controls, not blind discoveries. +other inputs raise `ValueError`. The counted event is +`A * (birth - death) <= t` (inclusive), so every positive finite bar contributes +`min((t / (a * lifetime))**alpha, 1)`; the inclusive selector +`short_bar_lifetimes` applies to a fixed realised barcode. Expected answers are +exposed regression controls, not blind discoveries. `source_manifest.json` allowlists the two open parent proof commits and records raw-byte SHA-256 separately from Git blob membership. Both entries explicitly diff --git a/experiments/reactor_v0/closure.json b/experiments/reactor_v0/closure.json index 6dfb58000..8d8c68329 100644 --- a/experiments/reactor_v0/closure.json +++ b/experiments/reactor_v0/closure.json @@ -1,13 +1,13 @@ { - ".github/workflows/reactor-v0-controls.yml": "64507243afbe7af49ff6be3d4ad07da45bc0608a0b60fbac3e36b93d8b0ebcb8", - "experiments/reactor_v0/README.md": "2a50cb3efb4b14338e1cad20e0f09c26778a21a4683d75708fb6b80356dc8e3a", + ".github/workflows/reactor-v0-controls.yml": "602293812abea738dfc8ae300a68bdae027d23be717db6a907133e248074705e", + "experiments/reactor_v0/README.md": "cde3ed5286a254ea8d817ad1cd92c71e8d4ba58670046e67fa4eb5df4f9bb474", "experiments/reactor_v0/control.json": "ad7066c7f8b7073edb5da910250f714f969bae2e164646a4c8c7cecffa9b43a1", "experiments/reactor_v0/evaluator.py": "92fe4dd24be870c1651b59a2e9f2a110a8b008d99f6c601efb60e11a6922c5dd", "experiments/reactor_v0/exact_helpers.py": "2569978f248a28b3754dad8d6ba4d80b47febf338a7db925f17f53723145cb61", "experiments/reactor_v0/fixture.json": "8fd0ffb74fc98ccb022c0f4652922bd2881dae11ef11902b7d4e79235b7f94ea", - "experiments/reactor_v0/mutation_harness.py": "0acb0a4300cb04eae12c3001c178eb32aac78ec8ae06de4c387cd48c11d09556", + "experiments/reactor_v0/mutation_harness.py": "ea74ee40a6ace0b6ee5152e67876be4841c2643a0646a658ab7d6758f441e78e", "experiments/reactor_v0/run_control.py": "6af0e3ab778dbe980860fb4d7d78d83f00bd67844c882ad72876b94d050854e3", "experiments/reactor_v0/source_manifest.json": "86c55b140acc6cf8219915f16df995085eafd95c61c249a6cde29b73a83f9c8d", - "experiments/reactor_v0/test_reactor_v0.py": "eb53592024f9cdb47ec253e564749fe174e4e7997f85ac700b2a97d904bf29e4", - "experiments/reactor_v0/validator.py": "b7fc075db19457b50a42c2295f7fbf39d045176c72577f86aff5ad0a5613b3af" + "experiments/reactor_v0/test_reactor_v0.py": "9a0dbd7d7a9e903466d6834f19e3917ce2877ea9b832cc8fffc119f131b86d68", + "experiments/reactor_v0/validator.py": "2d39c1bd844f49d43aa380443fa384f8e3a0aeb9df6173a3fcf9eeaeb150bef3" } diff --git a/experiments/reactor_v0/mutation_harness.py b/experiments/reactor_v0/mutation_harness.py index 75d47128b..713f6d9e8 100644 --- a/experiments/reactor_v0/mutation_harness.py +++ b/experiments/reactor_v0/mutation_harness.py @@ -13,10 +13,10 @@ MUTANTS = { - "allow_missing_field": ( + "allow_extra_field": ( "set(document) == expected", - "set(document) <= expected", - "missing", + "set(document) >= expected", + "extra", ), "allow_scientific_status_promotion": ( 'document["scientific_status_effect"] == "NONE"', @@ -36,17 +36,17 @@ } -PROBE = r'''import copy, importlib.util, json, pathlib, sys +PROBE = r'''import importlib.util, json, pathlib, sys, traceback spec = importlib.util.spec_from_file_location("mutated_validator", sys.argv[1]) module = importlib.util.module_from_spec(spec) -spec.loader.exec_module(module) here = pathlib.Path(sys.argv[2]) kind = sys.argv[3] control = json.loads((here / "control.json").read_text()) sources = json.loads((here / "source_manifest.json").read_text()) try: - if kind == "missing": - del control["scientific_status_effect"] + spec.loader.exec_module(module) + if kind == "extra": + control["unexpected"] = False module.validate_document(control) elif kind == "status": control["scientific_status_effect"] = "ACCEPTED" @@ -60,7 +60,10 @@ raise RuntimeError("unknown probe") except ValueError: raise SystemExit(0) -raise SystemExit(1) +except Exception: + traceback.print_exc() + raise SystemExit(4) +raise SystemExit(3) ''' @@ -74,16 +77,30 @@ def run(): with tempfile.TemporaryDirectory(prefix="reactor-v0-mutant-") as temporary: path = Path(temporary) / "validator.py" path.write_text(mutated, encoding="utf-8") + command = [ + sys.executable, "-O", "-B", "-c", PROBE, + str(path), str(HERE), probe, + ] + baseline = subprocess.run( + command[:5] + [str(VALIDATOR)] + command[6:], + text=True, capture_output=True, check=False, + ) + if baseline.returncode != 0: + raise RuntimeError( + name + " probe does not reject under the original validator: " + + baseline.stderr + ) completed = subprocess.run( - [sys.executable, "-O", "-B", "-c", PROBE, str(path), str(HERE), probe], - text=True, - capture_output=True, - check=False, + command, text=True, capture_output=True, check=False, ) - if completed.returncode != 0: + if completed.returncode == 3: killed.append(name) + elif completed.returncode == 4: + raise RuntimeError(name + " crashed instead of accepting its probe: " + + completed.stderr) else: - raise RuntimeError(name + " survived its negative probe") + raise RuntimeError(name + " returned unexpected probe status " + + str(completed.returncode)) return killed diff --git a/experiments/reactor_v0/test_reactor_v0.py b/experiments/reactor_v0/test_reactor_v0.py index 438916e3f..8aee242d0 100644 --- a/experiments/reactor_v0/test_reactor_v0.py +++ b/experiments/reactor_v0/test_reactor_v0.py @@ -1,10 +1,13 @@ import copy +import hashlib import json import os from fractions import Fraction from pathlib import Path +import shutil import subprocess import sys +import tempfile import unittest @@ -31,6 +34,27 @@ def test_exposed_control_is_exact_five_sixteenths(self): self.assertEqual(result["essential_birth"], 27) self.assertEqual(result["included_lifetimes"], (1, 8)) + def test_positive_integer_amplitude_scaling_scales_barcode_endpoints(self): + from exact_helpers import exact_periodic_h0 + + fixture = self.package["fixture"] + barcode = exact_periodic_h0(fixture["values"], fixture["grid_side"]) + for scale in (2, 3, 5, 7, 11): + with self.subTest(scale=scale): + scaled = exact_periodic_h0( + [scale * value for value in fixture["values"]], + fixture["grid_side"], + ) + self.assertEqual( + scaled["intervals"], + [[scale * birth, scale * death] + for birth, death in barcode["intervals"]], + ) + self.assertEqual( + scaled["essential"], + [scale * birth for birth in barcode["essential"]], + ) + def test_tampered_expected_control_is_rejected(self): package = copy.deepcopy(self.package) package["control"]["expected_control"] = {"numerator": 1, "denominator": 2} @@ -99,5 +123,254 @@ def test_optimized_child_process_runs_validator_and_evaluator(self): self.assertTrue(payload["validated"]) +class ValidatorNegativeTests(unittest.TestCase): + def setUp(self): + self.control = json.loads((HERE / "control.json").read_text(encoding="utf-8")) + self.fixture = json.loads((HERE / "fixture.json").read_text(encoding="utf-8")) + self.sources = json.loads( + (HERE / "source_manifest.json").read_text(encoding="utf-8") + ) + + def test_control_rejects_wrong_constants_types_and_local_names(self): + from validator import validate_document + + mutations = [] + for value in ("PROMOTED", "none", None, ["NONE"]): + document = copy.deepcopy(self.control) + document["scientific_status_effect"] = value + mutations.append(document) + for key, value in ( + ("schema_version", True), + ("scope", "OTHER"), + ("campaign_status", "RAN")): + document = copy.deepcopy(self.control) + document[key] = value + mutations.append(document) + for value in ("a/b", ".", ".."): + document = copy.deepcopy(self.control) + document["fixture"] = value + mutations.append(document) + document = copy.deepcopy(self.control) + document["alpha"]["numerator"] = True + mutations.append(document) + document = copy.deepcopy(self.control) + document["alpha"]["denominator"] = 0 + mutations.append(document) + for document in mutations: + with self.subTest(document=document), self.assertRaises(ValueError): + validate_document(document) + + def test_control_rejects_out_of_domain_rationals(self): + from validator import validate_document + + cases = ( + ("alpha", {"numerator": 0, "denominator": 1}), + ("alpha", {"numerator": -1, "denominator": 1}), + ("amplitude_scale", {"numerator": 0, "denominator": 1}), + ("amplitude_scale", {"numerator": -2, "denominator": 1}), + ("threshold", {"numerator": -1, "denominator": 4}), + ("expected_control", {"numerator": -1, "denominator": 16}), + ) + for key, value in cases: + document = copy.deepcopy(self.control) + document[key] = value + with self.subTest(key=key, value=value), self.assertRaises(ValueError): + validate_document(document) + + def test_fixture_rejects_each_wrong_contract_field(self): + from validator import _validate_fixture + + mutations = [] + for key, value in ( + ("schema_version", True), + ("grid_side", 5), + ("values", [0] * 15), + ("expected_barcode", {"intervals": [[1, 0]], "essential": [27]}), + ("exclusions", [])): + document = copy.deepcopy(self.fixture) + document[key] = value + mutations.append(document) + for document in mutations: + with self.subTest(document=document), self.assertRaises(ValueError): + _validate_fixture(document) + + def test_source_manifest_rejects_malformed_or_rebound_identities(self): + from validator import _validate_sources + + mutations = [] + replacements = ( + ("repository", "other/repository"), + ("commit", "z" * 40), + ("raw_sha256", "z" * 64), + ("git_blob_sha", "z" * 40), + ("theorem_conclusion_consumed", True), + ("theorem_conclusion_consumed", 0), + ("theorem_conclusion_consumed", "false"), + ("source_status", "MERGED"), + ) + for key, value in replacements: + document = copy.deepcopy(self.sources) + document["sources"][0][key] = value + mutations.append(document) + swapped = copy.deepcopy(self.sources) + swapped["sources"][0]["pull_request"] = 334 + swapped["sources"][1]["pull_request"] = 330 + mutations.append(swapped) + duplicate = copy.deepcopy(self.sources) + duplicate["sources"][1] = copy.deepcopy(duplicate["sources"][0]) + mutations.append(duplicate) + for value in ([], {}): + unhashable = copy.deepcopy(self.sources) + unhashable["sources"][0]["pull_request"] = value + mutations.append(unhashable) + widened = copy.deepcopy(self.sources) + widened["sources"].append(copy.deepcopy(widened["sources"][0])) + mutations.append(widened) + for document in mutations: + with self.subTest(document=document), self.assertRaises(ValueError): + _validate_sources(document) + + def test_duplicate_json_key_is_rejected(self): + from validator import _load_json + + with tempfile.TemporaryDirectory(prefix="reactor-duplicate-") as temporary: + path = Path(temporary) / "duplicate.json" + path.write_text('{"a": 1, "a": 2}\n', encoding="utf-8") + with self.assertRaisesRegex(ValueError, "duplicate JSON key"): + _load_json(path) + + def test_source_object_verifier_checks_bytes_length_hash_and_git_blob(self): + from validator import verify_source_objects + + with tempfile.TemporaryDirectory(prefix="reactor-source-git-") as temporary: + root = Path(temporary) + subprocess.run(["git", "init", "-q"], cwd=root, check=True) + subprocess.run(["git", "config", "user.name", "Reactor Test"], cwd=root, check=True) + subprocess.run( + ["git", "config", "user.email", "reactor@example.invalid"], + cwd=root, + check=True, + ) + source_path = root / "source.txt" + raw = b"source-bound bytes\n" + source_path.write_bytes(raw) + subprocess.run(["git", "add", "source.txt"], cwd=root, check=True) + subprocess.run(["git", "commit", "-qm", "source fixture"], cwd=root, check=True) + commit = subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=root, text=True + ).strip() + blob = subprocess.check_output( + ["git", "rev-parse", "HEAD:source.txt"], cwd=root, text=True + ).strip() + record = { + "commit": commit, + "path": "source.txt", + "byte_length": len(raw), + "raw_sha256": hashlib.sha256(raw).hexdigest(), + "git_blob_sha": blob, + } + self.assertTrue(verify_source_objects(root, [record])) + for key, value in ( + ("byte_length", len(raw) + 1), + ("raw_sha256", "0" * 64), + ("git_blob_sha", "0" * 40)): + changed = copy.deepcopy(record) + changed[key] = value + with self.subTest(key=key), self.assertRaises(ValueError): + verify_source_objects(root, [changed]) + + +class ClosureAndWorkflowTests(unittest.TestCase): + def _copy_frozen_tree(self, root): + from validator import REQUIRED_CLOSURE + + for relative in REQUIRED_CLOSURE: + source = ROOT / relative + target = root / relative + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(source, target) + closure = root / "experiments/reactor_v0/closure.json" + closure.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(HERE / "closure.json", closure) + return closure.parent + + def test_tampered_closure_byte_is_rejected_directly_and_by_loader(self): + from validator import load_and_validate, verify_closure + + with tempfile.TemporaryDirectory(prefix="reactor-closure-") as temporary: + root = Path(temporary) + package = self._copy_frozen_tree(root) + readme = package / "README.md" + readme.write_bytes(readme.read_bytes() + b"tampered\n") + closure = json.loads((package / "closure.json").read_text(encoding="utf-8")) + with self.assertRaisesRegex(ValueError, "closure hash mismatch"): + verify_closure(package, closure) + with self.assertRaisesRegex(ValueError, "closure hash mismatch"): + load_and_validate(package) + + def test_extra_package_file_is_rejected(self): + from validator import verify_closure + + with tempfile.TemporaryDirectory(prefix="reactor-extra-") as temporary: + root = Path(temporary) + package = self._copy_frozen_tree(root) + (package / "fractions.py").write_text("raise RuntimeError('shadowed')\n") + closure = json.loads((package / "closure.json").read_text(encoding="utf-8")) + with self.assertRaisesRegex(ValueError, "package file set"): + verify_closure(package, closure) + + def test_package_symlinks_are_rejected(self): + from validator import load_and_validate, verify_closure + + with tempfile.TemporaryDirectory(prefix="reactor-symlink-") as temporary: + root = Path(temporary) + outside = root / "outside" + outside.mkdir() + package = self._copy_frozen_tree(root / "copy") + closure = json.loads((package / "closure.json").read_text(encoding="utf-8")) + + (package / "extra-directory").symlink_to(outside, target_is_directory=True) + with self.assertRaisesRegex(ValueError, "symlink"): + verify_closure(package, closure) + (package / "extra-directory").unlink() + + package_link = root / "package-link" + package_link.symlink_to(package, target_is_directory=True) + with self.assertRaisesRegex(ValueError, "symlink"): + load_and_validate(package_link) + + readme = package / "README.md" + outside_readme = outside / "README.md" + outside_readme.write_bytes(readme.read_bytes()) + readme.unlink() + readme.symlink_to(outside_readme) + with self.assertRaisesRegex(ValueError, "symlink"): + verify_closure(package, closure) + + def test_workflow_hardens_actions_sources_and_freeze_boundary(self): + workflow = (ROOT / ".github/workflows/reactor-v0-controls.yml").read_text( + encoding="utf-8" + ) + required = ( + "actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1", + "actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97", + "persist-credentials: false", + "timeout-minutes:", + "REACTOR_VERIFY_SOURCES: '1'", + "git fetch --no-tags --depth=1 origin", + "git status --porcelain --untracked-files=all --ignored", + "github.event.pull_request.base.sha", + "is_symlink()", + "closure.json", + ) + for text in required: + with self.subTest(text=text): + self.assertIn(text, workflow) + self.assertLess( + workflow.index("is_symlink()"), + workflow.index("Base has no Reactor A freeze"), + ) + + if __name__ == "__main__": unittest.main() diff --git a/experiments/reactor_v0/validator.py b/experiments/reactor_v0/validator.py index adfc61391..fb4d8419b 100644 --- a/experiments/reactor_v0/validator.py +++ b/experiments/reactor_v0/validator.py @@ -2,7 +2,11 @@ import hashlib import json +import os from pathlib import Path +import re +import subprocess +from fractions import Fraction CONTROL_KEYS = { @@ -29,6 +33,17 @@ "experiments/reactor_v0/test_reactor_v0.py", "experiments/reactor_v0/mutation_harness.py", } +SOURCE_PINS = { + 330: ( + "88ff9223e57bf38c7fc33cb3559a88793a7b5087", + "experiments/universality/spectral_gaussian_admission/PROOF.md", + ), + 334: ( + "6bd133d591e43e75a9292463bb4bfde7a34984dc", + "experiments/universality/spectral_amplitude_crossover/PROOF.md", + ), +} +LOWER_HEX = re.compile(r"[0-9a-f]+\Z") def _require(condition, message): @@ -62,6 +77,7 @@ def _rational(document, name): _require(type(document["numerator"]) is int and type(document["denominator"]) is int and document["denominator"] > 0, name + " must be an exact rational") + return Fraction(document["numerator"], document["denominator"]) def validate_document(document): @@ -75,10 +91,17 @@ def validate_document(document): _require(document["campaign_status"] == "B_UNRESOLVED_NO_RUN", "campaign B must remain UNRESOLVED/no-run") for key in ("fixture", "sources", "closure"): - _require(type(document[key]) is str and document[key] and "/" not in document[key], + _require(type(document[key]) is str and document[key] not in ("", ".", "..") and + "/" not in document[key] and "\\" not in document[key], key + " must be a local filename") - for key in ("alpha", "amplitude_scale", "threshold", "expected_control"): - _rational(document[key], key) + alpha = _rational(document["alpha"], "alpha") + amplitude_scale = _rational(document["amplitude_scale"], "amplitude_scale") + threshold = _rational(document["threshold"], "threshold") + expected_control = _rational(document["expected_control"], "expected_control") + _require(alpha > 0, "alpha must be positive") + _require(amplitude_scale > 0, "amplitude_scale must be positive") + _require(threshold >= 0, "threshold must be nonnegative") + _require(expected_control >= 0, "expected_control must be nonnegative") return True @@ -105,36 +128,97 @@ def _validate_sources(document): "unsupported source manifest schema") sources = document["sources"] _require(type(sources) is list and len(sources) == 2, "exactly two parent sources required") + commits = [] + pull_requests = [] for source in sources: _strict_keys(source, SOURCE_KEYS, "source") _require(source["repository"] == "d6g8k5htny-coder/main", "unexpected source repository") - _require(type(source["commit"]) is str and len(source["commit"]) == 40, + _require(type(source["pull_request"]) is int and + source["pull_request"] in SOURCE_PINS, + "parent PR allowlist mismatch") + pull_requests.append(source["pull_request"]) + _require(type(source["commit"]) is str and len(source["commit"]) == 40 and + LOWER_HEX.fullmatch(source["commit"]) is not None, "full source commit required") - _require(type(source["path"]) is str and source["path"].endswith("/PROOF.md"), - "proof source path required") + _require((source["commit"], source["path"]) == + SOURCE_PINS[source["pull_request"]], + "source PR, commit, and path pin mismatch") + commits.append(source["commit"]) _require(type(source["byte_length"]) is int and source["byte_length"] > 0, "positive source byte length required") - _require(type(source["raw_sha256"]) is str and len(source["raw_sha256"]) == 64, + _require(type(source["raw_sha256"]) is str and len(source["raw_sha256"]) == 64 and + LOWER_HEX.fullmatch(source["raw_sha256"]) is not None, "raw SHA-256 required") - _require(type(source["git_blob_sha"]) is str and len(source["git_blob_sha"]) == 40, + _require(type(source["git_blob_sha"]) is str and len(source["git_blob_sha"]) == 40 and + LOWER_HEX.fullmatch(source["git_blob_sha"]) is not None, "Git blob membership identity required separately") - _require(type(source["pull_request"]) is int and source["pull_request"] in (330, 334), - "parent PR allowlist mismatch") _require(source["theorem_conclusion_consumed"] is False, "A may consume no theorem conclusion") _require(source["source_status"] == "OPEN_UNMERGED_AT_FREEZE", "source status must remain explicit") + _require(set(pull_requests) == set(SOURCE_PINS) and + len(set(pull_requests)) == len(pull_requests), + "parent PR identities must be unique and exact") + _require(len(set(commits)) == len(commits), "parent source commits must be unique") return sources +def _git(repo_root, *arguments): + completed = subprocess.run( + ["git", *arguments], + cwd=repo_root, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + check=False, + ) + _require(completed.returncode == 0, + "git source-object verification failed: " + + completed.stderr.decode("utf-8", errors="replace").strip()) + return completed.stdout + + +def verify_source_objects(repository_root, sources): + root = Path(repository_root).resolve() + for source in sources: + object_name = source["commit"] + ":" + source["path"] + raw = _git(root, "cat-file", "blob", object_name) + blob = _git(root, "rev-parse", object_name).decode("ascii").strip() + _require(len(raw) == source["byte_length"], + "source byte length mismatch: " + object_name) + _require(hashlib.sha256(raw).hexdigest() == source["raw_sha256"], + "source raw SHA-256 mismatch: " + object_name) + _require(blob == source["git_blob_sha"], + "source Git blob mismatch: " + object_name) + return True + + def verify_closure(package_directory, closure): - repository_root = Path(package_directory).resolve().parents[1] + package_directory = Path(package_directory) + _require(not package_directory.is_symlink(), "package directory symlink is forbidden") + repository_root = package_directory.resolve().parents[1] _require(type(closure) is dict and set(closure) == REQUIRED_CLOSURE, "consumed closure path set mismatch") + expected_package_files = { + Path(relative).relative_to("experiments/reactor_v0").as_posix() + for relative in REQUIRED_CLOSURE + if relative.startswith("experiments/reactor_v0/") + } | {"closure.json"} + package_entries = list(package_directory.rglob("*")) + _require(all(not path.is_symlink() for path in package_entries), + "package symlink is forbidden") + actual_package_files = { + path.relative_to(package_directory).as_posix() + for path in package_entries + if not path.is_dir() + } + _require(actual_package_files == expected_package_files, + "package file set differs from frozen closure") for relative, digest in closure.items(): - _require(type(digest) is str and len(digest) == 64, + _require(type(digest) is str and len(digest) == 64 and + LOWER_HEX.fullmatch(digest) is not None, "closure SHA-256 must be 64 lowercase hex characters") path = repository_root / relative + _require(not path.is_symlink(), "closure member symlink is forbidden: " + relative) _require(path.is_file(), "missing closure path: " + relative) actual = hashlib.sha256(path.read_bytes()).hexdigest() _require(actual == digest, "closure hash mismatch: " + relative) @@ -142,7 +226,10 @@ def verify_closure(package_directory, closure): def load_and_validate(package_directory): - directory = Path(package_directory).resolve() + supplied_directory = Path(package_directory) + _require(not supplied_directory.is_symlink(), + "package directory symlink is forbidden") + directory = supplied_directory.resolve() control = _load_json(directory / "control.json") validate_document(control) fixture = _load_json(directory / control["fixture"]) @@ -151,4 +238,6 @@ def load_and_validate(package_directory): sources = _validate_sources(source_manifest) closure = _load_json(directory / control["closure"]) verify_closure(directory, closure) + if os.environ.get("REACTOR_VERIFY_SOURCES") == "1": + verify_source_objects(directory.parents[1], sources) return {"control": control, "fixture": fixture, "sources": sources, "closure": closure} From 4cc17538c53569a668c9850ff5ca53cd448b65ca Mon Sep 17 00:00:00 2001 From: Dylan Roy <249851642+d6g8k5htny-coder@users.noreply.github.com> Date: Thu, 15 Oct 2026 20:48:14 -0500 Subject: [PATCH 3/4] fix: fail closed Reactor A workflow guard Run the inline guard and unittest suites in isolated Python mode, distinguish a genuine first introduction from invalid base-object and path-read errors, and add behavioral regressions. Engineering-only; no scientific-status change. --- .github/workflows/reactor-v0-controls.yml | 28 ++++-- experiments/reactor_v0/closure.json | 4 +- experiments/reactor_v0/test_reactor_v0.py | 105 ++++++++++++++++++++++ 3 files changed, 130 insertions(+), 7 deletions(-) diff --git a/.github/workflows/reactor-v0-controls.yml b/.github/workflows/reactor-v0-controls.yml index ea0bef9b8..599838aa2 100644 --- a/.github/workflows/reactor-v0-controls.yml +++ b/.github/workflows/reactor-v0-controls.yml @@ -38,7 +38,7 @@ jobs: env: BASE_SHA: ${{ github.event.pull_request.base.sha }} run: | - python3 -B - <<'PY' + python3 -I -B - <<'PY' import hashlib import json from pathlib import Path @@ -53,6 +53,25 @@ jobs: any(path.is_symlink() for path in package_entries)): raise SystemExit("frozen package may not contain symlinks") base = os.environ["BASE_SHA"] + base_commit = subprocess.run( + ["git", "cat-file", "-e", base + "^{commit}"], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=False, + ) + if base_commit.returncode != 0: + raise SystemExit("pull-request base is not an available commit") + base_path = subprocess.run( + ["git", "ls-tree", "-z", base, "--", closure_path], + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + check=False, + ) + if base_path.returncode != 0: + raise SystemExit("unable to inspect frozen closure at pull-request base") + if not base_path.stdout: + print("Base has no Reactor A freeze; introduction is permitted.") + raise SystemExit(0) prior = subprocess.run( ["git", "show", base + ":" + closure_path], stdout=subprocess.PIPE, @@ -60,8 +79,7 @@ jobs: check=False, ) if prior.returncode != 0: - print("Base has no Reactor A freeze; introduction is permitted.") - raise SystemExit(0) + raise SystemExit("unable to read frozen closure at pull-request base") current = closure_file.read_bytes() if current != prior.stdout: raise SystemExit("frozen closure.json differs from pull-request base") @@ -88,12 +106,12 @@ jobs: PY - name: Normal tests and control run: | - python3 -B -m unittest discover -s experiments/reactor_v0 -p 'test_*.py' -v + python3 -I -B -m unittest discover -s experiments/reactor_v0 -p 'test_*.py' -v python3 -B experiments/reactor_v0/mutation_harness.py python3 -B experiments/reactor_v0/run_control.py - name: Optimized tests and control run: | - python3 -B -O -m unittest discover -s experiments/reactor_v0 -p 'test_*.py' -v + python3 -I -B -O -m unittest discover -s experiments/reactor_v0 -p 'test_*.py' -v python3 -B -O experiments/reactor_v0/mutation_harness.py python3 -B -O experiments/reactor_v0/run_control.py - name: Frozen run stage is read-only diff --git a/experiments/reactor_v0/closure.json b/experiments/reactor_v0/closure.json index 8d8c68329..bc3a9e582 100644 --- a/experiments/reactor_v0/closure.json +++ b/experiments/reactor_v0/closure.json @@ -1,5 +1,5 @@ { - ".github/workflows/reactor-v0-controls.yml": "602293812abea738dfc8ae300a68bdae027d23be717db6a907133e248074705e", + ".github/workflows/reactor-v0-controls.yml": "117da0c992e25b788acea640f1d621036e5beb07c8274ac29b5c0adf1e2cf3b0", "experiments/reactor_v0/README.md": "cde3ed5286a254ea8d817ad1cd92c71e8d4ba58670046e67fa4eb5df4f9bb474", "experiments/reactor_v0/control.json": "ad7066c7f8b7073edb5da910250f714f969bae2e164646a4c8c7cecffa9b43a1", "experiments/reactor_v0/evaluator.py": "92fe4dd24be870c1651b59a2e9f2a110a8b008d99f6c601efb60e11a6922c5dd", @@ -8,6 +8,6 @@ "experiments/reactor_v0/mutation_harness.py": "ea74ee40a6ace0b6ee5152e67876be4841c2643a0646a658ab7d6758f441e78e", "experiments/reactor_v0/run_control.py": "6af0e3ab778dbe980860fb4d7d78d83f00bd67844c882ad72876b94d050854e3", "experiments/reactor_v0/source_manifest.json": "86c55b140acc6cf8219915f16df995085eafd95c61c249a6cde29b73a83f9c8d", - "experiments/reactor_v0/test_reactor_v0.py": "9a0dbd7d7a9e903466d6834f19e3917ce2877ea9b832cc8fffc119f131b86d68", + "experiments/reactor_v0/test_reactor_v0.py": "ad1a581ae03703cc91debd027849c655503a9f6ea908e28b2bf69c860a26b702", "experiments/reactor_v0/validator.py": "2d39c1bd844f49d43aa380443fa384f8e3a0aeb9df6173a3fcf9eeaeb150bef3" } diff --git a/experiments/reactor_v0/test_reactor_v0.py b/experiments/reactor_v0/test_reactor_v0.py index 8aee242d0..1c5a0f04b 100644 --- a/experiments/reactor_v0/test_reactor_v0.py +++ b/experiments/reactor_v0/test_reactor_v0.py @@ -4,10 +4,12 @@ import os from fractions import Fraction from pathlib import Path +import shlex import shutil import subprocess import sys import tempfile +import textwrap import unittest @@ -294,6 +296,38 @@ def _copy_frozen_tree(self, root): shutil.copy2(HERE / "closure.json", closure) return closure.parent + def _workflow_guard(self): + workflow = (ROOT / ".github/workflows/reactor-v0-controls.yml").read_text( + encoding="utf-8" + ) + lines = workflow.splitlines() + start = next( + index for index, line in enumerate(lines) + if line.strip().startswith("python3 ") and "<<'PY'" in line + ) + end = next( + index for index in range(start + 1, len(lines)) + if lines[index].strip() == "PY" + ) + command = shlex.split(lines[start].strip().split("<<", 1)[0]) + command[0] = sys.executable + script = textwrap.dedent("\n".join(lines[start + 1:end])) + "\n" + return workflow, command, script + + def _run_workflow_guard(self, root, base): + _, command, script = self._workflow_guard() + environment = os.environ.copy() + environment["BASE_SHA"] = base + return subprocess.run( + command, + cwd=root, + env=environment, + input=script, + text=True, + capture_output=True, + check=False, + ) + def test_tampered_closure_byte_is_rejected_directly_and_by_loader(self): from validator import load_and_validate, verify_closure @@ -371,6 +405,77 @@ def test_workflow_hardens_actions_sources_and_freeze_boundary(self): workflow.index("Base has no Reactor A freeze"), ) + def test_workflow_guard_and_unittests_use_isolated_python(self): + workflow, command, _ = self._workflow_guard() + with tempfile.TemporaryDirectory(prefix="reactor-root-shadow-") as temporary: + root = Path(temporary) + package = self._copy_frozen_tree(root) + subprocess.run(["git", "init", "-q"], cwd=root, check=True) + subprocess.run( + ["git", "config", "user.name", "Reactor Test"], cwd=root, check=True + ) + subprocess.run( + ["git", "config", "user.email", "reactor@example.invalid"], + cwd=root, + check=True, + ) + subprocess.run(["git", "add", "."], cwd=root, check=True) + subprocess.run(["git", "commit", "-qm", "frozen base"], cwd=root, check=True) + base = subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=root, text=True + ).strip() + + evaluator = package / "evaluator.py" + evaluator.write_bytes(evaluator.read_bytes() + b"# repinned edit\n") + closure_file = package / "closure.json" + closure = json.loads(closure_file.read_text(encoding="utf-8")) + closure["experiments/reactor_v0/evaluator.py"] = hashlib.sha256( + evaluator.read_bytes() + ).hexdigest() + closure_file.write_text( + json.dumps(closure, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + (root / "subprocess.py").write_text( + "PIPE = -1\n" + "DEVNULL = -3\n" + "class Result:\n" + " returncode = 128\n" + " stdout = b''\n" + "def run(*args, **kwargs):\n" + " return Result()\n", + encoding="utf-8", + ) + completed = self._run_workflow_guard(root, base) + self.assertNotEqual( + completed.returncode, + 0, + completed.stdout + completed.stderr, + ) + self.assertIn("-I", command) + self.assertIn( + "python3 -I -B -m unittest discover -s experiments/reactor_v0", + workflow, + ) + self.assertIn( + "python3 -I -B -O -m unittest discover -s experiments/reactor_v0", + workflow, + ) + + def test_workflow_guard_fails_closed_for_invalid_base(self): + workflow, _, _ = self._workflow_guard() + with tempfile.TemporaryDirectory(prefix="reactor-invalid-base-") as temporary: + root = Path(temporary) + self._copy_frozen_tree(root) + subprocess.run(["git", "init", "-q"], cwd=root, check=True) + completed = self._run_workflow_guard(root, "0" * 40) + self.assertNotEqual( + completed.returncode, + 0, + completed.stdout + completed.stderr, + ) + self.assertIn('["git", "cat-file", "-e", base + "^{commit}"]', workflow) + self.assertIn('["git", "ls-tree", "-z", base, "--", closure_path]', workflow) + if __name__ == "__main__": unittest.main() From c60c1cc9ddc208b9f1c178e8c2366594f37a3b41 Mon Sep 17 00:00:00 2001 From: Dylan Roy <249851642+d6g8k5htny-coder@users.noreply.github.com> Date: Thu, 15 Oct 2026 21:56:52 -0500 Subject: [PATCH 4/4] docs: enforce source verification in Reactor A run --- experiments/reactor_v0/README.md | 15 ++++++- experiments/reactor_v0/closure.json | 4 +- experiments/reactor_v0/test_reactor_v0.py | 51 +++++++++++++++++++++++ 3 files changed, 66 insertions(+), 4 deletions(-) diff --git a/experiments/reactor_v0/README.md b/experiments/reactor_v0/README.md index 184ab0c56..74f199ec3 100644 --- a/experiments/reactor_v0/README.md +++ b/experiments/reactor_v0/README.md @@ -29,14 +29,25 @@ and path-scoped workflow by raw SHA-256; it intentionally cannot hash itself. Run the complete frozen controls from the repository root: ```sh -python3 -B -m unittest discover -s experiments/reactor_v0 -p 'test_*.py' -v -python3 -B -O -m unittest discover -s experiments/reactor_v0 -p 'test_*.py' -v +git fetch --no-tags --depth=1 origin \ + 88ff9223e57bf38c7fc33cb3559a88793a7b5087 \ + 6bd133d591e43e75a9292463bb4bfde7a34984dc +export REACTOR_VERIFY_SOURCES=1 + +python3 -I -B -m unittest discover -s experiments/reactor_v0 -p 'test_*.py' -v +python3 -I -B -O -m unittest discover -s experiments/reactor_v0 -p 'test_*.py' -v python3 -B experiments/reactor_v0/mutation_harness.py python3 -B -O experiments/reactor_v0/mutation_harness.py python3 -B experiments/reactor_v0/run_control.py python3 -B -O experiments/reactor_v0/run_control.py ``` +The two fetched commits are exact, open parent-source identities. A missing +object, unavailable origin, or source length, raw SHA-256, or Git-blob mismatch +must stop this complete sequence; do not unset the selector to continue. Runs +without `REACTOR_VERIFY_SOURCES=1` are metadata/control utility runs, not the +complete source-verified control. + The workflow has read-only repository permissions, is triggered only by this directory or its own workflow file, and ends with a clean-worktree check so the run stage cannot silently edit the evaluator, tests, or any other tracked input. diff --git a/experiments/reactor_v0/closure.json b/experiments/reactor_v0/closure.json index bc3a9e582..a88c0fc73 100644 --- a/experiments/reactor_v0/closure.json +++ b/experiments/reactor_v0/closure.json @@ -1,6 +1,6 @@ { ".github/workflows/reactor-v0-controls.yml": "117da0c992e25b788acea640f1d621036e5beb07c8274ac29b5c0adf1e2cf3b0", - "experiments/reactor_v0/README.md": "cde3ed5286a254ea8d817ad1cd92c71e8d4ba58670046e67fa4eb5df4f9bb474", + "experiments/reactor_v0/README.md": "b78a30ccdaa52a00a1dd62599ee06899cfddf87b7081f3a06dce40722ae0bc85", "experiments/reactor_v0/control.json": "ad7066c7f8b7073edb5da910250f714f969bae2e164646a4c8c7cecffa9b43a1", "experiments/reactor_v0/evaluator.py": "92fe4dd24be870c1651b59a2e9f2a110a8b008d99f6c601efb60e11a6922c5dd", "experiments/reactor_v0/exact_helpers.py": "2569978f248a28b3754dad8d6ba4d80b47febf338a7db925f17f53723145cb61", @@ -8,6 +8,6 @@ "experiments/reactor_v0/mutation_harness.py": "ea74ee40a6ace0b6ee5152e67876be4841c2643a0646a658ab7d6758f441e78e", "experiments/reactor_v0/run_control.py": "6af0e3ab778dbe980860fb4d7d78d83f00bd67844c882ad72876b94d050854e3", "experiments/reactor_v0/source_manifest.json": "86c55b140acc6cf8219915f16df995085eafd95c61c249a6cde29b73a83f9c8d", - "experiments/reactor_v0/test_reactor_v0.py": "ad1a581ae03703cc91debd027849c655503a9f6ea908e28b2bf69c860a26b702", + "experiments/reactor_v0/test_reactor_v0.py": "8beb2b19a3ce37175521113637923b3a9a925b14915ef1cb0bd5a8431ebb88b1", "experiments/reactor_v0/validator.py": "2d39c1bd844f49d43aa380443fa384f8e3a0aeb9df6173a3fcf9eeaeb150bef3" } diff --git a/experiments/reactor_v0/test_reactor_v0.py b/experiments/reactor_v0/test_reactor_v0.py index 1c5a0f04b..898bd2ad9 100644 --- a/experiments/reactor_v0/test_reactor_v0.py +++ b/experiments/reactor_v0/test_reactor_v0.py @@ -328,6 +328,57 @@ def _run_workflow_guard(self, root, base): check=False, ) + def test_documented_complete_run_verifies_sources_and_fails_closed_when_missing(self): + readme = (HERE / "README.md").read_text(encoding="utf-8") + complete = readme.split("```sh", 1)[1].split("```", 1)[0] + first_command = complete.index("python3 ") + fetch = "git fetch --no-tags --depth=1 origin" + selector = "export REACTOR_VERIFY_SOURCES=1" + self.assertIn(fetch, complete) + self.assertIn("88ff9223e57bf38c7fc33cb3559a88793a7b5087", complete) + self.assertIn("6bd133d591e43e75a9292463bb4bfde7a34984dc", complete) + self.assertIn(selector, complete) + self.assertLess(complete.index(fetch), first_command) + self.assertLess(complete.index(selector), first_command) + + with tempfile.TemporaryDirectory(prefix="reactor-missing-sources-") as temporary: + root = Path(temporary) + package = self._copy_frozen_tree(root) + subprocess.run(["git", "init", "-q"], cwd=root, check=True) + subprocess.run( + ["git", "config", "user.name", "Reactor Test"], cwd=root, check=True + ) + subprocess.run( + ["git", "config", "user.email", "reactor@example.invalid"], + cwd=root, + check=True, + ) + subprocess.run(["git", "add", "."], cwd=root, check=True) + subprocess.run(["git", "commit", "-qm", "frozen candidate"], cwd=root, check=True) + environment = os.environ.copy() + environment.pop("REACTOR_VERIFY_SOURCES", None) + name, value = selector.removeprefix("export ").split("=", 1) + environment[name] = value + for optimized in (False, True): + command = [sys.executable, "-B"] + if optimized: + command.append("-O") + command.append(str(package / "run_control.py")) + completed = subprocess.run( + command, + cwd=root, + env=environment, + text=True, + capture_output=True, + check=False, + ) + with self.subTest(optimized=optimized): + self.assertNotEqual(completed.returncode, 0, completed.stdout) + self.assertIn( + "git source-object verification failed", completed.stderr + ) + self.assertNotIn('"validated": true', completed.stdout) + def test_tampered_closure_byte_is_rejected_directly_and_by_loader(self): from validator import load_and_validate, verify_closure