Circuit scientific replay (Python and C++17)
Quantum and Circuits
verify.py
This is the original source text. Reading it does not run or verify the program.
1 #!/usr/bin/env python3
2 """Execute a bounded verification mode without modifying source or baseline evidence."""
3 from __future__ import annotations
4 import argparse
5 from datetime import datetime, timezone
6 import hashlib
7 import json
8 import os
9 from pathlib import Path
10 import platform
11 import shlex
12 import shutil
13 import stat
14 import subprocess
15 import sys
16 import time
17 import zipfile
18
19 from check_integrity import verify as verify_integrity
20 from validate_manifest import validate as validate_manifest
21
22 ROOT = Path(__file__).resolve().parents[1]
23 SOURCE_NAME = 'Komorebi_PNP_Complete_Packets_And_Projection_Block_2026-09-21.zip'
24
25
26 def sha(path: Path) -> str:
27 h = hashlib.sha256()
28 with path.open('rb') as stream:
29 for block in iter(lambda: stream.read(1024 * 1024), b''):
30 h.update(block)
31 return h.hexdigest()
32
33
34 def relative(path: Path) -> str:
35 return path.resolve().relative_to(ROOT).as_posix()
36
37
38 def now() -> str:
39 return datetime.now(timezone.utc).isoformat()
40
41
42 def extract_safe(archive: Path, destination: Path) -> Path:
43 """Reject traversal and symlink entries before extracting the pinned ZIP."""
44 with zipfile.ZipFile(archive) as source:
45 if sum(item.file_size for item in source.infolist()) > 64 * 1024 * 1024:
46 raise ValueError('Archive exceeds the declared uncompressed size cap.')
47 for item in source.infolist():
48 path = (destination / item.filename).resolve()
49 if not path.is_relative_to(destination.resolve()):
50 raise ValueError(f'Unsafe archive path: {item.filename}')
51 if stat.S_ISLNK(item.external_attr >> 16):
52 raise ValueError(f'Archive symlink not allowed: {item.filename}')
53 source.extractall(destination)
54 return destination / 'komorebi_pnp_shared_generation'
55
56
57 def revision() -> tuple[str, bool]:
58 try:
59 commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT,
60 stderr=subprocess.DEVNULL, text=True).strip()
61 dirty = bool(subprocess.check_output(['git', 'status', '--porcelain'], cwd=ROOT,
62 stderr=subprocess.DEVNULL, text=True).strip())
63 return commit, dirty
64 except (OSError, subprocess.CalledProcessError):
65 return 'unavailable: source archive; source seal identifies inputs', True
66
67
68 def main() -> int:
69 parser = argparse.ArgumentParser(description=__doc__)
70 modes = parser.add_mutually_exclusive_group()
71 for mode in ('quick', 'full', 'history', 'all'):
72 modes.add_argument('--' + mode, action='store_true')
73 args = parser.parse_args()
74 mode = next((m for m in ('all', 'history', 'full', 'quick') if getattr(args, m)), 'quick')
75 if not __debug__ or os.environ.get('PYTHONOPTIMIZE', '') not in ('', '0'):
76 print('FAIL: optimized Python disables required scientific assertions.', file=sys.stderr)
77 return 2
78 try:
79 integrity = verify_integrity(ROOT)
80 except (ValueError, OSError, KeyError) as exc:
81 print(f'FAIL: source integrity: {exc}', file=sys.stderr)
82 return 2
83 stamp = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')
84 out = ROOT / 'build/verification' / f'{stamp}-{mode}'
85 out.mkdir(parents=True, exist_ok=False)
86 logs = out / 'logs'
87 logs.mkdir()
88 started, timer = now(), time.perf_counter()
89 sealed = json.loads((ROOT / 'integrity/SOURCE_SEAL.json').read_text(encoding='utf-8'))['files']
90 pinned = sorted(set(sealed) | {'integrity/SOURCE_SEAL.json'})
91 before = {p: sha(ROOT / p) for p in pinned}
92 commit, dirty = revision()
93 records, results, software = [], [], [{'name': 'Python', 'version': sys.version}]
94 declared = [relative(out / 'summary.json')]
95 if mode in ('full', 'all'):
96 declared += [relative(out / 'active/results' / name) for name in (
97 'completeness.json', 'projection.json', 'fingerprint.json',
98 *[f'profiles{n}.bin' for n in range(1, 5)], 'degree_block02.json')]
99 if mode in ('history', 'all'):
100 declared.append(relative(out / 'historical_comparison.json'))
101 status, exit_status, failure = 'completed', 0, None
102
103 def execute(name: str, argv: list[str], cwd: Path, limit: int) -> None:
104 start, launched = time.perf_counter(), now()
105 log = logs / f'{name}.log'
106 returncode, timed_out = None, False
107 with log.open('w', encoding='utf-8') as stream:
108 try:
109 result = subprocess.run(argv, cwd=cwd, stdout=stream,
110 stderr=subprocess.STDOUT, timeout=limit)
111 returncode = result.returncode
112 except subprocess.TimeoutExpired:
113 returncode, timed_out = 124, True
114 stream.write(f'\nTIMEOUT after {limit} seconds. Inconclusive.\n')
115 except OSError as exc:
116 stream.write(f'\nLAUNCH FAILED: {exc}\n')
117 returncode = 127
118 records.append({'name': name, 'argv': argv, 'cwd': relative(cwd),
119 'started_at': launched, 'elapsed_seconds': time.perf_counter() - start,
120 'wall_time_limit_seconds': limit, 'exit_status': returncode,
121 'log': relative(log), 'log_sha256': sha(log)})
122 print(f'{name}: {"PASS" if returncode == 0 else "FAIL"}', flush=True)
123 if timed_out:
124 raise TimeoutError(f'{name}: see {relative(log)}')
125 if returncode:
126 raise RuntimeError(f'{name} exited {returncode}; see {relative(log)}')
127
128 try:
129 if mode != 'history':
130 execute('quick_controls', [sys.executable, '-m', 'unittest', 'discover', '-s', 'tests', '-v'], ROOT, 120)
131 if mode in ('full', 'all'):
132 stage = out / 'active'
133 (stage / 'results').mkdir(parents=True)
134 shutil.copytree(ROOT / 'checks', stage / 'checks', ignore=shutil.ignore_patterns('__pycache__', '*.pyc'))
135 cxx = shlex.split(os.environ.get('CXX', 'g++'))
136 if not cxx:
137 raise ValueError('CXX is empty.')
138 version = subprocess.run(cxx + ['--version'], capture_output=True, text=True, timeout=15, check=True)
139 software.append({'name': 'C++ compiler', 'version': version.stdout.splitlines()[0]})
140 exe = stage / 'degree_profiles'
141 if os.name == 'nt':
142 exe = exe.with_suffix('.exe')
143 execute('compile_profiles', cxx + ['-O2', '-std=c++17', str(stage / 'checks/degree_profiles.cpp'), '-o', str(exe)], stage, 60)
144 for n in range(1, 5):
145 execute(f'profiles{n}', [str(exe), str(n), str(stage / 'results' / f'profiles{n}.bin')], stage, 30)
146 for checker in ('completeness', 'projection', 'fingerprint'):
147 execute(checker, [sys.executable, str(stage / 'checks' / f'verify_{checker}.py')], stage, 120)
148 expected = json.loads((ROOT / 'evidence/baseline/SHA256.json').read_text(encoding='utf-8'))
149 for name, digest in expected.items():
150 target = stage / 'results' / name
151 if not target.is_file() or sha(target) != digest:
152 raise ValueError(f'Active scientific output differs from baseline: {name}')
153 if name.endswith('.json'):
154 value = json.loads(target.read_text(encoding='utf-8'))
155 if value.get('status') != 'PASS':
156 raise ValueError(f'Nonpassing scientific report: {name}')
157 results.append(relative(target))
158 execute('degree_block02', [sys.executable, str(stage / 'checks/check_degree_block02.py'),
159 '--out', str(stage / 'results/degree_block02.json')], stage, 120)
160 new_result = stage / 'results/degree_block02.json'
161 if sha(new_result) != sha(ROOT / 'evidence/lean-block02/degree_controls.json'):
162 raise ValueError('Block 02 exact finite result differs from the retained output.')
163 results.append(relative(new_result))
164 if mode in ('history', 'all'):
165 archive = ROOT / 'archive/checkpoints' / SOURCE_NAME
166 historical = extract_safe(archive, out / 'history')
167 source_seal = json.loads((historical / 'ARTIFACT_SEAL.json').read_text(encoding='utf-8'))['files']
168 for name, digest in source_seal.items():
169 path = (historical / name).resolve()
170 if not path.is_relative_to(historical.resolve()) or not path.is_file() or sha(path) != digest:
171 raise ValueError(f'Historical source seal mismatch: {name}')
172 expected = json.loads((ROOT / 'evidence/baseline/SHA256.json').read_text(encoding='utf-8'))
173 execute('historical_full_runner', [sys.executable, 'checks/run_all.py'], historical, 300)
174 comparison = {name: sha(historical / 'results' / name) == digest for name, digest in expected.items()}
175 if not all(comparison.values()):
176 raise ValueError('Historical mathematical results do not match the sealed baseline.')
177 target = out / 'historical_comparison.json'
178 target.write_text(json.dumps({'status': 'PASS', 'archive_sha256': sha(archive),
179 'source_sealed_files': len(source_seal),
180 'scientific_outputs_equal': comparison,
181 'scope': 'Pinned latest runner including its recursive historical replay.'}, indent=2) + '\n', encoding='utf-8')
182 results.append(relative(target))
183 if any(sha(ROOT / p) != digest for p, digest in before.items()):
184 raise ValueError('An execution input changed during verification.')
185 except TimeoutError as exc:
186 status, exit_status, failure = 'timeout', 124, str(exc)
187 except Exception as exc:
188 status, exit_status, failure = 'failed', 1, str(exc)
189 summary = {'status': 'PASS' if exit_status == 0 else 'FAIL', 'mode': mode,
190 'source_integrity': integrity, 'subprocesses': len(records),
191 'scientific_results_matched': len(results), 'failure': failure,
192 'scope': 'Finite exact assertions and release reproduction; not universal formal verification.'}
193 (out / 'summary.json').write_text(json.dumps(summary, indent=2) + '\n', encoding='utf-8')
194 results.append(relative(out / 'summary.json'))
195 after = {p: sha(ROOT / p) if (ROOT / p).is_file() else None for p in before}
196 manifest = {
197 'schema_version': 2, 'claim_id': 'Komorebi-Circuit-Obstructions-v' + (ROOT / 'VERSION').read_text().strip() + '-' + mode,
198 'repository': {'commit': commit, 'dirty': dirty},
199 'command': [sys.executable, 'scripts/verify.py', '--' + mode],
200 'environment': {'software': software, 'hardware': platform.platform() + '; ' + platform.machine()},
201 'mathematics': {
202 'assertion_tested': 'Reproduce exact finite claim controls, canonical result files, and selected historical evidence in the declared verification mode.',
203 'coefficient_domain': 'Exact integers, F2 truth tables, GF16 via t^4+t+1.',
204 'conventions': 'Distinct-wire classical NCT gates; bit x is f(x); Toffoli and total gate costs are different.',
205 'inputs': ['Versioned checkers, fixed baseline outputs, pinned archives, and generated bounded functions.'],
206 'bounds': {'mode': mode, 'quick': 'all functions on 1..3 inputs and specified regression controls',
207 'full': 'profile tables 1..4 inputs; exact stated independent controls and family ranges in baseline JSON',
208 'history': 'pinned latest complete source runner; other archives only hash-checked'},
209 'non_claims': ['Not a P-versus-NP proof.', 'This finite runner does not perform Lean verification; use verify_lean.py. No independent review or novelty audit.',
210 'Finite and sampled assertions retain their declared ranges.']},
211 'randomness': {'used': mode in ('full', 'all', 'history'), 'generator': 'Python random.Random in fixed baseline controls', 'seed': 20260921},
212 'run': {'started_at': started, 'finished_at': now(), 'runtime_seconds': time.perf_counter() - timer,
213 'exit_status': exit_status, 'status': status, 'subprocesses': records,
214 'resource_limits': {'memory_bytes': None, 'cpu_seconds': None, 'max_cores': None, 'max_threads': None},
215 'limit_note': 'Per-command wall limits enforced; no extra OS memory/CPU/thread caps.'},
216 'input_artifacts': [{'path': p, 'sha256': h, 'sha256_after': after[p]} for p, h in before.items()],
217 'execution_artifacts': list(before), 'declared_results': declared,
218 'outputs': ([{'path': p, 'sha256': sha(ROOT / p), 'kind': 'result'} for p in results] +
219 [{'path': r['log'], 'sha256': r['log_sha256'], 'kind': 'log'} for r in records]),
220 'checks': ['Source-seal integrity', 'Bounded exact assertions for requested mode', 'Frozen scientific-output equality', 'Input hashes before/after'],
221 'result': 'All requested finite checks passed.' if exit_status == 0 else 'Incomplete or failed execution: ' + str(failure),
222 'residual_risks': ['Self-reviewed written mathematics, not a formal theorem certificate.', 'Runtime and compiler trusted.', 'Hosted CI not executed by local verification.']}
223 if failure:
224 manifest['run']['failure'] = failure
225 path = out / 'manifest.json'
226 path.write_text(json.dumps(manifest, indent=2) + '\n', encoding='utf-8')
227 if exit_status == 0:
228 errors = validate_manifest(manifest, root=ROOT, manifest_path=path)
229 if errors:
230 print('FAIL: manifest validation: ' + '; '.join(errors), file=sys.stderr)
231 return 1
232 print(json.dumps({'status': summary['status'], 'mode': mode, 'manifest': relative(path),
233 'seconds': manifest['run']['runtime_seconds'], 'failure': failure}, indent=2))
234 return exit_status
235
236
237 if __name__ == '__main__':
238 raise SystemExit(main())
Other PDFs for this work
Original file and source record
This copy matches the recorded source file. Its publication here does not change the work’s review status.
SHA-256: a88357eacb3387df2d3d6ee5922c00d5d041a276f344f6ccc77fdca7a643d615