verify_motor_arithmetic.py 23 KB

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