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_compose.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_compose.py` 969 lines ยท 42020 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Independent G2 composition validation (#623) against spec/universal/translation-compose-v1.md. 3 4 For the S1 family members C, Rust and Python, every directed composition A -> B (A != B, 6 in G2) and 5 every fixture of A (F1 + accepted C import controls for C, fixtures-f2-.json for Rust and Python): 6 U_A = import_A(src); src_B = export_B(U_A); U_B = import_B(src_B) 7 4.1 identity N(strip(U_B)) == N(strip(U_A)) byte for byte 8 4.2 DIFFERENTIAL A's oracle on src, this file's reference evaluator on U_A, B's oracle on src_B and the 9 native realization of U_A (R to C -> lower -> pinned omc -> pinned bridge -> omega_calc) 10 agree on the translation-v1 section 3 vectors 11 4.3 generated src_B equals export_B of the semantic-only envelope (and of R(U_A, M) for every member M) 12 Same-language round trips A -> A are reported separately. R, N, strip, the decoders, the renderings of 13 each exporter's frozen output form and the mutation operators are written here from the contracts; the 14 adapters are exercised only through their public commands, their sources are not read. 15 Oracles: cc (C17), rustc --edition 2021 -O -C overflow-checks=on (Rust), python3 (Python). 16 Exit: 0 PASS, 1 FAIL, 3 NOT_RUN (a pin or tool is absent; nothing is passed). 17 """ 18 from pathlib import Path 19 from types import SimpleNamespace 20 import argparse, hashlib, json, os, re, struct, sys 21 22 sys.dont_write_bytecode = True 23 HERE = Path(__file__).resolve().parent 24 sys.path.insert(0, str(HERE)) 25 import validate_g1 as G # noqa: E402 (this lane's own G1 validator: decoders, vectors, native seam) 26 27 ROOT = G.ROOT 28 MASK = G.MASK 29 U = 65535 30 COMPOSE = ('spec/universal/translation-compose-v1.md', '`51a7cc444e50fd114a6d2e2272d645333cec1ea92603a60cd9dde06fc7d4c3a0`') 31 LANE_SPECS = {'rust': 'spec/universal/rust-u64-v1.md', 'python': 'spec/universal/python-u64-v1.md'} 32 # compose section 1: header language, profile, op dialect byte, arithmetic (ops 2/3/4) obligations 33 MEMBERS = {'c': (1, 1, 1, 1), 'rust': (2, 2, 2, 1), 'python': (3, 4, 3, 5)} 34 LANGS = ['c', 'rust', 'python'] 35 # compose section 3: each importer's declared normalization pair (c-u64-import-v1, rust-u64-v1 section 3, 36 # python-u64-v1 section 3 all declare one) 37 DECLARES_PAIR = {'c': True, 'rust': True, 'python': True} 38 PY_MASK = '0xFFFFFFFFFFFFFFFF' 39 TOOLS = {'c': ('c-import', 'c-export'), 'rust': ('rust-import', 'rust-export'), 40 'python': ('python-import', 'python-export')} 41 RUSTC = ['--edition', '2021', '-O', '-C', 'overflow-checks=on'] 42 43 44 class Bad(Exception): 45 pass 46 47 48 def sha(b): 49 return hashlib.sha256(b).hexdigest() 50 51 52 # ---------------------------------------------------------------- family decoder, R, N, strip 53 54 def decode_family(sem): 55 """source-aware-v1 semantic bytes of an S1-family unit -> (member, ops).""" 56 if len(sem) < 44 or sem[:4] != b'OMSA' or sem[4] != 1 or sem[7] != 1: 57 raise Bad('semantic header') 58 count = struct.unpack_from(' 5: 74 raise Bad('record %d input' % k) 75 slots.append(imm) 76 elif op == 1: 77 if (attr, obl, a, b) != (1, 0, U, U): 78 raise Bad('record %d constant' % k) 79 elif op in (2, 3, 4): 80 if (attr, obl, imm) != (1, arith, 0) or a >= k or b >= k: 81 raise Bad('record %d arithmetic' % k) 82 else: 83 raise Bad('record %d opcode %d' % (k, op)) 84 ops.append((op, a, b, imm)) 85 if sorted(slots) != list(range(len(slots))): 86 raise Bad('input slots not a permutation') 87 return member, ops 88 89 90 def R(sem, member): 91 """compose section 2: rewrite header language/profile, every dialect byte and arithmetic obligations.""" 92 lang, prof, dialect, arith = MEMBERS[member] 93 b = bytearray(sem) 94 b[5], b[6] = lang, prof 95 for k in range(struct.unpack_from('\nuint64_t calc(%s) { return %s; }\n' % (params, c_expr(t)[0]) 176 if lang == 'rust': 177 return 'pub fn calc(%s) -> u64 { %s }\n' % (', '.join('i%d: u64' % s for s in range(n)), rust_expr(t)) 178 return 'def calc(%s):\n return %s\n' % (', '.join('i%d' % s for s in range(n)), py_expr(t, True)) 179 180 181 def bounds(lang, t, n): 182 """Re-import bounds of each exporter's contract rendering (translation-v1 section 6, rust-u64-v1 183 section 4, python-u64-v1 section 6): True iff the export must refuse 67 LIMIT.""" 184 def nodes(x): 185 return 0 if x['t'] == 'in' else 1 if x['t'] == 'k' else 1 + nodes(x['l']) + nodes(x['r']) 186 187 def rdepth(x): 188 return 0 if x['t'] != 'op' else max(rdepth(x['l']), rdepth(x['r']) + 1) 189 190 text = render(lang, t, n) 191 ops = n + nodes(t) + 2 192 body = text.split('return ' if lang != 'rust' else '-> u64 { ', 1)[1] 193 depth = best = 0 194 for ch in body: 195 depth += {'(': 1, ')': -1}.get(ch, 0) 196 best = max(best, depth) 197 if lang == 'c': 198 over = best > 16 199 elif lang == 'rust': 200 over = rdepth(t) > 16 201 else: 202 over = best > 128 203 return {'bytes': len(text.encode()), 'reimport_ops': ops, 'depth': rdepth(t) if lang == 'rust' else best, 204 'over': len(text.encode()) > 4096 or ops > 64 or over} 205 206 207 # ---------------------------------------------------------------- parsers of the exporters' output forms 208 209 class P: 210 def __init__(self, s): 211 self.s, self.i = s, 0 212 213 def eat(self, lit): 214 if not self.s.startswith(lit, self.i): 215 raise Bad('expected %r at %d' % (lit, self.i)) 216 self.i += len(lit) 217 218 def peek(self, lit): 219 return self.s.startswith(lit, self.i) 220 221 def num(self): 222 m = re.compile(r'\d+').match(self.s, self.i) 223 if not m: 224 raise Bad('number at %d' % self.i) 225 self.i = m.end() 226 return int(m.group()) 227 228 229 def parse_rust(text): 230 m = re.match(r'^pub fn calc\(([^)]*)\) -> u64 \{ (.*) \}\n$', text, re.S) 231 if not m: 232 raise Bad('rust frame') 233 p = P(m.group(2)) 234 235 def primary(): 236 if p.peek('i'): 237 p.eat('i') 238 return {'t': 'in', 's': p.num()} 239 v = p.num() 240 p.eat('u64') 241 return {'t': 'k', 'v': v} 242 243 def expr(): 244 x = primary() 245 while p.peek('.wrapping_'): 246 p.eat('.wrapping_') 247 op = next(o for o, w in RUST_M.items() if p.peek(w)) 248 p.eat(RUST_M[op] + '(') 249 y = expr() 250 p.eat(')') 251 x = {'t': 'op', 'op': op, 'l': x, 'r': y, 'mask': PY_MASK, 'plain': False} 252 return x 253 254 t = expr() 255 if p.i != len(p.s): 256 raise Bad('rust trailing text') 257 return t 258 259 260 def parse_python(text): 261 m = re.match(r'^def calc\(([^)]*)\):\n return (.*)\n$', text, re.S) 262 if not m: 263 raise Bad('python frame') 264 p = P(m.group(2)) 265 266 def operand(): 267 if p.peek('i'): 268 p.eat('i') 269 return {'t': 'in', 's': p.num()} 270 if p.peek('('): 271 p.eat('(') 272 x = masked() 273 p.eat(')') 274 return x 275 return {'t': 'k', 'v': p.num()} 276 277 def masked(): 278 p.eat('(') 279 a = operand() 280 p.eat(' ') 281 op = p.s[p.i] 282 p.eat(op + ' ') 283 b = operand() 284 p.eat(') & ' + PY_MASK) 285 return {'t': 'op', 'op': op, 'l': a, 'r': b, 'mask': PY_MASK, 'plain': False} 286 287 t = masked() if p.peek('(') else operand() 288 if p.i != len(p.s): 289 raise Bad('python trailing text') 290 return t 291 292 293 def clone(t): 294 return json.loads(json.dumps(t)) 295 296 297 def preorder(t): 298 out = [t] 299 if t['t'] == 'op': 300 out += preorder(t['l']) + preorder(t['r']) 301 return out 302 303 304 def mut_op_swap(t): 305 x = next((y for y in preorder(t) if y['t'] == 'op'), None) 306 if x: 307 x['op'] = {'+': '-', '-': '+', '*': '+'}[x['op']] 308 return t 309 310 311 def mut_operand_swap(t): 312 x = next((y for y in preorder(t) if y['t'] == 'op' and y['l'] != y['r']), None) 313 if x: 314 x['l'], x['r'] = x['r'], x['l'] 315 return t 316 317 318 def mut_const(t): 319 x = next((y for y in preorder(t) if y['t'] == 'k'), None) 320 if x: 321 x['v'] = (x['v'] + 1) & MASK 322 return t 323 324 325 def mut_slot_swap(t): 326 hit = False 327 for y in preorder(t): 328 if y['t'] == 'in' and y['s'] in (0, 1): 329 y['s'] = 1 - y['s'] 330 hit = True 331 return t if hit else None 332 333 334 def mut_plus0_dup(t): 335 return {'t': 'op', 'op': '+', 'l': t, 'r': {'t': 'k', 'v': 0}, 'mask': PY_MASK, 'plain': False} 336 337 338 def mut_plus0_strip(t): 339 if t['t'] == 'op' and t['op'] == '+' and t['r'] == {'t': 'k', 'v': 0}: 340 return t['l'] 341 342 343 def mut_plain(t): 344 x = next((y for y in preorder(t) if y['t'] == 'op'), None) 345 if x: 346 x['plain'] = True 347 return t 348 349 350 def mut_mask_drop(t): 351 x = next((y for y in preorder(t) if y['t'] == 'op'), None) 352 if x: 353 x['mask'] = None 354 return t 355 356 357 def mut_mask_wrong(t): 358 x = next((y for y in preorder(t) if y['t'] == 'op'), None) 359 if x: 360 x['mask'] = '0xFFFFFFFFFFFFFFFE' 361 return t 362 363 364 COMMON = [('op-swap', mut_op_swap), ('operand-swap', mut_operand_swap), ('const-off-by-one', mut_const), 365 ('slot-swap', mut_slot_swap), ('plus0-dup', mut_plus0_dup), ('plus0-strip', mut_plus0_strip)] 366 TREE_MUTANTS = {'rust': COMMON + [('plain-operator', mut_plain)], 367 'python': COMMON + [('mask-drop', mut_mask_drop), ('mask-wrong', mut_mask_wrong)]} 368 369 370 def tree_text(lang, t, n): 371 if lang == 'rust': 372 return 'pub fn calc(%s) -> u64 { %s }\n' % (', '.join('i%d: u64' % s for s in range(n)), rust_expr(t)) 373 return 'def calc(%s):\n return %s\n' % (', '.join('i%d' % s for s in range(n)), py_expr(t, True)) 374 375 376 # ---------------------------------------------------------------- oracles 377 378 RUST_DRIVER = ''' 379 #[allow(unused_variables)] 380 fn main() { 381 use std::io::{Read, Write}; 382 let mut b = Vec::new(); 383 std::io::stdin().read_to_end(&mut b).unwrap(); 384 let rd = |o: usize| u64::from_le_bytes(b[o..o + 8].try_into().unwrap()); 385 let n = rd(0) as usize; 386 let mut out = String::new(); 387 for j in 0..n { 388 let base = 8 + 8 * %(k)d * j; 389 out.push_str(&format!("0 {}\\n", %(name)s(%(args)s))); 390 } 391 std::io::stdout().write_all(out.as_bytes()).unwrap(); 392 } 393 ''' 394 PY_DRIVER = '''import struct, sys 395 path, name, k = sys.argv[1], sys.argv[2], int(sys.argv[3]) 396 ns = {} 397 exec(compile(open(path, 'rb').read(), path, 'exec'), ns) 398 f = ns[name] 399 b = sys.stdin.buffer.read() 400 n = struct.unpack_from(' pinned omc -> pinned bridge -> omega_calc.""" 459 k = ('native', sha(csem), key) 460 if k in self.cache: 461 return self.cache[k] 462 rc, L, err = self.tool('lower', G.envelope(csem)) 463 if rc != 0: 464 res = (None, 'lower exit %s: %s' % (rc, err.decode(errors='replace')[:200]), None) 465 else: 466 _, ops = decode_family(csem) 467 form = L.decode(errors='replace') == G.render_om(ops, 'calc', G.identity(csem)) 468 r = self.ctx.native(self.ctx.tmp('native-%s' % key), L.decode(errors='replace'), n, vs) 469 res = (r[0], r[1] if form else 'lower output differs from translation-v1 section 5 form', r[2]) 470 if not form: 471 res = (None, res[1], None) 472 self.cache[k] = res 473 return res 474 475 def imp(self, lang, src): 476 k = ('import', lang, sha(src)) 477 if k not in self.cache: 478 self.cache[k] = self.tool(TOOLS[lang][0], src) 479 return self.cache[k] 480 481 482 # ---------------------------------------------------------------- fixtures 483 484 def load_fixtures(): 485 """(lang, id, base id for vectors, source bytes, function name, inputs); NOT_IN_PROFILE records.""" 486 out, nip, info = [], {}, {} 487 f1 = json.loads((ROOT / 'tests/universal/translation/fixtures-f1.json').read_text()) 488 f1ids = {p['id']: p['sha256'] for p in f1['positives']} 489 for p in f1['positives']: 490 b = p['source'].encode() 491 if sha(b) != p['sha256']: 492 raise Bad('F1 %s sha256' % p['id']) 493 out.append(('c', p['id'], p['id'], b, p['name'], p['inputs'])) 494 for cid, src in G.controls(): 495 out.append(('c', cid, cid, src, 'calc', 2)) 496 for lang in ('rust', 'python'): 497 path = ROOT / ('tests/universal/translation/fixtures-f2-%s.json' % lang) 498 if not path.is_file(): 499 info[lang] = {'fixtures': 'absent'} 500 continue 501 d = json.loads(path.read_text()) 502 info[lang] = {'path': path.relative_to(ROOT).as_posix(), 'sha256': sha(path.read_bytes()), 503 'positives': len(d['positives']), 'controls': len(d.get('controls', [])), 504 'refusals': len(d.get('refusals', []))} 505 for p in d['positives']: 506 b = p['source'].encode() 507 f1id = p.get('f1_id') or p.get('f1') 508 if sha(b) != p['sha256'] or f1ids.get(f1id) != p['f1_sha256'] or p['id'] != 'F2-%s-%s' % (lang, f1id): 509 raise Bad('%s fixture %s: sha256 or F1 link' % (lang, p['id'])) 510 out.append((lang, p['id'], f1id, b, p['name'], p['inputs'])) 511 for c in d.get('controls', []): 512 b = c['source'].encode() 513 if sha(b) != c['sha256']: 514 raise Bad('%s control %s sha256' % (lang, c['id'])) 515 out.append((lang, c['id'], 'C-' + c['control'], b, c['name'], c['inputs'])) 516 nip[lang] = d.get('not_in_profile', []) 517 return out, nip, info 518 519 520 def lane_refusals(lang): 521 path = ROOT / ('tests/universal/translation/fixtures-f2-%s.json' % lang) 522 if not path.is_file(): 523 return [] 524 rows = [] 525 for r in json.loads(path.read_text()).get('refusals', []): 526 b = bytes.fromhex(r['source_hex']) if 'source_hex' in r else r['source'].encode() 527 rows.append((r['id'], b, r['status'], sha(b) == r['sha256'])) 528 return rows 529 530 531 # ---------------------------------------------------------------- one composition 532 533 def compose(run, ev, fx, B, U_A): 534 lang, fid, base, src, name, n = fx 535 env, sem, ops, vs, ref = U_A['env'], U_A['sem'], U_A['ops'], U_A['vs'], U_A['ref'] 536 rec = {'fixture': fid, 'A': lang, 'B': B, 'checks': {}, 'failures': []} 537 538 def fail(c, detail): 539 rec['checks'][c] = 'FAIL' 540 rec['failures'].append({'check': c, 'detail': detail}) 541 542 def ok(c): 543 rec['checks'].setdefault(c, 'PASS') 544 545 exp = TOOLS[B][1] 546 sem_only = G.envelope(sem) 547 rc, E, err = run.tool(exp, env) 548 mode = 'direct' 549 if B == 'c' and lang != 'c' and rc == 68: 550 # G1 c-export (translation-v1 section 6) accepts the C member only; the validator applies its own R. 551 mode = 'validator-R(U_A, C)' 552 env, sem_only = G.envelope(N(sem)), G.envelope(N(sem)) 553 rc, E, err = run.tool(exp, env) 554 rec['export_input'] = mode 555 t = root_tree(ops) 556 bd = bounds(B, t, n) 557 if bd['over']: 558 rec['expect'] = 'LIMIT' 559 if rc == 67 and E == b'': 560 ok('export-limit-67') 561 rec['result'] = 'PASS_LIMIT' 562 else: 563 fail('export-limit-67', {'status': rc, 'bounds': bd}) 564 rec['result'] = 'FAIL' 565 return rec, None 566 if rc != 0 or not E: 567 fail('export', {'status': rc, 'stderr': err.decode(errors='replace')[:200], 'bounds': bd}) 568 rec['result'] = 'FAIL' 569 return rec, None 570 text = E.decode(errors='replace') 571 rec['src_B_sha256'] = sha(E) 572 # 4.3 generated, not replayed 573 rc2, E2, _ = run.tool(exp, env) 574 if (rc2, E2) == (rc, E): 575 ok('export-deterministic') 576 else: 577 fail('export-deterministic', 'two runs differ') 578 rc3, E3, _ = run.tool(exp, sem_only) 579 if (rc3, E3) == (0, E): 580 ok('4.3-semantic-only-identical') 581 else: 582 fail('4.3-semantic-only-identical', {'status': rc3}) 583 if mode == 'direct': 584 for M in LANGS: 585 rcm, Em, _ = run.tool(exp, G.envelope(R(sem, M))) 586 if (rcm, Em) == (0, E): 587 ok('4.3-R-%s-identical' % M) 588 elif B == 'c' and M != 'c' and rcm == 68: 589 # the G1 C exporter (translation-v1 section 6) accepts the C member only; NOT_RUN until the 590 # #622 family extension lands (then validate_g1 requires acceptance) 591 rec['checks']['4.3-R-%s-identical' % M] = 'NOT_RUN' 592 else: 593 fail('4.3-R-%s-identical' % M, {'status': rcm}) 594 else: 595 rec['checks']['4.3-R-members-identical'] = 'NOT_RUN' 596 if text == render(B, t, n): 597 ok('export-form') 598 else: 599 fail('export-form', {'expected': render(B, t, n), 'got': text}) 600 # recorded only: a generated text may coincide with a source written in the exporter's own form 601 # (F1-P30 `return 7ULL;`); section 4.3 is decided by the semantic-only and retargeted exports above 602 rec['src_B_equals_source_bytes'] = E == src 603 # import_B 604 rc, envB, err = run.imp(B, E) 605 if rc != 0: 606 fail('import_B', {'status': rc, 'stderr': err.decode(errors='replace')[:200]}) 607 else: 608 try: 609 semB, sideB = G.decode_envelope(envB) 610 mB, opsB = decode_family(semB) 611 G.decode_sidecar(sideB, semB, len(opsB), E) 612 if mB != B: 613 raise Bad('importer %s emitted member %s' % (B, mB)) 614 if G.normalized_root(opsB) is None and DECLARES_PAIR[B]: 615 raise Bad('import_B is not NORMALIZED although the importer declares a pair') 616 if N(strip(semB, opsB, B)) == N(strip(sem, ops, lang)): 617 ok('4.1-identity') 618 else: 619 fail('4.1-identity', {'N_strip_U_A': G.identity(N(strip(sem, ops, lang))), 620 'N_strip_U_B': G.identity(N(strip(semB, opsB, B)))}) 621 if B == lang: 622 rec['same_language_semantic_bytes_equal'] = semB == sem 623 m = next(({'vector': [str(x) for x in v], 'reference': str(w), 'got': str(G.evaluate(opsB, v))} 624 for v, w in zip(vs, ref) if G.evaluate(opsB, v) != w), None) 625 (fail('U_B-vs-reference', m) if m else ok('U_B-vs-reference')) 626 except Bad as e: 627 fail('import_B-decode', str(e)) 628 # 4.2 DIFFERENTIAL legs 629 legs = {} 630 for leg, res in (('oracle_A', U_A['oracle']), ('oracle_B', run.oracle(B, E, 'calc', n, vs, base)), 631 ('native', U_A['native'][:2])): 632 if res[0] is None: 633 legs[leg] = 'FAIL' 634 fail('4.2-' + leg, res[1]) 635 else: 636 m = G.compare(ref, res[0], vs) 637 legs[leg] = 'FAIL' if m else 'PASS' 638 if m: 639 fail('4.2-' + leg, m) 640 else: 641 ok('4.2-' + leg) 642 legs['reference'] = 'PASS' 643 rec['legs'] = legs 644 ev['leg_comparisons'] += len(vs) * 4 645 rec['result'] = 'FAIL' if rec['failures'] else 'PASS' 646 return rec, (E, t) 647 648 649 # ---------------------------------------------------------------- mutants of exporter outputs 650 651 def mutants(run, ev, outputs): 652 """outputs: {(B, text): (ops, n, vs, ref, base)}. Every mutant of an exporter output goes through the 653 checks the real output passed; it is killed when at least one detects it.""" 654 rows = [] 655 for (B, text), (ops, n, vs, ref, base) in outputs.items(): 656 if B == 'c': 657 muts = [(nm, fn(text)) for nm, fn in G.MUT.C_OPERATORS] 658 else: 659 try: 660 t = parse_rust(text) if B == 'rust' else parse_python(text) 661 except Bad as e: 662 rows.append({'B': B, 'operator': 'parse', 'killed': False, 'error': str(e)}) 663 continue 664 if tree_text(B, t, n) != text: 665 rows.append({'B': B, 'operator': 'parse', 'killed': False, 'error': 'parse/render not exact'}) 666 continue 667 muts = [] 668 for nm, fn in TREE_MUTANTS[B]: 669 m = fn(clone(t)) 670 muts.append((nm, tree_text(B, m, n) if m is not None else None)) 671 sem0 = N(strip(G.build_sem(ops), ops, 'c')) 672 for nm, mt in muts: 673 if mt is None or mt == text: 674 continue 675 det = [] 676 if mt != render(B, root_tree(ops), n): 677 det.append('export-form') 678 res = run.oracle(B, mt.encode(), 'calc', n, vs, base + '-mut') 679 if res[0] is None: 680 det.append('oracle_B-failed') 681 elif G.compare(ref, res[0], vs): 682 det.append('oracle_B-vs-reference') 683 rc, envB, _ = run.imp(B, mt.encode()) 684 if rc != 0: 685 det.append('import_B-refused-%s' % rc) 686 else: 687 try: 688 semB, _ = G.decode_envelope(envB) 689 mB, opsB = decode_family(semB) 690 if N(strip(semB, opsB, mB)) != sem0: 691 det.append('4.1-identity') 692 if any(G.evaluate(opsB, v) != w for v, w in zip(vs, ref)): 693 det.append('U_B-vs-reference') 694 except Bad: 695 det.append('import_B-decode') 696 rows.append({'B': B, 'operator': nm if B == 'c' else '%s-%s' % (B, nm), 'mutant_sha256': sha(mt.encode()), 'detected_by': det, 697 'killed': bool(det), 'killed_beyond_form': bool([x for x in det if x != 'export-form'])}) 698 by = {} 699 for r in rows: 700 b = by.setdefault(r['operator'], {'total': 0, 'killed': 0, 'killed_beyond_form': 0, 'form_only': 0}) 701 b['total'] += 1 702 b['killed'] += r['killed'] 703 b['killed_beyond_form'] += r.get('killed_beyond_form', False) 704 b['form_only'] += r['killed'] and not r.get('killed_beyond_form', False) 705 ev['mutants'] = {'total': len(rows), 'killed': sum(r['killed'] for r in rows), 706 'killed_beyond_form': sum(r.get('killed_beyond_form', False) for r in rows), 707 'by_operator': by, 'rows': rows} 708 709 710 # ---------------------------------------------------------------- refusals 711 712 def outside_family(base_ops): 713 """Valid source-aware v1 units outside the S1 family (compose section 1): every exporter refuses 68.""" 714 u64 = lambda obl: (lambda op: {9: (1, 0, 0, 0, 1), 1: (1, 1, 0, 0, 0)}.get(op, (1, 1, 0, 0, obl))) 715 big = lambda op: {9: (2, 0, 0, 0, 1), 1: (2, 2, 0, 0, 0)}.get(op, (2, 2, 20, 255, 8)) 716 div = [(9, U, U, 0), (9, U, U, 1), (5, 0, 1, 0), (1, U, U, 0), (2, 2, 3, 0)] 717 divf = lambda arith: (lambda op: {9: (1, 0, 0, 0, 1), 1: (1, 1, 0, 0, 0), 5: (1, 1, 0, 0, arith | 2)}.get(op, (1, 1, 0, 0, arith))) 718 return [('cpython-bigint-profile-3', G.build_sem(base_ops, lang=3, prof=3, runtime=1, abi=1, fields=big)), 719 ('osc-profile-5', G.build_sem(base_ops, lang=4, prof=5, fields=u64(1))), 720 ('python-dynamic-profile-6', G.build_sem(base_ops, lang=3, prof=6, runtime=1, abi=2, fields=u64(5))), 721 ('c-member-division', G.build_sem(div, lang=1, prof=1, fields=divf(1))), 722 ('rust-member-division', G.build_sem(div, lang=2, prof=2, fields=divf(1))), 723 ('python-member-division', G.build_sem(div, lang=3, prof=4, fields=divf(5)))] 724 725 726 def refusals(run, ev, base_env, base_ops): 727 rows = [] 728 729 def expect(tool, label, data, args, want): 730 rc, out, err = run.tool(tool, data, *args) 731 rows.append({'tool': tool, 'case': label, 'want': want, 'status': rc, 'stdout_bytes': len(out), 732 'stderr': err.decode(errors='replace')[:100], 733 'result': 'NOT_RUN' if rc == 'absent' else 'PASS' if rc == want and out == b'' else 'FAIL'}) 734 735 for label, sem in outside_family(base_ops): 736 e = G.envelope(sem) 737 rc, out, _ = G.run([run.a.sa], b'\x02' + e) 738 if rc != 0 or out != e: 739 rows.append({'tool': 'sa', 'case': label, 'status': rc, 'result': 'FAIL', 740 'detail': 'probe is not a valid source-aware v1 unit, so it cannot test 68'}) 741 continue 742 for tool in ('c-export', 'rust-export', 'python-export', 'lower'): 743 expect(tool, 'outside-family ' + label, e, [], 68) 744 for label, bad in G.malformed_envelopes(base_env): 745 for tool in ('rust-export', 'python-export'): 746 expect(tool, 'malformed ' + label, bad, [], 65) 747 expect('rust-export', 'any argument', base_env, ['calc'], 64) 748 for nm in ['9x', 'Calc', 'def', 'a-b', 'x' * 33]: 749 expect('python-export', 'bad name %r' % nm[:12], base_env, [nm], 64) 750 for lang in ('rust', 'python'): 751 for rid, src, want, sha_ok in lane_refusals(lang): 752 if not sha_ok: 753 rows.append({'tool': TOOLS[lang][0], 'case': rid, 'result': 'FAIL', 'detail': 'fixture sha256'}) 754 continue 755 expect(TOOLS[lang][0], rid, src, [], want) 756 ev['refusals'] = {'total': len(rows), 'pass': sum(r['result'] == 'PASS' for r in rows), 757 'fail': sum(r['result'] == 'FAIL' for r in rows), 758 'not_run': sum(r['result'] == 'NOT_RUN' for r in rows), 'rows': rows} 759 760 761 # ---------------------------------------------------------------- main 762 763 def main(): 764 ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) 765 ap.add_argument('--repo', default=str(ROOT), help='checkout holding tools/adapters/* and their builds') 766 ap.add_argument('--omc', required=True) 767 ap.add_argument('--bridge-native', required=True) 768 ap.add_argument('--bridge-repo', default=os.environ.get('OMEGA_BRIDGE_REPO'), 769 help='omega-bridge clone (default $OMEGA_BRIDGE_REPO; no host default)') 770 ap.add_argument('--sa', required=True, help='#621 native sa binary (confirms refusal probes are valid v1)') 771 ap.add_argument('--cc', default=os.environ.get('CC', 'cc')) 772 ap.add_argument('--rustc', default='rustc') 773 ap.add_argument('--python', default=sys.executable) 774 ap.add_argument('--no-mutants', action='store_true') 775 ap.add_argument('--out', required=True) 776 a = ap.parse_args() 777 out = Path(a.out).resolve() 778 out.mkdir(parents=True, exist_ok=False) 779 (out / 'work').mkdir() 780 repo = Path(a.repo).resolve() 781 ev = {'schema': 'omega.universal.translation.validate.compose.v1', 782 'contract': {'path': COMPOSE[0], 'sha256': COMPOSE[1]}, 783 'validator_sha256': sha(Path(__file__).read_bytes()), 'validate_g1_sha256': sha((HERE / 'validate_g1.py').read_bytes()), 784 'evidence_class': 'REFERENCE + DIFFERENTIAL, NATIVE (host AArch64); no PROOF', 'leg_comparisons': 0} 785 786 def not_run(why): 787 ev['result'] = 'NOT_RUN' 788 ev['reason'] = why 789 (out / 'evidence.json').write_text(json.dumps(ev, indent=1) + '\n') 790 print('NOT_RUN', why) 791 return 3 792 793 pins = {} 794 for rel, want in [COMPOSE, G.CONTRACT] + list(G.FROZEN.items()): 795 p = ROOT / rel 796 got = sha(p.read_bytes()) if p.is_file() else None 797 if got != want: 798 return not_run('%s sha256 %s, pinned %s' % (rel, got, want)) 799 pins[rel] = got 800 for lang, rel in LANE_SPECS.items(): 801 p = ROOT / rel 802 pins[rel] = sha(p.read_bytes()) if p.is_file() else None 803 ev['pins'] = pins 804 if not a.bridge_repo: 805 return not_run('no omega-bridge clone: pass --bridge-repo or set OMEGA_BRIDGE_REPO') 806 for exe in (a.omc, a.bridge_native, a.sa): 807 if not Path(exe).is_file(): 808 return not_run('absent: %s' % exe) 809 if sha(Path(a.omc).read_bytes()) != G.OMC_SHA: 810 return not_run('omc is not the translation-v1 section 1 pin %s' % G.OMC_SHA) 811 rc, nsrc, _ = G.run(['git', '-C', a.bridge_repo, 'show', G.BRIDGE_COMMIT + ':src/native.om']) 812 if rc != 0 or G.run([a.omc], nsrc, timeout=120)[1] != Path(a.bridge_native).read_bytes(): 813 return not_run('bridge generator is not omc(native.om @ %s)' % G.BRIDGE_COMMIT) 814 tools, tinfo = {}, {} 815 for name in ['lower'] + [t for p in TOOLS.values() for t in p]: 816 p = repo / 'tools/adapters' / name 817 if p.is_file() and os.access(p, os.X_OK): 818 tools[name] = str(p) 819 tinfo[name] = {'path': str(p), 'sha256': sha(p.read_bytes())} 820 for bj in sorted(repo.glob('build/**/build.json')): 821 if (bj.parent / name).is_file(): 822 tinfo[name].update({'build': bj.parent.relative_to(repo).as_posix(), 'build_json_sha256': sha(bj.read_bytes()), 823 'binary_sha256': sha((bj.parent / name).read_bytes())}) 824 else: 825 tinfo[name] = 'ABSENT' 826 head = G.run(['git', '-C', repo, 'rev-parse', 'HEAD']) 827 ev['repo'] = {'path': str(repo), 'head': head[1].decode().strip() if head[0] == 0 else None} 828 ev['tools'] = tinfo 829 ev['toolchains'] = {k: G.run(v)[1].decode().split('\n')[0] for k, v in 830 {'cc': [a.cc, '--version'], 'rustc': [a.rustc, '--version'], 'python': [a.python, '--version']}.items()} 831 if 'lower' not in tools: 832 return not_run('tools/adapters/lower absent: no native realization') 833 try: 834 fixtures, nip, finfo = load_fixtures() 835 except Bad as e: 836 return not_run('fixtures: %s' % e) 837 ev['fixtures'] = finfo 838 ev['not_in_profile'] = nip 839 args = SimpleNamespace(omc=a.omc, bridge_native=a.bridge_native, cc=a.cc, rustc=a.rustc, python=a.python, 840 sa=a.sa, tools=tools) 841 run = Run(args, out) 842 843 # U_A per fixture, with the A oracle, reference and native legs (shared by every composition from it) 844 units, frows = [], [] 845 for fx in fixtures: 846 lang, fid, base, src, name, n = fx 847 imp, exp = TOOLS[lang] 848 row = {'fixture': fid, 'A': lang} 849 if imp not in tools: 850 row['result'] = 'NOT_RUN' 851 frows.append(row) 852 units.append((fx, None)) 853 continue 854 rc, env, err = run.imp(lang, src) 855 try: 856 if rc != 0: 857 raise Bad('import_%s exit %s %s' % (lang, rc, err.decode(errors='replace')[:120])) 858 sem, side = G.decode_envelope(env) 859 m, ops = decode_family(sem) 860 G.decode_sidecar(side, sem, len(ops), src) 861 if m != lang: 862 raise Bad('importer %s emitted member %s' % (lang, m)) 863 if DECLARES_PAIR[lang] and G.normalized_root(ops) is None: 864 raise Bad('import is not NORMALIZED although the importer declares a pair') 865 if G.arity(ops) != n: 866 raise Bad('arity %d != fixture %d' % (G.arity(ops), n)) 867 except Bad as e: 868 row.update({'result': 'FAIL', 'failure': str(e)}) 869 frows.append(row) 870 units.append((fx, None)) 871 continue 872 vs = G.vectors(n, base) 873 ref = [G.evaluate(ops, v) for v in vs] 874 U_A = {'env': env, 'sem': sem, 'ops': ops, 'vs': vs, 'ref': ref, 875 'oracle': run.oracle(lang, src, name, n, vs, base), 'native': run.native(N(sem), n, vs, base)} 876 if lang != 'c': 877 rc, _, _ = run.tool('lower', env) 878 row['lower_direct_status'] = rc # translation-v1 section 5 / coordinator ruling: lower is C-only (68) 879 if rc != 68: 880 row.setdefault('failures', []).append('lower accepted or mis-refused a non-C member: %s' % rc) 881 row.update({'semantic_identity': G.identity(sem), 'N_identity': G.identity(N(strip(sem, ops, lang))), 882 'vectors': len(vs), 'result': 'FAIL' if row.get('failures') else 'PASS'}) 883 frows.append(row) 884 units.append((fx, U_A)) 885 # F2 fidelity: every F2 rewrite evaluates like its F1 source (compose section 5); N equality recorded 886 byid = {fx[1]: u for fx, u in units} 887 fid_rows = [] 888 for fx, u in units: 889 if fx[0] == 'c' or u is None or not fx[1].startswith('F2-'): 890 continue 891 c = byid.get(fx[2]) 892 if c is None: 893 continue 894 same = all(G.evaluate(u['ops'], v) == G.evaluate(c['ops'], v) for v in u['vs']) 895 fid_rows.append({'fixture': fx[1], 'f1': fx[2], 'values_equal': same, 896 'N_strip_equal_to_C_import': N(strip(u['sem'], u['ops'], fx[0])) == N(strip(c['sem'], c['ops'], 'c')), 897 'result': 'PASS' if same else 'FAIL'}) 898 ev['f2_fidelity'] = {'total': len(fid_rows), 'pass': sum(r['result'] == 'PASS' for r in fid_rows), 899 'N_equal': sum(r['N_strip_equal_to_C_import'] for r in fid_rows), 'rows': fid_rows} 900 ev['fixture_imports'] = frows 901 902 comps, outputs = [], {} 903 for fx, U_A in units: 904 for B in LANGS: 905 key = '%s->%s' % (fx[0], B) 906 if U_A is None or TOOLS[B][1] not in tools or TOOLS[B][0] not in tools: 907 # an A import that failed is already a FAIL of that fixture; a missing tool is NOT_RUN 908 imported_failed = any(r['fixture'] == fx[1] and r.get('result') == 'FAIL' for r in frows) 909 comps.append({'fixture': fx[1], 'A': fx[0], 'B': B, 'composition': key, 910 'result': 'FAIL' if imported_failed else 'NOT_RUN'}) 911 continue 912 rec, art = compose(run, ev, fx, B, U_A) 913 rec['composition'] = key 914 comps.append(rec) 915 if art: 916 outputs.setdefault((B, art[0].decode(errors='replace')), (U_A['ops'], fx[5], U_A['vs'], U_A['ref'], fx[2])) 917 print(fx[1], ' '.join('%s:%s' % (c['B'], c['result']) for c in comps[-3:]), flush=True) 918 summary = {} 919 for c in comps: 920 s = summary.setdefault(c['composition'], {'PASS': 0, 'PASS_LIMIT': 0, 'FAIL': 0, 'NOT_RUN': 0, 921 'export_input': set()}) 922 s[c['result']] += 1 923 if 'export_input' in c: 924 s['export_input'].add(c['export_input']) 925 for s in summary.values(): 926 s['export_input'] = sorted(s['export_input']) 927 ev['compositions'] = {k: v for k, v in summary.items() if k.split('->')[0] != k.split('->')[1]} 928 ev['same_language_round_trips'] = {k: v for k, v in summary.items() if k.split('->')[0] == k.split('->')[1]} 929 legs = {} 930 for c in comps: 931 for leg, r in c.get('legs', {}).items(): 932 legs.setdefault(c['composition'], {}).setdefault(leg, {'PASS': 0, 'FAIL': 0})[r] += 1 933 for chk, r in c.get('checks', {}).items(): 934 legs.setdefault(c['composition'], {}).setdefault(chk, {'PASS': 0, 'FAIL': 0, 'NOT_RUN': 0}) 935 legs[c['composition']][chk][r] = legs[c['composition']][chk].get(r, 0) + 1 936 ev['per_check'] = legs 937 base = next((u for fx, u in units if fx[1] == 'F1-P05'), None) 938 if base: 939 refusals(run, ev, base['env'], base['ops']) 940 if not a.no_mutants: 941 mutants(run, ev, outputs) 942 ev['cases'] = comps 943 failed = ['%s %s' % (c['composition'], c['fixture']) for c in comps if c['result'] == 'FAIL'] 944 failed += ['import %s' % r['fixture'] for r in frows if r['result'] == 'FAIL'] 945 failed += ['f2-fidelity %s' % r['fixture'] for r in fid_rows if r['result'] != 'PASS'] 946 failed += ['refusal %s %s' % (r['tool'], r['case']) for r in ev.get('refusals', {}).get('rows', []) if r['result'] == 'FAIL'] 947 if 'mutants' in ev and ev['mutants']['killed'] != ev['mutants']['total']: 948 failed.append('mutants survived: %d' % (ev['mutants']['total'] - ev['mutants']['killed'])) 949 if not base: 950 failed.append('F1-P05 did not import: refusal probes not run') 951 notrun = [c for c in comps if c['result'] == 'NOT_RUN'] + [r for r in ev.get('refusals', {}).get('rows', []) if r['result'] == 'NOT_RUN'] 952 # a check that could not run (G1 C exporter refusing family members; validator-applied R) keeps the 953 # composition result but makes the whole run incomplete: never a plain PASS 954 notrun += ['%s %s %s' % (c['composition'], c['fixture'], k) for c in comps for k, v in c.get('checks', {}).items() if v == 'NOT_RUN'] 955 ev['not_run_checks'] = len(notrun) 956 ev['failed'] = failed 957 ev['result'] = 'FAIL' if failed else 'NOT_RUN' if notrun else 'PASS' 958 (out / 'evidence.json').write_text(json.dumps(ev, indent=1) + '\n') 959 print(json.dumps({'result': ev['result'], 'compositions': ev['compositions'], 960 'same_language_round_trips': ev['same_language_round_trips'], 961 'f2_fidelity': '%d/%d (N equal %d)' % (ev['f2_fidelity']['pass'], ev['f2_fidelity']['total'], ev['f2_fidelity']['N_equal']), 962 'refusals': {k: ev['refusals'][k] for k in ('total', 'pass', 'fail', 'not_run')} if 'refusals' in ev else 'NOT_RUN', 963 'mutants': '%d/%d killed (%d beyond the form check)' % (ev['mutants']['killed'], ev['mutants']['total'], ev['mutants']['killed_beyond_form']) if 'mutants' in ev else 'NOT_RUN', 964 'failed': failed[:40]}, indent=1)) 965 return 1 if failed else 3 if notrun else 0 966 967 968 if __name__ == '__main__': 969 raise SystemExit(main())