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
omega-mv / tests / universal / translation / validate_compose_v2.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Independent G3 composition validation (#623) against spec/universal/translation-compose-v2.md. |
| 3 | |
| 4 | Six members of the extended S1 family: C, Rust, Python (OMSA version 1, v1-core tools) and C++, Zig, Go |
| 5 | (OMSA version 2, v2-codec tools). For every directed composition A -> B (30, A != B) and every fixture of A |
| 6 | (F1 + accepted C import controls; fixtures-f2-<lang>.json positives, controls and extra positives): |
| 7 | U_A = import_A(src); src_B = export_B(U_A), or export_B(R(U_A, B)) through `retarget` when B is a v1-core |
| 8 | exporter and A a version-2 member (section 3); U_B = import_B(src_B) |
| 9 | 4.1 N(strip(U_B)) == N(strip(U_A)) byte for byte |
| 10 | 4.2 A's oracle on src, this file's reference on U_A, B's oracle on src_B and lower(N(U_A)) -> pinned omc -> |
| 11 | pinned bridge -> omega_calc agree on the translation-v1 section 3 vectors |
| 12 | 4.3 src_B is generated: the semantic-only input and R(U_A, M) for every member M export the same bytes |
| 13 | (a v1-core exporter given a version-2 R(U_A, M) must refuse 65 with no stdout, section 3) |
| 14 | Same-language round trips are reported separately. R, N, strip, the member decoder, each exporter's frozen |
| 15 | output form, the bounds and the mutation operators are written here from the contracts; the adapters, |
| 16 | `retarget` and the codecs are exercised only through their public commands (their sources are not read). |
| 17 | `retarget` output is cross-checked byte for byte against this file's R for every fixture and member. |
| 18 | Oracles: cc (C17), rustc --edition 2021 -O -C overflow-checks=on, python3, g++ -std=c++17 (flags of |
| 19 | cpp-u64-v1.md section 5), zig 0.17.0 build-exe -O Debug (safety-checked), go 1.27.3 build (GOTOOLCHAIN=local). |
| 20 | Exit: 0 PASS, 1 FAIL, 3 NOT_RUN. |
| 21 | """ |
| 22 | from pathlib import Path |
| 23 | from types import SimpleNamespace |
| 24 | import argparse, hashlib, json, os, re, shutil, struct, subprocess, sys |
| 25 | |
| 26 | sys.dont_write_bytecode = True |
| 27 | HERE = Path(__file__).resolve().parent |
| 28 | sys.path.insert(0, str(HERE)) |
| 29 | import validate_g1 as G # noqa: E402 |
| 30 | import validate_compose as C1 # noqa: E402 |
| 31 | |
| 32 | ROOT = G.ROOT |
| 33 | MASK = G.MASK |
| 34 | U = 65535 |
| 35 | COMPOSE2 = ('spec/universal/translation-compose-v2.md', '74cc22f371072f7acf3c3376dfb2ebc865c5ef67846316aa37c1eb5d254af159') |
| 36 | # source-aware-v2.md as amended at 621-source-aware-v2 fa9d9d19 (section 5 step 6 states the profile-6 rows; the |
| 37 | # codec is unchanged); translation-compose-v2.md names the earlier text ea2e1465, which this pin supersedes |
| 38 | SA2 = ('spec/universal/source-aware-v2.md', '2f894c7b923db7e4e89d7ed7339dae97cdb2969742e7b1ed2026637007edb5c7') |
| 39 | LANE_SPECS = {l: 'spec/universal/%s-u64-v1.md' % l for l in ('rust', 'python', 'cpp', 'zig', 'go')} |
| 40 | LANGS = ['c', 'rust', 'python', 'cpp', 'zig', 'go'] |
| 41 | V1CORE = {'c', 'rust', 'python'} |
| 42 | # compose-v2 section 1: OMSA version, language, profile, op dialect, arithmetic obligations |
| 43 | MEMBERS = {'c': (1, 1, 1, 1, 1), 'rust': (1, 2, 2, 2, 1), 'python': (1, 3, 4, 3, 5), |
| 44 | 'cpp': (2, 5, 7, 5, 1), 'zig': (2, 6, 8, 6, 1), 'go': (2, 7, 9, 7, 1)} |
| 45 | # compose-v1 section 3: every importer declares a normalization pair (c-u64-import-v1; rust/python/cpp/zig/go |
| 46 | # -u64-v1 section 3 "Normalization pair: yes") |
| 47 | DECLARES_PAIR = {l: True for l in LANGS} |
| 48 | TOOLS = {l: ('%s-import' % l, '%s-export' % l) for l in LANGS} |
| 49 | CXX_FLAGS = ['-std=c++17', '-O2', '-Wall', '-Wextra', '-Werror', '-Wconversion', '-Wsign-conversion', |
| 50 | '-pedantic-errors', '-Wno-unused-parameter'] |
| 51 | GO_ENV = {'GOTOOLCHAIN': 'local', 'GOFLAGS': '-mod=mod', 'GOPROXY': 'off', 'GOWORK': 'off', 'CGO_ENABLED': '0'} |
| 52 | |
| 53 | |
| 54 | class Bad(Exception): |
| 55 | pass |
| 56 | |
| 57 | |
| 58 | def sha(b): |
| 59 | return hashlib.sha256(b).hexdigest() |
| 60 | |
| 61 | |
| 62 | # ---------------------------------------------------------------- member decoder, R, N, strip |
| 63 | |
| 64 | def decode_member(sem): |
| 65 | if len(sem) < 44 or sem[:4] != b'OMSA' or sem[7] != 1: |
| 66 | raise Bad('semantic header') |
| 67 | count = struct.unpack_from('<H', sem, 10)[0] |
| 68 | if not 1 <= count <= 64 or len(sem) != 44 + 20 * count or sem[12:44] != G.SEMANTICS_DIGEST: |
| 69 | raise Bad('count/length/digest') |
| 70 | member = next((m for m, v in MEMBERS.items() if (sem[4], sem[5], sem[6]) == v[:3]), None) |
| 71 | if member is None or (sem[8], sem[9]) != (0, 1): |
| 72 | raise Bad('not an extended-family header %r' % (tuple(sem[4:10]),)) |
| 73 | dialect, arith = MEMBERS[member][3:] |
| 74 | ops, slots = [], [] |
| 75 | for k in range(count): |
| 76 | d, v, op, t, attr, eff, alias, obl, a, b, imm = struct.unpack_from('<8BHHQ', sem, 44 + 20 * k) |
| 77 | if (d, v, t, eff, alias) != (dialect, 1, 1, 0, 0): |
| 78 | raise Bad('record %d fields' % k) |
| 79 | if op == 9 and (attr, obl, a, b) == (0, 1, U, U) and imm <= 5: |
| 80 | slots.append(imm) |
| 81 | elif op == 1 and (attr, obl, a, b) == (1, 0, U, U): |
| 82 | pass |
| 83 | elif op in (2, 3, 4) and (attr, obl, imm) == (1, arith, 0) and a < k and b < k: |
| 84 | pass |
| 85 | else: |
| 86 | raise Bad('record %d op %d' % (k, op)) |
| 87 | ops.append((op, a, b, imm)) |
| 88 | if sorted(slots) != list(range(len(slots))): |
| 89 | raise Bad('input slots') |
| 90 | return member, ops |
| 91 | |
| 92 | |
| 93 | def R(sem, member): |
| 94 | ver, lang, prof, dialect, arith = MEMBERS[member] |
| 95 | b = bytearray(sem) |
| 96 | b[4], b[5], b[6] = ver, lang, prof |
| 97 | for k in range(struct.unpack_from('<H', sem, 10)[0]): |
| 98 | o = 44 + 20 * k |
| 99 | b[o] = dialect |
| 100 | if b[o + 2] in (2, 3, 4): |
| 101 | b[o + 7] = arith |
| 102 | return bytes(b) |
| 103 | |
| 104 | |
| 105 | def N(sem): |
| 106 | return R(sem, 'c') |
| 107 | |
| 108 | |
| 109 | def strip(sem, ops, member): |
| 110 | if not DECLARES_PAIR[member] or G.normalized_root(ops) is None: |
| 111 | return sem |
| 112 | c = len(ops) - 2 |
| 113 | return sem[:10] + struct.pack('<H', c) + sem[12:44 + 20 * c] |
| 114 | |
| 115 | |
| 116 | # ---------------------------------------------------------------- frozen output forms of the new exporters |
| 117 | |
| 118 | def cprec(t, leaf, sym): |
| 119 | """Infix rendering with the translation-v1 section 6 parenthesis rule (leaf 3, * 2, + - 1).""" |
| 120 | if t['t'] != 'op': |
| 121 | return leaf(t), 3 |
| 122 | p = 2 if t['op'] == '*' else 1 |
| 123 | (lt, lp), (rt, rp) = cprec(t['l'], leaf, sym), cprec(t['r'], leaf, sym) |
| 124 | if lp < p: |
| 125 | lt = '(' + lt + ')' |
| 126 | if rp <= p: |
| 127 | rt = '(' + rt + ')' |
| 128 | return '%s %s %s' % (lt, sym(t), rt), p |
| 129 | |
| 130 | |
| 131 | def cpp_leaf(t): |
| 132 | if t['t'] == 'in': |
| 133 | return 'i%d' % t['s'] |
| 134 | return ('%dULL' if t.get('bare') else 'std::uint64_t{%dULL}') % t['v'] |
| 135 | |
| 136 | |
| 137 | def zig_text(t): |
| 138 | """cpp-like rule; Zig symbols +% -% *%; a left constant operand of a constant-constant op is @as(u64, N).""" |
| 139 | def leaf(x): |
| 140 | return 'x%d' % x['s'] if x['t'] == 'in' else '%d' % x['v'] |
| 141 | |
| 142 | def walk(x): |
| 143 | if x['t'] != 'op': |
| 144 | return leaf(x), 3 |
| 145 | p = 2 if x['op'] == '*' else 1 |
| 146 | (lt, lp), (rt, rp) = walk(x['l']), walk(x['r']) |
| 147 | if x['l']['t'] == 'k' and x['r']['t'] == 'k': |
| 148 | lt = '@as(u64, %d)' % x['l']['v'] |
| 149 | if lp < p: |
| 150 | lt = '(' + lt + ')' |
| 151 | if rp <= p: |
| 152 | rt = '(' + rt + ')' |
| 153 | return '%s %s %s' % (lt, x['op'] if x['plain'] else x['op'] + '%', rt), p |
| 154 | return walk(t)[0] |
| 155 | |
| 156 | |
| 157 | def slots_of(t): |
| 158 | return {y['s'] for y in C1.preorder(t) if y['t'] == 'in'} |
| 159 | |
| 160 | |
| 161 | def render(lang, t, n, run): |
| 162 | if lang in V1CORE: |
| 163 | return C1.render(lang, t, n) |
| 164 | if lang == 'cpp': |
| 165 | params = ', '.join('std::uint64_t i%d' % s for s in range(n)) |
| 166 | return '#include <cstdint>\nstd::uint64_t calc(%s) { return %s; }\n' % (params, cprec(t, cpp_leaf, lambda x: x['op'])[0]) |
| 167 | if lang == 'zig': |
| 168 | used = slots_of(t) |
| 169 | params = ', '.join(('x%d: u64' % s) if s in used else '_: u64' for s in range(n)) |
| 170 | return 'pub fn calc(%s) u64 {\n return %s;\n}\n' % (params, zig_text(t)) |
| 171 | expr = cprec(t, lambda x: 'i%d' % x['s'] if x['t'] == 'in' else '%d' % x['v'], lambda x: x['op'])[0] |
| 172 | params = ', '.join('i%d uint64' % s for s in range(n)) |
| 173 | return run.gofmt('package main\n\nfunc calc(%s) uint64 {\n\treturn %s\n}\n' % (params, expr)) |
| 174 | |
| 175 | |
| 176 | def bounds(lang, t, n, run): |
| 177 | """True iff the exporter must refuse 67 (re-import bounds of each profile spec).""" |
| 178 | if lang in V1CORE: |
| 179 | return C1.bounds(lang, t, n) |
| 180 | text = render(lang, t, n, run) |
| 181 | nodes = sum(1 for y in C1.preorder(t) if y['t'] != 'in') |
| 182 | body = text.split('return ', 1)[1] |
| 183 | depth = best = 0 |
| 184 | for ch in body: |
| 185 | depth += {'(': 1, ')': -1}.get(ch, 0) |
| 186 | best = max(best, depth) |
| 187 | over = len(text.encode()) > 4096 or n + nodes + 2 > 64 or best > 16 |
| 188 | if lang == 'go': |
| 189 | def exact(x): # exact value of a constant-only node, None if it has an input (go-u64-v1 section 1.1) |
| 190 | if x['t'] == 'in': |
| 191 | return None |
| 192 | if x['t'] == 'k': |
| 193 | return x['v'] |
| 194 | a, b = exact(x['l']), exact(x['r']) |
| 195 | if a is None or b is None: |
| 196 | return None |
| 197 | return {'+': a + b, '-': a - b, '*': a * b}[x['op']] |
| 198 | over = over or any(x['t'] == 'op' and exact(x) is not None and not 0 <= exact(x) <= MASK for x in C1.preorder(t)) |
| 199 | return {'bytes': len(text.encode()), 'reimport_ops': n + nodes + 2, 'depth': best, 'over': over} |
| 200 | |
| 201 | |
| 202 | # ---------------------------------------------------------------- oracles (zig deferred and batched) |
| 203 | |
| 204 | CPP_DRIVER = ''' |
| 205 | #include <cstdio> |
| 206 | int main() |
| 207 | { |
| 208 | std::uint64_t n = 0; |
| 209 | if (std::fread(&n, 8, 1, stdin) != 1) |
| 210 | return 2; |
| 211 | std::uint64_t v[6] = {0, 0, 0, 0, 0, 0}; |
| 212 | for (std::uint64_t j = 0; j < n; j++) { |
| 213 | if (std::fread(v, 8, std::size_t{%(k)d}, stdin) != std::size_t{%(k)d}) |
| 214 | return 2; |
| 215 | std::printf("0 %%llu\\n", static_cast<unsigned long long>(%(name)s(%(args)s))); |
| 216 | } |
| 217 | return 0; |
| 218 | } |
| 219 | ''' |
| 220 | GO_DRIVER = '''package main |
| 221 | |
| 222 | import ( |
| 223 | "bufio" |
| 224 | "encoding/binary" |
| 225 | "fmt" |
| 226 | "io" |
| 227 | "os" |
| 228 | ) |
| 229 | |
| 230 | func oracleRead(d []byte, o uint64) uint64 { return binary.LittleEndian.Uint64(d[o : o+8]) } |
| 231 | |
| 232 | func main() { |
| 233 | d, _ := io.ReadAll(os.Stdin) |
| 234 | n := oracleRead(d, 0) |
| 235 | w := bufio.NewWriter(os.Stdout) |
| 236 | for j := uint64(0); j < n; j++ { |
| 237 | base := 8 + 8*%(k)d*j |
| 238 | _ = base |
| 239 | fmt.Fprintf(w, "0 %%d\\n", %(name)s(%(args)s)) |
| 240 | } |
| 241 | w.Flush() |
| 242 | } |
| 243 | ''' |
| 244 | |
| 245 | |
| 246 | class Run(C1.Run): |
| 247 | def __init__(self, a, out): |
| 248 | super().__init__(a, out) |
| 249 | self.res = {} |
| 250 | self.zig_pending = {} |
| 251 | self.toolcache = {} |
| 252 | self.fmtcache = {} |
| 253 | |
| 254 | def tool(self, name, data, *args, fresh=False): |
| 255 | k = (name, sha(data), args) |
| 256 | if fresh or k not in self.toolcache: |
| 257 | path = self.a.tools.get(name) |
| 258 | r = ('absent', b'', b'') if path is None else G.run([path] + list(args), data) |
| 259 | if fresh: |
| 260 | return r |
| 261 | self.toolcache[k] = r |
| 262 | return self.toolcache[k] |
| 263 | |
| 264 | def imp(self, lang, src): |
| 265 | return self.tool(TOOLS[lang][0], src) |
| 266 | |
| 267 | def gofmt(self, text): |
| 268 | if text not in self.fmtcache: |
| 269 | r = subprocess.run([self.a.gofmt], input=text.encode(), capture_output=True, timeout=60) |
| 270 | self.fmtcache[text] = r.stdout.decode() if r.returncode == 0 else text |
| 271 | return self.fmtcache[text] |
| 272 | |
| 273 | def oracle_key(self, lang, src, name, n, vs, key): |
| 274 | """Schedule or run B's oracle; the verdict is read later from self.res[k] = (rows, why).""" |
| 275 | k = (lang, sha(src), name, n, key) |
| 276 | if k in self.res or k in self.zig_pending: |
| 277 | return k |
| 278 | if lang in V1CORE: |
| 279 | self.res[k] = C1.Run.oracle(self, lang, src, name, n, vs, key) |
| 280 | elif lang == 'cpp': |
| 281 | d = self.ctx.tmp('oracle-cpp-%s' % key) |
| 282 | drv = CPP_DRIVER % {'k': n, 'name': name, 'args': ', '.join('v[%d]' % i for i in range(n))} |
| 283 | (d / 'prog.cpp').write_bytes(src + b'\n' + drv.encode()) |
| 284 | rc, _, err = G.run([self.a.cxx] + CXX_FLAGS + ['-o', d / 'run', d / 'prog.cpp'], timeout=180) |
| 285 | self.res[k] = (None, 'g++ exit %s: %s' % (rc, err.decode(errors='replace')[:300])) if rc != 0 else \ |
| 286 | self.collect(G.run([d / 'run'], G.pack_vectors(vs, n), timeout=120), vs) |
| 287 | elif lang == 'go': |
| 288 | d = self.ctx.tmp('oracle-go-%s' % key) |
| 289 | (d / 'go.mod').write_text('module oracle\n\ngo 1.27\n') |
| 290 | (d / 'unit.go').write_bytes(src) |
| 291 | (d / 'main.go').write_text(GO_DRIVER % {'k': n, 'name': name, 'args': ', '.join( |
| 292 | 'oracleRead(d, base+%d)' % (8 * i) for i in range(n))}) |
| 293 | env = dict(os.environ, **GO_ENV, GOCACHE=str(self.ctx.work / 'go-cache'), GOPATH=str(self.ctx.work / 'gopath')) |
| 294 | r = subprocess.run([self.a.go, 'build', '-trimpath', '-o', str(d / 'run'), '.'], cwd=d, env=env, |
| 295 | capture_output=True, timeout=300) |
| 296 | self.res[k] = (None, 'go build exit %s: %s' % (r.returncode, r.stderr.decode(errors='replace')[:300])) \ |
| 297 | if r.returncode != 0 else self.collect(G.run([d / 'run'], G.pack_vectors(vs, n), timeout=120), vs) |
| 298 | else: |
| 299 | self.zig_pending[k] = (src, name, n, vs) |
| 300 | return k |
| 301 | |
| 302 | def flush_zig(self, batch=60): |
| 303 | items = list(self.zig_pending.items()) |
| 304 | self.zig_pending = {} |
| 305 | for i in range(0, len(items), batch): |
| 306 | self.zig_batch(items[i:i + batch]) |
| 307 | |
| 308 | def zig_batch(self, items): |
| 309 | d = self.ctx.tmp('oracle-zig-batch') |
| 310 | main = ['const std = @import("std");', 'extern "c" fn getenv(name: [*:0]const u8) ?[*:0]const u8;'] |
| 311 | prongs = [] |
| 312 | for j, (k, (src, name, n, vs)) in enumerate(items): |
| 313 | (d / ('u%d.zig' % j)).write_bytes(src) |
| 314 | rows = ', '.join('.{ %s }' % ', '.join(str(x) for x in v) for v in vs) |
| 315 | main.append('const unit_%d = @import("u%d.zig");' % (j, j)) # `u<digits>` would shadow a Zig primitive |
| 316 | main.append('const V%d = [_][%d]u64{ %s };' % (j, n, rows)) |
| 317 | cap = 'v' if n else '_' |
| 318 | prongs.append(' %d => for (V%d) |%s| std.debug.print("0 {d}\\n", .{unit_%d.%s(%s)}),' % ( |
| 319 | j, j, cap, j, name, ', '.join('v[%d]' % i for i in range(n)))) |
| 320 | main += ['pub fn main() void {', |
| 321 | ' const sel = std.fmt.parseInt(usize, std.mem.span(getenv("ORACLE_UNIT").?), 10) catch unreachable;', |
| 322 | ' switch (sel) {'] + prongs + [' else => {},', ' }', '}'] |
| 323 | (d / 'main.zig').write_text('\n'.join(main) + '\n') |
| 324 | r = subprocess.run([self.a.zig, 'build-exe', 'main.zig', '-O', 'Debug', '-lc', '--cache-dir', 'zc', |
| 325 | '--global-cache-dir', str(self.ctx.work / 'zig-global-cache'), '-femit-bin=run'], |
| 326 | cwd=d, capture_output=True, timeout=1800) |
| 327 | if r.returncode != 0: |
| 328 | if len(items) == 1: |
| 329 | k = items[0][0] |
| 330 | self.res[k] = (None, 'zig build-exe exit %s: %s' % (r.returncode, r.stderr.decode(errors='replace')[-300:])) |
| 331 | return |
| 332 | h = len(items) // 2 # bisect to attribute a compile failure to its unit |
| 333 | self.zig_batch(items[:h]) |
| 334 | self.zig_batch(items[h:]) |
| 335 | return |
| 336 | for j, (k, (src, name, n, vs)) in enumerate(items): |
| 337 | p = subprocess.run([str(d / 'run')], env=dict(os.environ, ORACLE_UNIT=str(j)), capture_output=True, timeout=120) |
| 338 | self.res[k] = self.collect((p.returncode, p.stderr, p.stdout), vs) |
| 339 | |
| 340 | |
| 341 | # ---------------------------------------------------------------- fixtures |
| 342 | |
| 343 | def load_fixtures(): |
| 344 | out, nip, info = [], {}, {} |
| 345 | f1 = json.loads((ROOT / 'tests/universal/translation/fixtures-f1.json').read_text()) |
| 346 | f1ids = {p['id']: p['sha256'] for p in f1['positives']} |
| 347 | for p in f1['positives']: |
| 348 | b = p['source'].encode() |
| 349 | if sha(b) != p['sha256']: |
| 350 | raise Bad('F1 %s sha256' % p['id']) |
| 351 | out.append(('c', p['id'], p['id'], b, p['name'], p['inputs'])) |
| 352 | for cid, src in G.controls(): |
| 353 | out.append(('c', cid, cid, src, 'calc', 2)) |
| 354 | for lang in LANGS[1:]: |
| 355 | path = ROOT / ('tests/universal/translation/fixtures-f2-%s.json' % lang) |
| 356 | if not path.is_file(): |
| 357 | info[lang] = 'absent' |
| 358 | continue |
| 359 | d = json.loads(path.read_text()) |
| 360 | info[lang] = {'path': path.relative_to(ROOT).as_posix(), 'sha256': sha(path.read_bytes()), |
| 361 | 'positives': len(d['positives']), 'controls': len(d.get('controls', [])), |
| 362 | 'extra_positives': len(d.get('extra_positives', [])), 'refusals': len(d.get('refusals', []))} |
| 363 | for p in d['positives']: |
| 364 | b = p['source'].encode() |
| 365 | f1id = p.get('f1_id') or p.get('f1') |
| 366 | if sha(b) != p['sha256'] or f1ids.get(f1id) != p['f1_sha256'] or p['id'] != 'F2-%s-%s' % (lang, f1id): |
| 367 | raise Bad('%s fixture %s: sha256 or F1 link' % (lang, p['id'])) |
| 368 | out.append((lang, p['id'], f1id, b, p['name'], p['inputs'])) |
| 369 | for c in d.get('controls', []): |
| 370 | b = c['source'].encode() |
| 371 | if sha(b) != c['sha256']: |
| 372 | raise Bad('%s control %s sha256' % (lang, c['id'])) |
| 373 | out.append((lang, c['id'], 'C-' + c['control'], b, c['name'], c['inputs'])) |
| 374 | for x in d.get('extra_positives', []): |
| 375 | b = x['source'].encode() |
| 376 | if sha(b) != x['sha256']: |
| 377 | raise Bad('%s extra %s sha256' % (lang, x['id'])) |
| 378 | out.append((lang, x['id'], x['id'], b, x['function'], x['inputs'])) |
| 379 | nip[lang] = d.get('not_in_profile', []) |
| 380 | return out, nip, info |
| 381 | |
| 382 | |
| 383 | # ---------------------------------------------------------------- per fixture: U_A, retarget, native |
| 384 | |
| 385 | def prepare(run, fx): |
| 386 | lang, fid, base, src, name, n = fx |
| 387 | row = {'fixture': fid, 'A': lang, 'checks': {}, 'failures': []} |
| 388 | |
| 389 | def fail(c, d): |
| 390 | row['checks'][c] = 'FAIL' |
| 391 | row['failures'].append({'check': c, 'detail': d}) |
| 392 | |
| 393 | rc, env, err = run.imp(lang, src) |
| 394 | try: |
| 395 | if rc != 0: |
| 396 | raise Bad('import_%s exit %s %s' % (lang, rc, err.decode(errors='replace')[:120])) |
| 397 | sem, side = G.decode_envelope(env) |
| 398 | m, ops = decode_member(sem) |
| 399 | G.decode_sidecar(side, sem, len(ops), src) |
| 400 | if m != lang or G.normalized_root(ops) is None or G.arity(ops) != n: |
| 401 | raise Bad('member %s / NORMALIZED / arity %d' % (m, G.arity(ops))) |
| 402 | except Bad as e: |
| 403 | fail('import', str(e)) |
| 404 | row['result'] = 'FAIL' |
| 405 | return row, None |
| 406 | vs = G.vectors(n, base) |
| 407 | ref = [G.evaluate(ops, v) for v in vs] |
| 408 | Rs = {M: G.envelope(R(sem, M)) for M in LANGS} |
| 409 | tool_R = {} |
| 410 | for M in LANGS: # compose-v2 section 2: the public retarget equals this file's R, byte for byte |
| 411 | rcr, outr, _ = run.tool('retarget', env, M) |
| 412 | tool_R[M] = outr if rcr == 0 else None |
| 413 | if rcr == 'absent': |
| 414 | row['checks']['retarget-%s' % M] = 'NOT_RUN' |
| 415 | elif (rcr, outr) == (0, Rs[M]): |
| 416 | row['checks']['retarget-%s' % M] = 'PASS' |
| 417 | else: |
| 418 | fail('retarget-%s' % M, {'status': rcr, 'stdout_sha256': sha(outr), 'R_sha256': sha(Rs[M])}) |
| 419 | if tool_R['go'] is not None: # compose-v2 section 2: byte-deterministic |
| 420 | rcd, outd, _ = run.tool('retarget', env, 'go', fresh=True) |
| 421 | if (rcd, outd) == (0, tool_R['go']): |
| 422 | row['checks']['retarget-deterministic'] = 'PASS' |
| 423 | else: |
| 424 | fail('retarget-deterministic', {'status': rcd}) |
| 425 | rcl, outl, _ = run.tool('lower', env) |
| 426 | want_lower = 0 if lang == 'c' else 68 if lang in V1CORE else 65 |
| 427 | row['lower_direct_status'] = rcl |
| 428 | if rcl == want_lower and (rcl == 0) == bool(outl): |
| 429 | row['checks']['lower-direct-%s' % want_lower] = 'PASS' |
| 430 | else: |
| 431 | fail('lower-direct-%s' % want_lower, {'status': rcl, 'stdout_bytes': len(outl)}) |
| 432 | U_A = {'env': env, 'sem': sem, 'ops': ops, 'vs': vs, 'ref': ref, 'R': Rs, 'tool_R': tool_R, |
| 433 | 'oracle': run.oracle_key(lang, src, name, n, vs, base), 'native': run.native(N(sem), n, vs, base)} |
| 434 | row.update({'semantic_identity': G.identity(sem), 'N_identity': G.identity(N(strip(sem, ops, lang))), |
| 435 | 'vectors': len(vs)}) |
| 436 | return row, U_A |
| 437 | |
| 438 | |
| 439 | # ---------------------------------------------------------------- one composition |
| 440 | |
| 441 | def compose(run, fx, B, U_A): |
| 442 | lang, fid, base, src, name, n = fx |
| 443 | sem, ops, vs = U_A['sem'], U_A['ops'], U_A['vs'] |
| 444 | rec = {'fixture': fid, 'A': lang, 'B': B, 'composition': '%s->%s' % (lang, B), 'checks': {}, 'failures': []} |
| 445 | |
| 446 | def fail(c, d): |
| 447 | rec['checks'][c] = 'FAIL' |
| 448 | rec['failures'].append({'check': c, 'detail': d}) |
| 449 | |
| 450 | def ok(c): |
| 451 | rec['checks'].setdefault(c, 'PASS') |
| 452 | |
| 453 | exp = TOOLS[B][1] |
| 454 | env_in, mode = U_A['env'], 'direct' |
| 455 | if B in V1CORE and lang not in V1CORE: |
| 456 | rc0, o0, _ = run.tool(exp, U_A['env']) |
| 457 | (ok('v1-core-refuses-v2-65') if (rc0, o0) == (65, b'') else |
| 458 | fail('v1-core-refuses-v2-65', {'status': rc0, 'stdout_bytes': len(o0)})) |
| 459 | if U_A['tool_R'][B] is None: |
| 460 | rec['result'] = 'NOT_RUN' |
| 461 | rec['why'] = 'retarget absent or failed' |
| 462 | return rec, None |
| 463 | env_in, mode = U_A['tool_R'][B], 'retarget R(U_A, %s)' % B |
| 464 | rec['export_input'] = mode |
| 465 | rc, E, err = run.tool(exp, env_in) |
| 466 | t = C1.root_tree(ops) |
| 467 | bd = bounds(B, t, n, run) |
| 468 | if bd['over']: |
| 469 | rec['expect'] = 'LIMIT' |
| 470 | (ok('export-limit-67') if (rc, E) == (67, b'') else fail('export-limit-67', {'status': rc, 'bounds': bd})) |
| 471 | rec['result'] = 'FAIL' if rec['failures'] else 'PASS_LIMIT' |
| 472 | return rec, None |
| 473 | if rc != 0 or not E: |
| 474 | fail('export', {'status': rc, 'stderr': err.decode(errors='replace')[:200], 'bounds': bd}) |
| 475 | rec['result'] = 'FAIL' |
| 476 | return rec, None |
| 477 | rec['src_B_sha256'] = sha(E) |
| 478 | rc2, E2, _ = run.tool(exp, env_in, fresh=True) |
| 479 | (ok('export-deterministic') if (rc2, E2) == (rc, E) else fail('export-deterministic', 'two runs differ')) |
| 480 | so = G.envelope(G.decode_envelope(env_in)[0]) |
| 481 | rc3, E3, _ = run.tool(exp, so) |
| 482 | (ok('4.3-semantic-only-identical') if (rc3, E3) == (0, E) else fail('4.3-semantic-only-identical', {'status': rc3})) |
| 483 | for M in LANGS: |
| 484 | want = (65, b'') if B in V1CORE and M not in V1CORE else (0, E) |
| 485 | rcm, Em, _ = run.tool(exp, U_A['R'][M]) |
| 486 | (ok('4.3-R-%s' % M) if (rcm, Em) == want else fail('4.3-R-%s' % M, {'status': rcm, 'want': want[0]})) |
| 487 | expected = render(B, t, n, run) |
| 488 | (ok('export-form') if E.decode(errors='replace') == expected else |
| 489 | fail('export-form', {'expected': expected, 'got': E.decode(errors='replace')})) |
| 490 | rec['src_B_equals_source_bytes'] = E == src |
| 491 | rc, envB, err = run.imp(B, E) |
| 492 | if rc != 0: |
| 493 | fail('import_B', {'status': rc, 'stderr': err.decode(errors='replace')[:200]}) |
| 494 | else: |
| 495 | try: |
| 496 | semB, sideB = G.decode_envelope(envB) |
| 497 | mB, opsB = decode_member(semB) |
| 498 | G.decode_sidecar(sideB, semB, len(opsB), E) |
| 499 | if mB != B or G.normalized_root(opsB) is None: |
| 500 | raise Bad('member %s / NORMALIZED' % mB) |
| 501 | if N(strip(semB, opsB, B)) == N(strip(sem, ops, lang)): |
| 502 | ok('4.1-identity') |
| 503 | else: |
| 504 | fail('4.1-identity', {'N_strip_U_A': G.identity(N(strip(sem, ops, lang))), |
| 505 | 'N_strip_U_B': G.identity(N(strip(semB, opsB, B)))}) |
| 506 | if B == lang: |
| 507 | rec['same_language_semantic_bytes_equal'] = semB == sem |
| 508 | m = next(({'vector': [str(x) for x in v], 'reference': str(w), 'got': str(G.evaluate(opsB, v))} |
| 509 | for v, w in zip(vs, U_A['ref']) if G.evaluate(opsB, v) != w), None) |
| 510 | (fail('U_B-vs-reference', m) if m else ok('U_B-vs-reference')) |
| 511 | except Bad as e: |
| 512 | fail('import_B-decode', str(e)) |
| 513 | rec['_legs'] = {'oracle_A': U_A['oracle'], 'oracle_B': run.oracle_key(B, E, 'calc', n, vs, base)} |
| 514 | return rec, E |
| 515 | |
| 516 | |
| 517 | def finalize(run, rec, U_A): |
| 518 | if '_legs' not in rec: |
| 519 | return |
| 520 | legs = {'reference': 'PASS'} |
| 521 | for leg, res in [(l, run.res[k]) for l, k in rec.pop('_legs').items()] + [('native', U_A['native'][:2])]: |
| 522 | if res[0] is None: |
| 523 | legs[leg] = 'FAIL' |
| 524 | rec['checks']['4.2-' + leg] = 'FAIL' |
| 525 | rec['failures'].append({'check': '4.2-' + leg, 'detail': res[1]}) |
| 526 | continue |
| 527 | m = G.compare(U_A['ref'], res[0], U_A['vs']) |
| 528 | legs[leg] = 'FAIL' if m else 'PASS' |
| 529 | rec['checks']['4.2-' + leg] = legs[leg] |
| 530 | if m: |
| 531 | rec['failures'].append({'check': '4.2-' + leg, 'detail': m}) |
| 532 | rec['legs'] = legs |
| 533 | rec['result'] = 'FAIL' if rec['failures'] else 'PASS' |
| 534 | |
| 535 | |
| 536 | # ---------------------------------------------------------------- mutants of exporter outputs |
| 537 | |
| 538 | def mut_bare_ull(t): |
| 539 | x = next((y for y in C1.preorder(t) if y['t'] == 'k'), None) |
| 540 | if x: |
| 541 | x['bare'] = True |
| 542 | return t |
| 543 | |
| 544 | |
| 545 | NEW_MUTANTS = {'cpp': [m for m in C1.COMMON] + [('bare-ULL-literal', mut_bare_ull)], |
| 546 | 'zig': [m for m in C1.COMMON] + [('plain-operator', C1.mut_plain)], |
| 547 | 'go': [m for m in C1.COMMON]} |
| 548 | |
| 549 | |
| 550 | def mutants(run, ev, outputs): |
| 551 | rows = [] |
| 552 | for (B, text), (ops, n, vs, ref, base) in outputs.items(): |
| 553 | t0 = C1.root_tree(ops) |
| 554 | if B == 'c': |
| 555 | muts = [(nm, fn(text)) for nm, fn in G.MUT.C_OPERATORS] |
| 556 | elif B in ('rust', 'python'): |
| 557 | t = C1.parse_rust(text) if B == 'rust' else C1.parse_python(text) |
| 558 | muts = [(nm, C1.tree_text(B, m, n) if m is not None else None) |
| 559 | for nm, fn in C1.TREE_MUTANTS[B] for m in [fn(C1.clone(t))]] |
| 560 | else: |
| 561 | if text != render(B, t0, n, run): # mutate the tree only where the output is its rendering |
| 562 | rows.append({'B': B, 'operator': 'form-mismatch', 'killed': False}) |
| 563 | continue |
| 564 | muts = [(nm, render(B, m, n, run) if m is not None else None) |
| 565 | for nm, fn in NEW_MUTANTS[B] for m in [fn(C1.clone(t0))]] |
| 566 | semN = N(strip(G.build_sem(ops), ops, 'c')) |
| 567 | for nm, mt in muts: |
| 568 | if mt is None or mt == text: |
| 569 | continue |
| 570 | det = [] |
| 571 | if mt != render(B, t0, n, run): |
| 572 | det.append('export-form') |
| 573 | rc, envB, _ = run.imp(B, mt.encode()) |
| 574 | if rc != 0: |
| 575 | det.append('import_B-refused-%s' % rc) |
| 576 | else: |
| 577 | try: |
| 578 | semB, _ = G.decode_envelope(envB) |
| 579 | mB, opsB = decode_member(semB) |
| 580 | if N(strip(semB, opsB, mB)) != semN: |
| 581 | det.append('4.1-identity') |
| 582 | if any(G.evaluate(opsB, v) != w for v, w in zip(vs, ref)): |
| 583 | det.append('U_B-vs-reference') |
| 584 | except Bad: |
| 585 | det.append('import_B-decode') |
| 586 | rows.append({'B': B, 'operator': '%s-%s' % (B, nm) if not nm.startswith(B + '-') else nm, |
| 587 | 'mutant_sha256': sha(mt.encode()), 'detected_by': det, |
| 588 | '_oracle': run.oracle_key(B, mt.encode(), 'calc', n, vs, base + '-mut'), '_vs': vs, '_ref': ref}) |
| 589 | run.flush_zig() |
| 590 | for r in rows: |
| 591 | if '_oracle' in r: |
| 592 | res = run.res[r.pop('_oracle')] |
| 593 | vs, ref = r.pop('_vs'), r.pop('_ref') |
| 594 | if res[0] is None: |
| 595 | r['detected_by'].append('oracle_B-failed') |
| 596 | elif G.compare(ref, res[0], vs): |
| 597 | r['detected_by'].append('oracle_B-vs-reference') |
| 598 | r['killed'] = bool(r['detected_by']) |
| 599 | r['killed_beyond_form'] = bool([x for x in r['detected_by'] if x != 'export-form']) |
| 600 | by = {} |
| 601 | for r in rows: |
| 602 | b = by.setdefault(r['operator'], {'total': 0, 'killed': 0, 'killed_beyond_form': 0}) |
| 603 | b['total'] += 1 |
| 604 | b['killed'] += r['killed'] |
| 605 | b['killed_beyond_form'] += r.get('killed_beyond_form', False) |
| 606 | ev['mutants'] = {'total': len(rows), 'killed': sum(r['killed'] for r in rows), |
| 607 | 'killed_beyond_form': sum(r.get('killed_beyond_form', False) for r in rows), |
| 608 | 'by_operator': by, 'rows': rows} |
| 609 | |
| 610 | |
| 611 | # ---------------------------------------------------------------- refusals |
| 612 | |
| 613 | def refusals(run, ev, base_env, base_ops): |
| 614 | rows = [] |
| 615 | |
| 616 | def expect(tool, label, data, args, want): |
| 617 | rc, out, err = run.tool(tool, data, *args) |
| 618 | rows.append({'tool': tool, 'case': label, 'want': want, 'status': rc, 'stdout_bytes': len(out), |
| 619 | 'stderr': err.decode(errors='replace')[:100], |
| 620 | 'result': 'NOT_RUN' if rc == 'absent' else 'PASS' if rc == want and out == b'' else 'FAIL'}) |
| 621 | |
| 622 | rec = lambda lang, op, t, attr, eff, alias, obl, A=U, B=U, imm=0: struct.pack( |
| 623 | '<8BHHQ', lang, 1, op, t, attr, eff, alias, obl, A, B, imm) |
| 624 | dig = G.SEMANTICS_DIGEST |
| 625 | |
| 626 | def unit(ver, lang, prof, rt, abi, recs): |
| 627 | return G.envelope(b'OMSA' + bytes([ver, lang, prof, 1, rt, abi]) + struct.pack('<H', len(recs)) + dig + b''.join(recs)) |
| 628 | |
| 629 | units = [('cpython-bigint-profile-3', unit(1, 3, 3, 1, 1, [rec(3, 9, 2, 0, 0, 0, 1), rec(3, 9, 2, 0, 0, 0, 1, imm=1), |
| 630 | rec(3, 2, 2, 2, 20, 255, 8, 0, 1)]), 1), |
| 631 | ('osc-profile-5', G.envelope(G.build_sem(base_ops, lang=4, prof=5)), 1), |
| 632 | ('python-dynamic-profile-6', unit(1, 3, 6, 1, 2, [rec(3, 9, 1, 0, 0, 0, 1), rec(3, 9, 1, 0, 0, 0, 1, imm=1), |
| 633 | rec(3, 2, 1, 1, 0, 0, 5, 0, 1)]), 1)] |
| 634 | for m, (ver, lang, prof, dialect, arith) in MEMBERS.items(): |
| 635 | units.append(('%s-member-division' % m, unit(ver, lang, prof, 0, 1, [ |
| 636 | rec(dialect, 9, 1, 0, 0, 0, 1), rec(dialect, 9, 1, 0, 0, 0, 1, imm=1), rec(dialect, 5, 1, 1, 0, 0, arith | 2, 0, 1), |
| 637 | rec(dialect, 1, 1, 1, 0, 0, 0), rec(dialect, 2, 1, 1, 0, 0, arith, 2, 3)]), ver)) |
| 638 | for label, e, ver in units: |
| 639 | rc, out, _ = G.run([run.a.sa2], b'\x02' + e) |
| 640 | if (rc, out) != (0, e): |
| 641 | rows.append({'tool': 'sa-v2', 'case': label, 'status': rc, 'result': 'FAIL', |
| 642 | 'detail': 'probe is not a valid source-aware v2 unit, so it cannot test 68'}) |
| 643 | continue |
| 644 | for B in LANGS: # compose-v2 sections 1 and 3: family tools 68; v1-core tools see version 2 as 65 |
| 645 | expect(TOOLS[B][1], 'outside-family ' + label, e, [], 65 if B in V1CORE and ver == 2 else 68) |
| 646 | expect('lower', 'outside-family ' + label, e, [], 65 if ver == 2 else 68) |
| 647 | expect('retarget', 'outside-family ' + label, e, ['c'], 68) |
| 648 | for label, bad in G.malformed_envelopes(base_env): |
| 649 | for tool in ('cpp-export', 'zig-export', 'go-export', 'retarget'): |
| 650 | expect(tool, 'malformed ' + label, bad, ['c'] if tool == 'retarget' else [], 65) |
| 651 | for tool in ('cpp-export', 'zig-export', 'go-export'): |
| 652 | expect(tool, 'any argument', base_env, ['calc'], 64) |
| 653 | for args in ([], ['java'], ['c', 'go']): |
| 654 | expect('retarget', 'bad command %r' % args, base_env, args, 64) |
| 655 | for lang in LANGS[1:]: |
| 656 | for rid, src, want, sha_ok in C1.lane_refusals(lang): |
| 657 | if not sha_ok: |
| 658 | rows.append({'tool': TOOLS[lang][0], 'case': rid, 'result': 'FAIL', 'detail': 'fixture sha256'}) |
| 659 | continue |
| 660 | expect(TOOLS[lang][0], rid, src, [], want) |
| 661 | ev['refusals'] = {'total': len(rows), 'pass': sum(r['result'] == 'PASS' for r in rows), |
| 662 | 'fail': sum(r['result'] == 'FAIL' for r in rows), |
| 663 | 'not_run': sum(r['result'] == 'NOT_RUN' for r in rows), 'rows': rows} |
| 664 | |
| 665 | |
| 666 | # ---------------------------------------------------------------- main |
| 667 | |
| 668 | def main(): |
| 669 | ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) |
| 670 | ap.add_argument('--repo', default=str(ROOT)) |
| 671 | ap.add_argument('--omc', required=True) |
| 672 | ap.add_argument('--bridge-native', required=True) |
| 673 | ap.add_argument('--bridge-repo', default=os.environ.get('OMEGA_BRIDGE_REPO'), |
| 674 | help='omega-bridge clone holding %s (default $OMEGA_BRIDGE_REPO; no host default)' % G.BRIDGE_COMMIT) |
| 675 | ap.add_argument('--sa2', required=True, help='v2 codec binary build/L832/sa (refusal probes must be valid v2)') |
| 676 | ap.add_argument('--cc', default=os.environ.get('CC', 'cc')) |
| 677 | ap.add_argument('--cxx', default=os.environ.get('CXX', 'g++')) |
| 678 | ap.add_argument('--rustc', default=os.environ.get('RUSTC', 'rustc')) |
| 679 | ap.add_argument('--python', default=sys.executable) |
| 680 | # oracles come from the caller ($ZIG, $GO, $GOFMT) or PATH; a missing one is NOT_RUN, never a host default |
| 681 | ap.add_argument('--zig', default=os.environ.get('ZIG', 'zig')) |
| 682 | ap.add_argument('--go', default=os.environ.get('GO', 'go')) |
| 683 | ap.add_argument('--gofmt', default=os.environ.get('GOFMT', 'gofmt')) |
| 684 | ap.add_argument('--no-mutants', action='store_true') |
| 685 | ap.add_argument('--out', required=True) |
| 686 | a = ap.parse_args() |
| 687 | out = Path(a.out).resolve() |
| 688 | out.mkdir(parents=True, exist_ok=False) |
| 689 | (out / 'work').mkdir() |
| 690 | repo = Path(a.repo).resolve() |
| 691 | ev = {'schema': 'omega.universal.translation.validate.compose.v2', 'contract': {'path': COMPOSE2[0], 'sha256': COMPOSE2[1]}, |
| 692 | 'validator_sha256': sha(Path(__file__).read_bytes()), |
| 693 | 'validate_compose_sha256': sha((HERE / 'validate_compose.py').read_bytes()), |
| 694 | 'validate_g1_sha256': sha((HERE / 'validate_g1.py').read_bytes()), |
| 695 | 'evidence_class': 'REFERENCE + DIFFERENTIAL, NATIVE (host AArch64); no PROOF'} |
| 696 | |
| 697 | def not_run(why): |
| 698 | ev['result'] = 'NOT_RUN' |
| 699 | ev['reason'] = why |
| 700 | (out / 'evidence.json').write_text(json.dumps(ev, indent=1) + '\n') |
| 701 | print('NOT_RUN', why) |
| 702 | return 3 |
| 703 | |
| 704 | pins = {} |
| 705 | for rel, want in [COMPOSE2, SA2, C1.COMPOSE, G.CONTRACT] + list(G.FROZEN.items()): |
| 706 | p = ROOT / rel |
| 707 | got = sha(p.read_bytes()) if p.is_file() else None |
| 708 | if got != want: |
| 709 | return not_run('%s sha256 %s, pinned %s' % (rel, got, want)) |
| 710 | pins[rel] = got |
| 711 | for rel in LANE_SPECS.values(): |
| 712 | pins[rel] = sha((ROOT / rel).read_bytes()) if (ROOT / rel).is_file() else None |
| 713 | ev['pins'] = pins |
| 714 | found = {} |
| 715 | for key, exe in (('cc', a.cc), ('cxx', a.cxx), ('rustc', a.rustc), ('python', a.python), ('zig', a.zig), |
| 716 | ('go', a.go), ('gofmt', a.gofmt)): |
| 717 | found[key] = shutil.which(exe) |
| 718 | if found[key] is None: |
| 719 | return not_run('oracle %s absent: %r (set it explicitly or put it on PATH)' % (key, exe)) |
| 720 | a.cc, a.cxx, a.rustc, a.python, a.zig, a.go = (found[k] for k in ('cc', 'cxx', 'rustc', 'python', 'zig', 'go')) |
| 721 | gofmt = found['gofmt'] |
| 722 | if not a.bridge_repo: |
| 723 | return not_run('no omega-bridge clone: pass --bridge-repo or set OMEGA_BRIDGE_REPO') |
| 724 | for exe in (a.omc, a.bridge_native, a.sa2): |
| 725 | if not Path(exe).is_file(): |
| 726 | return not_run('absent: %s' % exe) |
| 727 | if sha(Path(a.omc).read_bytes()) != G.OMC_SHA: |
| 728 | return not_run('omc is not the translation-v1 section 1 pin') |
| 729 | rc, nsrc, _ = G.run(['git', '-C', a.bridge_repo, 'show', G.BRIDGE_COMMIT + ':src/native.om']) |
| 730 | if rc != 0 or G.run([a.omc], nsrc, timeout=120)[1] != Path(a.bridge_native).read_bytes(): |
| 731 | return not_run('bridge generator is not omc(native.om @ %s)' % G.BRIDGE_COMMIT) |
| 732 | tools, tinfo = {}, {} |
| 733 | for name in ['lower', 'retarget'] + [t for p in TOOLS.values() for t in p]: |
| 734 | p = repo / 'tools/adapters' / name |
| 735 | if p.is_file() and os.access(p, os.X_OK): |
| 736 | tools[name] = str(p) |
| 737 | tinfo[name] = {'sha256': sha(p.read_bytes())} |
| 738 | for bj in sorted(repo.glob('build/**/build.json')): |
| 739 | if (bj.parent / name).is_file(): |
| 740 | tinfo[name].update({'build': bj.parent.relative_to(repo).as_posix(), 'binary_sha256': sha((bj.parent / name).read_bytes())}) |
| 741 | else: |
| 742 | tinfo[name] = 'ABSENT' |
| 743 | head = G.run(['git', '-C', repo, 'rev-parse', 'HEAD']) |
| 744 | ev['repo'] = {'path': str(repo), 'head': head[1].decode().strip() if head[0] == 0 else None} |
| 745 | ev['tools'] = tinfo |
| 746 | ev['toolchains'] = {k: {'path': v[0], 'version': G.run(v)[1].decode().split('\n')[0], 'sha256': sha(Path(v[0]).read_bytes())} |
| 747 | for k, v in {'cc': [a.cc, '--version'], 'g++': [a.cxx, '--version'], 'rustc': [a.rustc, '--version'], |
| 748 | 'python': [a.python, '--version'], 'zig': [a.zig, 'version'], 'go': [a.go, 'version'], |
| 749 | 'gofmt': [gofmt, '-h']}.items()} |
| 750 | ev['sa2_sha256'] = sha(Path(a.sa2).read_bytes()) |
| 751 | if 'lower' not in tools: |
| 752 | return not_run('tools/adapters/lower absent') |
| 753 | try: |
| 754 | fixtures, nip, finfo = load_fixtures() |
| 755 | except Bad as e: |
| 756 | return not_run('fixtures: %s' % e) |
| 757 | ev['fixtures'] = finfo |
| 758 | ev['not_in_profile'] = nip |
| 759 | args = SimpleNamespace(omc=a.omc, bridge_native=a.bridge_native, cc=a.cc, cxx=a.cxx, rustc=a.rustc, python=a.python, |
| 760 | zig=a.zig, go=a.go, gofmt=gofmt, sa2=a.sa2, tools=tools) |
| 761 | run = Run(args, out) |
| 762 | |
| 763 | units, frows = [], [] |
| 764 | for fx in fixtures: |
| 765 | if TOOLS[fx[0]][0] not in tools: |
| 766 | frows.append({'fixture': fx[1], 'A': fx[0], 'result': 'NOT_RUN'}) |
| 767 | units.append((fx, None)) |
| 768 | continue |
| 769 | row, U_A = prepare(run, fx) |
| 770 | row.setdefault('result', 'FAIL' if row['failures'] else 'PASS') |
| 771 | frows.append(row) |
| 772 | units.append((fx, U_A)) |
| 773 | byid = {fx[1]: u for fx, u in units} |
| 774 | fid_rows = [] |
| 775 | for fx, u in units: |
| 776 | if fx[0] == 'c' or u is None or not fx[1].startswith('F2-') or fx[2] not in byid or byid[fx[2]] is None: |
| 777 | continue |
| 778 | c = byid[fx[2]] |
| 779 | same = all(G.evaluate(u['ops'], v) == G.evaluate(c['ops'], v) for v in u['vs']) |
| 780 | fid_rows.append({'fixture': fx[1], 'f1': fx[2], 'values_equal': same, |
| 781 | 'N_strip_equal_to_C_import': N(strip(u['sem'], u['ops'], fx[0])) == N(strip(c['sem'], c['ops'], 'c')), |
| 782 | 'result': 'PASS' if same else 'FAIL'}) |
| 783 | ev['f2_fidelity'] = {'total': len(fid_rows), 'pass': sum(r['result'] == 'PASS' for r in fid_rows), |
| 784 | 'N_equal': sum(r['N_strip_equal_to_C_import'] for r in fid_rows), 'rows': fid_rows} |
| 785 | ev['fixture_rows'] = frows |
| 786 | |
| 787 | comps, outputs, pairs = [], {}, [] |
| 788 | for fx, U_A in units: |
| 789 | for B in LANGS: |
| 790 | key = '%s->%s' % (fx[0], B) |
| 791 | if U_A is None or TOOLS[B][1] not in tools or TOOLS[B][0] not in tools: |
| 792 | failed = any(r['fixture'] == fx[1] and r.get('result') == 'FAIL' for r in frows) |
| 793 | comps.append({'fixture': fx[1], 'A': fx[0], 'B': B, 'composition': key, 'result': 'FAIL' if failed else 'NOT_RUN'}) |
| 794 | continue |
| 795 | rec, E = compose(run, fx, B, U_A) |
| 796 | comps.append(rec) |
| 797 | pairs.append((rec, U_A)) |
| 798 | if E is not None: |
| 799 | outputs.setdefault((B, E.decode(errors='replace')), (U_A['ops'], fx[5], U_A['vs'], U_A['ref'], fx[2])) |
| 800 | print(fx[1], flush=True) |
| 801 | run.flush_zig() |
| 802 | for rec, U_A in pairs: |
| 803 | finalize(run, rec, U_A) |
| 804 | summary = {} |
| 805 | for c in comps: |
| 806 | s = summary.setdefault(c['composition'], {'PASS': 0, 'PASS_LIMIT': 0, 'FAIL': 0, 'NOT_RUN': 0, 'export_input': set()}) |
| 807 | s[c['result']] += 1 |
| 808 | if 'export_input' in c: |
| 809 | s['export_input'].add(c['export_input']) |
| 810 | for s in summary.values(): |
| 811 | s['export_input'] = sorted(s['export_input']) |
| 812 | order = ['%s->%s' % (x, y) for x in LANGS for y in LANGS] |
| 813 | ev['compositions'] = {k: summary[k] for k in order if k in summary and k.split('->')[0] != k.split('->')[1]} |
| 814 | ev['same_language_round_trips'] = {k: summary[k] for k in order if k in summary and k.split('->')[0] == k.split('->')[1]} |
| 815 | per = {} |
| 816 | for c in comps: |
| 817 | for chk, r in c.get('checks', {}).items(): |
| 818 | per.setdefault(c['composition'], {}).setdefault(chk, {}).setdefault(r, 0) |
| 819 | per[c['composition']][chk][r] += 1 |
| 820 | ev['per_check'] = per |
| 821 | base = next((u for fx, u in units if fx[1] == 'F1-P05'), None) |
| 822 | if base: |
| 823 | refusals(run, ev, base['env'], base['ops']) |
| 824 | if not a.no_mutants: |
| 825 | mutants(run, ev, outputs) |
| 826 | ev['cases'] = comps |
| 827 | failed = ['%s %s' % (c['composition'], c['fixture']) for c in comps if c['result'] == 'FAIL'] |
| 828 | failed += ['fixture %s %s' % (r['fixture'], [f['check'] for f in r.get('failures', [])]) for r in frows if r.get('result') == 'FAIL'] |
| 829 | failed += ['f2-fidelity %s' % r['fixture'] for r in fid_rows if r['result'] != 'PASS'] |
| 830 | failed += ['refusal %s %s' % (r['tool'], r['case']) for r in ev.get('refusals', {}).get('rows', []) if r['result'] == 'FAIL'] |
| 831 | if 'mutants' in ev and ev['mutants']['killed'] != ev['mutants']['total']: |
| 832 | failed.append('mutants survived: %d' % (ev['mutants']['total'] - ev['mutants']['killed'])) |
| 833 | if not base: |
| 834 | failed.append('F1-P05 did not import: refusal probes not run') |
| 835 | 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'] |
| 836 | notrun += [1 for r in frows for v in r.get('checks', {}).values() if v == 'NOT_RUN'] |
| 837 | ev['not_run'] = len(notrun) |
| 838 | ev['failed'] = failed |
| 839 | ev['result'] = 'FAIL' if failed else 'NOT_RUN' if notrun else 'PASS' |
| 840 | (out / 'evidence.json').write_text(json.dumps(ev, indent=1) + '\n') |
| 841 | retarget_checks = sum(1 for r in frows for k, v in r.get('checks', {}).items() if k.startswith('retarget-') and v == 'PASS') |
| 842 | print(json.dumps({'result': ev['result'], |
| 843 | 'compositions': {k: {x: y for x, y in v.items() if y} for k, v in ev['compositions'].items()}, |
| 844 | 'same_language_round_trips': {k: {x: y for x, y in v.items() if y} for k, v in ev['same_language_round_trips'].items()}, |
| 845 | 'retarget_equals_R': retarget_checks, |
| 846 | 'f2_fidelity': '%d/%d (N equal %d)' % (ev['f2_fidelity']['pass'], ev['f2_fidelity']['total'], ev['f2_fidelity']['N_equal']), |
| 847 | 'refusals': {k: ev['refusals'][k] for k in ('total', 'pass', 'fail', 'not_run')} if 'refusals' in ev else 'NOT_RUN', |
| 848 | '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', |
| 849 | 'failed': failed[:40]}, indent=1)) |
| 850 | return 1 if failed else 3 if notrun else 0 |
| 851 | |
| 852 | |
| 853 | if __name__ == '__main__': |
| 854 | raise SystemExit(main()) |