verify_motor_arithmetic.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. #!/usr/bin/env python3
  2. """Scoped proofs of extracted RTL arithmetic, selection and storage.
  3. Each mode records its assumptions and scope; none is a full motor proof.
  4. """
  5. from pathlib import Path
  6. import argparse,datetime,hashlib,json,os,re,signal,subprocess,sys
  7. ROOT=Path(__file__).resolve().parents[1]
  8. if str(ROOT) not in sys.path:sys.path.insert(0,str(ROOT))
  9. from tools.source_identity import source_identity
  10. def prove_history_rotation(out):
  11. engine=ROOT/'src/motor/motor_engine.v';core=ROOT/'src/motor/motor_axis_core.v'
  12. text=engine.read_text(encoding='utf-8');producer=core.read_text(encoding='utf-8')
  13. module=re.search(r'module motor_limit_history #\(.*?endmodule',text,re.S).group(0)
  14. # Expose storage only in the proof copy; retain all actual state updates.
  15. module=module.replace('output wire [159:0] read_data',
  16. 'output wire [159:0] read_data, output wire [AXIS_COUNT*160-1:0] proof_records')
  17. module=module.replace('endmodule','genvar p; generate for(p=0;p<AXIS_COUNT;p=p+1)begin:proof_view\n'
  18. 'assign proof_records[p*160+:160]=records[p];\nend endgenerate\nendmodule')
  19. for expression in ('scan_axis<=0;', "scan_axis<=scan_axis==AXIS_COUNT-1 ? 0 : scan_axis+1'b1;",
  20. 'end else begin\n done_pulse<=0;seg_consumed<=0;limit_event_pulse<=0;'):
  21. if expression not in producer:raise ValueError('producer scan/clear shape changed')
  22. writes=re.findall(r'\blimit_event_pulse(\[[^\]]+\])?\s*<=\s*([^;]+);',producer)
  23. if not writes or any(not ((not index and value.strip()=='0') or (index=='[scan_axis]' and value.strip()=='1')) for index,value in writes):
  24. raise ValueError('producer event axis changed')
  25. variants={}
  26. for axes in (3,12):
  27. miter=f'''module proof(input clk,rst_n,emit,input [159:0] data,output bad,output observed);
  28. localparam N={axes},AW=$clog2(N);
  29. reg initialized=0;
  30. reg [AW-1:0] scan_axis,emitted_axis;reg event_valid;
  31. wire [AW-1:0] head;
  32. wire [159:0] actual;
  33. wire [N*160-1:0] physical;
  34. reg [159:0] reference [0:N-1];reg [N-1:0] valid;
  35. always @(posedge clk)initialized<=1;
  36. always @(posedge clk or negedge rst_n)begin
  37. if(!rst_n)begin scan_axis<=0;event_valid<=0;emitted_axis<=0;valid<=0;end
  38. else begin
  39. scan_axis<=scan_axis==N-1 ? 0 : scan_axis+1'b1;
  40. event_valid<=emit;emitted_axis<=scan_axis;
  41. if(event_valid)valid[emitted_axis]<=1;
  42. end
  43. end
  44. always @(posedge clk)if(rst_n && event_valid)reference[emitted_axis]<=data;
  45. motor_limit_history #(.AXIS_COUNT(N)) dut(.clk(clk),.rst_n(rst_n),.write_enable(event_valid),
  46. .write_data(data),.read_axis(head),.read_data(actual),.proof_records(physical));
  47. integer k,logical_axis;reg mismatch;
  48. always @* begin
  49. mismatch=(head>=N || scan_axis>=N || head!=(scan_axis==0 ? N-1 : scan_axis-1'b1));
  50. if(event_valid && emitted_axis!=head)mismatch=1;
  51. for(k=0;k<N;k=k+1)begin
  52. logical_axis=head+k;if(logical_axis>=N)logical_axis=logical_axis-N;
  53. if(valid[logical_axis] && physical[k*160+:160]!=reference[logical_axis])mismatch=1;
  54. end
  55. if(valid[head] && actual!=reference[head])mismatch=1;
  56. end
  57. assign bad=initialized && rst_n && mismatch;
  58. assign observed=&valid;
  59. endmodule
  60. '''
  61. full=module+'\n'+miter
  62. variants[f'history_{axes}_proof']=(full,'proof',axes)
  63. variants[f'history_{axes}_cover']=(full,'cover',axes)
  64. phase=full.replace('read_axis<=AXIS_COUNT-1;','read_axis<=0;')
  65. drop=full.replace('write_enable ? write_data : records[0]','records[0]')
  66. if phase==full or drop==full:raise ValueError('history mutation did not alter actual module')
  67. variants[f'history_{axes}_phase_mutation']=(phase,'mutation',axes)
  68. variants[f'history_{axes}_write_mutation']=(drop,'mutation',axes)
  69. result={'scope':'inductive rotating-history storage equivalence and checked producer scan form; not full motor/event proof',
  70. 'source':source_identity(ROOT),'inputs':{str(p.relative_to(ROOT)):hashlib.sha256(p.read_bytes()).hexdigest() for p in (engine,core,Path(__file__).resolve())},
  71. 'assumptions':'arbitrary record data and event enable; actual producer scan/reset/write form checked; initial reset, later reset unrestricted',
  72. 'tool':subprocess.check_output(['yosys','-V'],text=True).strip(),'results':[],'hardware':'NOT_RUN'}
  73. for name,(rtl,kind,axes) in variants.items():
  74. path=out/(name+'.v');path.write_text(rtl,encoding='utf-8');log=out/(name+'.log')
  75. goal=(f'sat -seq {axes+3} -set-init-zero -set rst_n 1 -set-at 1 rst_n 0 -set-at {axes+3} observed 1 -show observed' if kind=='cover' else
  76. 'sat -seq 2 -tempinduct -maxsteps 4 -set-init-zero -set-at 1 rst_n 0 -prove bad 0 -verify')
  77. command=['yosys','-p',f'read_verilog -formal {json.dumps(str(path),ensure_ascii=False)}; prep -top proof -flatten; memory_map; opt; async2sync; opt; {goal}']
  78. with log.open('w') as stream:
  79. process=subprocess.Popen(command,stdout=stream,stderr=subprocess.STDOUT,start_new_session=True)
  80. try:code=process.wait(timeout=90)
  81. except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait();code=124
  82. output=log.read_text(errors='replace')
  83. 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))
  84. result['results'].append({'name':name,'command':command,'exit_code':code,'status':'PASS' if ok else ('UNKNOWN_TIMEOUT' if code==124 else 'FAIL'),
  85. 'log_sha256':hashlib.sha256(log.read_bytes()).hexdigest(),'miter_sha256':hashlib.sha256(path.read_bytes()).hexdigest()})
  86. print(name,result['results'][-1]['status'],flush=True)
  87. result['status']='PASS' if all(row['status']=='PASS' for row in result['results']) else 'INCOMPLETE'
  88. (out/'RESULT.json').write_text(json.dumps(result,indent=2)+'\n')
  89. return 0 if result['status']=='PASS' else 1
  90. def prove_event_losses(out):
  91. engine=ROOT/'src/motor/motor_engine.v';core=ROOT/'src/motor/motor_axis_core.v'
  92. text=engine.read_text(encoding='utf-8');producer=core.read_text(encoding='utf-8')
  93. shapes={}
  94. for signal_name in ('done_pulse','limit_event_pulse'):
  95. writes=re.findall(r'\b'+signal_name+r'(\[[^\]]+\])?\s*<=\s*([^;]+);',producer)
  96. if not writes or not any(index for index,_ in writes):raise ValueError('producer write shape missing')
  97. if any(not ((not index and value.strip()=='0') or (index=='[scan_axis]' and value.strip()=='1')) for index,value in writes):
  98. raise ValueError('producer no longer has a single-destination write shape')
  99. if re.search(r'\b'+signal_name+r'(?:\[[^\]]+\])?\s*(?:\|=|&=|\^=|\+=|-=|=(?!=))',producer):
  100. raise ValueError('unexpected producer blocking/compound assignment')
  101. shapes[signal_name]=writes
  102. if 'end else begin\n done_pulse<=0;seg_consumed<=0;limit_event_pulse<=0;' not in producer:
  103. raise ValueError('unconditional per-clock producer clear changed')
  104. start=text.index(' for(ev_scan=0;',text.index('// The core emits at most one record'))
  105. end=text.index('\n end\n always @(posedge clk',start)
  106. body=text[start:end]
  107. condition='ax_done[ev_scan] && (event_for_stop(ax_reason[ev_scan])!=0 || (home_pending_r[ev_scan] && ax_reason[ev_scan]==SR_LOWER))'
  108. if body.count(condition)!=1:raise ValueError('completion qualification expression changed')
  109. body=body.replace(condition,'accepted_done[ev_scan]')
  110. declarations='\n'.join(re.search(r'wire\s+\[[^\]]+\]\s+'+name+r'=[^;]+;',text).group(0)
  111. for name in ('pending_loss_total','pending_losses'))
  112. variants={}
  113. for axes in (3,12):
  114. prefix=f'''module proof(input [{axes-1}:0] ax_limit_pulse,accepted_done,limit_pending,done_pending,
  115. input [{axes*4-1}:0] ax_limit_drops,input ev_wr_req,reset_pending,select_limit,event_dispatch_ready,
  116. input signed [31:0] ev_select,output bad,output [8:0] observed);
  117. localparam AXIS_COUNT={axes};
  118. integer ev_scan,j;reg [3:0] pending_drop_union;reg pending_limit_loss,pending_done_loss;
  119. reg[8:0] reference_losses;
  120. {declarations}
  121. always @* begin pending_drop_union=0;pending_limit_loss=0;pending_done_loss=0;
  122. '''
  123. reference=f'''
  124. end
  125. always @* begin
  126. reference_losses=0;
  127. for(j=0;j<{axes};j=j+1)begin
  128. if(ax_limit_pulse[j])begin
  129. reference_losses=reference_losses+ax_limit_drops[j*4+:4];
  130. if(limit_pending[j] && (ev_wr_req || reset_pending || ev_select!=j || !select_limit || !event_dispatch_ready))reference_losses=reference_losses+1'b1;
  131. end
  132. if(accepted_done[j] && done_pending[j] && (ev_wr_req || reset_pending || ev_select!=j || select_limit))reference_losses=reference_losses+1'b1;
  133. end
  134. end
  135. wire premise=((ax_limit_pulse & (ax_limit_pulse-1'b1))==0) && ((accepted_done & (accepted_done-1'b1))==0);
  136. assign bad=premise && (pending_losses!=reference_losses);
  137. assign observed=premise ? pending_losses : 0;
  138. endmodule
  139. '''
  140. rtl=prefix+body+reference
  141. variants[f'loss_{axes}_proof']=(rtl,'proof')
  142. mutation=rtl.replace("{1'b0,pending_drop_union}","5'd0")
  143. if mutation==rtl:raise ValueError('event-loss mutation did not change RTL')
  144. variants[f'loss_{axes}_mutation']=(mutation,'mutation')
  145. variants[f'loss_{axes}_cover']=(rtl,'cover')
  146. # The checked source write form is zero plus arbitrary enables writing
  147. # bit scan_axis. Model all enables and qualification masks freely.
  148. emitter=f'''module proof(input [3:0] scan_axis,input done_enable,limit_enable,
  149. input [{axes-1}:0] qualification,output bad,output [8:0] observed);
  150. reg [{axes-1}:0] done,limit;
  151. always @* begin done=0;limit=0;if(done_enable)done[scan_axis]=1;if(limit_enable)limit[scan_axis]=1;end
  152. wire [{axes-1}:0] accepted=done & qualification;
  153. assign bad=((done & (done-1'b1))!=0) || ((limit & (limit-1'b1))!=0) || ((accepted & (accepted-1'b1))!=0);
  154. assign observed=0;
  155. endmodule
  156. '''
  157. variants[f'producer_form_{axes}_proof']=(emitter,'proof')
  158. result={'scope':'event-loss combinational equivalence plus checked producer write-form proof; not full sequential motor proof',
  159. 'source':source_identity(ROOT),'inputs':{str(p.relative_to(ROOT)):hashlib.sha256(p.read_bytes()).hexdigest() for p in (core,engine,Path(__file__).resolve())},
  160. 'producer_write_shapes':shapes,'premise':'at most one emitted limit and one qualified completion per clock; producer form checked separately',
  161. 'tool':subprocess.check_output(['yosys','-V'],text=True).strip(),'results':[],'hardware':'NOT_RUN'}
  162. for name,(rtl,kind) in variants.items():
  163. path=out/(name+'.v');path.write_text(rtl,encoding='utf-8');log=out/(name+'.log')
  164. goal='sat -set observed 3 -show-inputs' if kind=='cover' else 'sat -verify -prove bad 0 -show-inputs'
  165. command=['yosys','-p',f'read_verilog -formal {json.dumps(str(path),ensure_ascii=False)}; prep -top proof; {goal}']
  166. with log.open('w') as stream:
  167. process=subprocess.Popen(command,stdout=stream,stderr=subprocess.STDOUT,start_new_session=True)
  168. try:code=process.wait(timeout=90)
  169. except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait();code=124
  170. output=log.read_text(errors='replace')
  171. 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))
  172. result['results'].append({'name':name,'command':command,'exit_code':code,'status':'PASS' if ok else ('UNKNOWN_TIMEOUT' if code==124 else 'FAIL'),
  173. 'log_sha256':hashlib.sha256(log.read_bytes()).hexdigest(),'miter_sha256':hashlib.sha256(path.read_bytes()).hexdigest()})
  174. result['status']='PASS' if all(row['status']=='PASS' for row in result['results']) else 'INCOMPLETE'
  175. (out/'RESULT.json').write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(result,indent=2))
  176. return 0 if result['status']=='PASS' else 1
  177. def prove_selector(out):
  178. source=ROOT/'src/motor/motor_engine.v'
  179. raw=source.read_text(encoding='utf-8')
  180. start=raw.index(' always @* begin',raw.index('// Factor one-bit eligibility/priority'))
  181. end=raw.index('\n end\n',start)+len('\n end\n')
  182. actual=raw[start:end]
  183. inputs={str(p.relative_to(ROOT)):hashlib.sha256(p.read_bytes()).hexdigest() for p in
  184. (source,Path(__file__).resolve(),ROOT/'projects/mrdimm-chamber/project.json')}
  185. result={'schema':'prod2u-queue-selector-proof-v1','scope':'extracted combinational eligibility and circular winner only; no sequential or STEP proof',
  186. 'source':source_identity(ROOT),'inputs':inputs,'source_manifest_sha256':hashlib.sha256(json.dumps(inputs,sort_keys=True).encode()).hexdigest(),
  187. 'tool':subprocess.check_output(['yosys','-V'],text=True).strip(),
  188. 'assumptions':['fx_round is a legal axis index; all eligibility/control/depth input bits otherwise arbitrary'],
  189. 'results':[],'hardware':'NOT_RUN','status':'RUNNING'}
  190. for axes in (3,12):
  191. width=(axes-1).bit_length()
  192. prefix=f'''module selector(input [{width-1}:0] fx_round,
  193. input [{axes-1}:0] ax_load_ready,ax_seg_load,queue_paused_r,cs_start_mask,cs_mask,urgent_valid_r,
  194. input [1:0] cs_state,input seek_context,input [{axes*6-1}:0] depths,
  195. output bad,output reg [7:0] fx_candidate,output reg fx_candidate_valid);
  196. localparam AXIS_COUNT={axes};
  197. wire [5:0] depth_r[0:AXIS_COUNT-1];
  198. genvar g;generate for(g=0;g<AXIS_COUNT;g=g+1)begin
  199. assign depth_r[g]=depths[g*6+:6];
  200. end endgenerate
  201. reg [AXIS_COUNT-1:0] fx_eligible;
  202. integer fx_k,fx_probe;
  203. '''
  204. reference='''
  205. integer axis,distance,best_distance;
  206. reg reference_valid;reg[7:0]reference_axis;reg allowed;
  207. always @* begin
  208. reference_valid=0;reference_axis=0;best_distance=AXIS_COUNT;distance=0;allowed=0;
  209. for(axis=0;axis<AXIS_COUNT;axis=axis+1)begin
  210. allowed=ax_load_ready[axis] && !ax_seg_load[axis] && !queue_paused_r[axis] &&
  211. ((cs_state==0) || (cs_state==3 && cs_start_mask[axis]) || (seek_context && cs_mask[axis])) &&
  212. (urgent_valid_r[axis] || (|depths[axis*6+:6]));
  213. distance=axis>=fx_round ? axis-fx_round : axis+AXIS_COUNT-fx_round;
  214. if(allowed && distance<best_distance)begin
  215. reference_valid=1;reference_axis=axis;best_distance=distance;
  216. end
  217. end
  218. end
  219. assign bad=(fx_round<AXIS_COUNT) && ((reference_valid!=fx_candidate_valid) ||
  220. (reference_valid && reference_axis!=fx_candidate));
  221. endmodule
  222. '''
  223. proof=prefix+actual+reference
  224. mutation=proof.replace('for(fx_k=AXIS_COUNT-1;fx_k>=0;fx_k=fx_k-1)','for(fx_k=0;fx_k<AXIS_COUNT;fx_k=fx_k+1)')
  225. if mutation==proof:raise ValueError('selector mutation did not change source')
  226. for kind,text in (('proof',proof),('reverse_priority_mutation',mutation),('nonempty_cover',proof)):
  227. name=f'axis{axes}_{kind}';vf=out/(name+'.v');vf.write_text(text,encoding='utf-8')
  228. goal='sat -set fx_round 0 -set fx_candidate_valid 1 -show-inputs' if kind=='nonempty_cover' else 'sat -verify -prove bad 0 -show-inputs'
  229. command=['yosys','-p',f'read_verilog -formal {json.dumps(str(vf),ensure_ascii=False)}; prep -top selector; {goal}']
  230. log=out/(name+'.log')
  231. with log.open('w') as stream:
  232. process=subprocess.Popen(command,stdout=stream,stderr=subprocess.STDOUT,start_new_session=True)
  233. try:code=process.wait(timeout=90)
  234. except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait();code=124
  235. output=log.read_text(encoding='utf-8',errors='replace')
  236. ok=(code==0 and 'SUCCESS!' in output) if kind=='proof' else (
  237. (code==1 and 'proof did fail' in output) if kind=='reverse_priority_mutation' else
  238. (code==0 and 'model found:' in output))
  239. result['results'].append({'name':name,'command':command,'exit_code':code,
  240. 'status':'PASS' if ok else ('UNKNOWN_TIMEOUT' if code==124 else 'FAIL'),
  241. 'log_sha256':hashlib.sha256(log.read_bytes()).hexdigest(),'miter_sha256':hashlib.sha256(vf.read_bytes()).hexdigest()})
  242. result['status']='PASS' if all(x['status']=='PASS' for x in result['results']) else 'INCOMPLETE'
  243. (out/'RESULT.json').write_text(json.dumps(result,indent=2)+'\n',encoding='utf-8')
  244. print(json.dumps(result,indent=2));return 0 if result['status']=='PASS' else 1
  245. def main():
  246. ap=argparse.ArgumentParser(description=__doc__)
  247. ap.add_argument('--run-root',type=Path,required=True)
  248. ap.add_argument('--selector',action='store_true',help='prove extracted queue selection for3/12 axes, a reversed-priority mutation and nonempty covers')
  249. ap.add_argument('--event-loss',action='store_true',help='prove extracted event-loss reduction and producer write form')
  250. ap.add_argument('--history-rotation',action='store_true',help='prove rotating history storage and producer scan alignment')
  251. args=ap.parse_args()
  252. if sys.platform!='linux':ap.error('Execute in the authorized Linux container')
  253. out=args.run_root.resolve()
  254. if out==ROOT or ROOT in out.parents:ap.error('run-root must be external')
  255. out.mkdir(parents=True,exist_ok=False)
  256. if args.history_rotation:return prove_history_rotation(out)
  257. if args.event_loss:return prove_event_losses(out)
  258. if args.selector:return prove_selector(out)
  259. source=ROOT/'src/motor/motor_axis_core.v'
  260. raw=source.read_text(encoding='utf-8')
  261. names=['deadline_span','planned_deadline','deadline_difference','deadline_now','deadline_next','total_sum','exec_sum','lower_hit_sum','upper_hit_sum','total_next','exec_next','position_delta','moved_position','pos_next','position_signed_overflow']
  262. substitutions={'now_us[33:0]':'now_time','due[scan_axis]':'deadline','s_due':'deadline','r_total[scan_axis]':'total',
  263. 's_total':'total','s_executed':'executed','s_position':'position','r_executed[scan_axis]':'executed','r_position[scan_axis]':'position','rise_pending[scan_axis]':'rise',
  264. 'r_dir_upper[scan_axis]':'up','selected_hits':'hits','lower_pending[scan_axis]':'lower_inc','upper_pending[scan_axis]':'upper_inc',
  265. 'deadline_base':'base','deadline_duration':'duration','deadline_setup':'setup'}
  266. declarations=[]
  267. for name in names:
  268. match=re.search(r'wire\s+(\[[^\]]+\]\s+)?'+re.escape(name)+r'\s*=([^;]*);',raw)
  269. if not match:raise ValueError('RTL expression missing: '+name)
  270. declaration=match.group(0)
  271. for before,after in substitutions.items():declaration=declaration.replace(before,after)
  272. declarations.append(declaration)
  273. prefix='''module arithmetic_equivalence(input [33:0] now_time,deadline,base,input [31:0] duration,setup,
  274. input [31:0] total,executed,position,input [63:0] hits,
  275. input [3:0] lower_inc,upper_inc,input rise,up,output bad);
  276. '''
  277. suffix='''
  278. wire [33:0] ref_now=now_time-deadline;
  279. wire [33:0] ref_next=(now_time+34'd1)-deadline;
  280. wire [31:0] ref_total=total+rise,ref_exec=executed+rise;
  281. wire [31:0] ref_lower=hits[31:0]+lower_inc,ref_upper=hits[63:32]+upper_inc;
  282. wire [31:0] ref_position=rise ? (up ? position+32'd1 : position-32'd1) : position;
  283. wire ref_position_wrap=rise && (up ? position==32'h7FFFFFFF : position==32'h80000000);
  284. wire [33:0] ref_planned=base+{2'd0,duration}+{2'd0,setup};
  285. assign bad=(planned_deadline!==ref_planned) || (deadline_now!==!ref_now[33]) || (deadline_next!==!ref_next[33]) ||
  286. (total_next!==ref_total) || (exec_next!==ref_exec) || (pos_next!==ref_position) ||
  287. (total_sum[32] !== (rise && total==32'hFFFFFFFF)) ||
  288. (exec_sum[32] !== (rise && executed==32'hFFFFFFFF)) ||
  289. (lower_hit_sum[31:0]!==ref_lower) || (upper_hit_sum[31:0]!==ref_upper) ||
  290. (lower_hit_sum[32] !== (ref_lower<hits[31:0])) || (upper_hit_sum[32] !== (ref_upper<hits[63:32])) ||
  291. ((rise && position_signed_overflow)!==ref_position_wrap);
  292. endmodule
  293. '''
  294. base=prefix+'\n'.join(declarations)+suffix
  295. variants={'proof':base,
  296. 'mutation_deadline_boundary':base.replace('deadline_now ^ (&deadline_difference[32:0])','deadline_now || (&deadline_difference)'),
  297. 'mutation_upper_carry':base.replace('(upper_hit_sum[32] !==','(1\'b0 !=='),
  298. 'mutation_position_delta':base.replace("up ? 32'd1 : 32'hFFFFFFFF","32'd1"),
  299. 'mutation_duration_high_bit':base.replace("{2'd0,duration}","{3'd0,duration[30:0]}",1)}
  300. manifest={str(p.relative_to(ROOT)):hashlib.sha256(p.read_bytes()).hexdigest() for p in
  301. (source,Path(__file__).resolve(),ROOT/'projects/mrdimm-chamber/project.json')}
  302. result={'schema':'prod2u-combinational-arithmetic-proof-v1','scope':'arithmetic expressions only; no state-machine proof',
  303. 'run_id':out.name,'inputs':manifest,'source_manifest_sha256':hashlib.sha256(json.dumps(manifest,sort_keys=True).encode()).hexdigest(),
  304. 'project_sha256':manifest['projects/mrdimm-chamber/project.json'],'bitstream_sha256':None,
  305. 'commit':source_identity(ROOT)['commit'],
  306. 'source_sha256':hashlib.sha256(source.read_bytes()).hexdigest(),'generated_at':datetime.datetime.now(datetime.timezone.utc).isoformat(),
  307. 'tool':subprocess.check_output(['yosys','-V'],text=True).strip(),'assumptions':[], 'results':[],'status':'RUNNING'}
  308. for name,text in variants.items():
  309. if name!='proof' and text==base:raise ValueError('mutation did not change the extracted RTL')
  310. vf=out/(name+'.v');vf.write_text(text,encoding='utf-8')
  311. log=out/(name+'.log')
  312. command=['yosys','-p',f'read_verilog -formal {json.dumps(str(vf),ensure_ascii=False)}; prep -top arithmetic_equivalence; sat -verify -prove bad 0 -show-inputs']
  313. with log.open('w') as stream:
  314. process=subprocess.Popen(command,stdout=stream,stderr=subprocess.STDOUT,start_new_session=True)
  315. try:code=process.wait(timeout=90)
  316. except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait();code=124
  317. output=log.read_text(encoding='utf-8',errors='replace')
  318. ok=(code==0 and 'SUCCESS!' in output) if name=='proof' else (code==1 and 'proof did fail' in output)
  319. result['results'].append({'name':name,'command':command,'exit_code':code,'status':'PASS' if ok else 'FAIL',
  320. 'log':str(log),'log_sha256':hashlib.sha256(log.read_bytes()).hexdigest(),'miter_sha256':hashlib.sha256(vf.read_bytes()).hexdigest()})
  321. result['status']='PASS' if all(x['status']=='PASS' for x in result['results']) else 'FAIL'
  322. (out/'RESULT.json').write_text(json.dumps(result,indent=2)+'\n',encoding='utf-8')
  323. print(json.dumps(result,indent=2))
  324. return 0 if result['status']=='PASS' else 1
  325. if __name__=='__main__':raise SystemExit(main())