interplane.Get Omega
Read in your language

omega-bridge

Omega-first language interoperability: checked conversion backends and native language bindings

Brought by drakestapleton

branch main Branches Tags History

omega-bridge / tests / seeded_views.py

334 lines · 13217 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Bit-exact seeded typed views/arrays, public float ABI and refusal/mutant controls.
3
4Pinned source semantics: omega-mv e5b32567 seed/omc/omc.om twid/tlog,
5ldop/stop, fintr; OMEGESE.md 9.3/9.4 and Float values.
6WolframLanguageEvaluator: {2^16,2^20,2^32-1} -> {65536,1048576,4294967295}.
7Expected floating results come from executing the pinned compiler, never Python FP.
8"""
9import ctypes as C
10import hashlib
11import os
12from pathlib import Path
13import random
14import re
15import subprocess
16import tempfile
17
18ROOT = Path(__file__).resolve().parents[1]
19PIN = "2c82480596bbdc50cda9626866209ef662d5834f278f839ff4ce0250c495029f"
20OMC = Path(os.environ["OMEGA_SEEDED_OMC"])
21assert hashlib.sha256(OMC.read_bytes()).hexdigest() == PIN
22
23
24def run(cmd, data=None, ok=0):
25 p = subprocess.run([str(x) for x in cmd], input=data, capture_output=True, timeout=300)
26 assert p.returncode == ok, (cmd, p.returncode, p.stderr.decode(errors="replace"))
27 return p.stdout
28
29
30def convert(src, mode="c"):
31 with tempfile.TemporaryDirectory(prefix="omega-seeded-source-") as td:
32 path = Path(td) / "unit.om"
33 path.write_text(src)
34 return run([ROOT / "tools/bridge-seeded", mode, path])
35
36
37def cc(src, out, shared=False, compiler=None):
38 p = out.with_suffix(".c")
39 p.write_bytes(src)
40 flags = ["-shared", "-fPIC", "-DOMEGA_LIBRARY"] if shared else []
41 run([compiler or os.environ.get("CC", "cc"), "-std=gnu11", "-O2", "-Wall", "-Wextra", "-Werror", *flags, p, "-o", out])
42
43
44def storage_codegen(generated, work):
45 """Use the emitted helpers, not hand-written stand-ins, for the GCC -O2 regression."""
46 compiler = os.environ.get("CC", "cc")
47 if "aarch64" not in run([compiler, "-dumpmachine"]).decode():
48 print("NOT_RUN fixed-width AArch64 codegen: CC is not an AArch64 compiler")
49 return
50
51 def violations(code, name):
52 lines = code.decode().splitlines()
53 helpers = []
54 for prefix in ("static unsigned o_width(", "static __int128 o_value(",
55 "static uint64_t o_norm(", "static uint64_t o_get(", "static void o_put("):
56 selected = [line for line in lines if line.startswith(prefix)]
57 assert len(selected) == 1, prefix
58 helpers.extend(selected)
59 probes = []
60 for typ in (3, 4, 5):
61 probes.append(f"uint64_t probe_load{typ}(const void*p,uint64_t n,uint64_t i)"
62 f"{{return o_get(p,n,i,{typ});}}")
63 probes.append(f"void probe_store{typ}(void*p,uint64_t n,uint64_t i,uint64_t v)"
64 f"{{o_put(p,n,i,v,{typ});}}")
65 source = work / (name + ".c")
66 assembly = source.with_suffix(".s")
67 source.write_text("#include <stdint.h>\n"
68 "void o_trap(int) __attribute__((noreturn));\n"
69 + "\n".join(helpers + probes) + "\n")
70 run([compiler, "-O2", "-S", source, "-o", assembly])
71 text = assembly.read_text()
72 bad = []
73 for typ, bits in ((3, 16), (4, 32), (5, 64)):
74 for operation, instruction in (("load", "ldr"), ("store", "str")):
75 symbol = f"probe_{operation}{typ}"
76 match = re.search(rf"(?ms)^{symbol}:\n(.*?)^\s*\.size\s+{symbol},", text)
77 assert match, ("missing assembly function", symbol)
78 body = match.group(1)
79 opcode = instruction + ("h" if bits == 16 else "")
80 register = "x" if bits == 64 else "w"
81 if (len(re.findall(rf"(?m)^\s*{opcode}\s+{register}\d+,", body)) != 1
82 or re.search(r"\b(?:ldrb|strb)\b", body)):
83 bad.append(symbol)
84 return bad
85
86 assert not violations(generated, "storage-codegen"), "fixed-width accesses were not scalarized"
87 # Restore the reported byte loop: the assembly contract must reject it.
88 copies = (b"if(w==8)v=b[0];else if(w==16){uint16_t x;__builtin_memcpy(&x,b,2);v=x;}"
89 b"else if(w==32){uint32_t x;__builtin_memcpy(&x,b,4);v=x;}"
90 b"else if(w==64)__builtin_memcpy(&v,b,8);")
91 assert generated.count(copies) == 1
92 loop = b"for(unsigned j=0;j<w/8;j++)v|=(uint64_t)b[j]<<(j*8);"
93 assert violations(generated.replace(copies, loop), "storage-byte-loop-mutant")
94 print("PASS fixed-width GCC -O2 loads/stores; byte-loop codegen mutant killed")
95
96
97PROGRAM = """fn inc16 a view ushort 1024 b edit ushort 1024 to void
98for i ulong 1024
99put b i add get a i 1
100end
101ret
102end
103fn inc32 a view uint 1024 b edit uint 1024 to void
104for i ulong 1024
105put b i add get a i 1
106end
107ret
108end
109fn copy32 a view f32 1024 b edit f32 1024 to void
110for i ulong 1024
111put b i get a i
112end
113ret
114end
115fn word out edit uchar 20480 off ulong value uint to void
116for j ulong 4
117shift = uint mul j 8
118part = and shr value shift 255
119put out add off j uchar part
120end
121ret
122end
123fn readword input view uchar 4096 off ulong to uint
124x = uint 0
125for j ulong 4
126p = add off j
127v = uint get input p
128shift = uint mul j 8
129x = or x shl v shift
130end
131ret x
132end
133fn process16 input view uchar 4096 output edit uchar 20480 to void
134a = new ushort 1024 0
135b = new ushort 1024 0
136for i ulong 1024
137x = readword view input mul i 4
138put a i ushort and x 65535
139end
140inc16 view a b
141for i ulong 1024
142word output mul i 20 uint get b i
143end
144ret
145end
146fn process32 input view uchar 4096 output edit uchar 20480 to void
147a = new uint 1024 0
148b = new uint 1024 0
149for i ulong 1024
150put a i readword view input mul i 4
151end
152inc32 view a b
153for i ulong 1024
154word output add mul i 20 4 get b i
155end
156ret
157end
158fn processf input view uchar 4096 output edit uchar 20480 to void
159a = new f32 1024 0.0f32
160b = new f32 1024 0.0f32
161for i ulong 1024
162put a i bitcast f32 readword view input mul i 4
163end
164copy32 view a b
165for i ulong 1024
166off = mul i 20
167word output add off 8 bitcast uint get b i
168word output add off 12 bitcast uint add get b i 1.0f32
169word output add off 16 bitcast uint fsqrt get b i
170end
171ret
172end
173fn main to int
174input = new uchar 4096 0
175output = new uchar 20480 0
176more = true
177while more
178have = ulong 0
179while lt have 4096
180n = read 0 input have sub 4096 have
181if lt n 0
182ret 9
183end
184if eq n 0
185if ne have 0
186ret 8
187end
188more = false
189break
190end
191have = add have ulong n
192end
193if more
194process16 view input output
195process32 view input output
196processf view input output
197sent = ulong 0
198while lt sent 20480
199n = write 1 output sent sub 20480 sent
200if le n 0
201ret 7
202end
203sent = add sent ulong n
204end
205end
206end
207ret 0
208end
209"""
210
211
212def main():
213 with tempfile.TemporaryDirectory(prefix="omega-seeded-views-") as td:
214 w = Path(td)
215 # Exhaustive u16 followed by exactly 2^20 deterministic random u32 bit patterns.
216 # The same words are bitcast to f32, not converted through a host float.
217 edges = [0, 0x80000000, 1, 0x80000001, 0x007fffff, 0x00800000,
218 0x7f7fffff, 0xff7fffff, 0x7f800000, 0xff800000,
219 0x7f800001, 0x7fc12345, 0xff800001, 0xffc12345, 0xffffffff]
220 rng = random.Random(0xE5B32567)
221 words = list(range(65536)) + edges + [rng.getrandbits(32) for _ in range(1048576)]
222 words.extend([0] * (-len(words) % 1024))
223 data = b"".join(x.to_bytes(4, "little") for x in words)
224 binary = w / "oracle"
225 binary.write_bytes(run([OMC], PROGRAM.encode()))
226 binary.chmod(0o755)
227 expected = run([binary], data)
228 generated = convert(PROGRAM)
229 storage_codegen(generated, w)
230 host = w / "host"
231 cc(generated, host)
232 actual = run([host], data)
233 assert actual == expected, "typed arrays/rounding/sqrt differ from pinned omc"
234 print("PASS exhaustive-u16=65536 random-u32-f32=1048576 edge-bits=15")
235 x86 = w / "x86"
236 cc(generated, x86, compiler="x86_64-linux-gnu-gcc")
237 assert run([os.environ.get("QEMU_X86_64", "qemu-x86_64"), "-L", "/usr/x86_64-linux-gnu", x86], data) == expected
238 print("PASS x86 emulated C identical on complete typed-view and fsqrt stream")
239 # Corrupt each new feature independently. Every comparison must detect it.
240 mutations = {
241 "ushort-load": (b"__builtin_memcpy(&x,b,2);v=x;", b"__builtin_memcpy(&x,b,2);v=x^(t==3);"),
242 "uint-store": (b"uint32_t x=(uint32_t)v;__builtin_memcpy(b,&x,4);", b"uint32_t x=(uint32_t)(v^(t==4));__builtin_memcpy(b,&x,4);"),
243 "f32-store": (b"uint32_t x=(uint32_t)v;__builtin_memcpy(b,&x,4);", b"uint32_t x=(uint32_t)(v&(t==11?~UINT64_C(1):UINT64_MAX));__builtin_memcpy(b,&x,4);"),
244 "fsqrt": (b"case 20:z=o_sqrt32(x);break;", b"case 20:z=x;break;"),
245 }
246 for name, (old, new) in mutations.items():
247 assert generated.count(old) == 1, (name, "mutation site")
248 exe = w / name
249 cc(generated.replace(old, new), exe)
250 assert run([exe], data) != expected, (name, "survived")
251 print("PASS killed", name)
252 # Compile-time out-of-range index is error 21 for every new view type.
253 for typ in ("ushort", "uint", "f32"):
254 src = f"fn bad a view {typ} 2 to {typ}\nret get a 2\nend\n"
255 path = w / ("refuse-" + typ + ".om")
256 path.write_text(src)
257 p = subprocess.run([ROOT / "tools/bridge-seeded", "c", path], capture_output=True)
258 assert p.returncode and not p.stdout and b"error 21" in p.stderr, (typ, p.stderr)
259 print("PASS refused out-of-range", typ)
260 # Seeded function-only units cannot access the global pool (error 9).
261 # Exercise global storage in a program instead of bypassing that gate.
262 for typ, literal, cast in (("ushort", "65535", "ulong"), ("uint", "4294967295", "ulong"), ("f32", "-0.0f32", "ulong bitcast uint")):
263 src = f"""global bank {typ} 2
264fn main to int
265put bank 0 {literal}
266put bank 1 get bank 0
267bits = {cast} get bank 1
268out = new uchar 8 0
269for j ulong 8
270shift = mul j 8
271put out j uchar and shr bits shift 255
272end
273n = write 1 out 0 8
274ret 0
275end
276"""
277 oracle = w / ("global-" + typ)
278 oracle.write_bytes(run([OMC], src.encode()))
279 oracle.chmod(0o755)
280 host = w / ("global-host-" + typ)
281 cc(convert(src), host)
282 assert run([host]) == run([oracle]), typ
283 print("PASS standalone global array", typ)
284 # All public view checks include true element width, exact count and result overlap.
285 for typ, ct, literal in (("ushort", C.c_uint16, "0"), ("uint", C.c_uint32, "0"), ("f32", C.c_uint32, "0.0f32")):
286 src = f"fn probe a view {typ} 2 b edit {typ} 2 i ulong to {typ}\nput b 0 get a i\nret get a i\nend\n"
287 libpath = w / (typ + ".so")
288 cc(convert(src), libpath, True)
289 lib = C.CDLL(str(libpath))
290 fn = lib.omega_probe
291 fn.restype = C.c_uint32
292 fn.argtypes = [C.c_void_p, C.c_void_p, C.c_uint64, C.c_void_p, C.c_uint64, C.c_uint64]
293 a, b = (ct * 2)(), (ct * 2)()
294 result = C.c_uint64(0x0123456789abcdef)
295 assert fn(C.byref(result), a, 2, b, 2, 2) == 3
296 assert result.value == 0x0123456789abcdef
297 assert fn(C.byref(result), a, 1, b, 2, 0) == 32
298 assert fn(C.byref(result), None, 2, b, 2, 0) == 32
299 assert fn(C.byref(result), a, 2, a, 2, 0) == 32
300 assert fn(C.cast(C.byref(a, C.sizeof(ct)), C.c_void_p), a, 2, b, 2, 0) == 32
301 assert fn(C.byref(result), a, 2, C.byref(b, 1), 2, 0) == 32
302 assert fn(C.byref(result, 1), a, 2, b, 2, 0) == 32
303 assert fn(C.byref(result), C.c_void_p(-C.sizeof(ct)), 2, b, 2, 0) == 32
304 assert fn(C.byref(result), a, 2, b, 2, 0) == 0
305 print("PASS runtime bounds/count/null/alias/overlap/recovery", typ)
306 for typ, ct, bits in (("f32", C.c_uint32, edges), ("f64", C.c_uint64, [0, 0x8000000000000000, 1, 0x7ff0000000000000, 0x7ff8000000012345])):
307 src = f"fn identity x {typ} to {typ}\nret x\nend\n"
308 so = w / (typ + "scalar.so")
309 ctype = C.c_float if typ == "f32" else C.c_double
310 cc(convert(src), so, True)
311 fn = C.CDLL(str(so)).omega_identity
312 fn.argtypes = [C.POINTER(ctype), ctype]
313 fn.restype = C.c_uint32
314 for value in bits:
315 arg = ctype.from_buffer_copy(ct(value))
316 out = ctype()
317 assert fn(C.byref(out), arg) == 0
318 assert ct.from_buffer_copy(out).value == value
319 # Mutant changes result-width marshalling; typed result bit oracle kills it.
320 code = convert(src)
321 old = b"o_put(result,1,0,_result," + (b"11" if typ == "f32" else b"12") + b")"
322 assert code.count(old) == 1
323 bad = code.replace(old, old.replace(b"_result", b"(_result^1)"))
324 cc(bad, so.with_name(typ + "mutant.so"), True)
325 mf = C.CDLL(str(so.with_name(typ + "mutant.so"))).omega_identity
326 mf.argtypes, mf.restype = fn.argtypes, fn.restype
327 out = ctype()
328 assert mf(C.byref(out), ctype()) == 0 and ct.from_buffer_copy(out).value != 0
329 print("PASS typed scalar and killed ABI mutant", typ)
330 print("SEEDED-VIEWS PASS")
331
332
333if __name__ == "__main__":
334 main()