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 / json / tests / growing.py
| 1 | #!/usr/bin/env python3 |
| 2 | # Test instrument and independent CPython float/serializer oracle. Never a product dependency. |
| 3 | def gate_require(condition, detail): |
| 4 | if not condition: |
| 5 | raise RuntimeError(detail) |
| 6 | |
| 7 | import argparse |
| 8 | import hashlib |
| 9 | from pathlib import Path |
| 10 | import random |
| 11 | import struct |
| 12 | import subprocess |
| 13 | import sys |
| 14 | sys.dont_write_bytecode = True |
| 15 | import field |
| 16 | |
| 17 | p=argparse.ArgumentParser() |
| 18 | p.add_argument('omc');p.add_argument('out') |
| 19 | p.add_argument('--wrong-expectation', action='store_true') |
| 20 | a=p.parse_args() |
| 21 | j=Path(__file__).resolve().parent.parent |
| 22 | out=Path(a.out).resolve();out.mkdir(parents=True,exist_ok=True) |
| 23 | omc=str(Path(a.omc).resolve()) |
| 24 | units={u:(j/u).read_text() for u in ('json.om','jsonw.om','jsonf.om')} |
| 25 | driver=(j/'tests/big.om').read_text() |
| 26 | |
| 27 | def 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 | |
| 37 | def 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 | |
| 44 | big=build('real',units) |
| 45 | checks=0 |
| 46 | # Preserve the original 4 MiB workflow-body case, not merely a whitespace-only size probe. |
| 47 | import json |
| 48 | workflow=json.dumps({'version':'v1','jobs':{'j':{'image':{'uri':'docker://alpine'},'script':'x'*(4194304-200)}}}).encode() |
| 49 | workflow += b' '*(4194304-len(workflow)) |
| 50 | gate_require(len(workflow)==4194304, 'gate condition failed') |
| 51 | r=subprocess.run([str(big),'p'],input=workflow,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=60) |
| 52 | gate_require(r.returncode==0 and r.stdout.startswith(b'OK '), (r.returncode,r.stdout)) |
| 53 | gate_require(run(big,'p',workflow+b'x',b'',rc=93), 'gate condition failed') |
| 54 | checks+=2 |
| 55 | print('PASS growing/workflow 4194304 bytes; appended x=93',flush=True) |
| 56 | # Reader at its presently reachable caller-local boundary, and one byte past it. |
| 57 | body=b'0'+b' '*4194303 |
| 58 | gate_require(run(big,'p',body,b'OK 2\n' if a.wrong_expectation else b'OK 1\n'), 'reader expectation mismatch');checks+=1 |
| 59 | gate_require(run(big,'p',body,b'ERR 5 4194303\n',[4194303]), 'gate condition failed');checks+=1 |
| 60 | gate_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). |
| 62 | fd=__import__('os').open(str(j),__import__('os').O_RDONLY) |
| 63 | try: |
| 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)) |
| 66 | finally: |
| 67 | __import__('os').close(fd) |
| 68 | checks+=1 |
| 69 | # EOF without input reaches the reader's EOF refusal, not the I/O error path. |
| 70 | gate_require(run(big,'p',b'',b'ERR 1 0\n'), 'gate condition failed');checks+=1 |
| 71 | print('PASS growing/reader 4194304 bytes; trailing x=93; read-error=90; EOF=ERR1',flush=True) |
| 72 | number=b'1'+b'0'*1000000 |
| 73 | raw=b'x'*1000001 |
| 74 | for 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. |
| 78 | for 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 |
| 81 | gate_require(run(big,'n',b'',b'WERR 24\n'), 'gate condition failed');checks+=1 |
| 82 | print('PASS growing/writer number/raw/token rewrite above 983040 bytes; short outputs=21',flush=True) |
| 83 | |
| 84 | balanced=b'1'+b'0'*1000000+b'e-1000000' |
| 85 | fractional=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. |
| 88 | rng=random.Random(78803) |
| 89 | lexemes=[balanced,fractional,b'-'+balanced,b'-'+fractional] |
| 90 | for 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) |
| 101 | lexemes += [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. |
| 104 | from decimal import Decimal, localcontext |
| 105 | threshold_labels={} |
| 106 | with 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) |
| 126 | for 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 | |
| 135 | gate_require(not field.check(omc,out/'field',units), 'gate condition failed') |
| 136 | checks+=len(field.field_cases()) |
| 137 | # Each defect has a compiling, behaviorally killed control. Mutations are test-only source twins. |
| 138 | mutants=0 |
| 139 | for 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. |
| 158 | for 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 |
| 164 | for 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. |
| 178 | for 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 |
| 193 | print('GROWING PASS checks='+str(checks)+' float-oracle='+str(len(lexemes))+' mutants='+str(mutants),flush=True) |
| 194 |