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/python_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 / python_selftest.py` 368 lines ยท 25757 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Python lane self-test (#627; spec/universal/python-u64-v1.md, translation-compose-v1.md). Author-run TESTED 3 evidence, not QUALIFIED. 4 5 Same-language (Python -> Python), for every F2-python positive and accepted boundary control: native import; 6 structural decode of the Python-member unit (header/op bytes, obligations, spans, sidecar); the #621 codec 7 (`bash tools/source-aware/sa identity` in --sa-root) accepts it and agrees with the SHA256 identity; export; 8 the semantic-only envelope exports the same bytes; re-import; compose section 4.1 identity 9 N(strip(U_B)) = N(strip(U_A)); the F2 rewrite has the same N(strip()) as the C import of its F1 source; 10 python3 runs the original and the exported source on boundary and seeded random vectors and both must equal 11 the bigint evaluation of the records (REFERENCE + DIFFERENTIAL). 12 13 Compositions: C -> Python on every F1 positive and accepted C boundary control (C importer, original C by cc, 14 generated Python by python3). The native realization leg (translation-v1 section 5 lowering) is NOT_RUN. 15 Python -> C runs only with --c-export (a translation-v1 section 6 exporter CLI); that exporter accepts the C 16 member only, so the Python unit is retargeted R(U, C) first. Without it the direction is NOT_RUN. 17 18 Also: every refusal fixture (exact status, no stdout), exporter family acceptance (R(U, C/Rust/Python) export 19 identically), exporter refusals (profiles 3/5/6, division, malformed, limit, bad name), constructed 20 non-NORMALIZED / permuted-slot / shared-SSA units, and the public-command identity guards.""" 21 from pathlib import Path 22 import argparse,hashlib,itertools,json,os,random,shutil,struct,subprocess,sys,tempfile 23 ROOT=Path(__file__).resolve().parents[3];sys.dont_write_bytecode=True 24 MASK=(1<<64)-1 25 BOUNDARY=[0,1,2,(1<<32)-1,1<<32,(1<<63)-1,1<<63,MASK-1,MASK] 26 IMPORTER=ROOT/'build/L627/import/python-import';EXPORTER=ROOT/'build/L627/export/python-export' 27 ICLI=ROOT/'tools/adapters/python-import';ECLI=ROOT/'tools/adapters/python-export' 28 SEMHASH=hashlib.sha256((ROOT/'spec/universal/semantics.md').read_bytes()).digest() 29 FAMILY={'C':(1,1,1,1),'Rust':(2,2,2,1),'Python':(3,4,3,5)} 30 CFLAGS=['-std=c17','-O2','-Wall','-Werror','-Wno-unused-parameter'] 31 PYORACLE='''import sys 32 path,name,n=sys.argv[1],sys.argv[2],int(sys.argv[3]) 33 ns={} 34 exec(compile(open(path,'rb').read().decode('ascii'),path,'exec'),ns) 35 f=ns[name] 36 for line in sys.stdin: 37 xs=[int(t) for t in line.split()] 38 assert len(xs)==n 39 v=f(*xs) 40 assert type(v) is int and 0<=v<2**64,(xs,v) 41 print(v) 42 ''' 43 44 class Fail(Exception):pass 45 46 def check(cond,msg): 47 if not cond:raise Fail(msg) 48 49 def run(cmd,data=b'',**kw): 50 return subprocess.run(cmd,input=data,capture_output=True,timeout=60,**kw) 51 52 def semantic(env): 53 check(env[:5]==b'OMSB\x01','bad envelope magic');ns,np=struct.unpack_from('=3 and ops[n-2]==(1,65535,65535,0) and ops[n-1][0]==2 and ops[n-1][2]==n-2 and ops[n-1][1]\n#include \nint main(void){printf("%" PRIu64 "\\n",'+name+'());return 0;}\n' 142 scan=' '.join(['%" SCNu64 "']*nargs);ptrs=','.join('&x['+str(j)+']' for j in range(nargs));args=','.join('x['+str(j)+']' for j in range(nargs)) 143 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' 144 145 def c_oracle(out,tag,src,name,nargs,vs): 146 c=out/(tag+'.c');exe=out/tag;c.write_bytes(src+c_harness(name,nargs).encode()) 147 r=run([os.environ.get('CC','cc')]+CFLAGS+[str(c),'-o',str(exe)]);check(r.returncode==0,tag+' cc failed: '+r.stderr.decode(errors='replace')[-400:]) 148 r=run([str(exe)],payload(vs));check(r.returncode==0,tag+' C run failed') 149 return [int(x) for x in r.stdout.split()] 150 151 class Ctx: 152 def __init__(s,a,out): 153 s.out=out;s.sa_root=Path(a.sa_root).resolve();s.cimport=Path(a.c_import).resolve();s.c_export=a.c_export 154 s.rng=random.Random(627624);s.observations=0;s.sa_requests=0 155 def sa(s,cmd,data): 156 s.sa_requests+=1;return run(['bash','tools/source-aware/sa',cmd],data,cwd=str(s.sa_root)) 157 def identity(s,env): 158 r=s.sa('identity',env);check(r.returncode==0 and len(r.stdout)==32,'sa identity refused: rc=%d %s'%(r.returncode,r.stderr.decode(errors='replace'))) 159 check(r.stdout==hashlib.sha256(b'omega.source.semantic.v1'+semantic(env)).digest(),'sa identity differs from SHA256 semantic identity') 160 return r.stdout.hex() 161 def pyimport(s,src): 162 r=run([str(IMPORTER)],src);check(r.returncode==0 and r.stdout,'python import refused rc=%d %s'%(r.returncode,r.stderr.decode(errors='replace'))) 163 return r.stdout 164 def pyexport(s,env,name=None): 165 r=run([sys.executable,str(ECLI)]+([name] if name else []),env) 166 check(r.returncode==0 and r.stdout,'python export refused rc=%d %s'%(r.returncode,r.stderr.decode(errors='replace'))) 167 return r.stdout 168 def cimp(s,src): 169 r=run([str(s.cimport)],src);check(r.returncode==0,'C import refused rc=%d'%r.returncode);return r.stdout 170 def agree(s,tag,ops,nargs,legs): 171 """legs: name -> list of outputs; all must equal the REFERENCE evaluation of ops.""" 172 vs=legs.pop('_vectors');ref=[evaluate(ops,v) for v in vs] 173 for leg,vals in legs.items(): 174 if vals!=ref: 175 bad=[(list(v),x,y) for v,x,y in zip(vs,vals,ref) if x!=y][:5] 176 raise Fail('%s: %s disagrees with REFERENCE on %d vectors, e.g. %s'%(tag,leg,sum(x!=y for x,y in zip(vals,ref))+abs(len(vals)-len(ref)),bad)) 177 s.observations+=len(vs)*len(legs);return len(vs) 178 179 def same_language(ctx,case,cases_c): 180 tag=case['id'];src=case['source'].encode();nargs=case['inputs'];name=case['name'];out=ctx.out 181 check(hashlib.sha256(src).hexdigest()==case['sha256'],tag+' fixture sha256') 182 ua=ctx.pyimport(src) 183 cli=run([sys.executable,str(ICLI)],src);check(cli.returncode==0 and cli.stdout==ua,'public python-import differs from native') 184 ops=decode_python(ua,src,nargs);ident=ctx.identity(ua) 185 srcb=ctx.pyexport(ua) 186 check(ctx.pyexport(semonly(semantic(ua)))==srcb,'semantic-only envelope exports differently (replayed, not generated)') 187 native=run([str(EXPORTER)],b'\x00'+ua);check(native.returncode==0 and native.stdout==srcb,'native exporter differs from public command') 188 ub=ctx.pyimport(srcb);decode_python(ub,srcb,nargs);ctx.identity(ub) 189 check(N(strip(semantic(ub)))==N(strip(semantic(ua))),'compose 4.1 identity N(strip(U_B)) != N(strip(U_A))') 190 exact=semantic(ub)==semantic(ua) 191 row={'id':tag,'inputs':nargs,'ops':len(ops),'source_bytes':len(src),'identity':ident,'reimport_semantic_bytes_equal':exact, 192 'exported_sha256':hashlib.sha256(srcb).hexdigest()} 193 csrc=cases_c.get(case.get('f1') or case.get('control')) 194 if csrc is not None: 195 uc=ctx.cimp(csrc);check(N(strip(semantic(uc)))==N(strip(semantic(ua))),'F2 rewrite is not the F1 expression: N(strip()) differs from the C import') 196 check(N(semantic(uc))==N(semantic(ua)),'F2 rewrite N() differs from the C import');row['same_N_as_F1_C_import']=True 197 vs=vectors(nargs,ctx.rng) 198 legs={'_vectors':vs,'python3(original)':python_oracle(out,tag+'-orig',src,name,nargs,vs),'python3(exported)':python_oracle(out,tag+'-exp',srcb,'calc',nargs,vs)} 199 row['vectors']=ctx.agree(tag,ops,nargs,legs);row['result']='PASS';(out/(tag+'.exported.py')).write_bytes(srcb) 200 return row,srcb 201 202 def c_to_python(ctx,tag,csrc,name,nargs): 203 out=ctx.out;ua=ctx.cimp(csrc);ctx.identity(ua);ops=ops_of(semantic(ua)) 204 srcb=ctx.pyexport(ua);check(ctx.pyexport(semonly(semantic(ua)))==srcb,'C->Python: semantic-only export differs') 205 for m in ['Rust','Python']: 206 env=semonly(retarget(semantic(ua),m));ctx.identity(env) 207 check(ctx.pyexport(env)==srcb,'family: R(U,%s) exports differently'%m) 208 ub=ctx.pyimport(srcb);decode_python(ub,srcb,nargs) 209 check(N(strip(semantic(ub)))==N(strip(semantic(ua))),'C->Python identity N(strip(U_B)) != N(strip(U_A))') 210 vs=vectors(nargs,ctx.rng) 211 legs={'_vectors':vs,'cc(original C)':c_oracle(out,tag+'-c',csrc,name,nargs,vs),'python3(generated)':python_oracle(out,tag+'-py',srcb,'calc',nargs,vs)} 212 n=ctx.agree(tag,ops,nargs,legs);(out/(tag+'.generated.py')).write_bytes(srcb) 213 return {'id':tag,'identity':'PASS','differential':'PASS','legs':['REFERENCE','cc(original C)','python3(generated Python)'], 214 'native_realization':'NOT_RUN','vectors':n,'generated_sha256':hashlib.sha256(srcb).hexdigest(),'result':'PASS'},srcb 215 216 def python_to_c(ctx,case): 217 out=ctx.out;tag='P2C-'+case['id'];src=case['source'].encode();nargs=case['inputs'] 218 ua=ctx.pyimport(src);ops=ops_of(semantic(ua)) 219 # The section 6 C exporter (G1) accepts the C member only: retarget R(U, C) first. 220 rc=semonly(retarget(semantic(ua),'C'));ctx.identity(rc) 221 r=run([sys.executable,ctx.c_export],rc);check(r.returncode==0,'C export refused R(U,C) rc=%d %s'%(r.returncode,r.stderr.decode(errors='replace'))) 222 srcb=r.stdout;ub=ctx.cimp(srcb) 223 check(N(strip(semantic(ub)))==N(strip(semantic(ua))),'Python->C identity N(strip(U_B)) != N(strip(U_A))') 224 vs=vectors(nargs,ctx.rng) 225 legs={'_vectors':vs,'python3(original Python)':python_oracle(out,tag+'-py',src,case['name'],nargs,vs),'cc(generated C)':c_oracle(out,tag+'-c',srcb,'calc',nargs,vs)} 226 return {'id':tag,'identity':'PASS','differential':'PASS','retargeted_to_C_first':True,'native_realization':'NOT_RUN','vectors':ctx.agree(tag,ops,nargs,legs),'result':'PASS'} 227 228 def unit(recs,lang=1,profile=1,runtime=0,abi=1,dialect=None,types=None,obl_arith=None,contract=SEMHASH): 229 """Semantic-only envelope from (op,a,b,imm) records with registry attributes for u64 members.""" 230 dialect=lang if dialect is None else dialect;body=b'' 231 if obl_arith is None:obl_arith=5 if profile in (4,6) else 1 232 for op,a,b,imm in recs: 233 attr=0 if op==9 else 1;obl=1 if op==9 else 0 if op==1 else (obl_arith|2 if op==5 else obl_arith) 234 body+=struct.pack('<8BHHQ',dialect,1,op,1,attr,0,0,obl,a,b,imm) 235 return semonly(b'OMSA\x01'+bytes([lang,profile,1,runtime,abi])+struct.pack('python '+case['id']]=srcb.decode() 328 except Fail as e:failures.append({'case':case['id'],'failure':str(e)});same.append({'id':case['id'],'result':'FAIL','failure':str(e)}) 329 for f in f1['positives']: 330 try: 331 row,srcb=c_to_python(ctx,'C2P-'+f['id'],f['source'].encode(),f['name'],f['inputs']);c2p.append(row) 332 if f['id'] in ('F1-P05','F1-P13'):shown['C->Python '+f['id']]=srcb.decode() 333 except Fail as e:failures.append({'case':'C2P-'+f['id'],'failure':str(e)}) 334 for cid,csrc in controls_c.items(): 335 try:c2p.append(c_to_python(ctx,'C2P-ctl-'+cid,csrc,'calc',2)[0]) 336 except Fail as e:failures.append({'case':'C2P-ctl-'+cid,'failure':str(e)}) 337 if a.c_export: 338 for case in fx['positives']+fx['controls']: 339 try:p2c.append(python_to_c(ctx,case)) 340 except Fail as e:failures.append({'case':'P2C-'+case['id'],'failure':str(e)}) 341 p2c_status={'status':'RUN','c_export':a.c_export,'note':'R(U, C) applied before the C exporter (it accepts the C member only)'} 342 else: 343 p2c_status={'status':'NOT_RUN','reason':'no --c-export given (translation-v1 section 6 exporter is not on this base)'} 344 try:exp=exporter_checks(ctx) 345 except Fail as e:failures.append({'case':'exporter-checks','failure':str(e)});exp=[] 346 neg=refusals(ctx,fx);failures+=[{'case':r['id'],'failure':'refusal status %d != %d'%(r['exit'],r['want'])} for r in neg if r['result']!='PASS'] 347 try:pub=public_checks(ctx) 348 except Fail as e:failures.append({'case':'public-commands','failure':str(e)});pub=[] 349 report.update({'result':'FAIL' if failures else 'PASS','same_language':{'executed':len(same),'passed':sum(r.get('result')=='PASS' for r in same),'cases':same}, 350 'not_in_profile':fx['not_in_profile'], 351 'compositions':{'C->Python':{'executed':len(c2p),'passed':sum(r['result']=='PASS' for r in c2p),'native_realization':'NOT_RUN (translation-v1 section 5 lowering is not on this base)','cases':c2p}, 352 'Python->C':dict(p2c_status,executed=len(p2c),passed=sum(r['result']=='PASS' for r in p2c),cases=p2c)}, 353 'refusals':{'executed':len(neg),'passed':sum(r['result']=='PASS' for r in neg),'cases':neg}, 354 'exporter_checks':{'executed':len(exp),'passed':len(exp),'cases':exp},'public_command_checks':pub, 355 'observations':ctx.observations,'source_aware_requests':ctx.sa_requests,'shown_exports':shown,'failures':failures}) 356 (out/'result.json').write_text(json.dumps(report,indent=2)+'\n') 357 for k,v in shown.items():print('--- '+k+'\n'+v,end='') 358 summary={'result':report['result'],'same_language':'%d/%d'%(report['same_language']['passed'],len(same)), 359 'C->Python':'%d/%d (native realization NOT_RUN)'%(report['compositions']['C->Python']['passed'],len(c2p)), 360 'Python->C':p2c_status['status']+(' %d/%d'%(len(p2c),len(p2c)) if a.c_export and not any(f['case'].startswith('P2C') for f in failures) else ''), 361 'refusals':'%d/%d'%(report['refusals']['passed'],len(neg)),'exporter_checks':len(exp),'public_command_checks':len(pub), 362 'not_in_profile':len(fx['not_in_profile']),'observations':ctx.observations,'sa_requests':ctx.sa_requests} 363 print(json.dumps(summary,indent=1)) 364 for f in failures[:20]:print('FAIL',f['case'],f['failure'][:300]) 365 print(('PASS' if not failures else 'FAIL')+' python-u64 selftest; report '+str(out/'result.json')) 366 return 1 if failures else 0 367 368 if __name__=='__main__':raise SystemExit(main())