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 / json / tests / growing.py

194 lines · 10842 bytes Raw Blame History
1#!/usr/bin/env python3
2# Test instrument and independent CPython float/serializer oracle. Never a product dependency.
3def gate_require(condition, detail):
4 if not condition:
5 raise RuntimeError(detail)
6
7import argparse
8import hashlib
9from pathlib import Path
10import random
11import struct
12import subprocess
13import sys
14sys.dont_write_bytecode = True
15import field
16
17p=argparse.ArgumentParser()
18p.add_argument('omc');p.add_argument('out')
19p.add_argument('--wrong-expectation', action='store_true')
20a=p.parse_args()
21j=Path(__file__).resolve().parent.parent
22out=Path(a.out).resolve();out.mkdir(parents=True,exist_ok=True)
23omc=str(Path(a.omc).resolve())
24units={u:(j/u).read_text() for u in ('json.om','jsonw.om','jsonf.om')}
25driver=(j/'tests/big.om').read_text()
26
27def build(name,u):
28 d=out/name;d.mkdir(exist_ok=True)
29 source='om2\n'+''.join(u.values())+driver
30 (d/'big.om').write_text(source)
31 r=subprocess.run([omc],input=source.encode(),stdout=subprocess.PIPE,stderr=subprocess.PIPE)
32 (d/'big.err').write_bytes(r.stderr)
33 gate_require(r.returncode==0, (name,r.returncode,r.stderr))
34 binary=d/'big';binary.write_bytes(r.stdout);binary.chmod(0o700)
35 return binary
36
37def run(binary,mode,data,want,args=(),rc=0):
38 r=subprocess.run([str(binary),mode,*map(str,args)],input=data,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=60)
39 ok=r.returncode==rc and r.stdout==want
40 if not ok:
41 print('MISMATCH mode='+mode+' bytes='+str(len(data))+' status='+str(r.returncode)+' got='+repr(r.stdout[:100])+' want='+repr(want[:100]),flush=True)
42 return ok
43
44big=build('real',units)
45checks=0
46# Preserve the original 4 MiB workflow-body case, not merely a whitespace-only size probe.
47import json
48workflow=json.dumps({'version':'v1','jobs':{'j':{'image':{'uri':'docker://alpine'},'script':'x'*(4194304-200)}}}).encode()
49workflow += b' '*(4194304-len(workflow))
50gate_require(len(workflow)==4194304, 'gate condition failed')
51r=subprocess.run([str(big),'p'],input=workflow,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=60)
52gate_require(r.returncode==0 and r.stdout.startswith(b'OK '), (r.returncode,r.stdout))
53gate_require(run(big,'p',workflow+b'x',b'',rc=93), 'gate condition failed')
54checks+=2
55print('PASS growing/workflow 4194304 bytes; appended x=93',flush=True)
56# Reader at its presently reachable caller-local boundary, and one byte past it.
57body=b'0'+b' '*4194303
58gate_require(run(big,'p',body,b'OK 2\n' if a.wrong_expectation else b'OK 1\n'), 'reader expectation mismatch');checks+=1
59gate_require(run(big,'p',body,b'ERR 5 4194303\n',[4194303]), 'gate condition failed');checks+=1
60gate_require(run(big,'p',body+b'x',b'',rc=93), 'gate condition failed');checks+=1
61# The kernel read error is not an EOF and not an overflow (directory fd as stdin).
62fd=__import__('os').open(str(j),__import__('os').O_RDONLY)
63try:
64 r=subprocess.run([str(big),'p'],stdin=fd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=30)
65 gate_require(r.returncode==90 and not r.stdout, (r.returncode,r.stdout))
66finally:
67 __import__('os').close(fd)
68checks+=1
69# EOF without input reaches the reader's EOF refusal, not the I/O error path.
70gate_require(run(big,'p',b'',b'ERR 1 0\n'), 'gate condition failed');checks+=1
71print('PASS growing/reader 4194304 bytes; trailing x=93; read-error=90; EOF=ERR1',flush=True)
72number=b'1'+b'0'*1000000
73raw=b'x'*1000001
74for mode,data,want in [('n',number,number),('s',raw,b'"'+raw+b'"')]:
75 gate_require(run(big,mode,data,want), 'gate condition failed');checks+=1
76 gate_require(run(big,mode,data,b'WERR 21\n',[1056]), 'gate condition failed');checks+=1
77# The reader+token writer path also traverses >1000000 bytes in both consumers.
78for data in (number,b'"'+raw+b'"'):
79 gate_require(run(big,'r',data,data), 'gate condition failed');checks+=1
80 gate_require(run(big,'r',data,b'WERR 21\n',[1056]), 'gate condition failed');checks+=1
81gate_require(run(big,'n',b'',b'WERR 24\n'), 'gate condition failed');checks+=1
82print('PASS growing/writer number/raw/token rewrite above 983040 bytes; short outputs=21',flush=True)
83
84balanced=b'1'+b'0'*1000000+b'e-1000000'
85fractional=b'0.'+b'0'*999999+b'1e1000000'
86# Deterministic independent oracle: long significant mantissas, cancellation in both directions,
87# signed values, finite/subnormal/overflow, and exponent tokens with many leading zeroes.
88rng=random.Random(78803)
89lexemes=[balanced,fractional,b'-'+balanced,b'-'+fractional]
90for i in range(32):
91 n=rng.randint(10001,180000)
92 digits=bytes([rng.randrange(49,58)])+bytes(rng.randrange(48,58) for _ in range(n-1))
93 shift=rng.randint(-345,325)
94 if i%2:
95 lex=b'0.'+b'0'*n+digits+b'e'+str(n+shift).encode()
96 else:
97 lex=digits+b'e'+str(-n+shift).encode()
98 if i%3==0:
99 lex=b'-'+lex
100 lexemes.append(lex)
101lexemes += [b'1e'+b'0'*1000001+b'1', b'1e-'+b'0'*1000001+b'1', b'1e'+b'9'*1000001,b'1e-'+b'9'*1000001]
102# Exact rounding midpoints, not rounded decimal approximations. The independent CPython oracle
103# consumes balanced million-digit encodings on both sides of, and exactly at, each midpoint.
104from decimal import Decimal, localcontext
105threshold_labels={}
106with localcontext() as ctx:
107 ctx.prec=4096 # test-only exact decimal work room, above all finite decimal expansions here
108 two=Decimal(2)
109 epsilon=Decimal(10)**-1200
110 thresholds=[('zero-minsubnormal',two**-1075),
111 ('subnormal-normal',two**-1022-two**-1075),
112 ('finite-overflow',two**1024-two**970)]
113 for name,middle in thresholds:
114 for side in (-1,0,1):
115 value=middle+side*epsilon
116 parts=value.as_tuple()
117 digits=bytes(d+48 for d in parts.digits)
118 for form in ('integer','fractional'):
119 if form=='integer':
120 lex=digits+b'0'*1000000+b'e'+str(parts.exponent-1000000).encode()
121 else:
122 lex=b'0.'+b'0'*1000000+digits+b'e'+str(parts.exponent+1000000+len(digits)).encode()
123 for sign in (b'',b'-'):
124 threshold_labels[len(lexemes)]=name+'/'+str(side)+'/'+form+'/'+('negative' if sign else 'positive')
125 lexemes.append(sign+lex)
126for index,lex in enumerate(lexemes):
127 x=float(lex)
128 bits=struct.pack('>d',x).hex().encode()
129 inf=bits in (b'7ff0000000000000',b'fff0000000000000')
130 want=b'F '+(b'1' if inf else b'0')+b' '+bits+b' '+(b'WERR 24' if inf else repr(x).encode())+b'\n'
131 gate_require(run(big,'f',lex,want), (index,len(lex)))
132 print('PASS growing/float case='+str(index)+' label='+threshold_labels.get(index,'corpus')+' bytes='+str(len(lex))+' sha256='+hashlib.sha256(lex).hexdigest()+' oracle='+want.decode().strip(),flush=True)
133 checks+=1
134
135gate_require(not field.check(omc,out/'field',units), 'gate condition failed')
136checks+=len(field.field_cases())
137# Each defect has a compiling, behaviorally killed control. Mutations are test-only source twins.
138mutants=0
139for label,filename,old,new,mode,data,want,args in [
140 ('copy-loop','jsonw.om','for i ulong sub e p bound 9223372036854775807','for i ulong sub e p','n',number,number,()),
141 ('string-loop','jsonw.om','for i ulong n bound 9223372036854775807','for i ulong n','s',raw,b'"'+raw+b'"',()),
142 ('exponent-saturation','jsonf.om','lim = add lim 331','lim = long 10000','f',balanced,b'F 0 3ff0000000000000 1.0\n',()),
143 ('driver-prefix','driver','k = read 0 x 0 1\nif lt k 0','k = long 0\nif lt k 0','p',body+b'x',b'',()),
144]:
145 twin=dict(units)
146 olddriver=driver
147 if filename=='driver':
148 gate_require(driver.count(old)==1, 'gate condition failed');driver=driver.replace(old,new)
149 else:
150 gate_require(twin[filename].count(old)==1, (label,twin[filename].count(old)))
151 twin[filename]=twin[filename].replace(old,new)
152 mutant=build(label,twin)
153 driver=olddriver
154 expected_rc=93 if label=='driver-prefix' else 0
155 gate_require(not run(mutant,mode,data,want,args,expected_rc), 'survived '+label)
156 print('PASS growing/mutant '+label+' caught',flush=True);mutants+=1
157# Exhaustion must avoid reading the PROT_NONE tail even with an admitted million-byte source view.
158for label,old in [('copy-stop','if ne get ob jswerr 0\nret\nend\njs_wb ob get s add p i'),('string-stop','if ne get ob jswerr 0\nret\nend\njs_wsb ob get s add off i')]:
159 twin=dict(units);gate_require(twin['jsonw.om'].count(old)==1, 'gate condition failed')
160 twin['jsonw.om']=twin['jsonw.om'].replace(old,old.split('\nend\n',1)[1])
161 failures=field.check(omc,out/label,twin,large_scans=False)
162 gate_require(('stop-copy' if label=='copy-stop' else 'stop-string') in failures, 'survived '+label)
163 print('PASS growing/mutant '+label+' caught',flush=True);mutants+=1
164for label,filename,old,new in [
165 ('preflight-narrow','json.om','js_hs tape jshn 0','js_hs tape jshn n'),
166 ('sentinel','jsonw.om','if eq e 0','if eq e jsnone'),
167]:
168 twin=dict(units);gate_require(twin[filename].count(old)==1, 'gate condition failed')
169 twin[filename]=twin[filename].replace(old,new)
170 if label=='sentinel':
171 start=twin[filename].index('fn js_numend ');end=twin[filename].index('\nfn js_wcopy',start)
172 twin[filename]=twin[filename][:start]+twin[filename][start:end].replace('ret 0','ret jsnone')+twin[filename][end:]
173 twin['jsonf.om']=twin['jsonf.om'].replace('if eq js_numend src off n 0','if eq js_numend src off n jsnone')
174 failures=field.check(omc,out/label,twin,large_scans=False)
175 gate_require(('parse-above' if label=='preflight-narrow' else 'float') in failures, 'survived '+label)
176 print('PASS growing/mutant '+label+' caught',flush=True);mutants+=1
177# Restore the original escape sentinel independently in reader and writer consumers.
178for label,filename,begin,endmarker,callold,callnew in [
179 ('reader-escape-sentinel','json.om','fn js_uesc ','\nfn js_strtok ',
180 'p = js_escape src tape p\nif eq p 0','p = js_escape src tape p\nif eq p jsnone'),
181 ('writer-escape-sentinel','jsonw.om','fn js_wsesc ','\nfn js_wsrc ',
182 'p = js_wsesc ob src p\nif eq p 0','p = js_wsesc ob src p\nif eq p jsnone'),
183]:
184 twin=dict(units)
185 start=twin[filename].index(begin)
186 end=twin[filename].index(endmarker,start)
187 twin[filename]=twin[filename][:start]+twin[filename][start:end].replace('ret 0','ret jsnone')+twin[filename][end:]
188 gate_require(twin[filename].count(callold)==1,'escape caller mutation is not unique')
189 twin[filename]=twin[filename].replace(callold,callnew)
190 failures=field.check(omc,out/label,twin,large_scans=(label=='reader-escape-sentinel'))
191 gate_require(('esc' if label=='reader-escape-sentinel' else 'wsrc') in failures,'survived '+label)
192 print('PASS growing/mutant '+label+' caught',flush=True);mutants+=1
193print('GROWING PASS checks='+str(checks)+' float-oracle='+str(len(lexemes))+' mutants='+str(mutants),flush=True)
194