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 / omc / diagnostics-v2.py

121 lines · 5724 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Independent diagnostic-v2 oracle; never part of the compiler."""
3import hashlib
4import json
5import os
6from pathlib import Path
7import re
8import subprocess
9import sys
10import tempfile
11
12root = Path(__file__).resolve().parents[2]
13compiler = Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else root / 'seed/out/omc'
14source = root / 'seed/omc/omc.om'
15text = source.read_text()
16pins = re.findall(r'^text d2pin "([0-9a-f]{64})"$', text, re.M)
17assert len(pins) == 1, 'source-pin-count'
18normalized = re.sub(r'^text d2pin "[0-9a-f]{64}"$', 'text d2pin "' + '0' * 64 + '"', text, flags=re.M)
19assert hashlib.sha256(normalized.encode()).hexdigest() == pins[0], 'source-pin-stale'
20sites = dict(re.findall(r'^note d2site (\d+)\|([^\n]+)$', text, re.M))
21assert len(sites) == len(re.findall(r'^note d2site ', text, re.M)), 'site-id-duplicate'
22lines = text.splitlines()
23function = ''
24for i, line in enumerate(lines):
25 if line.startswith('fn '):
26 function = line.split()[1]
27 if re.match(r'^(fail|nfail|unkfail) ', line):
28 if line == 'fail code' and function in ('nfail', 'unkfail'):
29 continue
30 assert re.fullmatch(r'put d2site 0 \d+', lines[i-1]), ('site-missing', i+1)
31 site = lines[i-1].split()[-1]
32 assert lines[i-2].startswith('note d2site ' + site + '|'), ('site-comment-mismatch', i+1)
33 assert site in sites, ('site-unregistered', site)
34
35env = os.environ.copy()
36env.pop('OMC_DIAGNOSTICS', None)
37env.pop('OMC_MEMORY_MAX', None)
38seen = set()
39rows = []
40def invoke(c, data, enabled=True, extra=None):
41 e = env.copy()
42 if enabled:
43 e['OMC_DIAGNOSTICS'] = '2'
44 e.update(extra or {})
45 return subprocess.run([str(c)], input=data, capture_output=True, env=e, timeout=30)
46def record(p, data):
47 found = re.findall(rb'^omc-diag 2 (.*)$', p.stderr, re.M)
48 assert len(found) == 1, 'record-count'
49 fields = dict(x.split(b'=', 1) for x in found[0].split())
50 assert int(fields[b'code']) == p.returncode, 'record-code'
51 n = int(fields[b'input_bytes'])
52 assert 0 <= n <= len(data), 'input-size'
53 assert fields[b'input_sha256'].decode() == hashlib.sha256(data[:n]).hexdigest(), 'input-hash'
54 assert fields[b'compiler_source_sha256'].decode() == pins[0], 'compiler-source-hash'
55 if fields[b'input_complete'] == b'1':
56 assert n == len(data), 'complete-size'
57 site = fields[b'site'].decode()
58 assert site.startswith('D') and site[1:] in sites, 'record-site'
59 seen.add(site[1:])
60 return fields
61def case(name, data, extra=None):
62 plain = invoke(compiler, data, False, extra)
63 rich = invoke(compiler, data, True, extra)
64 assert plain.returncode == rich.returncode, ('exit-parity', name)
65 assert plain.stdout == rich.stdout, ('stdout-parity', name)
66 if rich.returncode:
67 assert rich.returncode < 100, ('compiler-trap', name, rich.stderr)
68 fields = record(rich, data)
69 assert b'; ' in rich.stderr.splitlines()[0], ('human-reason', name)
70 else:
71 assert plain.stderr == rich.stderr, ('success-stderr-parity', name)
72 rows.append({'case': name, 'exit': rich.returncode})
73
74bad = b'fn main to int\nret missing\nend\n'
75good = b'fn main to int\nret 0\nend\n'
76for mode in (b'', b'om2\n', b'om2 diag\n', b'check\n', b'check span\n', b'usage\n', b'ir\n',
77 b'target x86linux\n', b'object\nom2\n'):
78 case('profile-' + repr(mode), mode + bad)
79case('good', good)
80# A failed check-record write must not recursively try stdout again.
81for prefix in (b'check\n', b''):
82 data = prefix + good
83 e = env.copy(); e['OMC_DIAGNOSTICS'] = '2'
84 with open('/dev/full','wb') as full:
85 result = subprocess.run([str(compiler)],input=data,stdout=full,stderr=subprocess.PIPE,env=e,timeout=10)
86 assert result.returncode == 2, result.stderr
87 record(result,data)
88 rows.append({"case": "stdout-refusal-" + repr(prefix), "exit": result.returncode})
89
90for n in (0, 1, 55, 56, 63, 64, 65, 4096, 65535, 65536, 65537, 131072):
91 case('sha-boundary-' + str(n), bad + b'note ' + b'x' * n + b'\n')
92case('environment-refusal', bad, {'OMC_MEMORY_MAX': 'bad'})
93case('partial-input', bad + b'note ' + b'x' * 300000 + b'\n', {'OMC_MEMORY_MAX': '1'})
94for fixture in sorted((root / 'seed/omc/sites').glob('*.om')):
95 case(fixture.relative_to(root).as_posix(), fixture.read_bytes())
96
97with tempfile.TemporaryDirectory(prefix='omc-d2-') as temp:
98 d = Path(temp)
99 # An actual broken compiler must be detected by the independent SHA oracle.
100 assert text.count('d2feed c\n') == 1, 'hash-mutant-site'
101 mutant = text.replace('d2feed c\n', 'd2feed 0\n')
102 p = invoke(compiler, mutant.encode(), False)
103 assert p.returncode == 0, ('mutant-build', p.stderr)
104 c = d / 'omc-no-hash'
105 c.write_bytes(p.stdout)
106 c.chmod(0o700)
107 p = invoke(c, bad)
108 try:
109 record(p, bad)
110 except AssertionError as error:
111 assert str(error) in ('complete-size', 'input-hash'), ('wrong-mutant-failure', str(error))
112 else:
113 raise AssertionError('hash-mutant-survived')
114report = {'schema': 1, 'verdict': 'PASS', 'compiler_sha256': hashlib.sha256(compiler.read_bytes()).hexdigest(),
115 'compiler_source_sha256': pins[0], 'cases': rows, 'sites_registered': len(sites),
116 'sites_exercised': sorted(seen, key=int), 'sites_not_exercised': sorted(set(sites)-seen, key=int),
117 'limits': 'Unexercised sites are not claimed covered; output is an explicit coverage inventory.'}
118out = root / 'build/seed/diagnostics-v2.json'
119out.parent.mkdir(parents=True, exist_ok=True)
120out.write_text(json.dumps(report, indent=2) + '\n')
121print('DIAGNOSTICS_V2 PASS cases=' + str(len(rows)) + ' sites=' + str(len(seen)) + '/' + str(len(sites)) + ' mutants=1')