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 / seed / qualification / om2 / current / qualify.py
| 1 | #!/usr/bin/env python3 |
| 2 | """External ABI/SHA qualification instrument; never part of Omega's runtime.""" |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import argparse |
| 6 | import hashlib |
| 7 | import json |
| 8 | import os |
| 9 | from pathlib import Path |
| 10 | import platform |
| 11 | import re |
| 12 | import shutil |
| 13 | import subprocess |
| 14 | import sys |
| 15 | |
| 16 | |
| 17 | class Failure(Exception): |
| 18 | pass |
| 19 | |
| 20 | |
| 21 | class NotRun(Failure): |
| 22 | pass |
| 23 | |
| 24 | |
| 25 | def digest(path: Path) -> str: |
| 26 | h = hashlib.sha256() |
| 27 | with path.open('rb') as f: |
| 28 | for block in iter(lambda: f.read(1048576), b''): |
| 29 | h.update(block) |
| 30 | return h.hexdigest() |
| 31 | |
| 32 | |
| 33 | class Qualification: |
| 34 | def __init__(self, root: Path, bridge: Path, out: Path): |
| 35 | self.root, self.bridge, self.out = root, bridge, out |
| 36 | self.report = {'schema': 1, 'scope': 'ABI/SHA external callers only', |
| 37 | 'verdict': 'NOT_RUN', 'commands': [], 'inputs': [], |
| 38 | 'cases': {}, 'controls': {}, |
| 39 | 'limits': ['Not the full RM7 gate or Omega 1.0 qualification.', |
| 40 | 'Leakage, all-language ABI-v2 traps and physical x86 are separate.']} |
| 41 | self.originals: list[tuple[Path, str]] = [] |
| 42 | self.tools: dict[str, str] = {} |
| 43 | self.save() |
| 44 | |
| 45 | def save(self): |
| 46 | temporary = self.out / 'result.json.tmp' |
| 47 | temporary.write_text(json.dumps(self.report, indent=2) + '\n') |
| 48 | temporary.replace(self.out / 'result.json') |
| 49 | |
| 50 | def run(self, tag, args, stdin=None, expected=0, extra_env=None, timeout=900): |
| 51 | stdout, stderr = self.out / (tag + '.stdout'), self.out / (tag + '.stderr') |
| 52 | command = [str(a) for a in args] |
| 53 | env = os.environ.copy() |
| 54 | # Unit generation must not inherit a caller's alternate unit list or destination. |
| 55 | for name in ('OMEGA_UNITS', 'OMEGA_UNITS_DEST', 'OMEGA_OMC', 'OMEGA_BRIDGE'): |
| 56 | env.pop(name, None) |
| 57 | env.update(extra_env or {}) |
| 58 | record = {'tag': tag, 'argv': command, 'cwd': str(self.root), |
| 59 | 'stdin': str(stdin) if stdin else None, |
| 60 | 'environment_overrides': extra_env or {}, |
| 61 | 'expected_exit': expected, 'exit': None} |
| 62 | self.report['commands'].append(record) |
| 63 | self.save() |
| 64 | with (Path(stdin).open('rb') if stdin else open(os.devnull, 'rb')) as inp, \ |
| 65 | stdout.open('wb') as out, stderr.open('wb') as err: |
| 66 | try: |
| 67 | p = subprocess.run(command, cwd=self.root, env=env, stdin=inp, |
| 68 | stdout=out, stderr=err, timeout=timeout) |
| 69 | record['exit'] = p.returncode |
| 70 | except (OSError, subprocess.TimeoutExpired) as e: |
| 71 | record['error'] = str(e) |
| 72 | self.save() |
| 73 | raise NotRun(f'{tag}: {e}') from e |
| 74 | record.update(stdout=str(stdout), stdout_sha256=digest(stdout), |
| 75 | stderr=str(stderr), stderr_sha256=digest(stderr)) |
| 76 | self.save() |
| 77 | if p.returncode != expected: |
| 78 | raise Failure(f'{tag}: exit {p.returncode}, expected {expected}; see {stderr}') |
| 79 | return stdout |
| 80 | |
| 81 | def require(self, condition, message): |
| 82 | if not condition: |
| 83 | raise Failure(message) |
| 84 | |
| 85 | def snapshot(self, path: Path, relative: str) -> Path: |
| 86 | if not path.is_file(): |
| 87 | raise NotRun(f'missing input: {path}') |
| 88 | target = self.out / 'inputs' / relative |
| 89 | target.parent.mkdir(parents=True, exist_ok=True) |
| 90 | shutil.copyfile(path, target) |
| 91 | sha = digest(target) |
| 92 | self.originals.append((path, sha)) |
| 93 | self.report['inputs'].append({'path': str(path), 'snapshot': str(target), 'sha256': sha}) |
| 94 | self.save() |
| 95 | return target |
| 96 | |
| 97 | def compile(self, tag: str, source: Path) -> Path: |
| 98 | target = self.run(tag, [self.omc], stdin=source) |
| 99 | target.chmod(0o700) |
| 100 | return target |
| 101 | |
| 102 | def frame(self, name: str, source: Path) -> bytes: |
| 103 | code = self.compile('compile-' + name, source).read_bytes() |
| 104 | self.require(len(code) < 100000000, 'artifact exceeds the native framing 8-digit length field') |
| 105 | src = source.read_bytes() |
| 106 | first = next((line.strip() for line in src.decode().splitlines() |
| 107 | if line.strip() and not re.match(r'^\s*note(?:\s|$)', line)), '') |
| 108 | self.require(first == 'om2' or name == 'abi1', f'unsupported fixture profile: {name}') |
| 109 | metadata = b'' if name == 'abi1' else f'omega-unit {name} {self.pin}\n'.encode() |
| 110 | return src + b'\0' + f'{len(code):08d}'.encode() + code + metadata |
| 111 | |
| 112 | def generated(self, tag, mode, frame, target): |
| 113 | got = self.run(tag, [self.native, mode], stdin=frame) |
| 114 | shutil.copyfile(got, target) |
| 115 | return target |
| 116 | |
| 117 | def record_case(self, name, evidence): |
| 118 | self.require(name not in self.report['cases'], f'duplicate case: {name}') |
| 119 | self.report['cases'][name] = {'verdict': 'PASS', 'evidence': evidence} |
| 120 | self.save() |
| 121 | |
| 122 | def caller_cases(self, source, output): |
| 123 | expected = re.findall(r'check\("([^"\n]+)"', source.read_text()) |
| 124 | self.require(len(expected) == len(set(expected)), f'duplicate oracle case in {source}') |
| 125 | observed = re.findall(r'^(PASS|FAIL) ((?:abi|sha)-\S+) ', output.read_text(), re.M) |
| 126 | self.require(len(observed) == len(expected), f'incomplete or duplicated caller output: {output}') |
| 127 | self.require({name for _, name in observed} == set(expected), f'caller case set differs: {output}') |
| 128 | for status, name in observed: |
| 129 | self.require(status == 'PASS', f'{name} failed in {output}') |
| 130 | self.record_case(name, output.name) |
| 131 | |
| 132 | def control(self, name, evidence): |
| 133 | self.report['controls'][name] = {'verdict': 'PASS', 'evidence': evidence} |
| 134 | self.save() |
| 135 | |
| 136 | def execute(self): |
| 137 | if not self.bridge.is_dir(): |
| 138 | raise NotRun(f"missing bridge checkout: {self.bridge}") |
| 139 | for tool in ('git', 'cc', 'nm', 'sh'): |
| 140 | found = shutil.which(tool) |
| 141 | if not found: |
| 142 | raise NotRun(f'missing qualification tool: {tool}') |
| 143 | self.tools[tool] = found |
| 144 | self.report['platform'] = {'uname': list(platform.uname()), 'python': sys.version, |
| 145 | 'python_executable': sys.executable} |
| 146 | if platform.system() != 'Linux' or platform.machine() not in ('aarch64', 'arm64'): |
| 147 | raise NotRun('this native caller instrument requires Linux AArch64') |
| 148 | self.run('source-clean', [self.tools['git'], 'diff', '--quiet', 'HEAD', '--']) |
| 149 | self.run('bridge-clean', [self.tools['git'], '-C', self.bridge, 'diff', '--quiet', 'HEAD', '--']) |
| 150 | source_head = self.run('source-head', [self.tools['git'], 'rev-parse', 'HEAD']).read_text().strip() |
| 151 | bridge_head = self.run('bridge-head', [self.tools['git'], '-C', self.bridge, 'rev-parse', 'HEAD']).read_text().strip() |
| 152 | lock_lines = [line.strip() for line in (self.root/'om/omega-bridge.lock').read_text().splitlines() |
| 153 | if line.strip() and not line.startswith('#')] |
| 154 | self.require(len(lock_lines) == 1 and re.fullmatch(r'[0-9a-f]{40}', lock_lines[0]) is not None, |
| 155 | 'invalid om/omega-bridge.lock') |
| 156 | if bridge_head != lock_lines[0]: |
| 157 | raise NotRun(f'bridge checkout {bridge_head} does not match lock {lock_lines[0]}') |
| 158 | self.report.update(source_head=source_head, bridge_head=bridge_head) |
| 159 | self.run('cc-version', [self.tools['cc'], '--version']) |
| 160 | self.run('nm-version', [self.tools['nm'], '--version']) |
| 161 | relative = [ |
| 162 | 'seed/out/omc', 'om/units.sh', 'om/omega-bridge.lock', |
| 163 | 'seed/qualification/om2/current/qualify.py', |
| 164 | 'seed/qualification/om2/sec/s5s7/candidate.cases', |
| 165 | 'seed/qualification/om2/oracle/s5s7/abi/driver.c', |
| 166 | 'seed/qualification/om2/oracle/s5s7/abi/v1link.c', |
| 167 | 'seed/qualification/om2/oracle/s5s7/sha/sha_driver.c', |
| 168 | 'seed/qualification/om2/oracle/s5s7/sha/expected.h', |
| 169 | ] |
| 170 | relative += [f'seed/qualification/om2/sec/s5s7/abi/{n}.om' for n in ('abiv','abiw','abi1')] |
| 171 | # Snapshot the source closure consumed by the existing unit generator, including its defaults. |
| 172 | omfiles = self.run('om-files', [self.tools['git'], 'ls-files', '-z', 'om']).read_bytes().split(b'\0') |
| 173 | relative += [os.fsdecode(name) for name in omfiles if name] |
| 174 | relative += ['src/' + name for name in ('omega_om_units.c','omega_om_units_fs.c', |
| 175 | 'omega_native.h','omega_api_decl.h','omega_om_units.ident')] |
| 176 | self.inputs = {name: self.snapshot(self.root/name, 'omega/'+name) for name in sorted(set(relative))} |
| 177 | native_source = self.snapshot(self.bridge/'src/native.om', 'bridge/src/native.om') |
| 178 | self.omc = self.inputs['seed/out/omc'] |
| 179 | self.omc.chmod(0o700) |
| 180 | self.pin = digest(self.omc) |
| 181 | self.report['compiler_sha256'] = self.pin |
| 182 | self.native = self.compile('native-build', native_source) |
| 183 | self.abi_and_sha() |
| 184 | self.unit_identity_controls() |
| 185 | declarations = re.findall(r'^((?:abi|sha)-\S+) notrun ', |
| 186 | self.inputs['seed/qualification/om2/sec/s5s7/candidate.cases'].read_text(), re.M) |
| 187 | self.require(len(declarations) == len(set(declarations)), 'duplicate external case declaration') |
| 188 | self.require(set(declarations) == set(self.report['cases']), |
| 189 | 'external declaration inventory differs from exercised cases') |
| 190 | for path, sha in self.originals: |
| 191 | self.require(digest(path) == sha, f'input changed during qualification: {path}') |
| 192 | self.run('source-clean-final', [self.tools['git'], 'diff', '--quiet', 'HEAD', '--']) |
| 193 | final_head = self.run('source-head-final', [self.tools['git'], 'rev-parse', 'HEAD']).read_text().strip() |
| 194 | self.require(final_head == source_head, 'source HEAD changed during qualification') |
| 195 | self.report['artifacts'] = [ |
| 196 | {'path': p.relative_to(self.out).as_posix(), 'sha256': digest(p)} |
| 197 | for p in sorted(self.out.rglob('*')) |
| 198 | if p.is_file() and p.name not in ('result.json', 'result.json.tmp') |
| 199 | ] |
| 200 | self.report['verdict'] = 'PASS' |
| 201 | self.save() |
| 202 | print(f'ABI_SHA_GATE PASS cases={len(self.report["cases"])} controls={len(self.report["controls"])} ' |
| 203 | f'source={source_head} compiler={self.pin} result={self.out / "result.json"}') |
| 204 | |
| 205 | def abi_and_sha(self): |
| 206 | src = 'seed/qualification/om2/' |
| 207 | abi = {n:self.inputs[src+f'sec/s5s7/abi/{n}.om'] for n in ('abiv','abiw','abi1')} |
| 208 | frame = self.out/'abi.in' |
| 209 | frame.write_bytes(b''.join(self.frame(n, p) for n,p in abi.items())) |
| 210 | c = self.generated('abi-c', 'c', frame, self.out/'abi.c') |
| 211 | lib = self.out/'libabi.so' |
| 212 | self.run('abi-library', [self.tools['cc'],'-std=gnu11','-O2','-Wall','-Wextra','-Werror', |
| 213 | '-fPIC','-shared',c,'-o',lib]) |
| 214 | driver = self.inputs[src+'oracle/s5s7/abi/driver.c'] |
| 215 | exe = self.out/'abi-driver' |
| 216 | self.run('abi-driver-build',[self.tools['cc'],'-std=gnu11','-O2','-Wall','-Wextra','-Werror',driver, |
| 217 | '-L'+str(self.out),'-labi','-Wl,-rpath,'+str(self.out),'-o',exe]) |
| 218 | sha_v, sha_w = digest(abi['abiv']), digest(abi['abiw']) |
| 219 | output = self.run('abi-driver',[exe,sha_v,sha_w,self.pin]) |
| 220 | self.caller_cases(driver, output) |
| 221 | symbols = self.run('abi-symbols',[self.tools['nm'],'-D','--defined-only',lib]) |
| 222 | names = {line.split()[-1] for line in symbols.read_text().splitlines() if line.split()} |
| 223 | self.require('omega2_vsum' in names and 'omega_vsum' not in names, 'ABI v2/v1 symbol boundary failed') |
| 224 | self.run('abi-v1-link',[self.tools['cc'],self.inputs[src+'oracle/s5s7/abi/v1link.c'], |
| 225 | '-L'+str(self.out),'-labi','-o',self.out/'v1-link'],expected=1) |
| 226 | error = (self.out/'abi-v1-link.stderr').read_text() |
| 227 | self.require('undefined reference' in error and 'omega_vsum' in error, 'link control failed for another reason') |
| 228 | self.record_case('abi-v1-absent','abi-v1-link.stderr; abi-symbols.stdout') |
| 229 | self.require('omega_madd1' in names and 'omega2_ident_abi1' not in names, 'OM-1 symbol boundary failed') |
| 230 | self.record_case('abi-v1-kept','abi-symbols.stdout') |
| 231 | program = ('import ctypes,sys; l=ctypes.CDLL(sys.argv[1]); f=l.omega2_vcnt; ' |
| 232 | 'f.argtypes=[ctypes.POINTER(ctypes.c_uint64),ctypes.c_void_p,ctypes.c_uint64]; ' |
| 233 | 'f.restype=ctypes.c_uint32; r=ctypes.c_uint64(123); ' |
| 234 | 's=f(ctypes.byref(r),ctypes.c_void_p(1),0); print(s,r.value); ' |
| 235 | 'sys.exit(0 if s==0 and r.value==0 else 1)') |
| 236 | empty = self.run('abi-empty-misaligned',[sys.executable,'-c',program,lib]) |
| 237 | self.require(empty.read_bytes() == b'0 0\n', 'empty misaligned view did not return status/result zero') |
| 238 | self.record_case('abi-misaligned-len0',empty.name) |
| 239 | wrong = self.run('control-wrong-compiler-identity',[exe,sha_v,sha_w,'0'*64],expected=1) |
| 240 | self.require('FAIL abi-ident-abiv ' in wrong.read_text() and 'FAIL abi-ident-abiw ' in wrong.read_text(), |
| 241 | 'wrong-identity control did not reach both identity assertions') |
| 242 | self.control('wrong-compiler-identity',wrong.name) |
| 243 | wrong = self.run('control-wrong-source-identity',[exe,'0'*64,sha_w,self.pin],expected=1) |
| 244 | self.require('FAIL abi-ident-abiv ' in wrong.read_text(), 'wrong-source control did not reach identity assertion') |
| 245 | self.control('wrong-source-identity',wrong.name) |
| 246 | frame = self.out/'sha.in' |
| 247 | frame.write_bytes(self.frame('sha256',self.inputs['om/sha256/sha256-om2.om'])) |
| 248 | c = self.generated('sha-c','c',frame,self.out/'sha.c') |
| 249 | api = self.generated('sha-api','apic',frame,self.out/'sha-api.c') |
| 250 | self.generated('sha-native-header','h',frame,self.out/'omega_native.h') |
| 251 | self.generated('sha-api-header','apih',frame,self.out/'omega_api_decl.h') |
| 252 | driver = self.inputs[src+'oracle/s5s7/sha/sha_driver.c'] |
| 253 | exe = self.out/'sha-driver' |
| 254 | cc = [self.tools['cc'],'-std=gnu11','-O2','-Wall','-Wextra','-Werror', |
| 255 | '-DGENHDR="omega_api_decl.h"','-I'+str(self.out)] |
| 256 | self.run('sha-driver-build',cc+[driver,c,api,'-o',exe]) |
| 257 | output = self.run('sha-driver',[exe,'big']) |
| 258 | self.caller_cases(driver,output) |
| 259 | # A wrong independent digest must be rejected by the same caller and generated library. |
| 260 | bad = self.out/'wrong-sha-oracle' |
| 261 | bad.mkdir() |
| 262 | shutil.copyfile(driver,bad/'sha_driver.c') |
| 263 | expected = self.inputs[src+'oracle/s5s7/sha/expected.h'].read_text() |
| 264 | match = re.search(r'(#define EXP_EMPTY\s+")([0-9a-f])',expected) |
| 265 | self.require(match is not None,'cannot locate the independent empty SHA digest') |
| 266 | pos = match.start(2) |
| 267 | (bad/'expected.h').write_text(expected[:pos]+('1' if expected[pos]=='0' else '0')+expected[pos+1:]) |
| 268 | self.run('control-sha-build',cc+[bad/'sha_driver.c',c,api,'-o',bad/'driver']) |
| 269 | wrong = self.run('control-sha-digest',[bad/'driver'],expected=1) |
| 270 | self.require('FAIL sha-empty ' in wrong.read_text(),'wrong SHA oracle did not fail its digest assertion') |
| 271 | self.control('wrong-sha-digest',wrong.name) |
| 272 | |
| 273 | def unit_identity_controls(self): |
| 274 | stage = self.out/'units-check' |
| 275 | for relative, source in self.inputs.items(): |
| 276 | if relative.startswith(('om/','src/')): |
| 277 | target = stage/relative |
| 278 | target.parent.mkdir(parents=True,exist_ok=True) |
| 279 | shutil.copyfile(source,target) |
| 280 | bridge = self.out/'inputs/bridge' |
| 281 | env = {'OMEGA_OMC':str(self.omc),'OMEGA_BRIDGE':str(bridge)} |
| 282 | # Test the existing identity checker on candidate-generated bindings. Only its |
| 283 | # compiler identity literal changes, mechanically derived from the snapshot. |
| 284 | # Canonical source/pins/generated outputs are never edited by this instrument. |
| 285 | script = stage/'om/units.sh' |
| 286 | original = script.read_text() |
| 287 | pins = re.findall(r'^OMC_PIN=([0-9a-f]{64})$', original, re.M) |
| 288 | self.require(len(pins) == 1, 'unit checker compiler-pin declaration changed') |
| 289 | projected, count = re.subn(r'^OMC_PIN=[0-9a-f]{64}$', |
| 290 | 'OMC_PIN=' + self.pin, original, flags=re.M) |
| 291 | self.require(count == 1, 'unit checker pin projection must match exactly once') |
| 292 | script.write_text(projected) |
| 293 | self.report['unit_checker_projection'] = { |
| 294 | 'original_compiler_pin': pins[0], 'candidate_compiler_pin': self.pin, |
| 295 | 'original_script_sha256': hashlib.sha256(original.encode()).hexdigest(), |
| 296 | 'projected_script_sha256': digest(script), |
| 297 | 'change': 'Only OMC_PIN is derived from the candidate compiler; checker logic unchanged.', |
| 298 | 'canonical_binding_check': 'NOT_RUN: this check uses freshly generated candidate bindings.' |
| 299 | } |
| 300 | self.save() |
| 301 | self.run('units-generate-candidate',[self.tools['sh'],script],extra_env=env) |
| 302 | command = [self.tools['sh'],script,'--check'] |
| 303 | self.run('units-baseline',command,extra_env=env) |
| 304 | source = stage/'om/sha256/sha256-om2.om' |
| 305 | before = source.read_bytes() |
| 306 | source.write_bytes(before+b'\nnote Qualification control: source identity changed.\n') |
| 307 | output = self.run('units-stale-source',command,expected=1,extra_env=env) |
| 308 | self.require('differs from the pinned tools' in output.read_text(),'stale-source refusal missing') |
| 309 | self.record_case('abi-units-stale-source',output.name) |
| 310 | source.write_bytes(before) |
| 311 | output = self.run('units-stale-omc',command,expected=3, |
| 312 | extra_env=dict(env,OMEGA_OMC=str(self.native))) |
| 313 | self.require('omc is not the pinned compiler' in output.read_text(),'stale-compiler refusal missing') |
| 314 | self.record_case('abi-units-stale-omc',output.name) |
| 315 | ident = stage/'src/omega_om_units.ident' |
| 316 | before = ident.read_text() |
| 317 | self.require('profile=OM-2' in before,'missing profile control target') |
| 318 | ident.write_text(before.replace('profile=OM-2','profile=OM-1',1)) |
| 319 | output = self.run('units-stale-profile',command,expected=1,extra_env=env) |
| 320 | self.require('omega_om_units.ident differs' in output.read_text(),'stale-profile refusal missing') |
| 321 | self.record_case('abi-units-stale-profile',output.name) |
| 322 | |
| 323 | |
| 324 | def main(): |
| 325 | parser = argparse.ArgumentParser(description=__doc__) |
| 326 | parser.add_argument('--bridge',type=Path,required=True,help='clean checkout at om/omega-bridge.lock') |
| 327 | parser.add_argument('--output',type=Path,required=True,help='new evidence directory, never overwritten') |
| 328 | args = parser.parse_args() |
| 329 | root = Path(__file__).resolve().parents[4] |
| 330 | output = args.output.resolve() |
| 331 | try: |
| 332 | output.mkdir(mode=0o700,parents=True,exist_ok=False) |
| 333 | except OSError as e: |
| 334 | print(f'ABI_SHA_GATE NOT_RUN: evidence directory must be new: {e}',file=sys.stderr) |
| 335 | return 3 |
| 336 | q = Qualification(root,args.bridge.resolve(),output) |
| 337 | try: |
| 338 | q.execute() |
| 339 | return 0 |
| 340 | except (Failure,KeyboardInterrupt) as e: |
| 341 | not_run = isinstance(e,(NotRun,KeyboardInterrupt)) |
| 342 | q.report['verdict'] = 'NOT_RUN' if not_run else 'FAIL' |
| 343 | q.report['error'] = str(e) or 'interrupted' |
| 344 | q.save() |
| 345 | print(f'ABI_SHA_GATE {q.report["verdict"]}: {q.report["error"]}; result={output / "result.json"}',file=sys.stderr) |
| 346 | return 3 if not_run else 1 |
| 347 | except Exception as e: |
| 348 | q.report.update(verdict='FAIL',error=f'{type(e).__name__}: {e}') |
| 349 | q.save() |
| 350 | print(f'ABI_SHA_GATE FAIL: {q.report["error"]}; result={output / "result.json"}',file=sys.stderr) |
| 351 | return 1 |
| 352 | |
| 353 | |
| 354 | if __name__ == '__main__': |
| 355 | sys.exit(main()) |