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/rust_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 / rust_selftest.py` 364 lines ยท 26143 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Rust lane (#626) author self-test: TESTED evidence only (translation-v1 section 10), never QUALIFIED. 3 4 For every F2-rust fixture: Rust import, independent decode, #621 `sa` identity/decode/replay, cross-importer 5 identity against the C import of the F1 source, export (all three S1 members, with and without sidecar), 6 re-import identity (translation-compose-v1 section 4.1), and rustc DIFFERENTIAL (original and exported 7 Rust, -O -C overflow-checks=on) against a bigint evaluation of the records. Compositions C->Rust always; 8 Rust->C only with --c-export (the G1 C exporter accepts C-member units only, so R(U, C) is applied first). 9 """ 10 from pathlib import Path 11 import argparse,hashlib,json,os,random,shutil,struct,subprocess,sys,tempfile 12 ROOT=Path(__file__).resolve().parents[3] 13 MASK=(1<<64)-1 14 SEMDOM=b'omega.source.semantic.v1' 15 CONTRACT=hashlib.sha256((ROOT/'spec/universal/semantics.md').read_bytes()).digest() 16 MEMBERS={'C':(1,1,1),'Rust':(2,2,1),'Python':(3,4,5)} # language, profile, arithmetic obligations 17 BOUNDARY=[0,1,2,(1<<32)-1,1<<32,(1<<63)-1,1<<63,MASK-1,MASK] 18 IMPORT=ROOT/'tools/adapters/rust-import';EXPORT=ROOT/'tools/adapters/rust-export' 19 20 class Fail(Exception):pass 21 def check(c,msg): 22 if not c:raise Fail(msg) 23 24 def run(cmd,data,cwd=None,timeout=60): 25 return subprocess.run(cmd,input=data,capture_output=True,timeout=timeout,cwd=cwd) 26 27 def py(tool,data):return run([sys.executable,str(tool)],data) 28 29 # ---- independent envelope model (not the #621 core) ---- 30 def split(env): 31 check(len(env)>=13 and env[:5]==b'OMSB\x01','bad envelope magic') 32 ns,np_=struct.unpack_from('=3 and ops[n-2][0]==1 and ops[n-2][3]==0 and ops[n-1][0]==2 and ops[n-1][2]==n-2 and ops[n-1][1] = line.split_whitespace().map(|x| x.parse().unwrap()).collect();\n' 100 ' assert_eq!(v.len(), %d);\n println!("{}", %s);\n }\n}\n'%(nargs,call)) 101 f=d/(key[:24]+'.rs');f.write_bytes(text+harness.encode()) 102 cmd=['nice','-n','19',s.rustc,'--edition','2021','-O','-C','overflow-checks=on','-o',str(exe),str(f)] 103 else: 104 f=d/(key[:24]+'.c') 105 body=('uint64_t x[6]={0};while(scanf("'+' '.join(['%" SCNu64 "']*nargs)+'",'+','.join('&x[%d]'%j for j in range(nargs))+')==%d)'%nargs+ 106 'printf("%" PRIu64 "\\n",'+name+'('+','.join('x[%d]'%j for j in range(nargs))+'));') if nargs else 'printf("%" PRIu64 "\\n",'+name+'());' 107 f.write_bytes(text+('\n#include \n#include \nint main(void){'+body+'return 0;}\n').encode()) 108 cmd=['nice','-n','19',s.cc,'-std=c17','-O2','-Wall','-Wextra','-Werror','-Wno-unused-parameter',str(f),'-o',str(exe)] 109 r=run(cmd,None,timeout=180);s.compiles+=1 110 check(r.returncode==0,kind+' oracle compile failed: '+r.stderr.decode(errors='replace')[-800:]) 111 s.cache[key]=exe;return exe 112 def values(s,kind,text,name,vectors): 113 nargs=len(vectors[0]);exe=s.build(kind,text,name,nargs) 114 r=run([str(exe)],''.join(' '.join(map(str,v))+'\n' for v in vectors).encode(),timeout=60) 115 check(r.returncode==0,kind+' oracle run failed: '+r.stderr.decode(errors='replace')[-400:]) 116 return [int(x) for x in r.stdout.split()] 117 118 def vectors(nargs,rng): 119 if nargs==0:return [()] 120 if nargs<=2:base=[(x,) for x in BOUNDARY] if nargs==1 else [(x,y) for x in BOUNDARY for y in BOUNDARY] 121 else:base=[tuple(BOUNDARY[(j+k)%len(BOUNDARY)] for k in range(nargs)) for j in range(len(BOUNDARY))] 122 return base+[tuple(rng.getrandbits(64) for _ in range(nargs)) for _ in range(32)] 123 124 def main(): 125 ap=argparse.ArgumentParser() 126 ap.add_argument('--out',required=True) 127 ap.add_argument('--c-import',default=str(ROOT/'build/L589/c-import'),help='native C importer (default: in-tree build of mk/c-u64-import.mk)') 128 ap.add_argument('--sa-root',default=str(ROOT),help='checkout holding tools/source-aware/sa and build/L574/sa (default: this repo)') 129 ap.add_argument('--c-export',default=os.environ.get('RUST_SELFTEST_C_EXPORT',''),help='public tools/adapters/c-export of a passing G1 checkout') 130 ap.add_argument('--rustc',default=shutil.which('rustc') or 'rustc') 131 ap.add_argument('--cc',default=os.environ.get('CC','cc')) 132 a=ap.parse_args() 133 out=Path(a.out).resolve();out.mkdir(parents=True,exist_ok=False) 134 cimp=Path(a.c_import);sa_root=Path(a.sa_root) 135 O=Oracles(out,a.rustc,a.cc);rng=random.Random(626);failures=[];counts={} 136 def bump(k,n=1):counts[k]=counts.get(k,0)+n 137 def sa(cmd,env,prefix=b''): 138 r=run(['bash','tools/source-aware/sa',cmd],prefix+env,cwd=sa_root);bump('sa_requests');return r 139 def rimport(src): 140 r=py(IMPORT,src);bump('rust_import_runs');return r 141 def rexport(env): 142 r=py(EXPORT,env);bump('rust_export_runs');return r 143 144 f1=json.loads((ROOT/'tests/universal/translation/fixtures-f1.json').read_text()) 145 f2=json.loads((ROOT/'tests/universal/translation/fixtures-f2-rust.json').read_text()) 146 f1pos={p['id']:p for p in f1['positives']} 147 check(len(f2['positives'])+len(f2['not_in_profile'])==len(f1pos),'F2-rust does not cover every F1 positive') 148 check({p['f1_id'] for p in f2['positives']}|{p['f1_id'] for p in f2['not_in_profile']}==set(f1pos),'F2-rust F1 id set') 149 150 # Oracle self-check: a plain-operator program must panic under the oracle flags (proves the flag bites). 151 plain=O.build('rust',b'pub fn calc(a: u64, b: u64) -> u64 { a + b }\n','calc',2) 152 r=run([str(plain)],b'%d 1\n'%MASK);check(r.returncode!=0 and b'overflow' in r.stderr,'overflow-checks oracle control did not panic') 153 counts['oracle_overflow_control']='PASS' 154 155 def export_checks(sem,env_with_sidecar,tag): 156 """Exporter: identical bytes for every member with or without sidecar; returns src_B.""" 157 r=rexport(env_with_sidecar);check(r.returncode==0 and r.stderr==b'',tag+' export refused rc=%d %s'%(r.returncode,r.stderr)) 158 text=r.stdout 159 for m in MEMBERS: 160 u=semonly(retarget(sem,m)) 161 check(sa('decode',u).returncode==0,tag+' R(U,%s) not a valid v1 unit'%m) 162 q=rexport(u);check(q.returncode==0 and q.stdout==text,tag+' export differs for member '+m+' (semantic-only)') 163 bump('member_exports',3) 164 check(text.startswith(b'pub fn calc(') and text.endswith(b' }\n') and text.count(b'\n')==1,tag+' export form') 165 check(not any(op in text for op in (b' + ',b' - ',b' * ')),tag+' plain operator in export') 166 return text 167 168 def reimport_identity(sem_a,src_b,tag): 169 r=rimport(src_b);check(r.returncode==0,tag+' re-import refused rc=%d %s'%(r.returncode,r.stderr)) 170 sem_b,side_b,ops_b=decode(r.stdout,'Rust');sidecar(sem_b,side_b,src_b,len(ops_b)) 171 check(N(strip(sem_b))==N(strip(sem_a)),tag+' identity N(strip(U_B)) != N(strip(U_A))') 172 return sem_b,ops_b 173 174 rows=[] 175 for fx in f2['positives']: 176 tag=fx['id'];item={'id':tag} 177 try: 178 src=fx['source'].encode();check(hashlib.sha256(src).hexdigest()==fx['sha256'],'fixture sha') 179 p1=f1pos[fx['f1_id']];check(p1['sha256']==fx['f1_sha256'] and p1['inputs']==fx['inputs'] and p1['name']==fx['name'],'F1 link') 180 r=rimport(src);check(r.returncode==0 and r.stderr==b'','import refused rc=%d %s'%(r.returncode,r.stderr)) 181 env=r.stdout;sem,side,ops=decode(env,'Rust');spans=sidecar(sem,side,src,len(ops)) 182 check(normalized(ops),'importer must append the normalization pair') 183 check(spans[-1]==spans[-2]==(0,0),'synthetic pair spans') 184 for (op,_,_,imm),(lo,hi) in zip(ops[:-2],spans[:-2]): 185 t=src[lo:hi] 186 if op==1:check(t==b'%du64'%imm,'literal span') 187 elif op==9:check(len(t)>0 and t.isascii(),'input span') 188 else:check(t==b'wrapping_'+{2:b'add',3:b'sub',4:b'mul'}[op],'method span') 189 ident=sa('identity',env);check(ident.returncode==0 and ident.stdout.hex()==identity(sem),'sa identity refused or differs') 190 check(sa('decode',env).stdout==env,'sa decode changed unit');check(sa('replay',env).stdout==src,'sa replay differs from source') 191 c=run([str(cimp)],p1['source'].encode());bump('c_import_runs') 192 check(c.returncode==0,'C import of F1 refused') 193 csem,_,cops=decode(c.stdout,'C') 194 check(N(sem)==N(csem),'cross-importer identity: N(import_Rust(F2)) != N(import_C(F1))') 195 exported=export_checks(sem,env,tag) 196 sem_b,ops_b=reimport_identity(sem,exported,tag) 197 check(sem_b==sem,'same-language round trip changed the semantic bytes') 198 vec=vectors(fx['inputs'],rng);ref=[evaluate(ops,v) for v in vec] 199 check(O.values('rust',src,fx['name'],vec)==ref,'rustc(original Rust) != reference') 200 check(O.values('rust',exported,'calc',vec)==ref,'rustc(exported Rust) != reference') 201 check(O.values('c',p1['source'].encode(),p1['name'],vec)==ref,'cc(F1 C) != reference') 202 # Non-NORMALIZED input: the exporter emits the last result; re-import gains one pair (recorded). 203 s2=strip(sem);q=rexport(semonly(s2));check(q.returncode==0,'export of stripped unit refused') 204 r2=rimport(q.stdout);check(r2.returncode==0,'re-import of stripped export refused') 205 sem2,_,ops2=decode(r2.stdout,'Rust');sops=[(o[2],o[8],o[9],o[10]) for o in ops_of(s2)] 206 check([evaluate(ops2,v) for v in vec]==[evaluate(sops,v) for v in vec],'stripped round trip evaluation differs') 207 item.update(result='PASS',ops=len(ops),vectors=len(vec),semantic_identity=identity(sem),N_identity=identity(N(sem)),exported=exported.decode(), 208 stripped_reimport_identity_equal=N(strip(sem2))==N(s2)) 209 bump('rustc_observations',2*len(vec));bump('cc_observations',len(vec)) 210 except (Fail,ValueError,KeyError,IndexError,struct.error,subprocess.TimeoutExpired) as e: 211 item.update(result='FAIL',failure=str(e));failures.append(item) 212 rows.append(item) 213 214 # ---- Rust import refusals ---- 215 refusals=[] 216 for fx in f2['refusals']: 217 src=bytes.fromhex(fx['source_hex']) if 'source_hex' in fx else fx['source'].encode() 218 r=rimport(src);ok=hashlib.sha256(src).hexdigest()==fx['sha256'] and r.returncode==fx['status'] and r.stdout==b'' and r.stderr.startswith(b'RUST_IMPORT_') 219 it={'id':fx['id'],'name':fx['name'],'want':fx['status'],'exit':r.returncode,'stderr':r.stderr.decode(errors='replace').strip(),'result':'PASS' if ok else 'FAIL'} 220 if not ok:failures.append(it) 221 refusals.append(it) 222 223 # ---- import boundary controls (exact and over capacity), each accepted one exported and re-imported ---- 224 head=b'pub fn calc(a: u64, b: u64) -> u64 { ' 225 base=head+b'a.wrapping_add(b) }' 226 chain=lambda k:head+b'a'+b'.wrapping_add(a)'*k+b' }' 227 right=lambda k:head+b'a.wrapping_add('*k+b'a'+b')'*k+b' }' 228 parens=lambda k:head+b'('*k+b'a'+b')'*k+b' }' 229 controls=[('exact-source-capacity',base+b' '*(4096-len(base)),0,12),('comment-at-capacity',base+b'//'+b'x'*(4096-len(base)-2),0,12), 230 ('operation-capacity',chain(60),0,61*5),('nesting-limit',parens(16),0,5),('call-nesting-limit',right(16),0,17*5), 231 ('over-source-capacity',base+b' '*(4097-len(base)),67,None),('over-operation-capacity',chain(61),67,None), 232 ('over-nesting-limit',parens(17),67,None),('over-call-nesting-limit',right(17),67,None)] 233 ctl=[] 234 for name,src,want,value in controls: 235 it={'name':name,'source_bytes':len(src)} 236 try: 237 r=rimport(src) 238 if want:check(r.returncode==want and not r.stdout and r.stderr==b'RUST_IMPORT_LIMIT\n','%s rc=%d'%(name,r.returncode)) 239 else: 240 check(r.returncode==0,'%s refused rc=%d %s'%(name,r.returncode,r.stderr));sem,side,ops=decode(r.stdout,'Rust');sidecar(sem,side,src,len(ops)) 241 check(evaluate(ops,[5,7])==value,name+' value');exported=export_checks(sem,r.stdout,name) 242 sem_b,_=reimport_identity(sem,exported,name);check(sem_b==sem,name+' round trip') 243 vec=vectors(2,rng);ref=[evaluate(ops,v) for v in vec] 244 check(O.values('rust',src,'calc',vec)==ref and O.values('rust',exported,'calc',vec)==ref,name+' rustc differential') 245 it.update(ops=len(ops),exported_bytes=len(exported)) 246 it.update(result='PASS',exit=r.returncode) 247 except (Fail,ValueError,struct.error) as e:it.update(result='FAIL',failure=str(e));failures.append(it) 248 ctl.append(it) 249 r=subprocess.run([str(ROOT/'build/L626/rust-import')],stdin=subprocess.DEVNULL,capture_output=True,preexec_fn=lambda:os.close(0),timeout=10) 250 ctl.append({'name':'import-closed-stdin','exit':r.returncode,'result':'PASS' if r.returncode==77 and not r.stdout and r.stderr==b'RUST_IMPORT_IO\n' else 'FAIL'}) 251 r=subprocess.run([str(ROOT/'build/L626/rust-export')],stdin=subprocess.DEVNULL,capture_output=True,preexec_fn=lambda:os.close(0),timeout=10) 252 ctl.append({'name':'export-closed-stdin','exit':r.returncode,'result':'PASS' if r.returncode==77 and not r.stdout and r.stderr==b'RUST_EXPORT_IO\n' else 'FAIL'}) 253 for tool in (IMPORT,EXPORT): 254 r=run([sys.executable,str(tool),'unexpected'],base);ctl.append({'name':tool.name+'-arguments-refused','exit':r.returncode,'result':'PASS' if r.returncode==64 and not r.stdout and b'BAD_COMMAND' in r.stderr else 'FAIL'}) 255 r=run([sys.executable,str(IMPORT)],base);d=run([str(ROOT/'build/L626/rust-import')],base) 256 ctl.append({'name':'public-import-identical-to-native','result':'PASS' if r.returncode==0 and r.stdout==d.stdout else 'FAIL'}) 257 for tool,victims in ((IMPORT,['src/adapters/rust-u64-import.om','build/L626/rust-import']),(EXPORT,['src/adapters/rust-u64-export.om','src/source-aware/core.om','build/L626/rust-export'])): 258 for victim in victims: 259 with tempfile.TemporaryDirectory(prefix='closed-build-',dir=out) as td: 260 t=Path(td) 261 for rel in ['tools/adapters/'+tool.name,'src/source-aware/vendor/sha256.om','src/source-aware/core.om','src/adapters/rust-u64-import.om','src/adapters/rust-u64-export.om','build/L626/build.json','build/L626/rust-import','build/L626/rust-export']: 262 p=t/rel;p.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(ROOT/rel,p);p.chmod(0o700) 263 with (t/victim).open('ab') as f:f.write(b'changed') 264 r=run([sys.executable,str(t/'tools/adapters'/tool.name)],base) 265 ok=r.returncode==78 and not r.stdout and b'STALE_OR_MISSING_BUILD' in r.stderr 266 ctl.append({'name':tool.name+'-stale-'+victim,'exit':r.returncode,'result':'PASS' if ok else 'FAIL'}) 267 failures+=[c for c in ctl if c['result']=='FAIL' and c not in failures] 268 269 # ---- exporter refusals ---- 270 good=rimport(base).stdout;gsem,gside=split(good) 271 def unit(lang,prof,runtime,abi,ops,typ=1): 272 sem=b'OMSA\x01'+bytes([lang,prof,1,runtime,abi])+struct.pack(' Rust: F1 positives and the four accepted C import boundary controls ---- 311 ch=b'#include \nuint64_t calc(uint64_t a,uint64_t b){return a+b;}' 312 cctl=[('C-exact-source-capacity',ch+b' '*(4096-len(ch)),'calc',2),('C-comment-at-capacity',ch+b'//'+b'x'*(4096-len(ch)-2),'calc',2), 313 ('C-operation-capacity',b'#include \nuint64_t calc(uint64_t a,uint64_t b){return '+b'+'.join([b'a']*61)+b';}','calc',2), 314 ('C-nesting-limit',b'#include \nuint64_t calc(uint64_t a,uint64_t b){return '+b'('*16+b'a'+b')'*16+b';}','calc',2)] 315 comp=[] 316 for tag,csrc,name,nargs in [(p['id'],p['source'].encode(),p['name'],p['inputs']) for p in f1['positives']]+cctl: 317 it={'id':'C->Rust '+tag} 318 try: 319 c=run([str(cimp)],csrc);bump('c_import_runs');check(c.returncode==0,'C import refused') 320 sem_a,_,ops_a=decode(c.stdout,'C') 321 src_b=export_checks(sem_a,c.stdout,tag) 322 sem_b,ops_b=reimport_identity(sem_a,src_b,tag) 323 vec=vectors(nargs,rng);ref=[evaluate(ops_a,v) for v in vec] 324 check(O.values('c',csrc,name,vec)==ref,'cc(original C) != reference(U_A)') 325 check(O.values('rust',src_b,'calc',vec)==ref,'rustc(src_B) != reference(U_A)') 326 check([evaluate(ops_b,v) for v in vec]==ref,'reference(U_B) != reference(U_A)') 327 it.update(result='PASS',identity=identity(N(strip(sem_a))),vectors=len(vec),native_realization='NOT_RUN (lowering not on this branch)') 328 except (Fail,ValueError,struct.error) as e:it.update(result='FAIL',failure=str(e));failures.append(it) 329 comp.append(it) 330 331 # ---- composition Rust -> C (only with a passing G1 C exporter) ---- 332 rc_rows=[];rust_to_c='NOT_RUN' 333 if a.c_export: 334 rust_to_c='RUN' 335 for fx in f2['positives']: 336 it={'id':'Rust->C '+fx['id']} 337 try: 338 src=fx['source'].encode();r=rimport(src);sem_a,_,ops_a=decode(r.stdout,'Rust') 339 q=py(Path(a.c_export),semonly(retarget(sem_a,'C')));check(q.returncode==0,'c-export refused R(U,C) rc=%d %s'%(q.returncode,q.stderr)) 340 c=run([str(cimp)],q.stdout);check(c.returncode==0,'C import of exported C refused') 341 sem_b,_,ops_b=decode(c.stdout,'C');check(N(strip(sem_b))==N(strip(sem_a)),'identity N(strip(U_B)) != N(strip(U_A))') 342 vec=vectors(fx['inputs'],rng);ref=[evaluate(ops_a,v) for v in vec] 343 check(O.values('rust',src,fx['name'],vec)==ref,'rustc(original Rust) != reference') 344 check(O.values('c',q.stdout,'calc',vec)==ref,'cc(src_B) != reference') 345 it.update(result='PASS',vectors=len(vec),exported_c=q.stdout.decode()) 346 except (Fail,ValueError,struct.error) as e:it.update(result='FAIL',failure=str(e));failures.append(it) 347 rc_rows.append(it) 348 349 report={'schema':'omega.rust-u64.selftest.v1','result':'FAIL' if failures else 'PASS','status_flags':'TESTED (author self-test), not QUALIFIED', 350 'evidence':'REFERENCE + DIFFERENTIAL (rustc/cc NATIVE AArch64); no PROOF','source_commit':subprocess.check_output(['git','-C',str(ROOT),'rev-parse','HEAD'],text=True).strip(), 351 'build':json.loads((ROOT/'build/L626/build.json').read_text()),'rustc':subprocess.check_output([a.rustc,'--version'],text=True).strip(), 352 'c_import_sha256':hashlib.sha256(cimp.read_bytes()).hexdigest(),'sa_binary_sha256':hashlib.sha256((sa_root/'build/L574/sa').read_bytes()).hexdigest(), 353 'positives':len(rows),'positives_passed':sum(r['result']=='PASS' for r in rows),'not_in_profile':len(f2['not_in_profile']), 354 'refusals':len(refusals),'refusals_passed':sum(r['result']=='PASS' for r in refusals), 355 'controls':len(ctl),'controls_passed':sum(r['result']=='PASS' for r in ctl),'export_refusals':len(xrows),'export_refusals_passed':sum(r['result']=='PASS' for r in xrows), 356 'c_to_rust':len(comp),'c_to_rust_passed':sum(r['result']=='PASS' for r in comp),'rust_to_c':rust_to_c,'rust_to_c_passed':sum(r['result']=='PASS' for r in rc_rows),'rust_to_c_cases':len(rc_rows), 357 'oracle_compiles':O.compiles,'counts':counts,'cases':rows,'refusal_cases':refusals,'control_cases':ctl,'export_cases':xrows,'c_to_rust_cases':comp,'rust_to_c_rows':rc_rows,'failures':failures} 358 (out/'result.json').write_text(json.dumps(report,indent=1)+'\n') 359 keys=['positives','positives_passed','not_in_profile','refusals','refusals_passed','controls','controls_passed','export_refusals','export_refusals_passed','c_to_rust','c_to_rust_passed','rust_to_c','rust_to_c_cases','rust_to_c_passed','oracle_compiles'] 360 print(report['result'],' '.join('%s=%s'%(k,report[k]) for k in keys),' '.join('%s=%s'%kv for kv in counts.items())) 361 for f in failures[:20]:print('FAIL',json.dumps(f)[:600]) 362 return 1 if failures else 0 363 364 if __name__=='__main__':raise SystemExit(main())