#!/usr/bin/env python3 """Scoped proofs of extracted RTL arithmetic, selection and storage. Each mode records its assumptions and scope; none is a full motor proof. """ from pathlib import Path import argparse,datetime,hashlib,json,os,re,signal,subprocess,sys ROOT=Path(__file__).resolve().parents[1] if str(ROOT) not in sys.path:sys.path.insert(0,str(ROOT)) from tools.source_identity import source_identity def plaintext_vendor_model(path,name): """Select an already-visible complete module; never decode protected data.""" original=Path(path).read_bytes() visible=original.split(b'`pragma protect begin_protected',1)[0] starts=re.findall(rb'(?m)^\s*module\s+(\w+)\b',visible) ends=list(re.finditer(rb'(?m)^\s*endmodule\b',visible)) if starts!=[name.encode('ascii')] or len(ends)!=1 or visible[ends[0].end():].strip(): raise ValueError('complete standalone plaintext vendor module unavailable: '+name) return visible,{'path':str(Path(path).resolve()),'size':len(original), 'sha256':hashlib.sha256(original).hexdigest(),'plaintext_size':len(visible), 'plaintext_sha256':hashlib.sha256(visible).hexdigest(), 'selection':'unchanged plaintext prefix before first protected section; protected contents not used'} def resolve_vendor_library(library_root=None): if library_root is not None:return Path(library_root) roots=[Path(os.environ.get('PRODU2_TD_ROOT','/data/anlogic/TD_Release_2026.1_SP2_NL')), Path('/data/prod2u/toolchain/TD_Release_2026.1_SP2_NL/TD_Release_2026.1_SP2_NL')] return next((r/'sim_release/ef2' for r in roots if os.access(r/'bin/td',os.X_OK)),roots[-1]/'sim_release/ef2') def verify_vendor_state_delay(out,library_root=None): source=ROOT/'src/motor/motor_axis_core.v';test=ROOT/'tests/sim/motor_axis_bank_tb.v' library_root=resolve_vendor_library(library_root) result={'scope':'actual EF2_LOGIC_MULT plaintext vendor model in the production state-bank path; not full vendor netlist or hardware verification', 'source':source_identity(ROOT),'inputs':{str(p.relative_to(ROOT)):hashlib.sha256(p.read_bytes()).hexdigest() for p in (source,test,Path(__file__).resolve())}, 'results':[],'hardware':'NOT_RUN','full_vendor_netlist':'NOT_RUN'} def run(name,command,expected=0,marker=None,counts=False): log=out/(name+'.log') with log.open('w') as stream: process=subprocess.Popen(command,cwd=ROOT,stdout=stream,stderr=subprocess.STDOUT,start_new_session=True) try:code=process.wait(timeout=180) except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait();code=124 text=log.read_text(errors='replace') checks={int(a):int(n) for a,n in re.findall(r'AXIS_BANK_(\d+)_CHECKS=(\d+)',text)} if counts else None ok=code==expected and (marker is None or marker in text) if counts:ok=ok and set(checks)=={1,2,3,12} and all(n>=1000 for n in checks.values()) result['results'].append({'name':name,'command':command,'exit_code':code,'expected_exit':expected, 'status':'PASS' if ok else ('UNKNOWN_TIMEOUT' if code==124 else 'FAIL'), 'checks_by_axis_count':checks,'log_sha256':hashlib.sha256(log.read_bytes()).hexdigest()}) print(name,result['results'][-1]['status'],flush=True) if not ok:raise RuntimeError(name) try: model,identity=plaintext_vendor_model(Path(library_root)/'ef2_logic_mult.v','EF2_LOGIC_MULT') result['vendor_model']=identity selected=out/'EF2_LOGIC_MULT.v';selected.write_bytes(model) result['tools']={name:subprocess.check_output([name,flag],stderr=subprocess.STDOUT).decode(errors='replace') for name,flag in [('iverilog','-V'),('verilator','--version')]} common=['-DPROD2U_TD_VENDOR_RAM','-I'+str(ROOT)] run('icarus-compile',['iverilog','-g2012',*common,'-s','motor_axis_bank_tb','-o',str(out/'bank.vvp'),str(source),str(selected),str(test)]) run('icarus-run',['vvp',str(out/'bank.vvp')],marker='motor_axis_bank_tb PASS',counts=True) obj=out/'obj' run('verilator-compile',['verilator','--binary','--timing','-Wno-fatal','-j','2',*common,'--top-module','motor_axis_bank_tb','--Mdir',str(obj),str(source),str(selected),str(test)]) run('verilator-run',[str(obj/'Vmotor_axis_bank_tb')],marker='motor_axis_bank_tb PASS',counts=True) original=source.read_text(encoding='utf-8');before='.OUTPUTREG("ENABLE"),.IMPLEMENT("DSP")' if original.count(before)!=1:raise ValueError('vendor output-register mutation target changed') mutant=out/'missing_product_register.v';mutant.write_text(original.replace(before,'.OUTPUTREG("DISABLE"),.IMPLEMENT("DSP")'),encoding='utf-8') run('mutation-compile',['iverilog','-g2012',*common,'-s','motor_axis_bank_tb','-o',str(out/'mutation.vvp'),str(mutant),str(selected),str(test)]) run('mutation-run',['vvp',str(out/'mutation.vvp')],expected=1,marker='post-clock rotation mismatch') result['status']='PASS' except Exception as error:result.update(status='INCOMPLETE',error=repr(error)) (out/'RESULT.json').write_text(json.dumps(result,indent=2)+'\n') return 0 if result['status']=='PASS' else 1 def prove_state_delay(out,library_root=None,vendor_model=False): source=ROOT/'src/motor/motor_axis_core.v';raw=source.read_text(encoding='utf-8') bank=re.search(r'module motor_axis_words #\(.*?endmodule',raw,re.S).group(0) primitive=re.search(r'module ef2_motor_delay18\(.*?endmodule',raw,re.S).group(0) required=['.INPUT_WIDTH_A(18)','.INPUT_WIDTH_B(18)','.OUTPUT_WIDTH(36)', '.INPUTFORMAT("UNSIGNED")','.INPUTREGA("ENABLE")','.INPUTREGB("DISABLE")', '.OUTPUTREG("ENABLE")','.IMPLEMENT("DSP")','.SRMODE("ASYNC")', '.a(data)',".b(18'd1)",'.p(product)',".cea(1'b1)",".ceb(1'b1)",".cepd(1'b1)", '.clk(clk)','.rstan(rst_n)','.rstbn(rst_n)','.rstpdn(rst_n)','assign delayed=product[17:0];'] if any(primitive.count(item)!=1 for item in required):raise ValueError('documented DSP configuration changed') bits=int(re.search(r'wire \[(\d+):0\] dsp_delayed;',bank).group(1))+1 bank=bank.replace('output wire [321:0] read_data);','output wire [321:0] read_data,output wire [321:0] reference_data,output wire proof_bad);') bank=bank.replace(f'wire [{bits-1}:0] dsp_delayed;',f'''wire [{bits-1}:0] dsp_delayed,proof_inputs; wire [AXIS_COUNT-1:0] proof_stages_bad; assign proof_stages_bad[0]=proof_inputs!=words[AXIS_COUNT-1][32+:{bits}]; assign proof_stages_bad[1]=dsp_delayed!=words[AXIS_COUNT-2][32+:{bits}]; assign proof_bad=|proof_stages_bad;''') bank=bank.replace('.delayed(dsp_delayed[d*18+:18]));', '.delayed(dsp_delayed[d*18+:18]),.proof_input_stage(proof_inputs[d*18+:18]));') bank=bank.replace('assign complete_delay=stages[AXIS_COUNT-3];',f'''assign complete_delay=stages[AXIS_COUNT-3]; genvar proof_i; for(proof_i=0;proof_i1: changed=(model.replace('.OUTPUTREG("ENABLE"),.IMPLEMENT("DSP")','.OUTPUTREG("DISABLE"),.IMPLEMENT("DSP")') if vendor_model else model.replace('product_stage<=input_stage','product_stage<=data')) if changed==model:raise ValueError('state delay mutation missing') variants[f'state_{axes}_latency_mutation']=(changed,'mutation',axes) result={'scope':'behavioral state-bank equivalence to original shift registers; documented primitive parameter check; not vendor/hardware simulation', 'source':source_identity(ROOT),'inputs':{str(p.relative_to(ROOT)):hashlib.sha256(p.read_bytes()).hexdigest() for p in (source,Path(__file__).resolve())}, 'primitive_configuration_checked':required,'inductive_invariant':'each DSP input/product and fabric tail stage equals the original shift-register stage at the same age', 'primitive_assumption':'UG401 section17 input A register plus product register with unsigned B=1; physical vendor model not exercised', 'tool':subprocess.check_output(['yosys','-V'],text=True).strip(),'results':[],'hardware':'NOT_RUN'} if vendor_model: result.update(scope='actual EF2_LOGIC_MULT functional RTL state-bank equivalence; not mapped whole-device or hardware proof', vendor_model=vendor_identity,primitive_assumption='supplied vendor functional RTL; physical timing and protected whole-device models are outside scope') for name,(rtl,kind,axes) in variants.items(): path=out/(name+'.v');path.write_text(rtl,encoding='utf-8');log=out/(name+'.log') goal=(f'sat -seq {axes+2} -set rst_n 1 -set-at 1 rst_n 0 -set-at {axes+2} observed 1 -show observed' if kind=='cover' else f'sat -seq 2 -tempinduct -maxsteps {axes+2} -set-at 1 rst_n 0 -prove bad 0 -verify') defines='-DPROD2U_TD_VENDOR_RAM ' if vendor_model else '' command=['yosys','-p',f'read_verilog -formal {defines}{json.dumps(str(path),ensure_ascii=False)}; prep -top proof -flatten; memory_map; opt; async2sync; opt; {goal}'] with log.open('w') as stream: process=subprocess.Popen(command,stdout=stream,stderr=subprocess.STDOUT,start_new_session=True) try:code=process.wait(timeout=90) except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait();code=124 output=log.read_text(errors='replace') ok=(code==0 and 'SUCCESS!' in output) if kind=='proof' else ((code==1 and 'proof did fail' in output) if kind=='mutation' else (code==0 and 'model found:' in output)) result['results'].append({'name':name,'command':command,'exit_code':code,'status':'PASS' if ok else ('UNKNOWN_TIMEOUT' if code==124 else 'FAIL'), 'log_sha256':hashlib.sha256(log.read_bytes()).hexdigest(),'miter_sha256':hashlib.sha256(path.read_bytes()).hexdigest()}) print(name,result['results'][-1]['status'],flush=True) result['status']='PASS' if all(x['status']=='PASS' for x in result['results']) else 'INCOMPLETE' (out/'RESULT.json').write_text(json.dumps(result,indent=2)+'\n') return 0 if result['status']=='PASS' else 1 def prove_history_rotation(out): engine=ROOT/'src/motor/motor_engine.v';core=ROOT/'src/motor/motor_axis_core.v' text=engine.read_text(encoding='utf-8');producer=core.read_text(encoding='utf-8') module=re.search(r'module motor_limit_history #\(.*?endmodule',text,re.S).group(0) # Expose storage only in the proof copy; retain all actual state updates. module=module.replace('output wire [159:0] read_data', 'output wire [159:0] read_data, output wire [AXIS_COUNT*160-1:0] proof_records') module=module.replace('endmodule','genvar p; generate for(p=0;p=N || scan_axis>=N || head!=(scan_axis==0 ? N-1 : scan_axis-1'b1)); if(event_valid && emitted_axis!=head)mismatch=1; for(k=0;k=N)logical_axis=logical_axis-N; if(valid[logical_axis] && physical[k*160+:160]!=reference[logical_axis])mismatch=1; end if(valid[head] && actual!=reference[head])mismatch=1; end assign bad=initialized && rst_n && mismatch; assign observed=&valid; endmodule ''' full=module+'\n'+miter if axes==3: variants[f'history_{axes}_proof']=(full,'proof',axes) else: # Prove the complete160-bit record as ten disjoint16-bit goals. # Each goal keeps the actual unmodified storage and all scan/valid # state; synthesis may discard unobserved data lanes. Their union # covers every bit, avoiding the monolithic million-variable SAT. for low in range(0,160,16): lane=full.replace('physical[k*160+:160]!=reference[logical_axis]', f'physical[k*160+{low}+:16]!=reference[logical_axis][{low}+:16]') lane=lane.replace('actual!=reference[head]',f'actual[{low}+:16]!=reference[head][{low}+:16]') variants[f'history_{axes}_bits_{low}_{low+15}_proof']=(lane,'proof',axes) variants[f'history_{axes}_cover']=(full,'cover',axes) phase=full.replace('read_axis<=AXIS_COUNT-1;','read_axis<=0;') drop=full.replace('write_enable ? write_data : records[0]','records[0]') if phase==full or drop==full:raise ValueError('history mutation did not alter actual module') variants[f'history_{axes}_phase_mutation']=(phase,'mutation',axes) variants[f'history_{axes}_write_mutation']=(drop,'mutation',axes) result={'scope':'inductive rotating-history storage equivalence and checked producer scan form; not full motor/event proof', 'source':source_identity(ROOT),'inputs':{str(p.relative_to(ROOT)):hashlib.sha256(p.read_bytes()).hexdigest() for p in (engine,core,Path(__file__).resolve())}, 'assumptions':'arbitrary record data and event enable; actual producer scan/reset/write form checked; initial reset, later reset unrestricted', 'tool':subprocess.check_output(['yosys','-V'],text=True).strip(),'results':[],'hardware':'NOT_RUN'} for name,(rtl,kind,axes) in variants.items(): path=out/(name+'.v');path.write_text(rtl,encoding='utf-8');log=out/(name+'.log') goal=(f'sat -seq {axes+3} -set rst_n 1 -set-at 1 rst_n 0 -set-at {axes+3} observed 1 -show observed' if kind=='cover' else 'sat -seq 2 -tempinduct -maxsteps 4 -set-at 1 rst_n 0 -prove bad 0 -verify') command=['yosys','-p',f'read_verilog -formal {json.dumps(str(path),ensure_ascii=False)}; prep -top proof -flatten; memory_map; opt; async2sync; opt; {goal}'] with log.open('w') as stream: process=subprocess.Popen(command,stdout=stream,stderr=subprocess.STDOUT,start_new_session=True) try:code=process.wait(timeout=90) except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait();code=124 output=log.read_text(errors='replace') ok=(code==0 and 'SUCCESS!' in output) if kind=='proof' else ((code==1 and 'proof did fail' in output) if kind=='mutation' else (code==0 and 'model found:' in output)) result['results'].append({'name':name,'command':command,'exit_code':code,'status':'PASS' if ok else ('UNKNOWN_TIMEOUT' if code==124 else 'FAIL'), 'log_sha256':hashlib.sha256(log.read_bytes()).hexdigest(),'miter_sha256':hashlib.sha256(path.read_bytes()).hexdigest()}) print(name,result['results'][-1]['status'],flush=True) result['status']='PASS' if all(row['status']=='PASS' for row in result['results']) else 'INCOMPLETE' (out/'RESULT.json').write_text(json.dumps(result,indent=2)+'\n') return 0 if result['status']=='PASS' else 1 def prove_event_losses(out): engine=ROOT/'src/motor/motor_engine.v';core=ROOT/'src/motor/motor_axis_core.v' text=engine.read_text(encoding='utf-8');producer=core.read_text(encoding='utf-8') shapes={} for signal_name in ('done_pulse','limit_event_pulse'): writes=re.findall(r'\b'+signal_name+r'(\[[^\]]+\])?\s*<=\s*([^;]+);',producer) if not writes or not any(index for index,_ in writes):raise ValueError('producer write shape missing') if any(not ((not index and value.strip()=='0') or (index=='[scan_axis]' and value.strip()=='1')) for index,value in writes): raise ValueError('producer no longer has a single-destination write shape') if re.search(r'\b'+signal_name+r'(?:\[[^\]]+\])?\s*(?:\|=|&=|\^=|\+=|-=|=(?!=))',producer): raise ValueError('unexpected producer blocking/compound assignment') shapes[signal_name]=writes if 'end else begin\n done_pulse<=0;seg_consumed<=0;limit_event_pulse<=0;' not in producer: raise ValueError('unconditional per-clock producer clear changed') start=text.index(' for(ev_scan=0;',text.index('// The core emits at most one record')) end=text.index('\n end\n always @(posedge clk',start) body=text[start:end] condition='ax_done[ev_scan] && (event_for_stop(ax_reason[ev_scan])!=0 || (home_pending_r[ev_scan] && ax_reason[ev_scan]==SR_LOWER))' if body.count(condition)!=1:raise ValueError('completion qualification expression changed') body=body.replace(condition,'accepted_done[ev_scan]') declarations='\n'.join(re.search(r'wire\s+\[[^\]]+\]\s+'+name+r'=[^;]+;',text).group(0) for name in ('pending_loss_total','pending_losses')) variants={} for axes in (3,12): prefix=f'''module proof(input [{axes-1}:0] ax_limit_pulse,accepted_done,limit_pending,done_pending, input [{axes*4-1}:0] ax_limit_drops,input ev_wr_req,reset_pending,select_limit,event_dispatch_ready, input signed [31:0] ev_select,output bad,output [8:0] observed); localparam AXIS_COUNT={axes}; integer ev_scan,j;reg [3:0] pending_drop_union;reg pending_limit_loss,pending_done_loss; reg[8:0] reference_losses; {declarations} always @* begin pending_drop_union=0;pending_limit_loss=0;pending_done_loss=0; ''' reference=f''' end always @* begin reference_losses=0; for(j=0;j<{axes};j=j+1)begin if(ax_limit_pulse[j])begin reference_losses=reference_losses+ax_limit_drops[j*4+:4]; if(limit_pending[j] && (ev_wr_req || reset_pending || ev_select!=j || !select_limit || !event_dispatch_ready))reference_losses=reference_losses+1'b1; end if(accepted_done[j] && done_pending[j] && (ev_wr_req || reset_pending || ev_select!=j || select_limit || !event_dispatch_ready))reference_losses=reference_losses+1'b1; end end wire premise=((ax_limit_pulse & (ax_limit_pulse-1'b1))==0) && ((accepted_done & (accepted_done-1'b1))==0); assign bad=premise && (pending_losses!=reference_losses); assign observed=premise ? pending_losses : 0; endmodule ''' rtl=prefix+body+reference variants[f'loss_{axes}_proof']=(rtl,'proof') mutation=rtl.replace("{1'b0,pending_drop_union}","5'd0") if mutation==rtl:raise ValueError('event-loss mutation did not change RTL') variants[f'loss_{axes}_mutation']=(mutation,'mutation') variants[f'loss_{axes}_cover']=(rtl,'cover') # The checked source write form is zero plus arbitrary enables writing # bit scan_axis. Model all enables and qualification masks freely. emitter=f'''module proof(input [3:0] scan_axis,input done_enable,limit_enable, input [{axes-1}:0] qualification,output bad,output [8:0] observed); reg [{axes-1}:0] done,limit; always @* begin done=0;limit=0;if(done_enable)done[scan_axis]=1;if(limit_enable)limit[scan_axis]=1;end wire [{axes-1}:0] accepted=done & qualification; assign bad=((done & (done-1'b1))!=0) || ((limit & (limit-1'b1))!=0) || ((accepted & (accepted-1'b1))!=0); assign observed=0; endmodule ''' variants[f'producer_form_{axes}_proof']=(emitter,'proof') result={'scope':'event-loss combinational equivalence plus checked producer write-form proof; not full sequential motor proof', 'source':source_identity(ROOT),'inputs':{str(p.relative_to(ROOT)):hashlib.sha256(p.read_bytes()).hexdigest() for p in (core,engine,Path(__file__).resolve())}, 'producer_write_shapes':shapes,'premise':'at most one emitted limit and one qualified completion per clock; producer form checked separately', 'tool':subprocess.check_output(['yosys','-V'],text=True).strip(),'results':[],'hardware':'NOT_RUN'} for name,(rtl,kind) in variants.items(): path=out/(name+'.v');path.write_text(rtl,encoding='utf-8');log=out/(name+'.log') goal='sat -set observed 3 -show-inputs' if kind=='cover' else 'sat -verify -prove bad 0 -show-inputs' command=['yosys','-p',f'read_verilog -formal {json.dumps(str(path),ensure_ascii=False)}; prep -top proof; {goal}'] with log.open('w') as stream: process=subprocess.Popen(command,stdout=stream,stderr=subprocess.STDOUT,start_new_session=True) try:code=process.wait(timeout=90) except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait();code=124 output=log.read_text(errors='replace') ok=(code==0 and 'SUCCESS!' in output) if kind=='proof' else ((code==1 and 'proof did fail' in output) if kind=='mutation' else (code==0 and 'model found:' in output)) result['results'].append({'name':name,'command':command,'exit_code':code,'status':'PASS' if ok else ('UNKNOWN_TIMEOUT' if code==124 else 'FAIL'), 'log_sha256':hashlib.sha256(log.read_bytes()).hexdigest(),'miter_sha256':hashlib.sha256(path.read_bytes()).hexdigest()}) result['status']='PASS' if all(row['status']=='PASS' for row in result['results']) else 'INCOMPLETE' (out/'RESULT.json').write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(result,indent=2)) return 0 if result['status']=='PASS' else 1 def prove_selector(out): source=ROOT/'src/motor/motor_engine.v' raw=source.read_text(encoding='utf-8') start=raw.index(' always @* begin',raw.index('// Factor one-bit eligibility/priority')) end=raw.index('\n end\n',start)+len('\n end\n') actual=raw[start:end] inputs={str(p.relative_to(ROOT)):hashlib.sha256(p.read_bytes()).hexdigest() for p in (source,Path(__file__).resolve(),ROOT/'projects/mrdimm-chamber/project.json')} result={'schema':'prod2u-queue-selector-proof-v1','scope':'extracted combinational eligibility and circular winner only; no sequential or STEP proof', 'source':source_identity(ROOT),'inputs':inputs,'source_manifest_sha256':hashlib.sha256(json.dumps(inputs,sort_keys=True).encode()).hexdigest(), 'tool':subprocess.check_output(['yosys','-V'],text=True).strip(), 'assumptions':['fx_round is a legal axis index; all eligibility/control/depth input bits otherwise arbitrary'], 'results':[],'hardware':'NOT_RUN','status':'RUNNING'} for axes in (3,12): width=(axes-1).bit_length() prefix=f'''module selector(input [{width-1}:0] fx_round, input [{axes-1}:0] ax_load_ready,ax_seg_load,queue_paused_r,cs_start_mask,cs_mask,urgent_valid_r, input [1:0] cs_state,input seek_context,input [{axes*6-1}:0] depths, output bad,output reg [7:0] fx_candidate,output reg fx_candidate_valid); localparam AXIS_COUNT={axes}; wire [5:0] depth_r[0:AXIS_COUNT-1]; genvar g;generate for(g=0;g=fx_round ? axis-fx_round : axis+AXIS_COUNT-fx_round; if(allowed && distance=0;fx_k=fx_k-1)','for(fx_k=0;fx_k