Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-mv/blob/main/tests/universal/translation/c_export_selftest.py # 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 Sign in to star 1 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omega-mv / tests / universal / translation / c_export_selftest.py` 295 lines ยท 23970 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """C export lane self-test (translation-v1 section 6, translation-compose-v1, #622). Author TESTED, not QUALIFIED. 3 4 For every F1 positive and the four accepted boundary controls of c_import_controls.py: 5 import (native importer) -> export (native exporter) -> re-import; the re-imported OMSA semantic bytes 6 must equal the first import's. The semantic-only envelope and its retargets R(U,Rust) and R(U,Python) 7 (compose section 2) must export byte-identically. Original and exported C are compiled with 8 cc -std=c17 -O2 -Wall -Werror and compared on boundary and seeded random vectors (DIFFERENTIAL), and 9 against the Python integer model of the imported graph (REFERENCE). Constructed units cover the 10 non-NORMALIZED, shared-SSA and permuted-slot paths and every refusal. 11 12 Optional compose leg (--rust-root / --python-root: checkouts holding the #626 / #627 adapters, built): 13 Rust -> C and Python -> C on fixtures-f2-.json per compose section 4: identity 14 N(strip(U_B)) = N(strip(U_A)), rustc/python3 original vs cc generated C vs REFERENCE, semantic-only 15 export identical. Not given = NOT_RUN.""" 16 from pathlib import Path 17 import argparse,hashlib,importlib.util,itertools,json,os,random,shutil,struct,subprocess,sys,tempfile 18 ROOT=Path(__file__).resolve().parents[3];sys.dont_write_bytecode=True 19 spec=importlib.util.spec_from_file_location('cgate',ROOT/'tests/universal/c_import_gate.py');g=importlib.util.module_from_spec(spec);spec.loader.exec_module(g) 20 MASK=g.MASK 21 IMPORTER=ROOT/'build/L589/c-import';EXPORTER=ROOT/'build/L622/c-export';CLI=ROOT/'tools/adapters/c-export';SA=ROOT/'tools/source-aware/sa' 22 BOUNDARY=[0,1,2,(1<<32)-1,1<<32,(1<<63)-1,1<<63,MASK-1,MASK] 23 CFLAGS=['-std=c17','-O2','-Wall','-Werror'] 24 SEMHASH=hashlib.sha256((ROOT/'spec/universal/semantics.md').read_bytes()).digest() 25 26 def controls(): 27 # Exactly the four accepted boundary controls of tests/universal/c_import_controls.py. 28 header=g.HEADER;base=(header+'uint64_t calc(uint64_t a,uint64_t b){return a+b;}').encode() 29 pad=base+b' '*(4096-len(base));comment=base+b'//'+b'x'*(4096-len(base)-2) 30 maximum=(header+'uint64_t calc(uint64_t a,uint64_t b){return '+'+'.join(['a']*61)+';}').encode() 31 deep=(header+'uint64_t calc(uint64_t a,uint64_t b){return '+'('*16+'a'+')'*16+';}').encode() 32 return [('exact-source-capacity',pad,'calc',2),('comment-at-capacity',comment,'calc',2),('operation-capacity',maximum,'calc',2),('nesting-limit',deep,'calc',2)] 33 34 def run(cmd,data): 35 return subprocess.run(cmd,input=data,capture_output=True,timeout=30) 36 37 def export(unit,name=None): 38 return run([sys.executable,str(CLI)]+([name] if name else []),unit) 39 40 def semantic(env): 41 assert env[:5]==b'OMSB\x01';ns,np=struct.unpack_from(' (language, profile, op dialect, arithmetic obligations). 61 FAMILY={'C':(1,1,1,1),'Rust':(2,2,2,1),'Python':(3,4,3,5)} 62 63 def retarget(sem,member): 64 """R(U, M), compose section 2: header language/profile, every op's dialect byte, arithmetic obligations.""" 65 lang,prof,dial,obl=FAMILY[member];b=bytearray(sem);b[5]=lang;b[6]=prof 66 for i in range(struct.unpack_from('=3 and ops[-2]==(1,65535,65535,0) and ops[-1][0]==2 and ops[-1][2]==n-2 and ops[-1][1]\n#include \nint main(void){printf("%" PRIu64 "\\n",'+name+'());return 0;}\n' 91 scan=' '.join(['%" SCNu64 "']*nargs);ptrs=','.join('&x['+str(j)+']' for j in range(nargs));args=','.join('x['+str(j)+']' for j in range(nargs)) 92 return '\n#include \n#include \nint main(void){uint64_t x[6]={0};while(scanf("'+scan+'",'+ptrs+')=='+str(nargs)+')printf("%" PRIu64 "\\n",'+name+'('+args+'));return 0;}\n' 93 94 def native(out,tag,src,name,nargs,payload): 95 c=out/(tag+'.c');exe=out/tag;c.write_bytes(src+harness(name,nargs).encode()) 96 r=subprocess.run([os.environ.get('CC','cc')]+CFLAGS+[str(c),'-o',str(exe)],capture_output=True,timeout=60) 97 assert r.returncode==0,tag+' compile failed: '+r.stderr.decode(errors='replace') 98 r=run([str(exe)],payload);assert r.returncode==0,tag+' run failed' 99 return [int(x) for x in r.stdout.split()] 100 101 def main(): 102 ap=argparse.ArgumentParser();ap.add_argument('--out',required=True) 103 ap.add_argument('--rust-root',default='',help='checkout with built #626 adapters (tools/adapters/rust-import, fixtures-f2-rust.json)') 104 ap.add_argument('--python-root',default='',help='checkout with built #627 adapters (tools/adapters/python-import, fixtures-f2-python.json)') 105 a=ap.parse_args() 106 out=Path(a.out).resolve();out.mkdir(parents=True,exist_ok=False) 107 for p in [IMPORTER,EXPORTER]:assert p.read_bytes()[:4]==b'\x7fELF',p 108 rng=random.Random(622624);rows=[];failures=[];observations=0 109 fixtures=json.loads((ROOT/'tests/universal/translation/fixtures-f1.json').read_text()) 110 cases=[] 111 for f in fixtures['positives']: 112 src=f['source'].encode();assert hashlib.sha256(src).hexdigest()==f['sha256'],f['id'] 113 cases.append((f['id'],src,f['name'],f['inputs'])) 114 for name,src,fn,nargs in controls():cases.append(('control-'+name,src,fn,nargs)) 115 # 1. Required boundaries: import -> export -> re-import identity; semantic-only; native differential. 116 for cid,src,name,nargs in cases: 117 item={'id':cid,'source_sha256':hashlib.sha256(src).hexdigest()} 118 try: 119 r=run([str(IMPORTER)],src);assert r.returncode==0,'import refused rc=%d'%r.returncode 120 u1=r.stdout;s1=semantic(u1);ops=g.decode(u1,src,nargs) 121 assert len(ops)>=3 and ops[-2]==(1,65535,65535,0) and ops[-1][0]==2 and ops[-1][2]==len(ops)-2 and ops[-1][1]\nuint64_t '+name.encode()+b'(') and c.endswith(b'; }\n') and c.count(b'\n')==2,'output form' 126 assert len(c)<=4096,'over 4096 bytes' 127 d=run([str(EXPORTER)],bytes([len(fname or '')])+(fname or '').encode()+u1);assert d.returncode==0 and d.stdout==c,'native direct differs from public command' 128 so=semonly(s1);v=run([str(SA),'decode'],so);assert v.returncode==0 and v.stdout==so,'semantic-only envelope not accepted by sa decode' 129 e2=export(so,fname);assert e2.returncode==0 and e2.stdout==c,'semantic-only envelope exported differently' 130 for m in ('Rust','Python'): 131 rm=semonly(retarget(s1,m));v=run([str(SA),'decode'],rm);assert v.returncode==0 and v.stdout==rm,'R(U,%s) not a valid v1 unit'%m 132 em=export(rm,fname);assert em.returncode==0 and em.stdout==c,'R(U,%s) exported differently'%m 133 assert retarget(retarget(s1,'Python'),'C')==s1 and retarget(retarget(s1,'Rust'),'C')==s1,'N(R(U,M)) != N(U)' 134 r2=run([str(IMPORTER)],c);assert r2.returncode==0,'re-import refused rc=%d %s'%(r2.returncode,r2.stderr) 135 s2=semantic(r2.stdout);assert s2==s1,'re-imported semantic bytes differ' 136 i1=run([str(SA),'identity'],u1).stdout;i2=run([str(SA),'identity'],r2.stdout).stdout;i3=run([str(SA),'identity'],so).stdout 137 assert len(i1)==32 and i1==i2==i3,'semantic identity differs' 138 vs=vectors(nargs,rng);payload=''.join(' '.join(map(str,x))+'\n' for x in vs).encode() 139 orig=native(out,cid+'-orig',src,name,nargs,payload);expo=native(out,cid+'-export',c,name,nargs,payload) 140 ref=[g.evaluate(ops,list(x)) for x in vs] 141 assert len(orig)==len(vs) and orig==expo,'native original C vs exported C mismatch' 142 assert expo==ref,'exported C vs REFERENCE model mismatch' 143 observations+=len(vs) 144 (out/(cid+'.export.c')).write_bytes(c) 145 item.update({'result':'PASS','ops':len(ops),'export_bytes':len(c),'export_sha256':hashlib.sha256(c).hexdigest(),'semantic_identity':i1.hex(),'vectors':len(vs),'export_head':c.split(b'\n')[1][:80].decode()}) 146 except (AssertionError,ValueError,struct.error,IndexError) as exc: 147 item.update({'result':'FAIL','failure':str(exc)});failures.append(item) 148 rows.append(item) 149 # 2. Constructed accepted units: non-NORMALIZED (+2 on re-import), shared SSA, permuted slots, zero inputs. 150 A,B=(9,65535,65535,0),(9,65535,65535,1) 151 built=[('non-normalized',[A,B,(2,0,1,0)],2,'i0 + i1'), 152 ('shared-ssa',[A,B,(2,0,1,0),(4,2,2,0)],2,'(i0 + i1) * (i0 + i1)'), 153 ('permuted-slots',[(9,65535,65535,1),(9,65535,65535,0),(3,0,1,0)],2,'i1 - i0'), 154 ('right-assoc-depth-16',[A]+[(2,0,0,0)]+[(2,0,k,0) for k in range(1,17)],1,None), 155 ('max-constant',[(1,65535,65535,MASK),(1,65535,65535,0),(3,1,0,0)],0,'0ULL - 18446744073709551615ULL')] 156 constructed=[] 157 for cid,recs,nargs,expr in built: 158 item={'id':'built-'+cid} 159 try: 160 env=unit(recs);v=run([str(SA),'decode'],env);assert v.returncode==0,'constructed unit not valid v1' 161 e=export(env);assert e.returncode==0,'export refused rc=%d %s'%(e.returncode,e.stderr) 162 c=e.stdout;body=c.split(b'{ return ')[1][:-4].decode() 163 if expr:assert body==expr,'expression '+body 164 else:assert body.count('(')==16 and body.endswith(')'*16),'depth 16 chain parentheses' 165 r2=run([str(IMPORTER)],c);assert r2.returncode==0,'re-import refused' 166 s2=semantic(r2.stdout);ops2=ops_of(s2);ops=[tuple(x) for x in recs] 167 vs=vectors(nargs,rng);payload=''.join(' '.join(map(str,x))+'\n' for x in vs).encode() 168 expo=native(out,'built-'+cid,c,'calc',nargs,payload);ref=[g.evaluate(ops,list(x)) for x in vs] 169 assert expo==ref,'exported C vs REFERENCE model mismatch' 170 assert [g.evaluate(ops2,list(x)) for x in vs]==ref,'re-import evaluation differs' 171 same=s2==semantic(env) 172 if cid=='non-normalized': 173 assert ops2==ops+[(1,65535,65535,0),(2,2,3,0)],'non-NORMALIZED unit must gain exactly one +0 pair' 174 item.update({'result':'PASS','export':body[:80],'reimport_identity_equal':same,'reimport_ops':len(ops2),'vectors':len(vs)});observations+=len(vs) 175 except (AssertionError,ValueError,struct.error,IndexError) as exc: 176 item.update({'result':'FAIL','failure':str(exc)});failures.append(item) 177 constructed.append(item) 178 # 3. Refusals: status, empty stdout, named stderr. 179 good=run([str(IMPORTER)],cases[2][1]).stdout 180 sem=semantic(good) 181 def patch(buf,off,val):b=bytearray(buf);b[off]=val;return bytes(b) 182 doubling=[A]+[(2,0,0,0)]+[(2,k,k,0) for k in range(1,62)] 183 def reob(s,obl): 184 b=bytearray(s) 185 for i in range(struct.unpack_from(' C and Python -> C on the lanes' F2 fixtures (scratch checkouts; NOT_RUN if absent). 231 compose={};pyoracle=out/'pyoracle.py' 232 pyoracle.write_text("import sys\npath,name,n=sys.argv[1],sys.argv[2],int(sys.argv[3])\nns={}\nexec(compile(open(path,'rb').read().decode('ascii'),path,'exec'),ns)\nf=ns[name]\nfor line in sys.stdin:\n xs=[int(t) for t in line.split()]\n assert len(xs)==n\n v=f(*xs)\n assert type(v) is int and 0<=v<2**64,(xs,v)\n print(v)\n") 233 def rust_oracle(tag,src,name,nargs,payload): 234 call=name+'('+', '.join('v[%d]'%j for j in range(nargs))+')' 235 harness=('\nfn main() {\n use std::io::BufRead;\n for line in std::io::stdin().lock().lines() {\n let line = line.unwrap();\n' 236 ' let v: Vec = line.split_whitespace().map(|x| x.parse().unwrap()).collect();\n assert_eq!(v.len(), %d);\n println!("{}", %s);\n }\n}\n'%(nargs,call)) 237 f=out/(tag+'.rs');exe=out/tag;f.write_bytes(src+harness.encode()) 238 rustc=shutil.which('rustc') or str(Path.home()/'.cargo/bin/rustc') 239 r=subprocess.run(['nice','-n','19',rustc,'--edition','2021','-O','-C','overflow-checks=on','-o',str(exe),str(f)],capture_output=True,timeout=300) 240 assert r.returncode==0,tag+' rustc failed: '+r.stderr.decode(errors='replace')[-600:] 241 r=run([str(exe)],payload);assert r.returncode==0,tag+' rust run failed' 242 return [int(x) for x in r.stdout.split()] 243 def python_oracle(tag,src,name,nargs,payload): 244 f=out/(tag+'.py');f.write_bytes(src) 245 r=run([sys.executable,'-I','-B',str(pyoracle),str(f),name,str(nargs)],payload);assert r.returncode==0,tag+' python3 failed: '+r.stderr.decode(errors='replace')[-400:] 246 return [int(x) for x in r.stdout.split()] 247 for lang,member,root,oracle in [('rust','Rust',a.rust_root,rust_oracle),('python','Python',a.python_root,python_oracle)]: 248 if not root:compose[member+'->C']={'result':'NOT_RUN'};continue 249 root=Path(root).resolve();fx=json.loads((root/('tests/universal/translation/fixtures-f2-%s.json'%lang)).read_text()) 250 imp=root/('tools/adapters/%s-import'%lang);lrows=[] 251 for f in fx['positives']+fx.get('controls',[]): 252 src=f['source'].encode();name=f['name'];nargs=f['inputs'];item={'id':f['id']} 253 try: 254 assert hashlib.sha256(src).hexdigest()==f['sha256'],'fixture hash' 255 r=run([sys.executable,str(imp)],src);assert r.returncode==0,'%s import refused rc=%d %s'%(lang,r.returncode,r.stderr) 256 ua=r.stdout;sa_=semantic(ua);l,p_=FAMILY[member][:2];assert sa_[5]==l and sa_[6]==p_,'importer member' 257 cname=name if name.startswith('omega_') and len(name)<=32 else None 258 e=export(ua,cname);assert e.returncode==0,'C export refused rc=%d %s'%(e.returncode,e.stderr) 259 srcb=e.stdout 260 assert export(semonly(sa_),cname).stdout==srcb,'semantic-only export differs' 261 assert export(semonly(retarget(sa_,'C')),cname).stdout==srcb,'export of R(U_A,C) differs' 262 r2=run([str(IMPORTER)],srcb);assert r2.returncode==0,'C import of generated C refused rc=%d'%r2.returncode 263 sb=semantic(r2.stdout) 264 assert retarget(strip(sb),'C')==retarget(strip(sa_),'C'),'N(strip(U_B)) != N(strip(U_A))' 265 vs=vectors(nargs,rng);payload=''.join(' '.join(map(str,x))+'\n' for x in vs).encode() 266 ref=[g.evaluate(ops_of(sa_),list(x)) for x in vs] 267 orig=oracle(f['id']+'-orig',src,name,nargs,payload);gen=native(out,f['id']+'-genC',srcb,cname or 'calc',nargs,payload) 268 assert orig==ref,'%s oracle(original) != REFERENCE(U_A)'%lang 269 assert gen==ref,'cc(generated C) != REFERENCE(U_A)' 270 observations+=len(vs) 271 item.update({'result':'PASS','vectors':len(vs),'n_identity':hashlib.sha256(retarget(strip(sa_),'C')).hexdigest(),'export_head':srcb.split(b'\n')[1][:80].decode()}) 272 except (AssertionError,ValueError,struct.error,IndexError,KeyError) as exc: 273 item.update({'result':'FAIL','failure':str(exc)});failures.append(item) 274 lrows.append(item) 275 compose[member+'->C']={'result':'FAIL' if any(x['result']!='PASS' for x in lrows) else 'PASS','root':str(root), 276 'root_commit':subprocess.check_output(['git','-C',str(root),'rev-parse','HEAD'],text=True).strip(), 277 'fixtures':len(lrows),'passed':sum(x['result']=='PASS' for x in lrows),'not_in_profile':[x['id'] for x in fx.get('not_in_profile',[])],'cases':lrows} 278 report={'schema':'omega.c-u64-export.selftest.v2','contract_sha256':hashlib.sha256((ROOT/'spec/universal/translation-v1.md').read_bytes()).hexdigest(), 279 'compose_contract_sha256':hashlib.sha256((ROOT/'spec/universal/translation-compose-v1.md').read_bytes()).hexdigest(), 280 'result':'FAIL' if failures else 'PASS','status':'TESTED (author self-test; not QUALIFIED)','evidence':['DIFFERENTIAL','REFERENCE'],'proof':False, 281 'source_commit':subprocess.check_output(['git','-C',str(ROOT),'rev-parse','HEAD'],text=True).strip(), 282 'exporter_sha256':hashlib.sha256(EXPORTER.read_bytes()).hexdigest(),'importer_sha256':hashlib.sha256(IMPORTER.read_bytes()).hexdigest(), 283 'cc':subprocess.check_output([os.environ.get('CC','cc'),'--version'],text=True).splitlines()[0],'cflags':CFLAGS, 284 'boundaries':len(rows),'boundaries_passed':sum(x['result']=='PASS' for x in rows), 285 'constructed':len(constructed),'constructed_passed':sum(x['result']=='PASS' for x in constructed), 286 'refusals':len(negatives),'refusals_passed':sum(x['result']=='PASS' for x in negatives),'native_C_observations':observations, 287 'compose':compose,'cases':rows,'constructed_cases':constructed,'refusal_cases':negatives,'failures':failures} 288 (out/'result.json').write_text(json.dumps(report,indent=2)+'\n') 289 for x in rows: 290 if x['id'] in ('F1-P05','F1-P13','control-operation-capacity'):print(x['id'],x.get('export_head',x.get('failure'))) 291 for x in failures:print('FAIL',json.dumps(x)[:400]) 292 print('%s boundaries=%d/%d identical_reimport=%d retarget_identical_exports=%d constructed=%d/%d refusals=%d/%d native_C_observations=%d'%(report['result'],report['boundaries_passed'],len(rows),report['boundaries_passed'],2*report['boundaries_passed'],report['constructed_passed'],len(constructed),report['refusals_passed'],len(negatives),observations)) 293 for k,v in compose.items():print('compose',k,v['result'],'%d/%d'%(v['passed'],v['fixtures']) if 'fixtures' in v else '','not_in_profile=%s'%v.get('not_in_profile','')) 294 return 1 if failures else 0 295 if __name__=='__main__':raise SystemExit(main())