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 / source-aware / v2_reference.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Independent source-aware v2 reference decoder (#623), written from spec/universal/source-aware-v2.md |
| 3 | (section 5 decode order, normative for v1 and v2) and the v1 typed registry it keeps; no codec source is |
| 4 | read. `--sa` runs a differential against a native codec (build/L832/sa): every request goes to the native |
| 5 | binary as one process (mode byte + envelope on stdin) and to this decoder; exit status and stdout must |
| 6 | agree exactly. Modes compared: 1 encode, 2 decode, 3 identity, 4 provenance, 5 replay, plus the mode and |
| 7 | size checks of `perform`. Mode 6 legality is not modelled (its per-operation reply is not specified |
| 8 | byte for byte in either spec) and is reported NOT_RUN. |
| 9 | |
| 10 | Corpus: every F1 import (C importer), every F2 import of each available importer, R(U, M) for the six |
| 11 | family members of each, the v2 corner cases (version/profile pairing, wrong dialect, obligation 4 on |
| 12 | profiles 7..9, division, ops 6/7/8, every version byte value, every truncation, header fields) and seeded |
| 13 | random byte mutations of valid envelopes (raw, with the sidecar hashes resealed, and semantic-only). |
| 14 | Exit 0 when every comparison agrees, 1 on any disagreement, 3 when the codec or a pin is absent. |
| 15 | """ |
| 16 | from pathlib import Path |
| 17 | import argparse, hashlib, json, os, random, struct, subprocess, sys |
| 18 | |
| 19 | sys.dont_write_bytecode = True |
| 20 | ROOT = Path(__file__).resolve().parents[3] |
| 21 | SPEC = ('spec/universal/source-aware-v2.md', '2f894c7b923db7e4e89d7ed7339dae97cdb2969742e7b1ed2026637007edb5c7') |
| 22 | SEMANTICS = 'spec/universal/semantics.md' |
| 23 | U = 65535 |
| 24 | MAX_INPUT, MAX_SEM, MAX_SIDE, MAX_SRC = 8192, 1324, 4682, 4096 |
| 25 | # profile -> (language, allowed (runtime, ABI) pairs, allowed types) |
| 26 | PROFILES = {1: (1, {(0, 1)}, {1}), 2: (2, {(0, 1)}, {1}), 3: (3, {(1, 1), (2, 1)}, {2}), |
| 27 | 4: (3, {(0, 1)}, {1}), 5: (4, {(0, 1)}, {1}), 6: (3, {(1, 2), (2, 2)}, {1, 2, 3, 4}), |
| 28 | 7: (5, {(0, 1)}, {1}), 8: (6, {(0, 1)}, {1}), 9: (7, {(0, 1)}, {1})} |
| 29 | # family members (translation-compose-v2 section 1): OMSA version, language, profile, dialect, arith obligations |
| 30 | MEMBERS = {'c': (1, 1, 1, 1, 1), 'rust': (1, 2, 2, 2, 1), 'python': (1, 3, 4, 3, 5), |
| 31 | 'cpp': (2, 5, 7, 5, 1), 'zig': (2, 6, 8, 6, 1), 'go': (2, 7, 9, 7, 1)} |
| 32 | |
| 33 | |
| 34 | def semantics_digest(root=ROOT): |
| 35 | return hashlib.sha256((root / SEMANTICS).read_bytes()).digest() |
| 36 | |
| 37 | |
| 38 | class Ref: |
| 39 | def __init__(self, digest): |
| 40 | self.digest = digest |
| 41 | |
| 42 | def decode(self, b): |
| 43 | """Returns (status, fields). Section 5 order; the first failure wins.""" |
| 44 | if len(b) > MAX_INPUT: |
| 45 | return 67, None |
| 46 | if len(b) < 13 or b[:4] != b'OMSB': |
| 47 | return 65, None |
| 48 | if b[4] != 1: |
| 49 | return 66, None |
| 50 | ns, np_ = struct.unpack_from('<II', b, 5) |
| 51 | if ns > MAX_SEM or np_ > MAX_SIDE: |
| 52 | return 67, None |
| 53 | if len(b) != 13 + ns + np_ or ns < 44: |
| 54 | return 65, None |
| 55 | s = b[13:13 + ns] |
| 56 | if s[:4] != b'OMSA': |
| 57 | return 65, None |
| 58 | if s[4] not in (1, 2) or s[7] != 1: |
| 59 | return 66, None |
| 60 | count = struct.unpack_from('<H', s, 10)[0] |
| 61 | if count == 0 or count > 64: |
| 62 | return 67, None |
| 63 | if ns != 44 + 20 * count: |
| 64 | return 65, None |
| 65 | if s[12:44] != self.digest: |
| 66 | return 78, None |
| 67 | version, lang, prof, rt, abi = s[4], s[5], s[6], s[8], s[9] |
| 68 | if prof == 0 or prof > 9 or lang != PROFILES[prof][0] or (version == 2) != (prof >= 7) \ |
| 69 | or (rt, abi) not in PROFILES[prof][1]: |
| 70 | return 68, None |
| 71 | types, slots, ops, aliases = [], set(), [], [] |
| 72 | for i in range(count): |
| 73 | d, v, op, t, attr, eff, alias, obl, A, B, imm = struct.unpack_from('<8BHHQ', s, 44 + 20 * i) |
| 74 | if d != lang: |
| 75 | return 68, None |
| 76 | if v != 1: |
| 77 | return 66, None |
| 78 | if t == 0 or t > 4: |
| 79 | return 70, None |
| 80 | if t not in PROFILES[prof][2]: |
| 81 | return 68, None |
| 82 | if op == 0 or op > 9: |
| 83 | return 69, None |
| 84 | st = self.row(prof, i, op, t, attr, eff, alias, obl, A, B, imm, types, slots, aliases) |
| 85 | if st: |
| 86 | return st, None |
| 87 | types.append(t) |
| 88 | aliases.append(alias) |
| 89 | ops.append((op, A, B, imm)) |
| 90 | side = b[13 + ns:] |
| 91 | if np_: |
| 92 | if np_ < 74 or side[:4] != b'OMSP': |
| 93 | return 65, None |
| 94 | if side[4] != 1: |
| 95 | return 66, None |
| 96 | if side[5] > 1: |
| 97 | return 76, None |
| 98 | n = struct.unpack_from('<I', side, 6)[0] |
| 99 | if n > MAX_SRC: |
| 100 | return 67, None |
| 101 | if np_ != 74 + 8 * count + n: |
| 102 | return 65, None |
| 103 | src = side[74 + 8 * count:] |
| 104 | if side[10:42] != hashlib.sha256(s).digest() or side[42:74] != hashlib.sha256(src).digest(): |
| 105 | return 74, None |
| 106 | if side[5] == 1: |
| 107 | try: |
| 108 | src.decode('utf-8', errors='strict') # strict: no overlong, surrogate or > U+10FFFF |
| 109 | except UnicodeDecodeError: |
| 110 | return 76, None |
| 111 | for k in range(count): |
| 112 | lo, hi = struct.unpack_from('<II', side, 74 + 8 * k) |
| 113 | if lo > hi or hi > n: |
| 114 | return 75, None |
| 115 | if side[5] == 1 and any(x != n and 0x80 <= src[x] <= 0xBF for x in (lo, hi)): |
| 116 | return 75, None |
| 117 | else: |
| 118 | src = None |
| 119 | return 0, {'sem': s, 'source': src, 'ops': ops, 'profile': prof, 'version': version} |
| 120 | |
| 121 | @staticmethod |
| 122 | def row(prof, i, op, t, attr, eff, alias, obl, A, B, imm, types, slots, aliases): |
| 123 | """One operation row, transcribed check by check from source-aware-v2.md section 5 step 6 |
| 124 | (sha256 2f894c7b...); within a row the first failing check decides.""" |
| 125 | def earlier(x, want): # an operand index < i whose record has type `want` (65535 is never one) |
| 126 | return x < i and types[x] == want |
| 127 | |
| 128 | if op == 1: |
| 129 | if t > 2 or attr != t or A != U or B != U: |
| 130 | return 70 |
| 131 | if obl != 0: |
| 132 | return 72 |
| 133 | if eff != 0 or alias != 0: |
| 134 | return 71 |
| 135 | return 0 |
| 136 | if op in (2, 3, 4, 5): |
| 137 | if t > 2 or attr != t or not earlier(A, t) or not earlier(B, t): |
| 138 | return 70 |
| 139 | if imm != 0: |
| 140 | return 65 |
| 141 | if t == 1 and (eff != 0 or alias != 0): |
| 142 | return 71 |
| 143 | if t == 2 and (eff != 20 or alias != 255): |
| 144 | return 71 |
| 145 | want = (1 | (4 if prof in (4, 6) else 0)) if t == 1 else 8 |
| 146 | if op == 5: |
| 147 | want += 2 |
| 148 | return 72 if obl != want else 0 |
| 149 | if op == 6: |
| 150 | if prof != 6: |
| 151 | return 68 |
| 152 | if t != 3 or attr != 3 or not earlier(A, 3) or B != U: |
| 153 | return 70 |
| 154 | if imm != 0: |
| 155 | return 65 |
| 156 | if eff != 63 or alias != 255: |
| 157 | return 71 |
| 158 | return 72 if obl != 8 else 0 |
| 159 | if op in (7, 8): |
| 160 | if prof != 6: |
| 161 | return 68 |
| 162 | if t != 1 or attr != 4 or not earlier(A, 4) or not earlier(B, 1): |
| 163 | return 70 |
| 164 | if not (1 <= alias <= 8 or alias == 255) or alias != aliases[A]: |
| 165 | return 71 |
| 166 | if op == 8 and not earlier(imm, 1): |
| 167 | return 70 |
| 168 | if op == 7 and imm != 0: |
| 169 | return 65 |
| 170 | if eff != (17 if op == 7 else 19): |
| 171 | return 71 |
| 172 | return 72 if obl != 24 else 0 |
| 173 | # op 9 (input) |
| 174 | if attr != 0 or A != U or B != U: |
| 175 | return 70 |
| 176 | if imm > 5: |
| 177 | return 67 |
| 178 | if imm in slots: |
| 179 | return 70 |
| 180 | slots.add(imm) |
| 181 | if obl != 1: |
| 182 | return 72 |
| 183 | if eff != 0: |
| 184 | return 71 |
| 185 | if (t == 4 and not (1 <= alias <= 8 or alias == 255)) or (t != 4 and alias != 0): |
| 186 | return 71 |
| 187 | return 0 |
| 188 | |
| 189 | def perform(self, mode, b): |
| 190 | """(status, stdout) of `sa` for mode byte + envelope.""" |
| 191 | if len(b) > MAX_INPUT: |
| 192 | return 67, b'' |
| 193 | if mode == 0 or mode > 6: |
| 194 | return 64, b'' |
| 195 | st, f = self.decode(b) |
| 196 | if st: |
| 197 | return st, b'' |
| 198 | if mode in (1, 2): |
| 199 | return 0, b |
| 200 | if mode == 3: |
| 201 | return 0, hashlib.sha256(b'omega.source.semantic.v1' + f['sem']).digest() |
| 202 | if mode == 4: |
| 203 | return 0, hashlib.sha256(b'omega.source.provenance.v1' + b).digest() |
| 204 | if mode == 5: |
| 205 | return (73, b'') if f['source'] is None else (0, f['source']) |
| 206 | raise ValueError('legality not modelled') |
| 207 | |
| 208 | |
| 209 | # ---------------------------------------------------------------- corpus construction |
| 210 | |
| 211 | def envelope(sem, side=b''): |
| 212 | return b'OMSB\x01' + struct.pack('<II', len(sem), len(side)) + sem + side |
| 213 | |
| 214 | |
| 215 | def split(env): |
| 216 | ns, np_ = struct.unpack_from('<II', env, 5) |
| 217 | return env[13:13 + ns], env[13 + ns:] |
| 218 | |
| 219 | |
| 220 | def R(sem, member): |
| 221 | """translation-compose-v2 section 2: version, language, profile, dialects, arithmetic obligations.""" |
| 222 | ver, lang, prof, dialect, arith = MEMBERS[member] |
| 223 | b = bytearray(sem) |
| 224 | b[4], b[5], b[6] = ver, lang, prof |
| 225 | for k in range(struct.unpack_from('<H', sem, 10)[0]): |
| 226 | o = 44 + 20 * k |
| 227 | b[o] = dialect |
| 228 | if b[o + 2] in (2, 3, 4): |
| 229 | b[o + 7] = arith |
| 230 | return bytes(b) |
| 231 | |
| 232 | |
| 233 | def reseal(env): |
| 234 | """Recompute the sidecar's semantic and source hashes after a mutation (when the framing allows).""" |
| 235 | try: |
| 236 | sem, side = split(env) |
| 237 | if len(side) >= 74 and len(sem) >= 12: |
| 238 | count = struct.unpack_from('<H', sem, 10)[0] |
| 239 | src = side[74 + 8 * count:] |
| 240 | side = side[:10] + hashlib.sha256(sem).digest() + hashlib.sha256(src).digest() + side[74:] |
| 241 | return env[:13 + len(sem)] + side |
| 242 | except struct.error: |
| 243 | pass |
| 244 | return env |
| 245 | |
| 246 | |
| 247 | def set_byte(b, off, v): |
| 248 | return b[:off] + bytes([v]) + b[off + 1:] |
| 249 | |
| 250 | |
| 251 | def corner_cases(env, full_sweep): |
| 252 | """Named corner cases derived from one valid envelope (with sidecar) of any family member.""" |
| 253 | sem, side = split(env) |
| 254 | count = struct.unpack_from('<H', sem, 10)[0] |
| 255 | out = [] |
| 256 | so = envelope(sem) |
| 257 | base = {m: R(sem, m) for m in MEMBERS} |
| 258 | for m, s in base.items(): |
| 259 | out.append(('R-%s' % m, envelope(s))) |
| 260 | c = base['c'] |
| 261 | # version / profile pairing (section 3) and every profile/language under both versions |
| 262 | for ver in (1, 2): |
| 263 | for prof in range(0, 11): |
| 264 | for lang in sorted({PROFILES.get(prof, (prof,))[0], 1, 5}): |
| 265 | s = bytearray(c) |
| 266 | s[4], s[5], s[6] = ver, lang, prof |
| 267 | for k in range(count): |
| 268 | s[44 + 20 * k] = lang |
| 269 | out.append(('ver%d-prof%d-lang%d' % (ver, prof, lang), envelope(bytes(s)))) |
| 270 | for m in ('cpp', 'zig', 'go'): |
| 271 | s = base[m] |
| 272 | k_arith = [k for k in range(count) if s[44 + 20 * k + 2] in (2, 3, 4)] |
| 273 | for k in range(count): |
| 274 | o = 44 + 20 * k |
| 275 | out.append(('%s-wrong-dialect-op%d' % (m, k), envelope(set_byte(s, o, 1)))) |
| 276 | out.append(('%s-op-version-2-op%d' % (m, k), envelope(set_byte(s, o + 1, 2)))) |
| 277 | for opc in (5, 6, 7, 8, 0, 10): |
| 278 | out.append(('%s-opcode%d-op%d' % (m, opc, k), envelope(set_byte(s, o + 2, opc)))) |
| 279 | for t in (0, 2, 3, 4, 5): |
| 280 | out.append(('%s-type%d-op%d' % (m, t, k), envelope(set_byte(s, o + 3, t)))) |
| 281 | for k in k_arith: |
| 282 | o = 44 + 20 * k |
| 283 | out.append(('%s-obligation4-op%d' % (m, k), envelope(set_byte(s, o + 7, 5)))) |
| 284 | out.append(('%s-obligation0-op%d' % (m, k), envelope(set_byte(s, o + 7, 0)))) |
| 285 | div = set_byte(s, o + 2, 5) |
| 286 | out.append(('%s-division-obl1-op%d' % (m, k), envelope(div))) |
| 287 | out.append(('%s-division-obl3-op%d' % (m, k), envelope(set_byte(div, o + 7, 3)))) |
| 288 | out.append(('%s-division-obl7-op%d' % (m, k), envelope(set_byte(div, o + 7, 7)))) |
| 289 | for rt in range(0, 3): |
| 290 | for abi in range(0, 4): |
| 291 | out.append(('%s-rt%d-abi%d' % (m, rt, abi), envelope(set_byte(set_byte(s, 8, rt), 9, abi)))) |
| 292 | # every version byte, every value |
| 293 | full = [('envelope', 4), ('omsa', 17), ('dialect-version', 20)] |
| 294 | full += [('op%d-version' % k, 13 + 44 + 20 * k + 1) for k in range(count)] |
| 295 | if side: |
| 296 | full.append(('omsp', 13 + len(sem) + 4)) |
| 297 | for vname, off in (full if full_sweep else full[:3]): |
| 298 | for v in (range(256) if full_sweep else (0, 1, 2, 3, 255)): |
| 299 | if v != env[off]: |
| 300 | out.append(('%s=%d' % (vname, v), set_byte(env, off, v))) |
| 301 | e2 = envelope(R(sem, 'go')) |
| 302 | if off < len(e2) and vname != 'omsp': |
| 303 | out.append(('go-%s=%d' % (vname, v), set_byte(e2, off, v))) |
| 304 | # every truncation (with and without length fix-up) and simple extensions |
| 305 | for n in range(len(env)): |
| 306 | out.append(('truncate-%d' % n, env[:n])) |
| 307 | out.append(('extend-1', env + b'\0')) |
| 308 | out.append(('semantic-only', so)) |
| 309 | out.append(('oversize', env + b'\0' * (MAX_INPUT + 1 - len(env)))) |
| 310 | return out |
| 311 | |
| 312 | |
| 313 | def rec(lang, op, t, attr, eff, alias, obl, A=U, B=U, imm=0): |
| 314 | return struct.pack('<8BHHQ', lang, 1, op, t, attr, eff, alias, obl, A, B, imm) |
| 315 | |
| 316 | |
| 317 | def sem_of(ver, lang, prof, rt, abi, recs, digest): |
| 318 | return b'OMSA' + bytes([ver, lang, prof, 1, rt, abi]) + struct.pack('<H', len(recs)) + digest + b''.join(recs) |
| 319 | |
| 320 | |
| 321 | def constructed_units(digest): |
| 322 | """Valid units of profiles 3 and 6 and of division in profiles 1/7, as named semantic-only envelopes.""" |
| 323 | p3 = [rec(3, 9, 2, 0, 0, 0, 1, imm=0), rec(3, 9, 2, 0, 0, 0, 1, imm=1), rec(3, 2, 2, 2, 20, 255, 8, 0, 1), |
| 324 | rec(3, 1, 2, 2, 0, 0, 0, imm=7), rec(3, 5, 2, 2, 20, 255, 10, 2, 3)] |
| 325 | p6u = [rec(3, 9, 1, 0, 0, 0, 1, imm=1), rec(3, 9, 1, 0, 0, 0, 1, imm=0), rec(3, 4, 1, 1, 0, 0, 5, 0, 1), |
| 326 | rec(3, 1, 1, 1, 0, 0, 0, imm=3), rec(3, 3, 1, 1, 0, 0, 5, 2, 3)] |
| 327 | p6v = [rec(3, 9, 4, 0, 0, 1, 1, imm=0), rec(3, 9, 1, 0, 0, 0, 1, imm=1), rec(3, 9, 3, 0, 0, 0, 1, imm=2), |
| 328 | rec(3, 7, 1, 4, 17, 1, 24, 0, 1), rec(3, 8, 1, 4, 19, 1, 24, 0, 1, imm=3), |
| 329 | rec(3, 6, 3, 3, 63, 255, 8, 2), rec(3, 9, 2, 0, 0, 0, 1, imm=3), rec(3, 1, 2, 2, 0, 0, 0, imm=9), |
| 330 | rec(3, 2, 2, 2, 20, 255, 8, 6, 7)] |
| 331 | d1 = [rec(1, 9, 1, 0, 0, 0, 1, imm=0), rec(1, 9, 1, 0, 0, 0, 1, imm=1), rec(1, 5, 1, 1, 0, 0, 3, 0, 1)] |
| 332 | d7 = [rec(5, 9, 1, 0, 0, 0, 1, imm=0), rec(5, 9, 1, 0, 0, 0, 1, imm=1), rec(5, 5, 1, 1, 0, 0, 3, 0, 1)] |
| 333 | return [('profile3-bigint', envelope(sem_of(1, 3, 3, 1, 1, p3, digest))), |
| 334 | ('profile3-runtime2', envelope(sem_of(1, 3, 3, 2, 1, p3, digest))), |
| 335 | ('profile6-u64', envelope(sem_of(1, 3, 6, 1, 2, p6u, digest))), |
| 336 | ('profile6-view-ops-6-7-8', envelope(sem_of(1, 3, 6, 2, 2, p6v, digest))), |
| 337 | ('profile6-write-alias-255-on-view-alias-1', envelope(sem_of(1, 3, 6, 2, 2, p6v[:4] + [ |
| 338 | rec(3, 8, 1, 4, 19, 255, 24, 0, 1, imm=3)], digest))), |
| 339 | ('profile1-division', envelope(sem_of(1, 1, 1, 0, 1, d1, digest))), |
| 340 | ('profile7-division', envelope(sem_of(2, 5, 7, 0, 1, d7, digest)))] |
| 341 | |
| 342 | |
| 343 | def random_mutations(envs, rng, count): |
| 344 | out = [] |
| 345 | for j in range(count): |
| 346 | base = rng.choice(envs) |
| 347 | kind = rng.choice(['raw', 'resealed', 'semantic-only', 'header']) |
| 348 | if kind == 'semantic-only': |
| 349 | base = envelope(split(base)[0]) |
| 350 | b = bytearray(base) |
| 351 | if kind == 'header': |
| 352 | pos = [rng.randrange(0, min(len(b), 57))] |
| 353 | else: |
| 354 | pos = [rng.randrange(0, len(b)) for _ in range(rng.choice([1, 1, 2, 3]))] |
| 355 | for p in pos: |
| 356 | b[p] = rng.choice([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, rng.randrange(256), b[p] ^ (1 << rng.randrange(8))]) |
| 357 | b = bytes(b) |
| 358 | if kind == 'resealed': |
| 359 | b = reseal(b) |
| 360 | out.append(('random-%05d-%s' % (j, kind), b)) |
| 361 | return out |
| 362 | |
| 363 | |
| 364 | # ---------------------------------------------------------------- differential runner |
| 365 | |
| 366 | def run(argv, data): |
| 367 | r = subprocess.run([str(x) for x in argv], input=data, capture_output=True, timeout=30) |
| 368 | return r.returncode, r.stdout |
| 369 | |
| 370 | |
| 371 | def collect_imports(args): |
| 372 | """Every F1 import plus every F2 import of each importer present: (label, envelope).""" |
| 373 | out = [] |
| 374 | f1 = json.loads((ROOT / 'tests/universal/translation/fixtures-f1.json').read_text()) |
| 375 | tools = Path(args.tools) |
| 376 | for p in f1['positives']: |
| 377 | rc, env = run([tools / 'c-import'], p['source'].encode()) |
| 378 | if rc == 0: |
| 379 | out.append(('import-c-' + p['id'], env)) |
| 380 | else: |
| 381 | out.append(('import-c-FAILED-' + p['id'], None)) |
| 382 | for lang in ('rust', 'python', 'cpp', 'zig', 'go'): |
| 383 | path = ROOT / ('tests/universal/translation/fixtures-f2-%s.json' % lang) |
| 384 | imp = tools / ('%s-import' % lang) |
| 385 | if not path.is_file() or not imp.is_file(): |
| 386 | continue |
| 387 | d = json.loads(path.read_text()) |
| 388 | for p in d['positives'] + d.get('extra_positives', []) + d.get('controls', []): |
| 389 | rc, env = run([imp], p['source'].encode()) |
| 390 | out.append(('import-%s-%s' % (lang, p['id']), env if rc == 0 else None)) |
| 391 | return out |
| 392 | |
| 393 | |
| 394 | def main(): |
| 395 | ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) |
| 396 | ap.add_argument('--sa', required=True, help='native v2 codec binary (build/L832/sa)') |
| 397 | ap.add_argument('--sa-v1', help='frozen v1 codec binary (build/L574/sa): must refuse every v2 unit 66') |
| 398 | ap.add_argument('--tools', default=str(ROOT / 'tools/adapters'), help='directory of the public importers') |
| 399 | ap.add_argument('--random', type=int, default=4000) |
| 400 | ap.add_argument('--seed', default='623-v2-reference') |
| 401 | ap.add_argument('--out', required=True) |
| 402 | a = ap.parse_args() |
| 403 | out = Path(a.out).resolve() |
| 404 | out.mkdir(parents=True, exist_ok=False) |
| 405 | ev = {'schema': 'omega.universal.source-aware.v2-reference.v1', 'spec': {'path': SPEC[0], 'sha256': SPEC[1]}, |
| 406 | 'reference_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), |
| 407 | 'legality_mode_6': 'NOT_RUN: the per-operation reply is not specified byte for byte'} |
| 408 | spec = ROOT / SPEC[0] |
| 409 | if not spec.is_file() or hashlib.sha256(spec.read_bytes()).hexdigest() != SPEC[1] or not Path(a.sa).is_file(): |
| 410 | ev['result'] = 'NOT_RUN' |
| 411 | (out / 'evidence.json').write_text(json.dumps(ev, indent=1) + '\n') |
| 412 | print('NOT_RUN spec pin or codec absent') |
| 413 | return 3 |
| 414 | ev['sa_sha256'] = hashlib.sha256(Path(a.sa).read_bytes()).hexdigest() |
| 415 | ref = Ref(semantics_digest()) |
| 416 | imports = collect_imports(a) |
| 417 | ev['imports'] = {'total': len(imports), 'failed': [l for l, e in imports if e is None]} |
| 418 | valid = [(l, e) for l, e in imports if e is not None] |
| 419 | cases = list(valid) |
| 420 | for l, e in valid: |
| 421 | sem, _ = split(e) |
| 422 | cases += [('%s/R-%s' % (l, m), envelope(R(sem, m))) for m in MEMBERS] |
| 423 | seen = set() |
| 424 | # corner sweep on the F1-P05 import of each importer present (its own member, with its own sidecar); |
| 425 | # every value of every version byte on the C and Go imports |
| 426 | for lang in MEMBERS: |
| 427 | pick = next(((l, e) for l, e in valid if l.startswith('import-%s-' % lang) and l.endswith('P05')), None) |
| 428 | if pick: |
| 429 | cases += [('%s/%s' % (pick[0], n), b) for n, b in corner_cases(pick[1], lang in ('c', 'go'))] |
| 430 | # valid profile 3 and 6 units (ops 6/7/8) and division, checked by the section 5 step 6 rows |
| 431 | built = constructed_units(semantics_digest()) |
| 432 | cases += [('constructed-%s' % n, e) for n, e in built] |
| 433 | rng = random.Random(a.seed) |
| 434 | cases += random_mutations([e for _, e in valid] + [envelope(R(split(e)[0], m)) for _, e in valid for m in MEMBERS], |
| 435 | rng, a.random) |
| 436 | cases += [('constructed-' + n, b) for n, b in random_mutations([e for _, e in built], rng, a.random // 4)] |
| 437 | base = valid[0][1] |
| 438 | cases += [('mode-check', base)] |
| 439 | agree, dis, by_status = 0, [], {} |
| 440 | modes = [1, 2, 3, 4, 5] |
| 441 | v1rows = {'total': 0, 'agree': 0, 'disagree': []} |
| 442 | for label, b in cases: |
| 443 | # every mode for a unit the reference accepts; for a refused unit decode (2) and replay (5), |
| 444 | # whose status is the shared decode status |
| 445 | accepted = ref.decode(b)[0] == 0 |
| 446 | for mode in ([0, 7, 9, 255] if label == 'mode-check' else modes if accepted else [2, 5]): |
| 447 | want = ref.perform(mode, b) |
| 448 | got = run([a.sa], bytes([mode]) + b) |
| 449 | if got == want: |
| 450 | agree += 1 |
| 451 | by_status[want[0]] = by_status.get(want[0], 0) + 1 |
| 452 | else: |
| 453 | dis.append({'case': label, 'mode': mode, 'reference': [want[0], want[1].hex()[:96]], |
| 454 | 'native': [got[0], got[1].hex()[:96]], 'envelope_hex': b.hex()}) |
| 455 | if a.sa_v1 and len(b) > 17 and b[:5] == b'OMSB\x01' and ref.decode(b)[0] == 0 and b[17] == 2: |
| 456 | v1rows['total'] += 1 |
| 457 | got = run([a.sa_v1], b'\x02' + b) |
| 458 | if got == (66, b''): |
| 459 | v1rows['agree'] += 1 |
| 460 | else: |
| 461 | v1rows['disagree'].append({'case': label, 'status': got[0], 'stdout_bytes': len(got[1])}) |
| 462 | ev.update({'cases': len(cases), 'comparisons': agree + len(dis), 'agree': agree, 'disagree': len(dis), |
| 463 | 'agreements_by_status': {str(k): v for k, v in sorted(by_status.items())}, |
| 464 | 'v1_codec_refuses_v2_66': v1rows if a.sa_v1 else 'NOT_RUN', 'disagreements': dis[:400]}) |
| 465 | v1ok = not a.sa_v1 or not v1rows['disagree'] |
| 466 | ev['result'] = 'FAIL' if dis or not v1ok else 'PASS' |
| 467 | (out / 'evidence.json').write_text(json.dumps(ev, indent=1) + '\n') |
| 468 | print(json.dumps({k: ev[k] for k in ('result', 'cases', 'comparisons', 'agree', 'disagree', |
| 469 | 'agreements_by_status')}, indent=1)) |
| 470 | if a.sa_v1: |
| 471 | print('v1 codec refuses v2 with 66: %d/%d' % (v1rows['agree'], v1rows['total'])) |
| 472 | for d in dis[:20]: |
| 473 | print('DISAGREE', d['case'], 'mode', d['mode'], 'ref', d['reference'][0], 'native', d['native'][0]) |
| 474 | return 1 if ev['result'] == 'FAIL' else 0 |
| 475 | |
| 476 | |
| 477 | if __name__ == '__main__': |
| 478 | raise SystemExit(main()) |