interplane.Get Omega
Read in your language

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

branch main Branches Tags History

omega-mv / seed / spirv / parity.py

255 lines · 10485 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0
3"""Verification oracle only: reads artifacts and runs the OpenCL CPU host.
4
5It never generates IR, SPIR-V, or native code. Exit codes are fail-closed:
60 every row matches, 1 at least one executed row mismatches, 2 anything else
7(missing artifact, malformed module, host/API failure, timeout, bad table).
8A host or API failure is therefore never counted as a mismatch.
9
10usage: parity.py DIR TABLE HOST PREFIX [--mutant-baseline]
11"""
12import os
13import re
14import struct
15import subprocess
16import sys
17
18MASK = (1 << 64) - 1
19HOST_TIMEOUT = 120
20OUTPUT = re.compile(rb'\A([0-9]+) ([0-9]+)\n\Z')
21
22
23class Refuse(Exception):
24 """A setup, artifact, or API failure: exit 2, never a parity verdict."""
25
26
27def words_of(blob, label):
28 if len(blob) < 20 or len(blob) % 4:
29 raise Refuse(f'{label}: SPIR-V length {len(blob)} is not a whole header plus words')
30 words = struct.unpack(f'<{len(blob) // 4}I', blob)
31 if words[0] != 0x07230203:
32 raise Refuse(f'{label}: bad SPIR-V magic {words[0]:#010x}')
33 if words[1] != 0x00010000:
34 raise Refuse(f'{label}: SPIR-V version {words[1]:#010x}, expected 1.0')
35 if words[4] != 0:
36 raise Refuse(f'{label}: nonzero reserved schema word')
37 return words
38
39
40def literal_string(operands, label):
41 raw = struct.pack(f'<{len(operands)}I', *operands)
42 end = raw.find(b'\0')
43 if end < 0:
44 raise Refuse(f'{label}: unterminated literal string')
45 return raw[:end].decode('ascii'), (end + 4) // 4
46
47
48def inspect_module(path):
49 """Check the module contract and return its kernel entry-point names."""
50 label = os.path.basename(path)
51 with open(path, 'rb') as handle:
52 words = words_of(handle.read(), label)
53 caps = set()
54 memory = None
55 entries = {}
56 ints = {}
57 voids = set()
58 pointers = {}
59 fntypes = {}
60 functions = {}
61 params = {}
62 current = None
63 at = 5
64 while at < len(words):
65 count, op = words[at] >> 16, words[at] & 0xffff
66 if count == 0 or at + count > len(words):
67 raise Refuse(f'{label}: malformed instruction at word {at}')
68 ops = words[at + 1:at + count]
69 if op == 17:
70 caps.add(ops[0])
71 elif op == 14:
72 memory = tuple(ops)
73 elif op == 15:
74 name, used = literal_string(ops[2:], label)
75 if name in entries:
76 raise Refuse(f'{label}: duplicate entry point {name}')
77 entries[name] = (ops[0], ops[1])
78 elif op == 19:
79 voids.add(ops[0])
80 elif op == 21:
81 ints[ops[0]] = ops[1]
82 elif op == 32:
83 pointers[ops[0]] = (ops[1], ops[2])
84 elif op == 33:
85 fntypes[ops[0]] = (ops[1], tuple(ops[2:]))
86 elif op == 54:
87 current = ops[1]
88 functions[current] = ops[3]
89 params[current] = []
90 elif op == 55:
91 if current is None:
92 raise Refuse(f'{label}: parameter outside function')
93 params[current].append(ops[0])
94 elif op == 56:
95 current = None
96 at += count
97 missing = {4: 'Addresses', 6: 'Kernel', 11: 'Int64'}.keys() - caps
98 if missing:
99 raise Refuse(f'{label}: missing capabilities {sorted(missing)}')
100 if memory != (2, 2):
101 raise Refuse(f'{label}: memory model {memory}, expected Physical64 OpenCL (2, 2)')
102 if not entries:
103 raise Refuse(f'{label}: no entry points')
104 for name, (model, fn) in entries.items():
105 if model != 6:
106 raise Refuse(f'{label}: {name} execution model {model}, expected Kernel 6')
107 if fn not in functions or functions[fn] not in fntypes:
108 raise Refuse(f'{label}: {name} has no function definition')
109 ret, kinds = fntypes[functions[fn]]
110 if ret not in voids or len(kinds) != 2 or len(params[fn]) != 2:
111 raise Refuse(f'{label}: {name} is not void(inputs, outputs)')
112 for kind in kinds:
113 storage, pointee = pointers.get(kind, (None, None))
114 if storage != 5 or ints.get(pointee) != 64:
115 raise Refuse(f'{label}: {name} parameter is not a CrossWorkgroup 64-bit pointer')
116 return set(entries)
117
118
119def canonical(typed):
120 if typed == '-':
121 return []
122 out = []
123 for arg in typed.split(','):
124 kind, value = arg.split(':')
125 if kind == 'bool':
126 if value not in ('true', 'false'):
127 raise Refuse(f'bad bool literal {value}')
128 out.append(1 if value == 'true' else 0)
129 else:
130 out.append(int(value, 10) & MASK)
131 if len(out) > 6:
132 raise Refuse('more than six arguments')
133 return out
134
135
136def run_host(host, module, kernel, args, log):
137 command = [host, module, kernel] + [str(arg) for arg in args]
138 try:
139 done = subprocess.run(command, capture_output=True, timeout=HOST_TIMEOUT)
140 except subprocess.TimeoutExpired:
141 raise Refuse(f'API failure: host timed out on {kernel} ({os.path.basename(module)})')
142 except OSError as error:
143 raise Refuse(f'API failure: cannot execute host: {error}')
144 with open(log + '.out', 'wb') as handle:
145 handle.write(done.stdout)
146 with open(log + '.err', 'wb') as handle:
147 handle.write(done.stderr)
148 if done.returncode != 0:
149 raise Refuse(f'API failure: host exited {done.returncode} on {kernel} '
150 f'({os.path.basename(module)}); see {log}.err')
151 match = OUTPUT.match(done.stdout)
152 if not match:
153 raise Refuse(f'API failure: malformed host output for {kernel}; see {log}.out')
154 value, status = int(match[1]), int(match[2])
155 if value > MASK:
156 raise Refuse(f'API failure: host value out of 64-bit range for {kernel}')
157 return value, status
158
159
160def main(argv):
161 if len(argv) not in (5, 6) or (len(argv) == 6 and argv[5] != '--mutant-baseline'):
162 raise Refuse(__doc__.strip().splitlines()[-1])
163 directory, table, host, prefix = argv[1:5]
164 mutant_mode = len(argv) == 6
165 tag = 'mutant' if mutant_mode else 'spirv'
166 rows = []
167 with open(table, encoding='ascii') as handle:
168 for line in handle.read().split('\n'):
169 if not line or line.startswith('#'):
170 continue
171 fields = line.split('\t')
172 if len(fields) != 5:
173 raise Refuse(f'{table}: row has {len(fields)} fields')
174 rows.append(fields)
175 if not rows:
176 raise Refuse(f'{table}: empty denominator')
177 modules = {}
178 covered = {}
179 mismatches = []
180 traps = 0
181 lines = ['case\tunit\tfunction\tcanonical_args\tnative_status\tnative_bits\t'
182 'spirv_status\tspirv_bits\tverdict']
183 for index, (unit, name, ret, typed, status) in enumerate(rows, 1):
184 if unit not in modules:
185 file = 'mutant-flipped.spv' if mutant_mode and unit == 'mutant' else f'{unit}.spv'
186 path = os.path.join(directory, file)
187 modules[unit] = (path, inspect_module(path))
188 covered[unit] = set()
189 path, exports = modules[unit]
190 if name not in exports:
191 raise Refuse(f'{unit}: missing kernel {name}')
192 covered[unit].add(name)
193 args = canonical(typed)
194 base = os.path.join(directory, f'{prefix}-{index}')
195 with open(base + '.status', encoding='ascii') as handle:
196 native_status = int(handle.read().strip())
197 with open(base + '.out', 'rb') as handle:
198 native = handle.read()
199 if native_status != int(status):
200 raise Refuse(f'{unit}.{name}: native status {native_status} expected {status}')
201 if native_status:
202 if not 101 <= native_status <= 114:
203 raise Refuse(f'{unit}.{name}: native status {native_status} is not an Omega trap')
204 if native:
205 raise Refuse(f'{unit}.{name}: native trap wrote a value')
206 native_bits = 0
207 traps += 1
208 else:
209 if len(native) != 8:
210 raise Refuse(f'{unit}.{name}: incomplete native result')
211 native_bits = struct.unpack('<Q', native)[0]
212 value, spirv_status = run_host(host, path, name, args, f'{base}.{tag}')
213 same = value == native_bits and spirv_status == native_status
214 lines.append(f'{index}\t{unit}\t{name}\t{",".join(map(str, args)) or "-"}\t'
215 f'{native_status}\t{native_bits}\t{spirv_status}\t{value}\t'
216 f'{"match" if same else "MISMATCH"}')
217 if not same:
218 mismatches.append(f'result mismatch at case {index} {unit}.{name}: native '
219 f'{native_bits}/{native_status} spirv {value}/{spirv_status}')
220 for unit, (path, exports) in modules.items():
221 if covered[unit] != exports:
222 raise Refuse(f'{unit}: untested kernels {sorted(exports - covered[unit])}')
223 parity = os.path.join(directory, f'{prefix}-{tag}-parity.tsv')
224 with open(parity, 'w', encoding='ascii') as handle:
225 handle.write('\n'.join(lines) + '\n')
226 if mismatches:
227 for message in mismatches:
228 print(message)
229 print(f'FAIL parity mismatches={len(mismatches)} of cases={len(rows)}; table {parity}')
230 return 1
231 print(f'PASS parity cases={len(rows)} units={len(modules)} traps={traps} '
232 f'matches={len(rows)}; every kernel exercised; table {parity}')
233 if 'mutant' in modules and not mutant_mode:
234 good = run_host(host, os.path.join(directory, 'mutant.spv'), 'mutadd', [19, 7],
235 os.path.join(directory, 'mutant-probe.base'))
236 inspect_module(os.path.join(directory, 'mutant-flipped.spv'))
237 bad = run_host(host, os.path.join(directory, 'mutant-flipped.spv'), 'mutadd', [19, 7],
238 os.path.join(directory, 'mutant-probe.flipped'))
239 if good != (26, 0) or bad != (12, 0):
240 print(f'result mismatch in mutant probe: baseline {good} flipped {bad}, '
241 'expected (26, 0) and (12, 0)')
242 return 1
243 print('PASS add-to-sub IR-byte mutant executes successfully and computes 19-7=12')
244 return 0
245
246
247if __name__ == '__main__':
248 try:
249 sys.exit(main(sys.argv))
250 except Refuse as error:
251 print(f'ERROR {error}')
252 sys.exit(2)
253 except Exception as error: # noqa: BLE001 - any oracle fault is exit 2, never 1
254 print(f'ERROR oracle fault {type(error).__name__}: {error}')
255 sys.exit(2)