interplane.Get Omega
Read in your language

omega-helix

This project has not described itself yet.

Brought by drakestapleton

branch main Branches Tags History

omega-helix / tests / test_omg_graph.py

886 lines · 25515 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0
3"""tests/test_omg_graph.py: Referee & A/B verification suite for native/omg.om (Pillar 8).
4
5Verifies:
6 1. Cross-target compilation of native/omg.om with native/math.om, native/data.om,
7 native/lpool.om for BOTH `target a64macos` and `gb10` (`om2` Linux AArch64 ELF).
8 2. Built-in `omg_selftest` and V=256 vs V=4096 logit/CE footprint metrics.
9 3. Alpha-equivalent & formatting-invariant De Bruijn canonicalization (`OMG` u16 stream
10 and 64-bit/256-bit `SEMANTIC_ID`), plus non-equivalent program separation.
11 4. Binary-to-binary .om -> OMG -> .om -> omc -> execute parity roundtrips across
12 arithmetic, loops, branches, local arrays, view/edit slices, floats, and calls.
13 5. 1,000 adversarial/random `omg_valid_mask` samples (0% invalid graphs, 100% omc
14 compile on decoded batch) + invalid-token mutant rejection + O(1) mask invariants.
15 6. `OMG_MACRO` registration, semantic deduplication, context-typed mask gating,
16 deterministic expansion, and semantic-ID equivalence.
17 7. `OMGC` binary corpus packing, semantic deduplication, and >=3x token compression vs
18 raw `.om` text and JSON AST.
19"""
20
21import json
22import os
23import platform
24import shutil
25import struct
26import subprocess
27import sys
28import tempfile
29import unittest
30
31HERE = os.path.dirname(os.path.abspath(__file__))
32REPO = os.path.dirname(HERE)
33
34
35def find_omc():
36 for cand in (
37 os.environ.get("OMC", ""),
38 shutil.which("omc") or "",
39 os.path.expanduser("~/.local/bin/omc"),
40 ):
41 if cand and os.path.isfile(cand) and os.access(cand, os.X_OK):
42 return cand
43 raise FileNotFoundError("seeded omc compiler not found")
44
45
46OMC = find_omc()
47
48IO_STUBS = r"""
49fn oargc to ulong
50 ret ulong argcnt
51end
52fn oargr i ulong to long
53 ret argread i oarg 0 4096
54end
55fn oflush to void
56 n = get oon 0
57 p = ulong 0
58 while lt p n bound 4097
59 w = write 1 oout p sub n p
60 if le w 0
61 exit 70
62 end
63 p = add p ulong w
64 end
65 put oon 0 0
66end
67fn owflush k ulong to void
68end
69fn owopen k ulong i ulong to void
70end
71fn owclose k ulong to void
72end
73fn oprd ai ulong pos ulong off ulong n ulong to ulong
74 ret 0
75end
76fn odread i ulong to ulong
77 ret 0
78end
79fn ooffrd ai ulong to void
80end
81fn ofsz ai ulong to ulong
82 ret 0
83end
84"""
85
86TEST_DRIVER = r"""
87fn read_stdin_src to void
88 p = ulong 0
89 while lt p 65536 bound 65536
90 r = read 0 omg_src p sub 65536 p
91 if le r 0
92 break
93 end
94 p = add p ulong r
95 end
96 put omg_nsrc 0 p
97end
98
99fn read_stdin_toks to void
100 lenb = ulong 0
101 while lt lenb 32768 bound 32768
102 r = read 0 omg_corpus lenb sub 32768 lenb
103 if le r 0
104 break
105 end
106 lenb = add lenb ulong r
107 end
108 nt = div lenb 2
109 for i ulong nt
110 lo = ulong get omg_corpus mul i 2
111 hi = ulong get omg_corpus add mul i 2 1
112 put omg_toks i ushort or shl hi 8 lo
113 end
114 put omg_ntok 0 nt
115end
116
117fn write_dec_all fd int n ulong to void
118 p = ulong 0
119 while lt p n bound 65536
120 w = write fd omg_dec p sub n p
121 if le w 0
122 break
123 end
124 p = add p ulong w
125 end
126end
127
128fn write_corp_all fd int n ulong to void
129 p = ulong 0
130 while lt p n bound 65536
131 w = write fd omg_corpus p sub n p
132 if le w 0
133 break
134 end
135 p = add p ulong w
136 end
137end
138
139fn setup_test_macros to void
140 put omg_mac_cnt 0 0
141 put omg_mac_pcur 0 0
142 note MAC_0: expr (U64) -> U64: add mul x 2 1
143 put omg_mac_tmp_in 0 OMG_TY_U64
144 put omg_mac_tmp_tok 0 ushort OMG_OP_ADD
145 put omg_mac_tmp_tok 1 ushort OMG_OP_MUL
146 put omg_mac_tmp_tok 2 ushort 256
147 put omg_mac_tmp_tok 3 ushort add OMG_LIT_BASE 2
148 put omg_mac_tmp_tok 4 ushort add OMG_LIT_BASE 1
149 put omg_mac_tmp_len 0 5
150 m0 = omg_macro_register 0 OMG_TY_U64 1
151 note MAC_1: stmt (U64, U64) -> VOID: v = add x y
152 put omg_mac_tmp_in 0 OMG_TY_U64
153 put omg_mac_tmp_in 1 OMG_TY_U64
154 put omg_mac_tmp_tok 0 ushort OMG_LET
155 put omg_mac_tmp_tok 1 ushort OMG_TY_U64
156 put omg_mac_tmp_tok 2 ushort OMG_OP_ADD
157 put omg_mac_tmp_tok 3 ushort 256
158 put omg_mac_tmp_tok 4 ushort 257
159 put omg_mac_tmp_len 0 5
160 m1 = omg_macro_register 1 OMG_TY_VOID 2
161end
162
163fn cmd_parse to int
164 read_stdin_src
165 rc = omg_parse_om
166 if ne rc 0
167 ret int rc
168 end
169 sid = omg_semantic_id
170 oputx get omg_sem_hash 0
171 oputx get omg_sem_hash 1
172 oputx get omg_sem_hash 2
173 oputx get omg_sem_hash 3
174 oputc 32
175 oputu get omg_ntok 0
176 oputc 10
177 oflush
178 nb = omg_encode_stream
179 write_corp_all 2 nb
180 ret 0
181end
182
183fn cmd_decode to int
184 read_stdin_toks
185 rc = omg_decode_om
186 if ne rc 0
187 ret 10
188 end
189 write_dec_all 1 get omg_ndec 0
190 ret 0
191end
192
193fn cmd_validate to int
194 read_stdin_toks
195 rc = omg_validate
196 if ne rc 0
197 oputl rc
198 oputc 32
199 oputu get omg_st 14
200 oputc 10
201 oflush
202 ret 1
203 end
204 ret 0
205end
206
207fn cmd_sample_n to int
208 count = oargu 2
209 budget = oargu 3
210 setup_test_macros
211 for sd ulong count
212 rc = omg_sample_masked add 5000 sd budget
213 if ne rc 0
214 oputu sd
215 oputc 32
216 oputl rc
217 oputc 10
218 oflush
219 ret 1
220 end
221 vr = omg_validate
222 if ne vr 0
223 oputu sd
224 oputc 32
225 oputl vr
226 oputc 10
227 oflush
228 ret 2
229 end
230 if lt sd 200
231 rc2 = omg_decode_om
232 if ne rc2 0
233 ret 3
234 end
235 oputc 61
236 oputc 61
237 oputc 61
238 oputu sd
239 oputc 10
240 oflush
241 write_dec_all 1 get omg_ndec 0
242 end
243 end
244 ret 0
245end
246
247fn cmd_mask_probe to int
248 setup_test_macros
249 omg_init
250 rc = omg_step OMG_BEGIN
251 rc = omg_step OMG_FN_MAIN
252 note Inside main (ret I32): check mask at EK_STMT
253 omg_valid_mask 40
254 for i ulong 256
255 oputu ulong get omg_mask i
256 end
257 oputc 10
258 note Start OMG_LET TY_U64 -> check mask at EK_EXPR(TY_U64) (MAC_0 should be allowed!)
259 rc = omg_step OMG_LET
260 rc = omg_step OMG_TY_U64
261 omg_valid_mask 40
262 for i2 ulong 256
263 oputu ulong get omg_mask i2
264 end
265 oputc 10
266 note Step OMG_MACRO -> check mask at EK_MAC_SLOT(TY_U64) (only MAC_0=224 allowed)
267 rc = omg_step OMG_MACRO
268 omg_valid_mask 40
269 for i3 ulong 256
270 oputu ulong get omg_mask i3
271 end
272 oputc 10
273 note Step MAC_0 + LIT_5, then start OMG_LET TY_F32 -> MAC_0 must NOT be allowed!
274 rc = omg_step add OMG_MAC_BASE 0
275 rc = omg_step add OMG_LIT_BASE 5
276 rc = omg_step OMG_LET
277 rc = omg_step OMG_TY_F32
278 omg_valid_mask 40
279 for i4 ulong 256
280 oputu ulong get omg_mask i4
281 end
282 oputc 10
283 oflush
284 ret 0
285end
286
287fn cmd_macro_expand to int
288 setup_test_macros
289 read_stdin_toks
290 rc = omg_validate
291 if ne rc 0
292 ret 1
293 end
294 rc2 = omg_macro_expand
295 if ne rc2 0
296 ret 2
297 end
298 sid = omg_semantic_id
299 oputx sid
300 oputc 32
301 oputu get omg_ntok 0
302 oputc 10
303 oflush
304 nb = omg_encode_stream
305 write_corp_all 2 nb
306 ret 0
307end
308
309fn cmd_corpus to int
310 omg_corp_reset
311 note Program 1 (scale vA)
312 omg_load_text omg_ex_a
313 if ne omg_parse_om 0
314 ret 1
315 end
316 r1 = omg_corpus_add
317 note Program 2 (alpha-renamed scale vB -> must dedup to 0!)
318 omg_load_text omg_ex_b
319 if ne omg_parse_om 0
320 ret 2
321 end
322 r2 = omg_corpus_add
323 note Program 3 (distinct program: simple add)
324 omg_init_parse
325 put omg_ntok 0 0
326 omg_emit OMG_BEGIN
327 omg_emit OMG_FN_MAIN
328 omg_emit OMG_RET
329 omg_emit add OMG_LIT_BASE 7
330 omg_emit OMG_END
331 omg_emit OMG_END_UNIT
332 r3 = omg_corpus_add
333 if or ne r1 1 or ne r2 0 ne r3 1
334 ret 3
335 end
336 nb = omg_pack_corpus
337 if eq nb 0
338 ret 4
339 end
340 write_corp_all 1 nb
341 ret 0
342end
343
344fn main to int
345 na = oargc
346 if lt na 2
347 ret 2
348 end
349 m = oargu 1
350 if eq m 0
351 ret int omg_selftest
352 end
353 if eq m 1
354 ret cmd_parse
355 end
356 if eq m 2
357 ret cmd_decode
358 end
359 if eq m 3
360 ret cmd_validate
361 end
362 if eq m 4
363 ret cmd_sample_n
364 end
365 if eq m 5
366 ret cmd_mask_probe
367 end
368 if eq m 6
369 ret cmd_macro_expand
370 end
371 if eq m 7
372 ret cmd_corpus
373 end
374 ret 2
375end
376"""
377
378
379def compile_om(src_text, out_path):
380 p = subprocess.run([OMC], input=src_text.encode("utf-8"), capture_output=True)
381 if p.returncode != 0:
382 raise RuntimeError(f"omc failed rc={p.returncode}: {p.stderr.decode('latin-1')}")
383 with open(out_path + ".tmp", "wb") as f:
384 f.write(p.stdout)
385 os.chmod(out_path + ".tmp", 0o755)
386 os.replace(out_path + ".tmp", out_path)
387 if platform.system() == "Darwin" and shutil.which("codesign"):
388 subprocess.run(
389 ["codesign", "-s", "-", "-f", out_path],
390 check=True,
391 stdout=subprocess.DEVNULL,
392 stderr=subprocess.DEVNULL,
393 )
394
395
396def pack_tokens(toks):
397 return struct.pack(f"<{len(toks)}H", *toks)
398
399
400def unpack_tokens(raw):
401 assert len(raw) % 2 == 0
402 return list(struct.unpack(f"<{len(raw) // 2}H", raw))
403
404
405class TestOmgGraph(unittest.TestCase):
406 @classmethod
407 def setUpClass(cls):
408 cls.tmpdir = tempfile.mkdtemp(prefix="omg_graph_test_")
409 unit_files = [
410 os.path.join(REPO, "native", "math.om"),
411 os.path.join(REPO, "native", "data.om"),
412 os.path.join(REPO, "native", "lpool.om"),
413 os.path.join(REPO, "native", "omg.om"),
414 ]
415 parts = []
416 for path in unit_files:
417 with open(path, "r", encoding="utf-8") as f:
418 parts.append(f.read())
419 cls.base_om = "\n".join(parts) + "\n" + IO_STUBS + "\n" + TEST_DRIVER + "\n"
420 cls.bin_gb10 = os.path.join(cls.tmpdir, "omg_test_gb10")
421 compile_om("om2\n" + cls.base_om, cls.bin_gb10)
422 if platform.system() == "Darwin":
423 cls.bin_host = os.path.join(cls.tmpdir, "omg_test_macos")
424 cls.host_hdr = "target a64macos\n"
425 compile_om("target a64macos\nom2\n" + cls.base_om, cls.bin_host)
426 elif platform.machine() in ("x86_64", "amd64"):
427 cls.bin_host = os.path.join(cls.tmpdir, "omg_test_x86")
428 cls.host_hdr = "target x86linux\n"
429 compile_om("target x86linux\nom2\n" + cls.base_om, cls.bin_host)
430 else:
431 cls.bin_host = cls.bin_gb10
432 cls.host_hdr = ""
433
434 @classmethod
435 def tearDownClass(cls):
436 shutil.rmtree(cls.tmpdir, ignore_errors=True)
437
438 def run_cli(self, *args, stdin_bytes=b""):
439 p = subprocess.run(
440 [self.bin_host] + [str(a) for a in args],
441 input=stdin_bytes,
442 capture_output=True,
443 timeout=60,
444 )
445 return p.returncode, p.stdout, p.stderr
446
447 def parse_om(self, src):
448 rc, out, err = self.run_cli("1", stdin_bytes=src.encode("utf-8"))
449 self.assertEqual(rc, 0, f"parse failed rc={rc} err={err}")
450 fields = out.decode("utf-8").strip().split()
451 sem_id_hex = fields[0]
452 ntok = int(fields[1])
453 toks = unpack_tokens(err)
454 self.assertEqual(len(toks), ntok)
455 for t in toks:
456 self.assertLess(t, 256)
457 return sem_id_hex, toks
458
459 def decode_omg(self, toks):
460 rc, out, err = self.run_cli("2", stdin_bytes=pack_tokens(toks))
461 self.assertEqual(rc, 0, f"decode failed rc={rc} err={err}")
462 return out.decode("utf-8")
463
464 def test_01_cross_target_gb10_elf_and_macos(self):
465 with open(self.bin_gb10, "rb") as f:
466 hdr = f.read(20)
467 self.assertEqual(hdr[:4], b"\x7fELF")
468 e_machine = struct.unpack("<H", hdr[18:20])[0]
469 self.assertEqual(e_machine, 183, "gb10 output must be AArch64 ELF (EM_AARCH64=183)")
470 if platform.system() == "Darwin":
471 with open(self.bin_host, "rb") as f:
472 mhdr = f.read(4)
473 self.assertEqual(mhdr, b"\xcf\xfa\xed\xfe", "macos output must be 64-bit Mach-O")
474
475 def test_02_builtin_selftest_and_metrics(self):
476 rc, out, err = self.run_cli("0")
477 txt = out.decode("utf-8")
478 self.assertEqual(rc, 0, f"selftest failed rc={rc}: {txt} {err}")
479 self.assertIn("OMG_METRICS V=256 V_BASE=4096 LOGIT_REDUCTION=16x", txt)
480 self.assertIn("OMG_SELFTEST PASS samples=200", txt)
481
482 def test_03_alpha_equivalence_and_semantic_id_separation(self):
483 pairs = [
484 (
485 """om2
486note Variant A: helper + loop + branches
487fn accum_step acc ulong x ulong to ulong
488 t = add mul acc 3 x
489 ret add t 1
490end
491fn main to int
492 s = ulong 1
493 for i ulong 4
494 s = accum_step s i
495 end
496 if gt s 20
497 ret int rem s 251
498 else
499 ret 0
500 end
501end
502""",
503 """om2
504note Completely different names, parens, blank lines & comments
505fn f_renamed p_state ulong p_elem ulong to ulong
506 note extra comment inside fn
507 intermediate_val = add (mul p_state 3) p_elem
508 ret (add intermediate_val 1)
509end
510
511fn main to int
512 total = ulong 1
513 for loop_idx ulong 4
514 total = f_renamed total loop_idx
515 end
516 if gt total 20
517 ret int (rem total 251)
518 else
519 ret 0
520 end
521end
522""",
523 ),
524 (
525 """om2
526fn sum_arr a view ulong * n ulong to ulong
527 acc = ulong 0
528 i = ulong 0
529 while lt i n bound 64
530 acc = add acc get a i
531 i = add i 1
532 end
533 ret acc
534end
535fn main to int
536 buf = new ulong 4 3
537 put buf 1 9
538 put buf 2 5
539 s = sum_arr view buf len buf
540 ret int s
541end
542""",
543 """om2
544fn reduce_slice vec view ulong * cnt ulong to ulong
545 res = ulong 0
546 idx = ulong 0
547 while lt idx cnt bound 64
548 res = add res (get vec idx)
549 idx = add idx 1
550 end
551 ret res
552end
553fn main to int
554 arr = new ulong 4 3
555 put arr 1 9
556 put arr 2 5
557 total = reduce_slice view arr (len arr)
558 ret int total
559end
560""",
561 ),
562 (
563 """om2
564fn fmix x ulong y f64 to ulong
565 z = rotr x 3
566 w = fma y 2.0f64 1.5f64
567 b = bitcast ulong w
568 ret xor z b
569end
570fn main to int
571 r = fmix 0xdeadbeef 1.25f64
572 ret int and r 255
573end
574""",
575 """om2
576fn hash_mix a ulong b f64 to ulong
577 r1 = rotr a 3
578 r2 = fma b 2.0f64 1.5f64
579 bits = bitcast ulong r2
580 ret xor r1 bits
581end
582fn main to int
583 out_val = hash_mix 0xdeadbeef 1.25f64
584 ret int (and out_val 255)
585end
586""",
587 ),
588 ]
589
590 seen_ids = set()
591 for idx, (src_a, src_b) in enumerate(pairs):
592 sid_a, toks_a = self.parse_om(src_a)
593 sid_b, toks_b = self.parse_om(src_b)
594 self.assertEqual(toks_a, toks_b, f"pair {idx}: OMG tokens must match under alpha-renaming")
595 self.assertEqual(sid_a, sid_b, f"pair {idx}: 256-bit SEMANTIC_ID must match")
596 self.assertNotIn(sid_a, seen_ids)
597 seen_ids.add(sid_a)
598
599 # Semantically distinct programs MUST produce distinct SEMANTIC_IDs
600 d1, _ = self.parse_om("om2\nfn main to int\n a = int 10\n b = int 3\n ret sub a b\nend\n")
601 d2, _ = self.parse_om("om2\nfn main to int\n a = int 10\n b = int 3\n ret sub b a\nend\n")
602 d3, _ = self.parse_om("om2\nfn main to int\n a = int 10\n b = int 3\n ret add a b\nend\n")
603 self.assertEqual(len({d1, d2, d3}), 3)
604
605 def test_04_roundtrip_om_omg_om_compile_and_execute_parity(self):
606 programs = [
607 (
608 "arith_loop_branch",
609 """om2
610fn step a ulong b ulong to ulong
611 ret add mul a 2 xor b 5
612end
613fn main to int
614 x = ulong 3
615 for i ulong 5
616 x = step x i
617 end
618 if gt x 50
619 ret int rem x 127
620 end
621 ret 1
622end
623""",
624 ),
625 (
626 "local_array_edit_view",
627 """om2
628fn bump a edit ulong * i ulong d ulong to void
629 put a i add get a i d
630end
631fn sum a view ulong * to ulong
632 s = ulong 0
633 for i ulong len a
634 s = add s get a i
635 end
636 ret s
637end
638fn main to int
639 arr = new ulong 5 2
640 bump edit arr 2 10
641 bump edit arr 4 7
642 ret int sum view arr
643end
644""",
645 ),
646 (
647 "signed_neg_float_bitcast",
648 """om2
649fn main to int
650 a = long -15
651 b = long 28
652 c = add a b
653 f = add mul 2.0f64 3.5f64 1.0f64
654 fi = long f
655 ret int add c fi
656end
657""",
658 ),
659 (
660 "while_break_continue",
661 """om2
662fn main to int
663 i = ulong 0
664 acc = ulong 0
665 while lt i 12 bound 20
666 i = add i 1
667 if eq rem i 2 0
668 continue
669 end
670 if gt acc 20
671 break
672 end
673 acc = add acc i
674 end
675 ret int acc
676end
677""",
678 ),
679 ]
680
681 for name, src in programs:
682 bin_orig = os.path.join(self.tmpdir, f"rt_{name}_orig")
683 bin_dec = os.path.join(self.tmpdir, f"rt_{name}_dec")
684 compile_om(self.host_hdr + src, bin_orig)
685 rc_orig = subprocess.run([bin_orig], capture_output=True).returncode
686
687 sid1, toks1 = self.parse_om(src)
688 dec_om = self.decode_omg(toks1)
689 compile_om(self.host_hdr + dec_om, bin_dec)
690 rc_dec = subprocess.run([bin_dec], capture_output=True).returncode
691 self.assertEqual(rc_dec, rc_orig, f"{name}: runtime exit parity mismatch")
692
693 sid2, toks2 = self.parse_om(dec_om)
694 self.assertEqual(toks1, toks2, f"{name}: OMG roundtrip idempotence failed")
695 self.assertEqual(sid1, sid2, f"{name}: SEMANTIC_ID roundtrip idempotence failed")
696
697 def test_05_1000_masked_samples_and_mutant_rejection(self):
698 # Generate & validate 1,000 random/adversarial masked streams, decode & compile first 200
699 rc, out, err = self.run_cli("4", "1000", "96")
700 self.assertEqual(rc, 0, f"1000 masked samples failed rc={rc}: {out.decode()} {err.decode()}")
701
702 progs = out.decode("utf-8").split("===")
703 self.assertEqual(len(progs) - 1, 200)
704 # x86linux omc does not support AArch64 `fma`, so compile decoded samples as AArch64 om2 on x86_64
705 sample_hdr = "" if platform.machine().lower() in ("x86_64", "amd64") else self.host_hdr
706 for chunk in progs[1:]:
707 idx, body = chunk.split("\n", 1)
708 p = subprocess.run(
709 [OMC],
710 input=(sample_hdr + body).encode("utf-8"),
711 capture_output=True,
712 )
713 self.assertEqual(
714 p.returncode,
715 0,
716 f"decoded sample {idx} failed omc: {p.stderr.decode('latin-1')}\n{body}",
717 )
718
719 # Also test tight budgets (12, 24, 48) across 100 samples each
720 for b in (12, 24, 48):
721 rc_b, out_b, err_b = self.run_cli("4", "100", str(b))
722 self.assertEqual(rc_b, 0, f"budget={b} failed: {out_b.decode()} {err_b.decode()}")
723
724 # Mutant rejection tests: every corrupted stream MUST be rejected by omg_validate
725 valid_src = "om2\nfn main to int\n x = ulong 5\n ret int add x 1\nend\n"
726 _, valid_toks = self.parse_om(valid_src)
727 rc_v, _, _ = self.run_cli("3", stdin_bytes=pack_tokens(valid_toks))
728 self.assertEqual(rc_v, 0)
729
730 mutants = [
731 # Out-of-vocab token (>= 256)
732 [valid_toks[0], 300] + valid_toks[2:],
733 # Wrong header (missing OMG_BEGIN)
734 [4] + valid_toks[1:],
735 # Type mismatch in OMG_LET: TY_BOOL with LIT_5
736 [1, 4, 8, 25, 105, 10, 100, 7, 2],
737 # Undeclared De Bruijn REF_3 when n_live == 0
738 [1, 4, 10, 163, 7, 2],
739 # Statement after OMG_RET (dead code -> omc error 17)
740 [1, 4, 10, 100, 10, 100, 7, 2],
741 # Missing OMG_RET in non-void fn main
742 [1, 4, 7, 2],
743 # Truncated stream (missing OMG_END_UNIT)
744 valid_toks[:-1],
745 # OMG_BREAK outside any loop
746 [1, 4, 15, 10, 100, 7, 2],
747 ]
748 for mi, mut in enumerate(mutants):
749 rc_m, out_m, _ = self.run_cli("3", stdin_bytes=pack_tokens(mut))
750 self.assertNotEqual(rc_m, 0, f"mutant {mi} unexpectedly accepted: {mut}")
751
752 def test_06_macro_mask_gating_and_expansion(self):
753 # Probe O(1) bitmask gating for OMG_MACRO & MAC_0
754 rc, out, _ = self.run_cli("5")
755 self.assertEqual(rc, 0)
756 masks = [ln.strip() for ln in out.decode("utf-8").splitlines()]
757 self.assertEqual(len(masks), 4)
758 m_stmt, m_u64, m_mac_slot, m_f32 = masks
759 # In EK_STMT: MAC_1 is stmt macro -> OMG_MACRO (21) allowed
760 self.assertEqual(m_stmt[21], "1")
761 # In EK_EXPR(TY_U64): MAC_0 is (U64)->U64 -> OMG_MACRO (21) allowed
762 self.assertEqual(m_u64[21], "1")
763 # In EK_MAC_SLOT(TY_U64): MAC_0 (224) allowed, MAC_1 (225, VOID) forbidden
764 self.assertEqual(m_mac_slot[224], "1")
765 self.assertEqual(m_mac_slot[225], "0")
766 # In EK_EXPR(TY_F32): no F32 macro registered -> OMG_MACRO (21) forbidden!
767 self.assertEqual(m_f32[21], "0")
768
769 # Build stream using MAC_1 (stmt: if true; v1 = add 10 20; end) and MAC_0 (expr: add mul v0 2 1) -> 61
770 # OMG_BEGIN=1, OMG_FN_MAIN=4, OMG_LET=8, TY_U64=29, LIT_30=130,
771 # OMG_MACRO=21, MAC_1=225, LIT_10=110, LIT_20=120,
772 # OMG_RET=10, OP_CAST=67, TY_U64=29, OMG_MACRO=21, MAC_0=224, REF_0=160, OMG_END=7, OMG_END_UNIT=2
773 mac_toks = [1, 4, 8, 29, 130, 21, 225, 110, 120, 10, 67, 29, 21, 224, 160, 7, 2]
774 rc_e, out_e, err_e = self.run_cli("6", stdin_bytes=pack_tokens(mac_toks))
775 self.assertEqual(rc_e, 0, f"macro expand failed rc={rc_e}")
776 sid_exp, ntok_exp = out_e.decode("utf-8").strip().split()
777 exp_toks = unpack_tokens(err_e)
778 self.assertEqual(len(exp_toks), int(ntok_exp))
779
780 # Must match hand-written un-macro'd equivalent program's SEMANTIC_ID!
781 equiv_src = """om2
782fn main to int
783 a = ulong 30
784 if true
785 x = ulong 10
786 y = ulong 20
787 v = add x y
788 end
789 ret int add mul a 2 1
790end
791"""
792 sid_eq, _ = self.parse_om(equiv_src)
793 self.assertEqual(sid_exp, sid_eq[:16], "macro-expanded SEMANTIC_ID must match canonical source")
794
795 # Decode macro stream directly (omg_decode_om auto-expands) -> compile -> run == 61!
796 dec_om = self.decode_omg(exp_toks)
797 bin_mac_prog = os.path.join(self.tmpdir, "mac_prog")
798 compile_om(self.host_hdr + dec_om, bin_mac_prog)
799 run_rc = subprocess.run([bin_mac_prog], capture_output=True).returncode
800 self.assertEqual(run_rc, 61)
801
802 def test_07_omgc_binary_corpus_and_compression_ab(self):
803 # 1. Verify OMGC packed corpus binary format & semantic deduplication
804 rc, corp_bytes, _ = self.run_cli("7")
805 self.assertEqual(rc, 0)
806 magic, ver, n_rec, total_toks = struct.unpack("<4sIII", corp_bytes[:16])
807 self.assertEqual(magic, b"OMGC")
808 self.assertEqual(ver, 1)
809 self.assertEqual(n_rec, 2, "3 programs with 1 alpha-duplicate must deduplicate to 2 records")
810 expected_len = 16 + n_rec * 16 + total_toks * 2
811 self.assertEqual(len(corp_bytes), expected_len)
812
813 dir_entries = []
814 for r in range(n_rec):
815 off = 16 + r * 16
816 sid, toff, tlen = struct.unpack("<QII", corp_bytes[off : off + 16])
817 dir_entries.append((sid, toff, tlen))
818 self.assertEqual(sum(e[2] for e in dir_entries), total_toks)
819
820 # 2. A/B Token Compression & Footprint Comparison: V=256 OMG vs raw .om & JSON AST
821 sample_om = """om2
822note Compute polynomial and checksum over loop
823fn poly_step state ulong idx ulong to ulong
824 scaled = mul state 3
825 mixed = xor scaled add idx 7
826 ret add mixed 1
827end
828fn main to int
829 acc = ulong 5
830 for k ulong 8
831 acc = poly_step acc k
832 end
833 if gt acc 100
834 ret int rem acc 199
835 else
836 ret int acc
837 end
838end
839"""
840 _, omg_toks = self.parse_om(sample_om)
841 json_ast = json.dumps(
842 {
843 "kind": "unit",
844 "fns": [
845 {
846 "name": "poly_step",
847 "params": [{"name": "state", "type": "u64"}, {"name": "idx", "type": "u64"}],
848 "ret": "u64",
849 "body": [
850 {"let": "scaled", "op": "mul", "args": [{"var": "state"}, {"lit": 3}]},
851 {"let": "mixed", "op": "xor", "args": [{"var": "scaled"}, {"op": "add", "args": [{"var": "idx"}, {"lit": 7}]}]},
852 {"ret": {"op": "add", "args": [{"var": "mixed"}, {"lit": 1}]}},
853 ],
854 },
855 {
856 "name": "main",
857 "params": [],
858 "ret": "i32",
859 "body": [
860 {"let": "acc", "type": "u64", "val": 5},
861 {"for": "k", "type": "u64", "count": 8, "body": [{"set": "acc", "call": "poly_step", "args": [{"var": "acc"}, {"var": "k"}]}]},
862 {"if": {"op": "gt", "args": [{"var": "acc"}, {"lit": 100}]}, "then": [{"ret": {"cast": "i32", "val": {"op": "rem", "args": [{"var": "acc"}, {"lit": 199}]}}}], "else": [{"ret": {"cast": "i32", "val": {"var": "acc"}}}]},
863 ],
864 },
865 ],
866 },
867 separators=(",", ":"),
868 )
869
870 raw_om_byte_tokens = len(sample_om.encode("utf-8"))
871 json_byte_tokens = len(json_ast.encode("utf-8"))
872 omg_token_count = len(omg_toks)
873
874 ratio_vs_om = raw_om_byte_tokens / omg_token_count
875 ratio_vs_json = json_byte_tokens / omg_token_count
876 self.assertGreaterEqual(ratio_vs_om, 3.0, f"expected >=3x compression vs .om text, got {ratio_vs_om:.2f}x")
877 self.assertGreaterEqual(ratio_vs_json, 10.0, f"expected >=10x compression vs JSON AST, got {ratio_vs_json:.2f}x")
878 print(
879 f"\n[OMG A/B] V=256 vs V=4096 (16x logit reduction): "
880 f"omg_toks={omg_token_count}, .om_bytes={raw_om_byte_tokens} ({ratio_vs_om:.2f}x), "
881 f"json_bytes={json_byte_tokens} ({ratio_vs_json:.2f}x)"
882 )
883
884
885if __name__ == "__main__":
886 unittest.main(verbosity=2)