Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-mv/blob/main/tests/universal/translation/validate_g1.py # 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 Sign in to star 1 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omega-mv / tests / universal / translation / validate_g1.py` 1010 lines ยท 46488 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Independent G1 translation validation (#623) against spec/universal/translation-v1.md. 3 4 Five representations of every F1 positive and every accepted c_import_controls.py boundary are compared on 5 boundary and seeded random input vectors: 6 oracle the original C, compiled by cc (external oracle) 7 reference this file's own decoder (from source-aware-v1.md) and bigint evaluator of the upper records 8 export `c-export` output, compiled by cc 9 reimport import(export): semantic identity per section 4 plus evaluation of the re-imported records 10 native `lower` -> pinned omc (function mode) -> pinned bridge generator -> linked caller -> omega_calc 11 The lowering and export tools are exercised only through their public commands; their sources are not read. 12 Exit: 0 PASS, 1 FAIL, 3 NOT_RUN (a tool or pin is absent or wrong; nothing is passed). 13 """ 14 from pathlib import Path 15 import argparse, hashlib, importlib.util, itertools, json, os, random, re, struct, subprocess, sys 16 17 ROOT = Path(__file__).resolve().parents[3] 18 HERE = Path(__file__).resolve().parent 19 sys.dont_write_bytecode = True 20 sys.path.insert(0, str(HERE / 'mutants')) 21 import operators as MUT # noqa: E402 22 23 MASK = (1 << 64) - 1 24 CONTRACT = ('spec/universal/translation-v1.md', '`063f1d630e31925876454129c0024539bea0c7eb17f7187bc0e7ef56790de86e`') 25 FROZEN = { # section 1 of the contract, plus the fixture/control files this validator reads 26 'spec/universal/semantics.md': '`d4ed6148bfa97cc693d3fa4495e2d7e2e68aba04607a7e96dd9a9c54bf9073a8`', 27 # translation-compose-v1 section 2: c-export accepts the Rust and Python S1-family members 28 'spec/universal/translation-compose-v1.md': '`51a7cc444e50fd114a6d2e2272d645333cec1ea92603a60cd9dde06fc7d4c3a0`', 29 'spec/universal/source-aware-v1.md': '`e0efbc717b61976614c1a1e9eee543284bcfb5410922d23b4ad70cb6a99615ec`', 30 'spec/universal/c-u64-import-v1.md': '`84f06ce1ad1653bed08c940696b23d87ce22afb7ebb1b5c3e5970a23b3916012`', 31 'tests/universal/translation/fixtures-f1.json': '`da567a67f747596b1a7285f046119296f1d3b45d2d057053e5d8a084639c7c2d`', 32 'tests/universal/c_import_gate.py': '`aef6a0bed19205e2a4ed96263fccc23b16654d0cf2c1af382e78ed455db6b02b`', 33 'tests/universal/c_import_controls.py': '`6991dc771d288357d8814c2de44663d0604d5cfebd6cba8d8374fa0aa9cfa652`', 34 } 35 OMC_SHA = '`734f0a39319fbfa930bcc62cb30dbf06d47d78e126372b74f5baf478e6126b61`' 36 IMPORT_COMPILER_SHA = '`191b776ef98821597c3e30655da6d680a9b66edbc9ceaca3c39c61ea6df098e9`' 37 IMPORT_INPUTS = ['src/source-aware/vendor/sha256.om', 'src/adapters/c-u64-import.om'] 38 BRIDGE_COMMIT = '`012860dbf26ee62a9838594b9dfd1e3e94a540a9`' 39 SEMANTICS_DIGEST = bytes.fromhex(FROZEN['spec/universal/semantics.md']) 40 BOUNDARY = [0, 1, 2, (1 << 32) - 1, 1 << 32, (1 << 63) - 1, 1 << 63, MASK - 1, MASK] 41 RANDOM_PER_CASE = 64 42 SAMPLE_CAP = 2048 43 CC_FLAGS = ['-std=c17', '-O2', '-Wall', '-Wextra', '-Werror', '-Wno-unused-parameter'] 44 REPS = ['oracle', 'reference', 'export', 'reimport', 'native'] 45 NAME = re.compile(r'^[A-Za-z_][A-Za-z0-9_]*$') 46 47 48 class NotRun(Exception): 49 pass 50 51 52 class Bad(Exception): 53 pass 54 55 56 def sha(b): 57 return hashlib.sha256(b).hexdigest() 58 59 60 # ---------------------------------------------------------------- independent decoder (source-aware-v1.md) 61 62 def decode_envelope(buf): 63 """Canonical wire format: OMSB, version 1, u32 semantic length, u32 sidecar length, exact total.""" 64 if len(buf) < 13 or buf[:4] != b'OMSB' or buf[4] != 1: 65 raise Bad('envelope header') 66 ns, np_ = struct.unpack_from(' 5: 91 raise Bad('record %d input' % k) 92 slots.append(imm) 93 elif op == 1: 94 if (attr, obl, a, b) != (1, 0, 65535, 65535): 95 raise Bad('record %d constant' % k) 96 elif op in (2, 3, 4): 97 if (attr, obl, imm) != (1, 1, 0) or a >= k or b >= k: 98 raise Bad('record %d arithmetic' % k) 99 else: 100 raise Bad('record %d opcode %d' % (k, op)) 101 ops.append((op, a, b, imm)) 102 if sorted(slots) != list(range(len(slots))): 103 raise Bad('input slots not a permutation') 104 return ops 105 106 107 def decode_sidecar(side, sem, count, src): 108 """OMSP v1 sidecar bound to the semantic bytes and the exact source.""" 109 if side is None or len(side) < 74 or side[:4] != b'OMSP' or side[4] != 1 or side[5] not in (0, 1): 110 raise Bad('sidecar header') 111 n = struct.unpack_from('=3, result n-2 is const 0 and n-1 is add(r, n-2) with r < n-2.""" 149 n = len(ops) 150 if n >= 3 and ops[n - 2] == (1, 65535, 65535, 0) and ops[n - 1][0] == 2 and ops[n - 1][2] == n - 2 \ 151 and ops[n - 1][1] < n - 2: 152 return ops[n - 1][1] 153 return None 154 155 156 def arity(ops): 157 return sum(1 for o in ops if o[0] == 9) 158 159 160 # ---------------------------------------------------------------- contract renderings (sections 5 and 6) 161 162 def render_expr(ops, k): 163 op, a, b, imm = ops[k] 164 if op == 9: 165 return 'i%d' % imm, 3 166 if op == 1: 167 return '%dULL' % imm, 3 168 p = 2 if op == 4 else 1 169 (lt, lp), (rt, rp) = render_expr(ops, a), render_expr(ops, b) 170 if lp < p: 171 lt = '(' + lt + ')' 172 if rp <= p: 173 rt = '(' + rt + ')' 174 return '%s %s %s' % (lt, {2: '+', 3: '-', 4: '*'}[op], rt), p 175 176 177 def render_c(ops, name): 178 r = normalized_root(ops) 179 expr = render_expr(ops, len(ops) - 1 if r is None else r)[0] 180 n = arity(ops) 181 params = ', '.join('uint64_t i%d' % s for s in range(n)) if n else 'void' 182 return '#include \nuint64_t %s(%s) { return %s; }\n' % (name, params, expr) 183 184 185 def c_bounds(ops, text): 186 """The c-u64-import-v1 bounds of the contract rendering: bytes, expression parenthesis depth and the 187 upper operation count its re-import would have (inputs, one record per operator and per constant 188 occurrence, plus the synthetic pair).""" 189 expr = text.split('{ return ', 1)[1] 190 depth = best = 0 191 for ch in expr: 192 depth += {'(': 1, ')': -1}.get(ch, 0) 193 best = max(best, depth) 194 nodes = sum(1 for ch in expr if ch in '+-*') + len(re.findall(r'\d+ULL', expr)) 195 return {'bytes': len(text.encode()), 'depth': best, 'reimport_ops': arity(ops) + nodes + 2} 196 197 198 def render_om(ops, name, ident): 199 n = arity(ops) 200 sig = ''.join(' i%d ulong' % s for s in range(n)) 201 out = ['note omega.universal.lower.v1 semantic ' + ident, 'fn %s%s to ulong' % (name, sig), 202 'v = new ulong %d 0' % len(ops)] 203 for k, (op, a, b, imm) in enumerate(ops): 204 if op == 9: 205 out.append('put v %d i%d' % (k, imm)) 206 elif op == 1: 207 out.append('put v %d %d' % (k, imm)) 208 else: 209 out.append('put v %d %s get v %d get v %d' % (k, {2: 'add', 3: 'sub', 4: 'mul'}[op], a, b)) 210 out += ['ret get v %d' % (len(ops) - 1), 'end'] 211 return '\n'.join(out) + '\n' 212 213 214 # ---------------------------------------------------------------- envelopes built by this validator 215 216 def build_sem(ops, lang=1, prof=1, runtime=0, abi=1, fields=None): 217 recs = b'' 218 for k, (op, a, b, imm) in enumerate(ops): 219 if fields: 220 f = fields(op) 221 else: 222 f = {9: (1, 0, 0, 0, 1), 1: (1, 1, 0, 0, 0)}.get(op, (1, 1, 0, 0, 1)) 223 t, attr, eff, alias, obl = f 224 recs += struct.pack('<8BHHQ', lang, 1, op, t, attr, eff, alias, obl, a, b, imm) 225 return b'OMSA' + bytes([1, lang, prof, 1, runtime, abi]) + struct.pack(' 359 #include 360 %(proto)s 361 int main(void) 362 { 363 uint64_t n, v[6] = {0}; 364 if (fread(&n, 8, 1, stdin) != 1) 365 return 2; 366 for (uint64_t j = 0; j < n; j++) { 367 if (%(k)d && fread(v, 8, %(k)d, stdin) != %(k)d) 368 return 2; 369 %(call)s 370 } 371 return 0; 372 } 373 ''' 374 375 376 def c_driver(name, n): 377 proto = 'uint64_t %s(%s);' % (name, ', '.join(['uint64_t'] * n) or 'void') 378 call = 'printf("0 %%llu\\n", (unsigned long long)%s(%s));' % (name, ', '.join('v[%d]' % i for i in range(n))) 379 return DRIVER % {'proto': proto, 'k': n, 'call': call} 380 381 382 def native_driver(sym, n): 383 proto = 'uint32_t %s(uint64_t *result%s);' % (sym, ''.join(', uint64_t' for _ in range(n))) 384 call = ('uint64_t r = UINT64_C(`6148914691236517205`); uint32_t s = %s(&r%s); ' 385 'printf("%%u %%llu\\n", s, (unsigned long long)r);') % (sym, ''.join(', v[%d]' % i for i in range(n))) 386 return DRIVER % {'proto': proto, 'k': n, 'call': call} 387 388 389 class Ctx: 390 def __init__(self, a, work): 391 self.a = a 392 self.work = work 393 self.cc = a.cc 394 self.counter = 0 395 396 def tmp(self, label): 397 self.counter += 1 398 d = self.work / ('%04d-%s' % (self.counter, re.sub(r'[^A-Za-z0-9_.-]', '_', label))) 399 d.mkdir(parents=True) 400 return d 401 402 def tool(self, which, data, *args): 403 return run([getattr(self.a, which)] + list(args), data) 404 405 def compile_run(self, d, sources, n, vs, flags): 406 for fname, text in sources: 407 (d / fname).write_bytes(text if isinstance(text, bytes) else text.encode()) 408 exe = d / 'run' 409 rc, _, err = run([self.cc] + flags + [str(d / f) for f, _ in sources] + ['-o', str(exe)], timeout=120) 410 if rc != 0: 411 return None, 'cc exit %s: %s' % (rc, err.decode(errors='replace')[:400]) 412 rc, out, err = run([exe], pack_vectors(vs, n), timeout=120) 413 if rc != 0: 414 return None, 'run exit %s' % rc 415 rows = out.decode().split('\n')[:-1] 416 if len(rows) != len(vs): 417 return None, 'row count %d != %d' % (len(rows), len(vs)) 418 return [tuple(int(x) for x in r.split()) for r in rows], None 419 420 def native(self, d, om_text, n, vs, sym='omega_calc'): 421 """Pinned omc (function mode) -> pinned bridge generator -> caller linked with the binding.""" 422 om = om_text.encode() 423 (d / 'unit.om').write_bytes(om) 424 rc, binary, err = run([self.a.omc], om, timeout=120) 425 if rc != 0 or not binary: 426 return None, 'omc exit %s: %s' % (rc, err.decode(errors='replace')[:300]), None 427 (d / 'unit.bin').write_bytes(binary) 428 frame = om + b'\0' + b'%08d' % len(binary) + binary 429 rc, binding, err = run([self.a.bridge_native], frame, timeout=120) 430 if rc != 0 or not binding: 431 return None, 'bridge generator exit %s: %s' % (rc, err.decode(errors='replace')[:300]), None 432 res, why = self.compile_run(d, [('binding.c', binding), ('caller.c', native_driver(sym, n))], n, vs, 433 ['-std=gnu11', '-O2', '-Wall', '-Wextra', '-Werror']) 434 return res, why, {'unit_bin_sha256': sha(binary), 'binding_sha256': sha(binding)} 435 436 437 def compare(ref, got, vs, need_status=True): 438 """First disagreement against the reference, as (vector, reference, got).""" 439 for v, want, row in zip(vs, ref, got): 440 st, val = row 441 if (need_status and st != 0) or val != want: 442 return {'vector': [str(x) for x in v], 'reference': str(want), 'got': str(val), 'status': st} 443 return None 444 445 446 # ---------------------------------------------------------------- one unit through every representation 447 448 def check_unit(ctx, case_id, env, src, oracle_name, export_name, expect, ev): 449 """env: the upper envelope (importer output, or validator-built semantic-only). 450 expect: 'ok' or 'limit' (export must refuse 67). Returns the case record and the artifacts for mutants.""" 451 rec = {'id': case_id, 'reps': {}, 'checks': {}, 'failures': []} 452 art = {} 453 454 def fail(check, detail): 455 rec['checks'][check] = 'FAIL' 456 rec['failures'].append({'check': check, 'detail': detail}) 457 458 def ok(check): 459 rec['checks'].setdefault(check, 'PASS') 460 461 d = ctx.tmp(case_id) 462 try: 463 sem, side = decode_envelope(env) 464 ops = decode_s1(sem) 465 if src is not None: 466 decode_sidecar(side, sem, len(ops), src) 467 except Bad as e: 468 rec['reps'] = {r: 'FAIL' if r == 'reference' else 'NOT_RUN' for r in REPS} 469 fail('reference-decode', str(e)) 470 return rec, None 471 n = arity(ops) 472 ident = identity(sem) 473 root = normalized_root(ops) 474 vs = vectors(n, case_id) 475 ref = [evaluate(ops, v) for v in vs] 476 rec.update({'arity': n, 'records': len(ops), 'normalized': root is not None, 'semantic_identity': ident, 477 'vectors': len(vs), 'expect_export': expect}) 478 rec['reps']['reference'] = 'PASS' 479 art.update({'ops': ops, 'sem': sem, 'ident': ident, 'vs': vs, 'ref': ref, 'n': n, 'env': env, 'src': src, 480 'export_name': export_name, 'identity_required': src is not None and root is not None}) 481 sem_only = envelope(sem) 482 483 # 1. oracle 484 if src is None: 485 rec['reps']['oracle'] = 'NOT_APPLICABLE' 486 else: 487 (d / 'oracle').mkdir() 488 res, why = ctx.compile_run(d / 'oracle', [('source.c', src), ('driver.c', c_driver(oracle_name, n))], 489 n, vs, CC_FLAGS) 490 if res is None: 491 rec['reps']['oracle'] = 'FAIL' 492 fail('oracle', why) 493 else: 494 m = compare(ref, res, vs) 495 rec['reps']['oracle'] = 'FAIL' if m else 'PASS' 496 if m: 497 fail('oracle-vs-reference', m) 498 ev['observations']['oracle'] += len(vs) 499 500 # 3/4. export and re-import 501 eargs = [export_name] if export_name != 'calc' else [] 502 rc, E, err = ctx.tool('export', env, *eargs) 503 rc2, E2, _ = ctx.tool('export', env, *eargs) 504 rc3, E3, _ = ctx.tool('export', sem_only, *eargs) 505 rec['export_status'] = rc 506 if (rc, E) != (rc2, E2): 507 fail('export-deterministic', 'two runs differ') 508 else: 509 ok('export-deterministic') 510 if (rc, E) != (rc3, E3): 511 fail('export-generated-not-replayed', 'semantic-only envelope exports differently (status %s vs %s)' % (rc, rc3)) 512 else: 513 ok('export-generated-not-replayed') 514 expected_c = render_c(ops, export_name) 515 bounds = rec['contract_rendering_bounds'] = c_bounds(ops, expected_c) 516 over = bounds['bytes'] > 4096 or bounds['depth'] > 16 or bounds['reimport_ops'] > 64 517 if over != (expect == 'limit'): 518 fail('validator-case-design', 'expected %s but the contract rendering bounds are %r' % (expect, bounds)) 519 if expect == 'limit': 520 rec['reps']['export'] = rec['reps']['reimport'] = 'NOT_APPLICABLE' 521 if rc == 67 and E == b'': 522 ok('export-limit-refusal') 523 else: 524 fail('export-limit-refusal', {'status': rc, 'stdout_bytes': len(E), 525 'contract': 'section 6: unimportable export refuses 67 with no stdout'}) 526 elif rc != 0 or not E: 527 rec['reps']['export'] = rec['reps']['reimport'] = 'FAIL' 528 fail('export', {'status': rc, 'stderr': err.decode(errors='replace')[:300], 529 'contract': 'section 6: a required boundary that refuses is a FAIL'}) 530 else: 531 (d / 'export.c').write_bytes(E) 532 art['export'] = E.decode(errors='replace') 533 if E.decode(errors='replace') == expected_c: 534 ok('export-form') 535 else: 536 fail('export-form', {'expected': expected_c, 'got': E.decode(errors='replace')}) 537 rec['export_equals_source'] = None if src is None else E == src 538 (d / 'export').mkdir() 539 res, why = ctx.compile_run(d / 'export', [('export.c', E), ('driver.c', c_driver(export_name, n))], n, vs, CC_FLAGS) 540 if res is None: 541 rec['reps']['export'] = 'FAIL' 542 fail('export-compile-run', why) 543 else: 544 m = compare(ref, res, vs) 545 rec['reps']['export'] = 'FAIL' if m else 'PASS' 546 if m: 547 fail('export-vs-reference', m) 548 ev['observations']['export'] += len(vs) 549 rec['reps']['reimport'] = reimport_check(ctx, E, ops, sem, root, vs, ref, rec, fail, ok, export_name, 550 src is not None) 551 if 'reimport_identity' in rec: 552 ev['observations']['reimport'] += len(vs) 553 554 # 5. native 555 rc, L, err = ctx.tool('lower', env) 556 rcb, L2, _ = ctx.tool('lower', env) 557 rcc, L3, _ = ctx.tool('lower', sem_only) 558 rec['lower_status'] = rc 559 if (rc, L) != (rcb, L2): 560 fail('lower-deterministic', 'two runs differ') 561 else: 562 ok('lower-deterministic') 563 if (rc, L) != (rcc, L3): 564 fail('lower-sidecar-independent', 'semantic-only envelope lowers differently') 565 else: 566 ok('lower-sidecar-independent') 567 if rc != 0 or not L: 568 rec['reps']['native'] = 'FAIL' 569 fail('lower', {'status': rc, 'stderr': err.decode(errors='replace')[:300]}) 570 else: 571 text = L.decode(errors='replace') 572 art['lower'] = text 573 expected_om = render_om(ops, 'calc', ident) 574 if text == expected_om: 575 ok('lower-form') 576 else: 577 fail('lower-form', {'expected': expected_om, 'got': text}) 578 m = re.match(r'^note omega\.universal\.lower\.v1 semantic ([0-9a-f]{64})\n', text) 579 if m and m.group(1) == ident: 580 ok('lower-semantic-note') 581 else: 582 fail('lower-semantic-note', 'note line does not carry the unit semantic identity %s' % ident) 583 (d / 'native').mkdir() 584 res, why, meta = ctx.native(d / 'native', text, n, vs) 585 rec['native_artifacts'] = meta 586 if res is None: 587 rec['reps']['native'] = 'FAIL' 588 fail('native', why) 589 else: 590 mm = compare(ref, res, vs) 591 rec['reps']['native'] = 'FAIL' if mm else 'PASS' 592 if mm: 593 fail('native-vs-reference', mm) 594 ev['observations']['native'] += len(vs) 595 # determinism of the native realization: the same unit compiles to the same bytes 596 rc4, b4, _ = run([ctx.a.omc], L, timeout=120) 597 if rc4 == 0 and sha(b4) == meta['unit_bin_sha256']: 598 ok('native-deterministic') 599 else: 600 fail('native-deterministic', 'omc output differs between runs') 601 ev['observations']['reference'] += len(vs) 602 rec['result'] = 'FAIL' if rec['failures'] else 'PASS' 603 return rec, art 604 605 606 def reimport_check(ctx, E, ops, sem, root, vs, ref, rec, fail, ok, name, from_importer): 607 """Section 4. A NORMALIZED unit from the C importer must re-import to the same identity. Any other unit 608 is checked by equal evaluation; its identity difference is recorded, and the re-import must be 609 NORMALIZED (the importer adds its pair). Every export must be a fixpoint: export(import(E)) == E.""" 610 rc, env2, err = ctx.tool('importer', E) 611 if rc != 0 or not env2: 612 fail('reimport', {'status': rc, 'stderr': err.decode(errors='replace')[:200]}) 613 return 'FAIL' 614 try: 615 sem2, side2 = decode_envelope(env2) 616 ops2 = decode_s1(sem2) 617 decode_sidecar(side2, sem2, len(ops2), E) 618 except Bad as e: 619 fail('reimport-decode', str(e)) 620 return 'FAIL' 621 status = 'PASS' 622 rec['reimport_identity'] = identity(sem2) 623 if root is not None and from_importer: 624 if sem2 != sem: 625 fail('reimport-identity', {'original': identity(sem), 'reimported': identity(sem2), 626 'contract': 'section 4: NORMALIZED U must re-import to the same identity'}) 627 status = 'FAIL' 628 else: 629 ok('reimport-identity') 630 else: 631 rec['reimport_identity_differs_recorded'] = sem2 != sem 632 if normalized_root(ops2) is None: 633 fail('reimport-identity', 'the re-import is not NORMALIZED') 634 status = 'FAIL' 635 else: 636 ok('reimport-identity') 637 for v, want in zip(vs, ref): 638 got = evaluate(ops2, v) 639 if got != want: 640 fail('reimport-vs-reference', {'vector': [str(x) for x in v], 'reference': str(want), 'got': str(got)}) 641 status = 'FAIL' 642 break 643 rc, E2, _ = ctx.tool('export', env2, *([name] if name != 'calc' else [])) 644 if rc == 0 and E2 == E: 645 ok('export-fixpoint') 646 else: 647 fail('export-fixpoint', 'export(import(export(U))) != export(U) (status %s)' % rc) 648 return status 649 650 651 # ---------------------------------------------------------------- mutation controls 652 653 def mutant_checks(ctx, case_id, art, op_name, text, kind): 654 """Run a mutated tool output through the comparisons the real output passed; list what detects it.""" 655 d = ctx.tmp('mut-%s-%s' % (case_id, op_name)) 656 ops, vs, ref, n = art['ops'], art['vs'], art['ref'], art['n'] 657 detected, notes = [], {} 658 if kind == 'om': 659 if text != render_om(ops, 'calc', art['ident']): 660 detected.append('lower-form') 661 res, why, _ = ctx.native(d, text, n, vs) 662 if res is None: 663 notes['native'] = why 664 detected.append('native-build') 665 else: 666 m = compare(ref, res, vs) 667 if m: 668 detected.append('native-vs-reference') 669 notes['first_mismatch'] = m 670 else: 671 name = art['export_name'] 672 if text != render_c(ops, name): 673 detected.append('export-form') 674 res, why = ctx.compile_run(d, [('export.c', text), ('driver.c', c_driver(name, n))], n, vs, CC_FLAGS) 675 if res is None: 676 notes['export'] = why 677 detected.append('export-compile') 678 else: 679 m = compare(ref, res, vs) 680 if m: 681 detected.append('export-vs-reference') 682 notes['first_mismatch'] = m 683 rc, env2, _ = ctx.tool('importer', text.encode()) 684 if rc != 0: 685 detected.append('reimport-refused') 686 else: 687 try: 688 sem2, _ = decode_envelope(env2) 689 ops2 = decode_s1(sem2) 690 if art['identity_required'] and sem2 != art['sem']: 691 detected.append('reimport-identity') 692 if any(evaluate(ops2, v) != w for v, w in zip(vs, ref)): 693 detected.append('reimport-vs-reference') 694 except Bad: 695 detected.append('reimport-decode') 696 behaviour = [x for x in detected if x.endswith('vs-reference') or x == 'reimport-identity'] 697 return {'case': case_id, 'operator': op_name, 'mutant_sha256': sha(text.encode()), 'detected_by': detected, 698 'killed': bool(detected), 'killed_by_behaviour_or_identity': bool(behaviour), 699 **({'notes': notes} if notes else {})} 700 701 702 def run_mutants(ctx, arts, ev): 703 rows = [] 704 for case_id, art in arts: 705 if 'lower' in art: 706 for op_name, fn in MUT.OM_OPERATORS: 707 t = fn(art['lower']) 708 if t is not None and t != art['lower']: 709 rows.append(mutant_checks(ctx, case_id, art, op_name, t, 'om')) 710 if 'export' in art: 711 ops = list(MUT.C_OPERATORS) 712 if art['src'] is not None: 713 ops.append(('c-replay-source', lambda _t, s=art['src']: s.decode(errors='replace'))) 714 for op_name, fn in ops: 715 t = fn(art['export']) 716 if t is not None and t != art['export']: 717 rows.append(mutant_checks(ctx, case_id, art, op_name, t, 'c')) 718 by = {} 719 for r in rows: 720 b = by.setdefault(r['operator'], {'total': 0, 'killed': 0, 'killed_by_behaviour_or_identity': 0, 721 'killed_by_form_only': 0, 'survivors': []}) 722 b['total'] += 1 723 b['killed'] += r['killed'] 724 b['killed_by_behaviour_or_identity'] += r['killed_by_behaviour_or_identity'] 725 b['killed_by_form_only'] += r['killed'] and not r['killed_by_behaviour_or_identity'] 726 if not r['killed']: 727 b['survivors'].append(r['case']) 728 ev['mutants'] = {'total': len(rows), 'killed': sum(r['killed'] for r in rows), 729 'killed_by_behaviour_or_identity': sum(r['killed_by_behaviour_or_identity'] for r in rows), 730 'by_operator': by, 731 'rows': rows} 732 733 734 # ---------------------------------------------------------------- refusals 735 736 def refusal_checks(ctx, base_env, ev): 737 rows = [] 738 739 def expect(label, which, data, args, want): 740 rc, out, err = ctx.tool(which, data, *args) 741 good = (rc == want) and out == b'' 742 rows.append({'tool': which, 'case': label, 'want': want, 'status': rc, 'stdout_bytes': len(out), 743 'stderr': err.decode(errors='replace')[:120], 'result': 'PASS' if good else 'FAIL'}) 744 745 sem, _ = decode_envelope(base_env) 746 base_ops = decode_s1(sem) 747 for label, bad, family in non_s1_envelopes(base_ops): 748 e = envelope(bad) 749 if ctx.a.sa: 750 rc, out, _ = run([ctx.a.sa], b'\x02' + e) 751 if rc != 0 or out != e: 752 rows.append({'tool': 'sa', 'case': label, 'result': 'FAIL', 'status': rc, 753 'detail': 'probe is not a valid source-aware v1 unit; it cannot test 68'}) 754 continue 755 expect('non-S1 ' + label, 'lower', e, [], 68) 756 if not family: 757 expect('non-S1 ' + label, 'export', e, [], 68) 758 continue 759 rc, out, err = ctx.tool('export', e) 760 rcc, outc, _ = ctx.tool('export', envelope(build_sem(base_ops))) 761 good = rc == 0 and rcc == 0 and out != b'' and out == outc 762 rows.append({'tool': 'export', 'case': 'S1-family ' + label + ' exports as R(U, C)', 'want': 0, 763 'status': rc, 'stdout_bytes': len(out), 'stderr': err.decode(errors='replace')[:120], 764 'contract': 'translation-compose-v1 section 2', 'result': 'PASS' if good else 'FAIL'}) 765 for label, bad in malformed_envelopes(base_env): 766 if ctx.a.sa: 767 rc, _, _ = run([ctx.a.sa], b'\x02' + bad) 768 if rc != 65: 769 rows.append({'tool': 'sa', 'case': label, 'result': 'FAIL', 'status': rc, 770 'detail': 'source-aware decoder does not call this MALFORMED'}) 771 continue 772 for which in ('lower', 'export'): 773 expect('malformed ' + label, which, bad, [], 65) 774 for nm in ['9x', 'a-b', 'x' * 64, 'end', '']: 775 expect('bad name %r' % nm[:12], 'lower', base_env, [nm], 64) 776 expect('two arguments', 'lower', base_env, ['calc', 'calc'], 64) 777 for nm in ['foo', 'Calc', 'omega_', 'main', 'omega_' + 'x' * 27, 'a b', '']: 778 expect('bad name %r' % nm[:12], 'export', base_env, [nm], 64) 779 expect('two arguments', 'export', base_env, ['calc', 'calc'], 64) 780 ev['tool_refusals'] = {'total': len(rows), 'pass': sum(r['result'] == 'PASS' for r in rows), 'rows': rows} 781 782 783 def named_checks(ctx, env, ev): 784 """`lower NAME` binds omega_NAME; `c-export omega_x` names the C function.""" 785 rows = [] 786 sem, _ = decode_envelope(env) 787 ops = decode_s1(sem) 788 n = arity(ops) 789 vs = vectors(n, 'named') 790 ref = [evaluate(ops, v) for v in vs] 791 rc, L, _ = ctx.tool('lower', env, 'fold') 792 if rc == 0 and L.decode(errors='replace') == render_om(ops, 'fold', identity(sem)): 793 res, why, _ = ctx.native(ctx.tmp('named-lower'), L.decode(), n, vs, 'omega_fold') 794 rows.append({'case': 'lower fold -> omega_fold', 'result': 'PASS' if res and not compare(ref, res, vs) else 'FAIL', 795 **({'detail': why} if why else {})}) 796 else: 797 rows.append({'case': 'lower fold -> omega_fold', 'result': 'FAIL', 'status': rc}) 798 rc, E, _ = ctx.tool('export', env, 'omega_x1') 799 rows.append({'case': 'c-export omega_x1', 'status': rc, 800 'result': 'PASS' if rc == 0 and E.decode(errors='replace') == render_c(ops, 'omega_x1') else 'FAIL'}) 801 ev['named'] = rows 802 803 804 # ---------------------------------------------------------------- pins and inputs 805 806 def check_pins(a): 807 pins = {} 808 p = ROOT / CONTRACT[0] 809 if not p.is_file() or sha(p.read_bytes()) != CONTRACT[1]: 810 raise NotRun('contract %s sha256 is not %s' % CONTRACT) 811 pins[CONTRACT[0]] = CONTRACT[1] 812 for rel, want in FROZEN.items(): 813 got = sha((ROOT / rel).read_bytes()) if (ROOT / rel).is_file() else None 814 if got != want: 815 raise NotRun('frozen input %s sha256 %s, contract/validator pin %s' % (rel, got, want)) 816 pins[rel] = got 817 tools = {} 818 for key in ('lower', 'export', 'importer', 'omc', 'bridge_native'): 819 path = getattr(a, key) 820 if not path or not Path(path).is_file() or not os.access(path, os.X_OK): 821 raise NotRun('tool %s absent or not executable: %s' % (key, path)) 822 tools[key] = {'path': str(path), 'sha256': sha(Path(path).read_bytes())} 823 if tools['omc']['sha256'] != OMC_SHA: 824 raise NotRun('omc sha256 %s, contract section 1 pins %s' % (tools['omc']['sha256'], OMC_SHA)) 825 imp = Path(a.importer) 826 try: 827 m = json.loads((imp.parent / 'build.json').read_text()) 828 except (OSError, ValueError) as e: 829 raise NotRun('importer build.json unreadable: %s' % e) 830 if m.get('compiler_sha256') != IMPORT_COMPILER_SHA or m.get('binary_sha256') != tools['importer']['sha256']: 831 raise NotRun('importer does not match its build.json / compiler pin %s' % IMPORT_COMPILER_SHA) 832 if set(m.get('inputs', {})) != set(IMPORT_INPUTS) or any(sha((ROOT / r).read_bytes()) != m['inputs'][r] for r in IMPORT_INPUTS): 833 raise NotRun('importer build.json inputs differ from this checkout') 834 tools['importer']['build_json'] = m 835 if not a.bridge_repo: 836 raise NotRun('no omega-bridge clone: pass --bridge-repo or set OMEGA_BRIDGE_REPO') 837 repo = Path(a.bridge_repo) 838 rc, src, _ = run(['git', '-C', repo, 'show', BRIDGE_COMMIT + ':src/native.om']) 839 if rc != 0: 840 raise NotRun('bridge repository %s lacks pinned commit %s' % (repo, BRIDGE_COMMIT)) 841 rc, built, _ = run([a.omc], src, timeout=120) 842 if rc != 0 or built != Path(a.bridge_native).read_bytes(): 843 raise NotRun('bridge generator is not omc(native.om @ %s)' % BRIDGE_COMMIT) 844 tools['bridge_native'].update({'commit': BRIDGE_COMMIT, 'native_om_sha256': sha(src)}) 845 for key in ('lower', 'export'): 846 top = run(['git', '-C', Path(getattr(a, key)).resolve().parent, 'rev-parse', 'HEAD']) 847 dirty = run(['git', '-C', Path(getattr(a, key)).resolve().parent, 'status', '--porcelain', '--untracked-files=no']) 848 tools[key]['repo_head'] = top[1].decode().strip() if top[0] == 0 else None 849 tools[key]['repo_dirty'] = bool(dirty[1].strip()) if dirty[0] == 0 else None 850 last = run(['git', '-C', Path(getattr(a, key)).resolve().parent, 'log', '-1', '--format=%H', '--', 851 Path(getattr(a, key)).resolve()]) 852 tools[key]['last_commit_touching_command'] = last[1].decode().strip() if last[0] == 0 else None 853 repo_root = Path(getattr(a, key)).resolve().parents[2] 854 exe_name = Path(getattr(a, key)).name 855 for bj in sorted(repo_root.glob('build/*/build.json')): 856 if (bj.parent / exe_name).is_file(): 857 tools[key]['build'] = {'dir': bj.parent.relative_to(repo_root).as_posix(), 'build_json_sha256': sha(bj.read_bytes()), 858 'binary_sha256': sha((bj.parent / exe_name).read_bytes()), 859 'build_json': json.loads(bj.read_text())} 860 if a.sa: 861 tools['sa'] = {'path': str(a.sa), 'sha256': sha(Path(a.sa).read_bytes())} 862 return pins, tools 863 864 865 def load_fixtures(): 866 d = json.loads((ROOT / 'tests/universal/translation/fixtures-f1.json').read_text()) 867 pos = [] 868 for p in d['positives']: 869 b = p['source'].encode() 870 if sha(b) != p['sha256']: 871 raise NotRun('fixture %s bytes do not match its sha256' % p['id']) 872 pos.append((p['id'], b, p['name'], p['inputs'])) 873 spec = importlib.util.spec_from_file_location('f1gate', ROOT / 'tests/universal/c_import_gate.py') 874 g = importlib.util.module_from_spec(spec) 875 spec.loader.exec_module(g) # data only: NEGATIVES; its decode/evaluate helpers are not used 876 negs = list(g.NEGATIVES) 877 if len(negs) != len(d['refusals']) or any(sha(b) != r['sha256'] or len(b) != r['bytes'] for b, r in zip(negs, d['refusals'])): 878 raise NotRun('F1 refusal bytes do not match fixtures-f1.json') 879 return pos, [(r['id'], b) for r, b in zip(d['refusals'], negs)] 880 881 882 def controls(): 883 """The four accepted boundaries of c_import_controls.py (pinned above by sha256), rebuilt byte for byte.""" 884 header = '#include \n' 885 base = (header + 'uint64_t calc(uint64_t a,uint64_t b){return a+b;}').encode() 886 pad = base + b' ' * (4096 - len(base)) 887 comment = base + b'//' + b'x' * (4096 - len(base) - 2) 888 maximum = (header + 'uint64_t calc(uint64_t a,uint64_t b){return ' + '+'.join(['a'] * 61) + ';}').encode() 889 deep = (header + 'uint64_t calc(uint64_t a,uint64_t b){return ' + '(' * 16 + 'a' + ')' * 16 + ';}').encode() 890 return [('C-exact-source-capacity', pad), ('C-comment-at-capacity', comment), 891 ('C-operation-capacity', maximum), ('C-nesting-limit', deep)] 892 893 894 def main(): 895 ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) 896 for k in ('lower', 'export', 'importer', 'omc', 'bridge_native'): 897 ap.add_argument('--' + k.replace('_', '-'), dest=k) 898 ap.add_argument('--bridge-repo', default=os.environ.get('OMEGA_BRIDGE_REPO'), 899 help='omega-bridge clone holding commit %s (the generator is rebuilt and compared)' % BRIDGE_COMMIT) 900 ap.add_argument('--sa', help='optional #621 native sa binary: confirms refusal probes are valid / malformed v1') 901 ap.add_argument('--cc', default=os.environ.get('CC', 'cc')) 902 ap.add_argument('--no-mutants', action='store_true') 903 ap.add_argument('--out', required=True, help='new directory; evidence.json is written inside it') 904 a = ap.parse_args() 905 out = Path(a.out).resolve() 906 out.mkdir(parents=True, exist_ok=False) 907 work = out / 'work' 908 work.mkdir() 909 ev = {'schema': 'omega.universal.translation.validate.g1.v1', 'contract': {'path': CONTRACT[0], 'sha256': CONTRACT[1]}, 910 'validator_sha256': sha(Path(__file__).read_bytes()), 911 'mutant_operators_sha256': sha((HERE / 'mutants/operators.py').read_bytes()), 912 'evidence_class': 'REFERENCE + DIFFERENTIAL, NATIVE (host AArch64); no PROOF', 913 'boundary_values': [str(x) for x in BOUNDARY], 'random_per_case': RANDOM_PER_CASE, 914 'observations': {r: 0 for r in REPS}} 915 try: 916 ev['pins'], ev['tools'] = check_pins(a) 917 positives, negatives = load_fixtures() 918 except NotRun as e: 919 ev['result'] = 'NOT_RUN' 920 ev['reason'] = str(e) 921 (out / 'evidence.json').write_text(json.dumps(ev, indent=1) + '\n') 922 print('NOT_RUN', e) 923 return 3 924 ev['cc_version'] = run([a.cc, '--version'])[1].decode().split('\n')[0] 925 ctx = Ctx(a, work) 926 cases, arts = [], [] 927 928 def import_case(cid, src, name): 929 rc, env, err = run([a.importer], src) 930 if rc != 0: 931 rec = {'id': cid, 'reps': {r: 'NOT_RUN' for r in REPS}, 'result': 'FAIL', 932 'failures': [{'check': 'import', 'detail': {'status': rc, 'stderr': err.decode(errors='replace')}}]} 933 cases.append(rec) 934 return None 935 rec, art = check_unit(ctx, cid, env, src, name, name, 'ok', ev) 936 rec['kind'] = 'source' 937 rec['source_sha256'] = sha(src) 938 cases.append(rec) 939 if art: 940 arts.append((cid, art)) 941 return env 942 943 envs = {} 944 for cid, src, name, k in positives: 945 envs[cid] = import_case(cid, src, name) 946 print(cid, cases[-1]['result'], flush=True) 947 for cid, src in controls(): 948 envs[cid] = import_case(cid, src, 'calc') 949 print(cid, cases[-1]['result'], flush=True) 950 for cid, ops, expect in probes(): 951 rec, art = check_unit(ctx, cid, envelope(build_sem(ops)), None, None, 'calc', expect, ev) 952 rec['kind'] = 'probe' 953 cases.append(rec) 954 if art and expect == 'ok': 955 arts.append((cid, art)) 956 print(cid, rec['result'], flush=True) 957 958 # generated, not replayed: comments + CRLF + renamed parameters (F1-P33) export to different text with 959 # equal semantics, and a semantic-only envelope exports the same bytes (checked for every case above) 960 p33 = next(c for c in cases if c['id'] == 'F1-P33') 961 g = {'export_differs_from_source': p33.get('export_equals_source') is False, 962 'reimport_identity_equal': p33['checks'].get('reimport-identity') == 'PASS', 963 'semantic_only_export_identical': p33['checks'].get('export-generated-not-replayed') == 'PASS'} 964 g['result'] = 'PASS' if all(g.values()) else 'FAIL' 965 ev['generated_not_replayed_P33'] = g 966 # import refusals F1 967 rrows = [] 968 for rid, src in negatives: 969 rc, o, err = run([a.importer], src) 970 rrows.append({'id': rid, 'status': rc, 'stdout_bytes': len(o), 'result': 'PASS' if rc not in (0, 'timeout', 'oserror') and o == b'' and b'C_IMPORT_' in err else 'FAIL'}) 971 ev['f1_refusals'] = {'total': len(rrows), 'pass': sum(r['result'] == 'PASS' for r in rrows), 'rows': rrows} 972 base = envs.get('F1-P05') 973 if base: 974 refusal_checks(ctx, base, ev) 975 if envs.get('F1-P34'): 976 named_checks(ctx, envs['F1-P34'], ev) 977 if not a.no_mutants: 978 run_mutants(ctx, arts, ev) 979 980 summary = {r: {'PASS': 0, 'FAIL': 0, 'NOT_RUN': 0, 'NOT_APPLICABLE': 0} for r in REPS} 981 for c in cases: 982 for r in REPS: 983 summary[r][c['reps'].get(r, 'NOT_RUN')] += 1 984 ev['representations'] = summary 985 ev['cases'] = cases 986 failed = [c['id'] for c in cases if c['result'] != 'PASS'] 987 failed += ['refusal:' + r['id'] for r in ev['f1_refusals']['rows'] if r['result'] != 'PASS'] 988 failed += ['tool-refusal:%s:%s' % (r['tool'], r['case']) for r in ev.get('tool_refusals', {}).get('rows', []) if r['result'] != 'PASS'] 989 failed += ['named:' + r['case'] for r in ev.get('named', []) if r['result'] != 'PASS'] 990 if ev['generated_not_replayed_P33']['result'] != 'PASS': 991 failed.append('generated-not-replayed:F1-P33') 992 if not base: 993 failed.append('refusal probes NOT_RUN: F1-P05 did not import') 994 if 'mutants' in ev and ev['mutants']['killed'] != ev['mutants']['total']: 995 failed.append('mutants survived: %d' % (ev['mutants']['total'] - ev['mutants']['killed'])) 996 ev['failed'] = failed 997 ev['result'] = 'FAIL' if failed else 'PASS' 998 (out / 'evidence.json').write_text(json.dumps(ev, indent=1) + '\n') 999 print(json.dumps({'result': ev['result'], 'representations': summary, 1000 'f1_refusals': '%d/%d' % (ev['f1_refusals']['pass'], ev['f1_refusals']['total']), 1001 'tool_refusals': '%d/%d' % (ev.get('tool_refusals', {}).get('pass', 0), ev.get('tool_refusals', {}).get('total', 0)), 1002 'mutants': '%d/%d killed (%d by behaviour or identity, rest by contract form only)' % ( 1003 ev['mutants']['killed'], ev['mutants']['total'], ev['mutants']['killed_by_behaviour_or_identity']) 1004 if 'mutants' in ev else 'NOT_RUN', 1005 'failed': failed[:40]}, indent=1)) 1006 return 1 if failed else 0 1007 1008 1009 if __name__ == '__main__': 1010 raise SystemExit(main())