interplane.Get Omega
Read in your language

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

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
4For every F2-rust fixture: Rust import, independent decode, #621 `sa` identity/decode/replay, cross-importer
5identity against the C import of the F1 source, export (all three S1 members, with and without sidecar),
6re-import identity (translation-compose-v1 section 4.1), and rustc DIFFERENTIAL (original and exported
7Rust, -O -C overflow-checks=on) against a bigint evaluation of the records. Compositions C->Rust always;
8Rust->C only with --c-export (the G1 C exporter accepts C-member units only, so R(U, C) is applied first).
9"""
10from pathlib import Path
11import argparse,hashlib,json,os,random,shutil,struct,subprocess,sys,tempfile
12ROOT=Path(__file__).resolve().parents[3]
13MASK=(1<<64)-1
14SEMDOM=b'omega.source.semantic.v1'
15CONTRACT=hashlib.sha256((ROOT/'spec/universal/semantics.md').read_bytes()).digest()
16MEMBERS={'C':(1,1,1),'Rust':(2,2,1),'Python':(3,4,5)} # language, profile, arithmetic obligations
17BOUNDARY=[0,1,2,(1<<32)-1,1<<32,(1<<63)-1,1<<63,MASK-1,MASK]
18IMPORT=ROOT/'tools/adapters/rust-import';EXPORT=ROOT/'tools/adapters/rust-export'
19
20class Fail(Exception):pass
21def check(c,msg):
22 if not c:raise Fail(msg)
23
24def run(cmd,data,cwd=None,timeout=60):
25 return subprocess.run(cmd,input=data,capture_output=True,timeout=timeout,cwd=cwd)
26
27def py(tool,data):return run([sys.executable,str(tool)],data)
28
29# ---- independent envelope model (not the #621 core) ----
30def split(env):
31 check(len(env)>=13 and env[:5]==b'OMSB\x01','bad envelope magic')
32 ns,np_=struct.unpack_from('<II',env,5);check(len(env)==13+ns+np_,'bad envelope length')
33 return env[13:13+ns],env[13+ns:]
34
35def ops_of(sem):
36 count=struct.unpack_from('<H',sem,10)[0];check(len(sem)==44+20*count,'bad semantic length')
37 return [struct.unpack_from('<8BHHQ',sem,44+20*i) for i in range(count)]
38
39def decode(env,member):
40 lang,prof,arob=MEMBERS[member]
41 sem,side=split(env)
42 check(sem[:5]==b'OMSA\x01' and sem[5]==lang and sem[6]==prof and sem[7:10]==b'\x01\x00\x01','wrong %s header'%member)
43 check(sem[12:44]==CONTRACT,'wrong parent semantics hash')
44 ops=[];slots=[]
45 for i,(d,v,op,t,attr,eff,alias,obl,a,b,imm) in enumerate(ops_of(sem)):
46 check(d==lang and v==1 and t==1 and eff==0 and alias==0,'op %d fields'%i)
47 if op==9:check(attr==0 and obl==1 and a==b==65535,'input op');slots.append(imm)
48 elif op==1:check(attr==1 and obl==0 and a==b==65535,'const op')
49 else:check(op in (2,3,4) and attr==1 and obl==arob and a<i and b<i and imm==0,'arith op %d'%i)
50 ops.append((op,a,b,imm))
51 check(sorted(slots)==list(range(len(slots))),'input slots not a permutation')
52 return sem,side,ops
53
54def sidecar(sem,side,src,count):
55 check(side[:6]==b'OMSP\x01\x01','sidecar must be v1 encoding 1 (strict UTF-8)')
56 check(struct.unpack_from('<I',side,6)[0]==len(src) and side[10:42]==hashlib.sha256(sem).digest() and side[42:74]==hashlib.sha256(src).digest(),'bad sidecar binding')
57 check(len(side)==74+8*count+len(src) and side[74+8*count:]==src,'sidecar source mismatch')
58 return [struct.unpack_from('<II',side,74+8*i) for i in range(count)]
59
60def evaluate(ops,args):
61 vals=[]
62 for op,a,b,imm in ops:
63 v=args[imm] if op==9 else imm if op==1 else vals[a]+vals[b] if op==2 else vals[a]-vals[b] if op==3 else vals[a]*vals[b]
64 vals.append(v&MASK)
65 return vals[-1]
66
67def normalized(ops):
68 n=len(ops)
69 return n>=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]<n-2
70
71def retarget(sem,member):
72 """R(U, M), translation-compose-v1 section 2: header language/profile, op dialect, arithmetic obligations."""
73 lang,prof,arob=MEMBERS[member];b=bytearray(sem);b[5]=lang;b[6]=prof
74 for i,(_,_,op,*_) in enumerate(ops_of(sem)):
75 b[44+20*i]=lang
76 if op in (2,3,4):b[44+20*i+7]=arob
77 return bytes(b)
78
79def N(sem):return retarget(sem,'C')
80
81def strip(sem):
82 ops=ops_of(sem)
83 if not normalized([(o[2],o[8],o[9],o[10]) for o in ops]):return sem
84 n=len(ops)-2;b=bytearray(sem[:44+20*n]);struct.pack_into('<H',b,10,n);return bytes(b)
85
86def semonly(sem):return b'OMSB\x01'+struct.pack('<II',len(sem),0)+sem
87def identity(sem):return hashlib.sha256(SEMDOM+sem).hexdigest()
88
89# ---- oracles ----
90class Oracles:
91 def __init__(s,out,rustc,cc):s.out=out;s.rustc=rustc;s.cc=cc;s.cache={};s.compiles=0
92 def build(s,kind,text,name,nargs):
93 key=hashlib.sha256(kind.encode()+b'\0'+name.encode()+b'\0'+text).hexdigest()
94 if key in s.cache:return s.cache[key]
95 d=s.out/'oracle';d.mkdir(exist_ok=True);exe=d/key[:24]
96 if kind=='rust':
97 call=name+'('+', '.join('v[%d]'%j for j in range(nargs))+')'
98 harness=('\nfn main() {\n use std::io::BufRead;\n for line in std::io::stdin().lock().lines() {\n'
99 ' let line = line.unwrap();\n let v: Vec<u64> = 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 <stdio.h>\n#include <inttypes.h>\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
118def 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
124def 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('<H',len(ops))+CONTRACT
273 for op,attr,eff,alias,obl,a,b,imm in ops:sem+=struct.pack('<8BHHQ',lang,1,op,typ,attr,eff,alias,obl,a,b,imm)
274 return semonly(sem)
275 U=65535
276 def shared(k): # t_j = add(t_{j-1}, t_{j-1}): tree size 2^k, depth k
277 ops=[(9,0,0,0,1,U,U,0)]+[(2,1,0,0,1,j,j,0) for j in range(k)]
278 return unit(2,2,0,1,ops)
279 bigint=unit(3,3,1,1,[(9,0,0,0,1,U,U,0),(9,0,0,0,1,U,U,1),(2,2,20,255,8,0,1,0)],typ=2)
280 divc=unit(1,1,0,1,[(9,0,0,0,1,U,U,0),(9,0,0,0,1,U,U,1),(5,1,0,0,3,0,1,0)])
281 gap=unit(2,2,0,1,[(9,0,0,0,1,U,U,1)])
282 flipped=bytearray(good);flipped[-3]^=1
283 xr=[('truncated',good[:-1],65),('bad-magic',b'X'+good[1:],65),('sidecar-source-mismatch',bytes(flipped),65),('oversize',good+b'\0'*(8193-len(good)),65),
284 ('profile3-bigint',bigint,68),('c-div-op5',divc,68),('slot-gap',gap,68),('language-profile-mismatch',bytes(good[:18])+b'\x01'+good[19:],68),
285 ('shared-ops-over-capacity',shared(6),67),('depth-over-limit',None,67),('size-over-limit',shared(9),67)]
286 deep=[(9,0,0,0,1,U,U,0)]
287 for j in range(17):deep.append((2,1,0,0,1,0,j,0))
288 xr[9]=('depth-over-limit',unit(2,2,0,1,deep),67)
289 xrows=[]
290 for name,env,want in xr:
291 if name in ('profile3-bigint','c-div-op5'):check(sa('decode',env).returncode==0,name+' control is not a valid v1 unit')
292 r=rexport(env);ok=r.returncode==want and not r.stdout and r.stderr.startswith(b'RUST_EXPORT_')
293 it={'name':name,'want':want,'exit':r.returncode,'stderr':r.stderr.decode(errors='replace').strip(),'result':'PASS' if ok else 'FAIL'}
294 if not ok:failures.append(it)
295 xrows.append(it)
296 # Accepted exporter boundaries: shared SSA expanded to exactly 64 re-import operations, call depth exactly 16.
297 exact=[(9,0,0,0,1,U,U,0)]+[(2,1,0,0,1,j,j,0) for j in range(5)]+[(2,1,0,0,1,5,4,0),(2,1,0,0,1,6,3,0),(2,1,0,0,1,7,2,0),(2,1,0,0,1,8,1,0)]
298 for name,env in (('shared-ops-at-capacity',unit(2,2,0,1,exact)),('depth-at-limit',unit(2,2,0,1,deep[:17]))):
299 it={'name':name}
300 try:
301 sem,_=split(env);ops=[(o[2],o[8],o[9],o[10]) for o in ops_of(sem)];r=rexport(env);check(r.returncode==0,name+' refused rc=%d'%r.returncode)
302 q=rimport(r.stdout);check(q.returncode==0,name+' re-import refused');_,_,ops2=decode(q.stdout,'Rust')
303 check(len(ops2)==(64 if name=='shared-ops-at-capacity' else 19),name+' re-import operation count %d'%len(ops2))
304 vec=vectors(1,rng);ref=[evaluate(ops,v) for v in vec]
305 check([evaluate(ops2,v) for v in vec]==ref and O.values('rust',r.stdout,'calc',vec)==ref,name+' evaluation')
306 it.update(result='PASS',reimport_ops=len(ops2),identity_equal=N(strip(split(q.stdout)[0]))==N(strip(sem)))
307 except (Fail,ValueError,struct.error) as e:it.update(result='FAIL',failure=str(e));failures.append(it)
308 xrows.append(it)
309
310 # ---- composition C -> Rust: F1 positives and the four accepted C import boundary controls ----
311 ch=b'#include <stdint.h>\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 <stdint.h>\nuint64_t calc(uint64_t a,uint64_t b){return '+b'+'.join([b'a']*61)+b';}','calc',2),
314 ('C-nesting-limit',b'#include <stdint.h>\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
364if __name__=='__main__':raise SystemExit(main())