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 / translation / lower_selftest.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Lowering lane self-test (TESTED evidence for translation-v1 section 5, not qualification). |
| 3 | |
| 4 | Every F1 positive, the accepted c_import_controls boundaries and crafted semantic-only S1 units go |
| 5 | upper envelope -> tools/adapters/lower -> pinned omc 734f0a39 (function mode) -> pinned omega-bridge |
| 6 | native.om 012860db binding -> C caller, and every native result is compared with a Python bigint |
| 7 | evaluation of the upper records. Expected unit bytes are rebuilt here from the records and compared |
| 8 | exactly. Refusals check status, empty stdout and the named stderr message. Tools run as separate |
| 9 | processes, one at a time. |
| 10 | """ |
| 11 | from pathlib import Path |
| 12 | import argparse,hashlib,json,os,random,struct,subprocess,sys |
| 13 | ROOT=Path(__file__).resolve().parents[3] |
| 14 | MASK=(1<<64)-1 |
| 15 | OMC_PIN='734f0a39319fbfa930bcc62cb30dbf06d47d78e126372b74f5baf478e6126b61' |
| 16 | BRIDGE_COMMIT='012860dbf26ee62a9838594b9dfd1e3e94a540a9' |
| 17 | NATIVE_OM_PIN='2c2c53f61d4ab302f1a2092c3c32189335dd53f6cf2b388f47a475f99f2c3940' |
| 18 | BOUNDARY=[0,1,2,(1<<32)-1,1<<32,(1<<63)-1,1<<63,MASK-1,MASK] |
| 19 | SEMDOM=b'omega.source.semantic.v1' |
| 20 | CONTRACT=hashlib.sha256((ROOT/'spec/universal/semantics.md').read_bytes()).digest() |
| 21 | LOWER=[sys.executable,str(ROOT/'tools/adapters/lower')] |
| 22 | IMPORT=[sys.executable,str(ROOT/'tools/adapters/c-import')] |
| 23 | fails=[] |
| 24 | |
| 25 | def check(ok,what): |
| 26 | if not ok: |
| 27 | fails.append(what);print('FAIL',what,flush=True) |
| 28 | return ok |
| 29 | |
| 30 | def run(cmd,data,timeout=60): |
| 31 | r=subprocess.run(cmd,input=data,capture_output=True,timeout=timeout) |
| 32 | return r.returncode,r.stdout,r.stderr |
| 33 | |
| 34 | def records(env): |
| 35 | """Independent parse of the semantic bytes (structure only; the native core does validation).""" |
| 36 | ns=struct.unpack_from('<I',env,5)[0];sem=env[13:13+ns] |
| 37 | count=struct.unpack_from('<H',sem,10)[0] |
| 38 | ops=[struct.unpack_from('<8BHHQ',sem,44+20*i) for i in range(count)] |
| 39 | return sem,[(o[2],o[8],o[9],o[10]) for o in ops] |
| 40 | |
| 41 | def evaluate(ops,args): |
| 42 | vals=[] |
| 43 | for op,a,b,imm in ops: |
| 44 | v={9:lambda:args[imm],1:lambda:imm,2:lambda:vals[a]+vals[b],3:lambda:vals[a]-vals[b],4:lambda:vals[a]*vals[b]}[op]() |
| 45 | vals.append(v&MASK) |
| 46 | return vals[-1] |
| 47 | |
| 48 | def expected_unit(sem,ops,name): |
| 49 | n=sum(1 for o in ops if o[0]==9) |
| 50 | sig=''.join(f' i{s} ulong' for s in range(n)) |
| 51 | lines=['note omega.universal.lower.v1 semantic '+hashlib.sha256(SEMDOM+sem).hexdigest(),f'fn {name}{sig} to ulong',f'v = new ulong {len(ops)} 0'] |
| 52 | for k,(op,a,b,imm) in enumerate(ops): |
| 53 | if op==9:lines.append(f'put v {k} i{imm}') |
| 54 | elif op==1:lines.append(f'put v {k} {imm}') |
| 55 | else:lines.append(f'put v {k} {"add sub mul".split()[op-2]} get v {a} get v {b}') |
| 56 | lines+=[f'ret get v {len(ops)-1}','end'] |
| 57 | return ('\n'.join(lines)+'\n').encode(),n |
| 58 | |
| 59 | def envelope(ops,lang=1,prof=1,runtime=0,abi=1,contract=CONTRACT): |
| 60 | """Semantic-only OMSB v1 envelope from full records (d,v,op,type,attr,effects,alias,oblig,a,b,imm).""" |
| 61 | sem=b'OMSA'+bytes([1,lang,prof,1,runtime,abi])+struct.pack('<H',len(ops))+contract |
| 62 | for o in ops:sem+=struct.pack('<8BHHQ',*o) |
| 63 | return b'OMSB\x01'+struct.pack('<II',len(sem),0)+sem |
| 64 | |
| 65 | def semantic_only(env): |
| 66 | ns=struct.unpack_from('<I',env,5)[0] |
| 67 | return env[:9]+b'\0\0\0\0'+env[13:13+ns] |
| 68 | |
| 69 | U=65535 |
| 70 | def inp(s,lang=1):return (lang,1,9,1,0,0,0,1,U,U,s) |
| 71 | def const(v,lang=1):return (lang,1,1,1,1,0,0,0,U,U,v) |
| 72 | def arith(op,a,b,lang=1,obl=1):return (lang,1,op,1,1,0,0,obl,a,b,0) |
| 73 | |
| 74 | def vectors(n,rng): |
| 75 | if n==0:return [()] |
| 76 | if n<=2: |
| 77 | vs=[tuple(v) for v in __import__('itertools').product(BOUNDARY,repeat=n)] |
| 78 | else: |
| 79 | vs=[tuple([b]*n) for b in BOUNDARY] |
| 80 | for i in range(n): |
| 81 | for b in BOUNDARY: |
| 82 | v=[rng.getrandbits(64) for _ in range(n)];v[i]=b;vs.append(tuple(v)) |
| 83 | vs+=[tuple(rng.getrandbits(64) for _ in range(n)) for _ in range(32)] |
| 84 | return vs |
| 85 | |
| 86 | def caller_c(name,n): |
| 87 | params=''.join(', uint64_t i%d'%i for i in range(n));args=''.join(', a[%d]'%i for i in range(n)) |
| 88 | return f'''#include <inttypes.h> |
| 89 | #include <stdio.h> |
| 90 | #include <stdlib.h> |
| 91 | uint32_t omega_{name}(uint64_t *result{params}); |
| 92 | int main(void) |
| 93 | {{ |
| 94 | char line[512]; |
| 95 | while (fgets(line, sizeof line, stdin)) {{ |
| 96 | char *p = line; |
| 97 | uint64_t a[6] = {{0}}; |
| 98 | for (int i = 0; i < {n}; i++) |
| 99 | a[i] = strtoull(p, &p, 10); |
| 100 | (void)a; |
| 101 | (void)p; |
| 102 | uint64_t r = UINT64_C(6148914691236517205); |
| 103 | uint32_t s = omega_{name}(&r{args}); |
| 104 | printf("%" PRIu32 " %" PRIu64 "\\n", s, r); |
| 105 | }} |
| 106 | return 0; |
| 107 | }} |
| 108 | ''' |
| 109 | |
| 110 | class Native: |
| 111 | def __init__(self,out,omc,bridge): |
| 112 | self.out=out;self.omc=omc |
| 113 | check(hashlib.sha256(Path(omc).read_bytes()).hexdigest()==OMC_PIN,'omc sha256 pin') |
| 114 | src=subprocess.run(['git','-C',bridge,'show',f'{BRIDGE_COMMIT}:src/native.om'],capture_output=True,check=True).stdout |
| 115 | if not check(hashlib.sha256(src).hexdigest()==NATIVE_OM_PIN,'bridge native.om sha256 pin'):raise SystemExit(1) |
| 116 | rc,gen,err=run([omc],src) |
| 117 | if not check(rc==0,'bridge native.om compiles: '+err.decode()):raise SystemExit(1) |
| 118 | self.gen=out/'native';self.gen.write_bytes(gen);self.gen.chmod(0o700) |
| 119 | self.calls=0;self.vectors=0 |
| 120 | def realize(self,tag,unit,name,n,ops,rng): |
| 121 | d=self.out/tag;d.mkdir() |
| 122 | (d/'unit.om').write_bytes(unit) |
| 123 | rc,code,err=run([self.omc],unit) |
| 124 | if not check(rc==0 and len(code)>0,f'{tag}: omc function-mode compile rc={rc} {err.decode().strip()}'):return |
| 125 | (d/'unit.bin').write_bytes(code) |
| 126 | frame=unit+b'\0'+b'%08d'%len(code)+code |
| 127 | rc,c,err=run([str(self.gen)],frame) |
| 128 | if not check(rc==0 and c,f'{tag}: bridge binding rc={rc} {err.decode().strip()}'):return |
| 129 | (d/'omega_native.c').write_bytes(c);(d/'caller.c').write_text(caller_c(name,n)) |
| 130 | r=subprocess.run(['cc','-std=gnu11','-O2','-Wall','-Wextra','-Werror','-pthread',str(d/'caller.c'),str(d/'omega_native.c'),'-o',str(d/'caller')],capture_output=True) |
| 131 | if not check(r.returncode==0,f'{tag}: cc caller: '+r.stderr.decode()[-400:]):return |
| 132 | vs=vectors(n,rng) |
| 133 | rc,o,err=run([str(d/'caller')],''.join(' '.join(map(str,v))+'\n' for v in vs).encode()) |
| 134 | got=o.decode().split('\n')[:-1] |
| 135 | if not check(rc==0 and len(got)==len(vs),f'{tag}: caller ran {len(got)}/{len(vs)} rc={rc}'):return |
| 136 | for v,line in zip(vs,got): |
| 137 | want=f'0 {evaluate(ops,v)}' |
| 138 | check(line==want,f'{tag}: omega_{name}{v} -> {line}, reference {want}') |
| 139 | self.vectors+=len(vs);self.calls+=len(got) |
| 140 | |
| 141 | def lower_ok(tag,env,name,expected): |
| 142 | cmd=LOWER+([name] if name is not None else []) |
| 143 | rc,o,err=run(cmd,env) |
| 144 | ok=check(rc==0 and err==b'',f'{tag}: lower rc={rc} {err.decode().strip()}') |
| 145 | ok=ok and check(o==expected,f'{tag}: lowered unit differs from the section-5 form') |
| 146 | rc2,o2,_=run(cmd,env) |
| 147 | ok=ok and check(rc2==0 and o2==o,f'{tag}: lower not byte-deterministic') |
| 148 | return ok |
| 149 | |
| 150 | def main(): |
| 151 | ap=argparse.ArgumentParser();ap.add_argument('--out',required=True) |
| 152 | ap.add_argument('--omc',default=os.environ.get('OMEGA_NATIVE_OMC')) |
| 153 | ap.add_argument('--bridge',default=os.environ.get('OMEGA_BRIDGE_REPO')) |
| 154 | a=ap.parse_args() |
| 155 | if not a.omc or not a.bridge:ap.error('set OMEGA_NATIVE_OMC and OMEGA_BRIDGE_REPO (or --omc/--bridge); no $HOME defaults') |
| 156 | out=ROOT/a.out;out.mkdir(parents=True) |
| 157 | rng=random.Random(624831) |
| 158 | nat=Native(out,a.omc,a.bridge) |
| 159 | f1=json.loads((ROOT/'tests/universal/translation/fixtures-f1.json').read_text()) |
| 160 | cases=[] |
| 161 | for p in f1['positives']: |
| 162 | src=p['source'].encode() |
| 163 | check(hashlib.sha256(src).hexdigest()==p['sha256'],p['id']+': fixture sha256') |
| 164 | cases.append((p['id'],src,None if p['name']=='calc' else p['name'])) |
| 165 | # Accepted boundary controls, constructed exactly as tests/universal/c_import_controls.py does. |
| 166 | header='#include <stdint.h>\n' |
| 167 | base=(header+'uint64_t calc(uint64_t a,uint64_t b){return a+b;}').encode() |
| 168 | cases+=[('C-exact-source-capacity',base+b' '*(4096-len(base)),None), |
| 169 | ('C-comment-at-capacity',base+b'//'+b'x'*(4096-len(base)-2),None), |
| 170 | ('C-operation-capacity',(header+'uint64_t calc(uint64_t a,uint64_t b){return '+'+'.join(['a']*61)+';}').encode(),None), |
| 171 | ('C-nesting-limit',(header+'uint64_t calc(uint64_t a,uint64_t b){return '+'('*16+'a'+')'*16+';}').encode(),None)] |
| 172 | p05=None;fixtures=0 |
| 173 | for tag,src,name in cases: |
| 174 | rc,env,err=run(IMPORT,src) |
| 175 | if not check(rc==0,f'{tag}: import rc={rc} {err.decode().strip()}'):continue |
| 176 | sem,ops=records(env) |
| 177 | uname=name or 'calc' |
| 178 | exp,n=expected_unit(sem,ops,uname) |
| 179 | if tag=='C-operation-capacity':check(len(ops)==64,f'{tag}: 64 upper operations, got {len(ops)}') |
| 180 | if not lower_ok(tag,env,name,exp):continue |
| 181 | check(lower_ok(tag+'/semantic-only',semantic_only(env),name,exp),f'{tag}: semantic-only envelope lowers identically') |
| 182 | if tag=='F1-P05':p05=exp;(out/'F1-P05.om').write_bytes(exp) |
| 183 | nat.realize(tag,exp,uname,n,ops,rng);fixtures+=1 |
| 184 | # Crafted semantic-only S1 units: input records out of slot order, lone extreme constants, |
| 185 | # and a 64-result unit with six inputs in reverse slot order and every arithmetic op. |
| 186 | big=[inp(s) for s in range(5,-1,-1)]+[const(0),const(MASK),const(1<<63)] |
| 187 | while len(big)<64: |
| 188 | k=len(big);big.append(arith(rng.choice([2,3,4]),rng.randrange(k),rng.randrange(k))) |
| 189 | crafted=[('X-permuted-inputs',[inp(1),inp(0),arith(3,0,1)],'perm'), |
| 190 | ('X-const-zero',[const(0)],None),('X-const-max',[const(MASK)],None), |
| 191 | ('X-64-results-6-inputs',big,'six'), |
| 192 | ('X-name-63',[inp(0),inp(1),arith(4,0,1)],'N'+'_'*61+'9')] |
| 193 | for tag,recs,name in crafted: |
| 194 | env=envelope(recs);sem,ops=records(env) |
| 195 | exp,n=expected_unit(sem,ops,name or 'calc') |
| 196 | if lower_ok(tag,env,name,exp):nat.realize(tag,exp,name or 'calc',n,ops,rng);fixtures+=1 |
| 197 | for name in ['_x','Calc','i6','mainx','vv','get_v']: |
| 198 | env=envelope([inp(0),inp(1),arith(2,0,1)]);sem,ops=records(env) |
| 199 | lower_ok('accept-name-'+name,env,name,expected_unit(sem,ops,name)[0]) |
| 200 | # Refusals: status, no stdout, named stderr. |
| 201 | rc,p05env,_=run(IMPORT,f1['positives'][5]['source'].encode()) |
| 202 | def flip(env,off,val):b=bytearray(env);b[off]=val;return bytes(b) |
| 203 | div=[inp(0),inp(1),arith(5,0,1,obl=3)] |
| 204 | rust=[inp(0,2),inp(1,2),arith(2,0,1,2)] |
| 205 | refusals=[('truncated-envelope',p05env[:-1],[],65),('empty-input',b'',[],65), |
| 206 | ('over-8192-bytes',p05env+b'\0'*(8193-len(p05env)),[],65),('bad-magic',flip(p05env,0,0),[],65), |
| 207 | ('forward-operand',envelope([inp(0),arith(2,0,2),const(1)]),[],65), |
| 208 | ('add-obligation-0',envelope([inp(0),arith(2,0,0,obl=0)]),[],65), |
| 209 | ('wrong-semantics-hash',envelope([const(1)],contract=b'\0'*32),[],65), |
| 210 | ('sidecar-mismatch',flip(p05env,len(p05env)-2,0x41),[],65), |
| 211 | ('trailing-byte',p05env+b'\0',[],65), |
| 212 | ('op5-div',envelope(div),[],68),('wrong-profile-byte',flip(p05env,19,2),[],68), |
| 213 | ('runtime-byte',flip(semantic_only(p05env),21,1),[],68), |
| 214 | ('rust-profile-2',envelope(rust,lang=2,prof=2),[],68), |
| 215 | ('input-slot-gap',envelope([inp(1),const(3),arith(2,0,1)]),[],68)] |
| 216 | for bad in ['get','u64','argcnt','v','i0','i5','main','a-b','1a','','a'*64,'é']: |
| 217 | refusals.append(('name-'+repr(bad),p05env,[bad],64)) |
| 218 | refusals.append(('two-names',p05env,['calc','x'],64)) |
| 219 | names={64:b'LOWER_BAD_COMMAND\n',65:b'LOWER_MALFORMED\n',68:b'LOWER_PROFILE_MISMATCH\n'} |
| 220 | refused=0 |
| 221 | for tag,data,argv,want in refusals: |
| 222 | rc,o,err=run(LOWER+argv,data) |
| 223 | if check(rc==want and o==b'' and err==names[want],f'refusal {tag}: rc={rc} want {want} stdout={len(o)} stderr={err!r}'):refused+=1 |
| 224 | report={'schema':'omega.upper-lower.selftest.v1','evidence':'TESTED (lane self-test), DIFFERENTIAL + REFERENCE, NATIVE', |
| 225 | 'fixtures':fixtures,'vectors':nat.vectors,'native_calls':nat.calls,'refusals':refused,'refusal_cases':len(refusals),'failures':fails} |
| 226 | (out/'report.json').write_text(json.dumps(report,indent=2)+'\n') |
| 227 | if p05 is not None:print(p05.decode(),end='') |
| 228 | if fails: |
| 229 | print(f'FAIL lower selftest: {len(fails)} failures');return 1 |
| 230 | print(f'PASS lower selftest fixtures={fixtures} vectors={nat.vectors} native_calls={nat.calls} refusals={refused}/{len(refusals)}') |
| 231 | return 0 |
| 232 | |
| 233 | if __name__=='__main__':raise SystemExit(main()) |