omega-mv
Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.
Brought by drakestapleton
omega-mv / tests / universal / semantics.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Development-oracle conformance; not a language adapter or proof checker.""" |
| 3 | import hashlib |
| 4 | import json |
| 5 | import os |
| 6 | from pathlib import Path |
| 7 | import platform |
| 8 | import random |
| 9 | import subprocess |
| 10 | import sys |
| 11 | |
| 12 | ROOT = Path(__file__).resolve().parents[2] |
| 13 | |
| 14 | def run(args, data=None): |
| 15 | p = subprocess.run(args, input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=60) |
| 16 | if p.returncode: |
| 17 | raise AssertionError(f'command failed rc={p.returncode}: {args!r}\n{p.stderr.decode(errors="replace")}') |
| 18 | return p.stdout |
| 19 | |
| 20 | def main(): |
| 21 | # Invalidate transient evidence before every possible refusal. Published |
| 22 | # append-only evidence is copied elsewhere, never reused as this output. |
| 23 | out = Path(os.environ.get('UNIVERSAL_OUT', str(ROOT / 'build/universal-semantics'))).resolve() |
| 24 | out.mkdir(parents=True, exist_ok=True) |
| 25 | (out / 'receipt.json').unlink(missing_ok=True) |
| 26 | contract = ROOT / 'spec/universal/semantics.md' |
| 27 | profiles = ROOT / 'spec/universal/profiles.json' |
| 28 | assert contract.is_file() and profiles.is_file(), 'MISSING_SEMANTIC_CONTRACT: #625 has no versioned observation/fidelity contract' |
| 29 | manifest = json.loads(profiles.read_text()) |
| 30 | assert manifest['schema'] == 'omega.universal.semantics.v1' |
| 31 | assert manifest['contract_sha256'] == hashlib.sha256(contract.read_bytes()).hexdigest(), 'STALE_CONTRACT_DIGEST' |
| 32 | assert manifest['fidelity'] == ['EXACT_SOURCE_REPLAY', 'PROVEN_EQUIVALENCE', 'PROVEN_REFINEMENT', 'BOUNDED_VALIDATION', 'DIFFERENTIAL_COMPATIBILITY', 'RUNTIME_INTEROPERABILITY', 'EXPLICIT_APPROXIMATION', 'UNSUPPORTED', 'UNKNOWN'] |
| 33 | assert manifest['non_success'] == ['FAIL', 'UNKNOWN', 'TIMEOUT', 'UNSUPPORTED', 'UB', 'MISSING_RUNTIME', 'NOT_RUN'] |
| 34 | assert manifest['adapters_implemented_by_this_change'] == [] |
| 35 | fixtures = ROOT / 'tests/universal' |
| 36 | cc = os.environ.get('CC', 'cc') |
| 37 | rustc = os.environ.get('RUSTC', 'rustc') |
| 38 | versions = {cc: run([cc, '--version']).decode(), rustc: run([rustc, '--version','--verbose']).decode(), 'python': sys.version, 'host': platform.uname()._asdict()} |
| 39 | run([cc, '-std=c11', '-O2', '-Wall', '-Wextra', '-Werror', str(fixtures/'arithmetic.c'), '-o', str(out/'c-oracle')]) |
| 40 | run([rustc, '--edition=2021', '-C', 'overflow-checks=yes', str(fixtures/'arithmetic.rs'), '-o', str(out/'rust-oracle')]) |
| 41 | m = (1 << 64) - 1 |
| 42 | boundaries = [0, 1, 2, 255, 256, 65535, 65536, (1<<32)-1, 1<<32, (1<<63)-1, 1<<63, m-1, m] |
| 43 | pairs = [(a,b) for a in boundaries for b in boundaries if b != 0] |
| 44 | rng = random.Random(625) |
| 45 | pairs += [(rng.getrandbits(64), rng.randrange(1, 1<<64)) for _ in range(256)] |
| 46 | payload = ''.join(f'{a} {b}\n' for a,b in pairs).encode() |
| 47 | expected = ''.join(f'{(a+b)&m} {(a-b)&m} {(a*b)&m} {a//b}\n' for a,b in pairs).encode() |
| 48 | observations = {} |
| 49 | for name, cmd in [('c', [str(out/'c-oracle')]), ('rust', [str(out/'rust-oracle')]), ('python_explicit_u64', [sys.executable, str(fixtures/'arithmetic.py'), 'u64']), ('osc_interp_native', [str(out/'osc-oracle'), str(fixtures/'arithmetic.osc')])]: |
| 50 | actual = run(cmd,payload) |
| 51 | assert actual == expected, f'ARITHMETIC_MISMATCH:{name}' |
| 52 | observations[name] = {'rows': len(actual.splitlines()), 'sha256': hashlib.sha256(actual).hexdigest()} |
| 53 | big = run([sys.executable, str(fixtures/'arithmetic.py'), 'bigint'], payload) |
| 54 | assert len(big.splitlines()) == len(pairs) |
| 55 | differing = sum(a != b for a,b in zip(big.splitlines(), expected.splitlines())) |
| 56 | assert differing > 0, 'BIGINT_SILENTLY_NARROWED' |
| 57 | for pair in [(m,1),(0,1),(m,2)]: |
| 58 | i = pairs.index(pair) |
| 59 | assert big.splitlines()[i] != expected.splitlines()[i], f'COUNTEREXAMPLE_LOST:{pair}' |
| 60 | mutants=[] |
| 61 | for name, old, new, compiler in [ |
| 62 | ('c-xor-not-add', 'a + b', 'a ^ b', 'c'), |
| 63 | ('rust-saturate-not-wrap', 'a.wrapping_add(b)', 'a.saturating_add(b)', 'rust')]: |
| 64 | src=fixtures/('arithmetic.c' if compiler=='c' else 'arithmetic.rs') |
| 65 | text=src.read_text();assert text.count(old)==1 |
| 66 | mutant=out/(name+src.suffix);mutant.write_text(text.replace(old,new)) |
| 67 | binary=out/name |
| 68 | run([cc,'-std=c11','-O2',str(mutant),'-o',str(binary)] if compiler=='c' else [rustc,'--crate-name','semantic_mutant','--edition=2021',str(mutant),'-o',str(binary)]) |
| 69 | actual=run([str(binary)],payload) |
| 70 | assert len(actual.splitlines())==len(pairs), 'mutant failed without semantic observation' |
| 71 | kills=sum(a!=b for a,b in zip(actual.splitlines(),expected.splitlines())) |
| 72 | assert kills>0, f'MUTANT_SURVIVED:{name}' |
| 73 | mutants.append({'name':name,'mismatched_rows':kills,'compiled':True}) |
| 74 | tracked = [contract,profiles,Path(__file__).resolve()] + sorted(fixtures.glob('arithmetic.*')) + [fixtures/'osc_probe.c', fixtures/'test_evidence_lifecycle.py', ROOT/'mk/universal.mk'] |
| 75 | report={'schema':'omega.universal.semantics.conformance.v1','classification':'DIFFERENTIAL_COMPATIBILITY','result':'PASS','proof':False,'conversion_implemented':False,'source_commit':run(['git','-C',str(ROOT),'rev-parse','HEAD']).decode().strip(),'rows_per_oracle':len(pairs),'boundary_rows':len(pairs)-256,'random_rows':256,'random_seed':625,'bigint_counterexample_rows':differing,'observations':observations,'mutants':mutants,'versions':versions,'inputs':{p.relative_to(ROOT).as_posix():hashlib.sha256(p.read_bytes()).hexdigest() for p in tracked},'artifacts':{p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in [out/'c-oracle',out/'rust-oracle',out/'osc-oracle']},'not_run':['x86_64','RV64GC_QEMU','GPU','checker2_translation_proof','language_import_export']} |
| 76 | (out/'receipt.json').write_text(json.dumps(report,indent=2)+'\n') |
| 77 | print(f'PASS rows_per_oracle={len(pairs)} bigint_counterexamples={differing} compiled_mutants={len(mutants)} evidence={out}/receipt.json') |
| 78 | |
| 79 | if __name__ == '__main__': |
| 80 | try: |
| 81 | main() |
| 82 | except (AssertionError, OSError, KeyError, ValueError, subprocess.TimeoutExpired) as exc: |
| 83 | print(f'FAIL: {exc}', file=sys.stderr) |
| 84 | sys.exit(1) |