
    UHj I                    t   d Z ddlmZ ddlZddlZddlZddlmZ ddlm	Z	  ee
      j                         j                  d   Zedz  ZdZd	Zg d
Zg dZdddddddddgZd#dZd$dZd%dZd&dZd'dZd(dZd)dZd*dZd+dZ	 	 	 d,	 	 	 	 	 	 	 d-dZd.dZd/dZd/dZ efd0d Z!d1d!Z"e#d"k(  r e"        yy)2zKCombine corrected gate byte samples with branch-state pass/fail hypotheses.    )annotationsN)Path)Any   outmap1_01amap2_02d)zcurrent-selector-2-0-samplezruntime-base-at-gatezpredecessor-state-persistencezstrict-source-hotspot)z?current selector 2:0 sample proving gate indices for this routez6runtime context+0xa8 base at 0x005428c4 and 0x005428ccz@predecessor 1:0 state persistence into the current 2:0 gate pathzstrict map1_01a source hotspotz)out/save_selector_gate_sample_values.jsonz.corrected public savedat gate-byte sample rows)pathdescriptionz/out/save_selector_predecessor_state_effect.jsonzGpredecessor branch-state table hypothesis used for pass/fail evaluationz!out/save_selector_gate_paths.jsonz8current gate trace rows and branch/fallthrough addressesc                p    | j                         s|S t        j                  | j                  d            S )Nutf-8encoding)existsjsonloads	read_text)r
   fallbacks     E/home/exedev/hwanse/tools/summarize_save_selector_gate_pass_matrix.py	load_jsonr   ,   s*    ;;=::dnngn677    c                     | sy t        | d      S )N   )intvalues    r   	parse_hexr   2   s    ub>r   c                    | y d| dS )N0x02x r   s    r   hex8r"   8   s    }c{r   c                   | sg S | d   }g }dD ].  }|j                  |      xs g }|s|j                  |d          0 g }|D ]  }t        |j                  d            }||dz	  dz  nd }||dz	  dz  nd }|j                  |j                  d      |j                  d      |t        |      t        |      |dk(  rdnd	|j                  d
      |j                  d      d        |S )Nr   )firstGateTracesecondGateTracevalueHex      r   vaHexprimaryBranchStatesecondaryBranchStatebranchTargetHexfallthroughVaHex)	gateVaHexr&   selectionBufferOffsetselectionBufferOffsetHexstreamPlus1Hex
stateTabler,   r-   )getappendr   r"   )	
gate_pathsrowtraces
trace_nametracegatesr   stream_plus_1stream_plus_2s	            r   	gate_rowsr=   >   s   	
Q-CF; $

#)rMM%(#$ E %))J/0/4/@!t+d050A",t7+		*-%2(,](;"=12?12D.J`$yy):; %		*< =	
 			 Lr   c                    | j                  d      }t        |t              rt        |      dk7  rddgdgdz  z   }dd|dd	d
ddgdz  dd	gS )NsecondaryBranchStateAfterFill   r   r   
   predecessor_1_0_case0z"predecessor 1:0 opcode 0x10 case 0&save_selector_predecessor_state_effect)idlabelr2   sourceEvidence
zero_tablezall-zero secondaryBranchStateznegative control)r3   
isinstancelistlen)predecessor_state_effectpredecessor_tables     r   table_hypothesesrM   Y   sw    0445TU'.#6G2HB2NFaS2X- *9+F		
 4#(0		
 r   c                    i }| D ]8  }|j                  d      xs d}|j                  |g       j                  |       : |D ]  }||   j                  d         t	        t        |j                                     S )NsampleId-c                ,    | j                  d      xs dS )NgateOffsetHex )r3   )r6   s    r   <lambda>zsample_groups.<locals>.<lambda>s   s    0H0NB r   )key)r3   
setdefaultr4   sortdictsorteditems)rowsgroupedr6   	sample_ids       r   sample_groupsr^   m   s    %'G 6GGJ'.3	9b)0056  P		$NOPw}}'((r   c                   | j                  d      }t        |t              xr d|cxk  xr t        |      k  nc }|r||   nd }| j                  d      | j                  d      |t        |t              rt	        |      nd |||dk(  dS )Nr   r   rR   saveOffsetHexr   )rR   r`   indexindexHexindexInRange
stateValuefallsThrough)r3   rH   r   rJ   r"   )r6   state_tabler   in_rangestate_values        r   evaluate_gateri   w   s    GGGE%%G!u*Gs;7G*GH(0+e$dK11#-eS#9DKt !#q( r   c                   t        | j                  d      xs g       }g }|j                         D ]  \  }}|d   }|D ]  }|D cg c]  }t        ||d          }	}|j	                  ||j                  d      |j                  d      |j                  d      |d   |d   |	t        d	 |	D              t        d
 |	D              d	         |S c c}w )NsaveRuntimeGateSampleRowsr   r2   selectortilecoversCurrentFrontierSelectorrD   rE   c              3  &   K   | ]	  }|d      yw)rc   Nr!   .0r6   s     r   	<genexpr>z&save_runtime_matrix.<locals>.<genexpr>   s     ,YSS-@,Y   c              3  &   K   | ]	  }|d      yw)re   Nr!   rp   s     r   rr   z&save_runtime_matrix.<locals>.<genexpr>   s     *W33~+>*Wrs   )	rO   rl   rm   rn   hypothesisIdhypothesisLabelgateResultsallGateIndicesInRangeallGatesFallThrough)r^   r3   rZ   ri   r4   all)
gate_sample_values
hypothesesr\   r[   r]   sample_rowssample
hypothesisr6   gate_resultss
             r   save_runtime_matrixr      s    .223NOUSUVGD")--/ 	;Q$ 	J ' c:l#;<L  KK%"JJz2

6*17<[1\ *4 0#-g#6+),,YL,Y)Y'**W,*W'W
 
	$ Ks   Cc                l   | j                  d      xs g }|D cg c]  }|j                  d      s| }}t        |D ch c]%  }|j                  d      s|j                  d      ' c}      }t        |      t        |      t        |      t        |      z
  |t        |      dkD  dS c c}w c c}w )NpartySlotStatSampleRowsinExpectedIndexRanger&   r   )sampleValueCountinRangeSampleValueCountoutOfRangeSampleValueCountdistinctValuesHexusableAsGateIndexEvidence)r3   rY   rJ   )r{   r[   r6   rg   distincts        r   party_slot_summaryr      s    !!";<BD#Gsww/E'FGHGdRscggj>Qswwz*RSHI#&x=&)$i#h-&?%%(]Q%6  HRs   B,B, B1B1c           	        | | nt        t        dz  i       } ||nt        t        dz  i       }||nt        t        dz  g       }t        |      }t        | |      }|D cg c]  }|d   dk(  s| }}|D cg c]  }|d   dk(  s| }}t	        |       }d}	i dt
        d	t        d
t        |      d| j                  d      d| j                  d      d| j                  d      xs g d|d|dt        d |D              dt        |      dt        d |D              dt        |      d|dddddddddt        t        t        t        t              d|	dS c c}w c c}w )N%save_selector_gate_sample_values.json+save_selector_predecessor_state_effect.jsonsave_selector_gate_paths.jsonru   rB   rG   a  With the corrected save/runtime mapping, public samples put both gate indices at 0. Under the strongest predecessor 1:0 hypothesis, secondaryBranchState[0] is 1, so both current control gates 0x005428c4 and 0x005428cc would fall through for every public sample. Under an all-zero table they would not. This narrows the gate problem but does not promote map1_01a -> map2_02d: the public samples do not cover selector 2:0, the runtime context+0xa8 base at the gates is still unproven, and there is still no strict map1_01a source hotspot.sourcetargetgateRowscurrentFrontierSelectorcurrentFrontierSampleCovered saveRuntimeGateDistinctValuesHextableHypothesessaveRuntimePassMatrix,saveRuntimePredecessorAllGatePassSampleCountc              3  ,   K   | ]  }|d    s	d  ywry   r   Nr!   rp   s     r   rr   z build_summary.<locals>.<genexpr>   s     ;x#]`av]wA;x   
!saveRuntimePredecessorSampleCount*saveRuntimeZeroTableAllGatePassSampleCountc              3  ,   K   | ]  }|d    s	d  ywr   r!   rp   s     r   rr   z build_summary.<locals>.<genexpr>   s     9oTWXmTn!9or   saveRuntimeZeroTableSampleCountpartySlotStatSummaryruntimeBaseProofRequiredT#predecessorPersistenceProofRequiredstrictHotspotProofRequired
proofFoundFblocked)gatePassMatrixProofFoundfailedGatePassMatrixGateIdsmissingEvidenceevidenceRefsevidenceRefCountpromotionStatus
conclusion)r   OUTrM   r   r   SOURCETARGETr=   r3   sumrJ    FAILED_GATE_PASS_MATRIX_GATE_IDS!GATE_PASS_MATRIX_MISSING_EVIDENCEGATE_PASS_MATRIX_EVIDENCE_REFS)
r{   rK   r5   r|   matrixr6   predecessor_rows	zero_rowsparty_summaryr   s
             r   build_summaryr      s#   
 0B/M+S\55
T <T;_7en;;
f  *59SKjEjln;oJ!":;J !3Z@F'-`^1DH_1_`` &N#n*=*MNIN&'9:M	* && 	Ij) 	"#5#9#9:S#T	
 	'(:(>(>?](^ 	+,>,B,BCe,f,ljl 	: 	  	7;xIY;x8x 	,S1A-B 	5c9oy9o6o 	*3y> 	 	#D 	.t  	%d!" 	e#$ %*'G<6 >?$ 1  aNs   !E&/E&9E+E+c                    g }| D ]D  }|d   dnt        |d         }|j                  |d    d|d   xs d d| d|d   rd	nd
        F dj                  |      S )Nrd   rP   rR   z idx rb   z
 -> state  -> re   fallthroughbranchz; )strr4   join)resultspiecesr6   states       r   gate_result_textr      s    F 
<(0c#l:K6L?#$E#j/*@S)AE7RV #N 3}BD	

 99Vr   c                .   | d   }ddd| d    d| d    d| d	    d
d| d    ddj                  d | d   D               d| d    d| d    d| d    d| d    d|d    d|d    d| d    d| d    d| d     d!| d"    d
d#| d$    d
d%| d&    d
d| d'   dd(dg}|j                  d) | d*   D               |j                  g d+       |j                  d, | d-   D               |j                  g d.       |j                  d/ | d0   D               |j                  g d1       | d2   D ]8  }|j                  d3|d4    d5|d6    d5|d7    d8|d9    d:|d;    d5|d<    d=       : |j                  g d>       | d?   D ];  }|j                  d@|dA    d:|dB    d8|dC    dDt        |dE          dD|dF    dG       = |j                  ddHddI|d    dJ|d    dK|dL    dMdj                  dN |dO   D               dg       dPj                  |      S )QNr   z # Save Selector Gate Pass MatrixrS   z	- route: r   r   r   z- current frontier selector: `r   `z#- current frontier sample covered: r   z%- save/runtime distinct gate values: , c              3  (   K   | ]
  }d | d   ywr   Nr!   rq   items     r   rr   zmarkdown.<locals>.<genexpr>   s     9~$AdV1+9~   r   z- predecessor pass samples: r    / r   z- zero-table pass samples: r   r   z%- party-slot usable in-range values: r   r   z- runtime base proof required: r   z*- predecessor persistence proof required: r   z!- strict hotspot proof required: r   z- proofFound: `r   z- gatePassMatrixProofFound: `r   z- promotion status: `r   r   z## Failed Gatesc              3  (   K   | ]
  }d | d  yw)- `r   Nr!   r   s     r   rr   zmarkdown.<locals>.<genexpr>  s     R43tfARr   r   )rS   z## Missing EvidencerS   c              3  &   K   | ]	  }d |   yw)z- Nr!   r   s     r   rr   zmarkdown.<locals>.<genexpr>  s     D2dVDrs   r   )rS   z## Evidence RefsrS   c              3  8   K   | ]  }d |d    d|d      yw)r   r
   z`: r   Nr!   rp   s     r   rr   zmarkdown.<locals>.<genexpr>  s/       c&k]#c-012s   r   )rS   z## Current GatesrS   zI| gate | value | selection offset | table | branch target | fallthrough |z%| --- | --- | --- | --- | --- | --- |r   z| `r.   z` | `r&   r0   z` | r2   z | `r,   r-   z` |)rS   z## Save/Runtime MatrixrS   zJ| sample | selector | hypothesis | gate results | all gates fall through |z| --- | --- | --- | --- | --- |r   z| rO   rl   rv   z | rw   ry   z |z## Party Slot Stat Summaryz- sample values: z- in range: z- out of range: r   z- distinct values: c              3  (   K   | ]
  }d | d   ywr   r!   r   s     r   rr   zmarkdown.<locals>.<genexpr>4  s     '[!D6'[r   r   
)r   extendr4   r   )summarypartylinesr6   s       r   markdownr      s   *+E*

GH%&d78+<*=>
(1J)K(LAN
-g6T.U-VW
/		9~RYZ|R}9~0~/  	A
&w/]'^&__bcj  lO  dP  cQ  	R
%g.Z&[%\\_`g  iJ  aK  `L  	M
/6O0P/QQTUZ[mUnTop
)'2L*M)NO
4W=b5c4de
+G4P,Q+RS
',/02
'0J(K'LAN
(9 :;1=


)E, 
LLR73P+QRR	LL  
 
LLD1B)CDD	LL  
 
LL >*  
LL   z" 
#k"#5Z(9sC]?^>__c< !c*;&<%=U3GYCZB[[^`	


 
LL   ./ 
Z!c*o%6d3?P;Q:RRUM 234C<Q8R7SSUW	


 
LL
$

E"4567
u6789
5!=>?@
dii'[FY@Z'[[\]
	 	 99Ur   c                    dj                  d | d   D              }dj                  d | d   D              }dj                  d | d   D              }g }| d   D ]  }|j                  d	t        j                  |d
   xs d       dt        j                  |d   xs d       dt        j                  |d   xs d       dt        j                  |d          dt        j                  |d   xs d       dt        j                  |d   xs d       d        g }| d   D ]  }|j                  dt        j                  |d          dt        j                  |d          dt        j                  |d          dt        j                  t	        |d                d|d    d        | d   }dj                  g d d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4t        j                  | d5          d6t        j                  | d7          d8| d9    d:| d;    d<| d=    d:| d>    d?|d@    d:|dA    dB| dC    dD| dE    dF| dG    dH| dI    dJt        j                  | dK          dLdMt        j                  | dN          dOdPdQ| dRdSdQ| dRdTdQ| dRdUdV|dWdXdY|dWdZd[|dA    d\|d@    d]|d^    d_t        j                  d`j                  |da                db	dcddd      S )eNrS   c              3  N   K   | ]  }d t        j                  |       d  yw)
<li><code>z</code></li>Nhtmlescaper   s     r   rr   zhtml_page.<locals>.<genexpr>;  s+       T[[&'|4   #%r   c              3  N   K   | ]  }d t        j                  |       d  yw)z<li></li>Nr   r   s     r   rr   zhtml_page.<locals>.<genexpr>?  s+       t{{4 !'r   r   c              3     K   | ]9  }d t        j                  |d          dt        j                  |d          d ; yw)r   r
   z	</code>: r   r   Nr   rp   s     r   rr   zhtml_page.<locals>.<genexpr>C  sE       T[[V-.iCDV8W7XX]^s   ?Ar   r   z<tr><td><code>r.   rP   z</code></td><td><code>r&   r0   z</code></td><td>r2   z</td><td><code>r,   r-   z</code></td></tr>r   z<tr><td>rO   rl   rv   z	</td><td>rw   ry   z
</td></tr>r   r   z<!doctype html>z<html lang="en">z<head>z  <meta charset="utf-8">zF  <meta name="viewport" content="width=device-width, initial-scale=1">z/  <title>Save Selector Gate Pass Matrix</title>z	  <style>zg    :root { color-scheme: dark; font-family: system-ui, sans-serif; background: #101010; color: #eee; }z&    body { margin: 0; padding: 24px; }z,    h1 { margin: 0 0 8px; font-size: 24px; }z/    h2 { margin: 24px 0 8px; font-size: 18px; }z<    p { max-width: 1120px; color: #bbb; line-height: 1.45; }z[    table { width: 100%; border-collapse: collapse; margin: 12px 0 20px; font-size: 13px; }zi    th, td { border-bottom: 1px solid #303030; padding: 7px 8px; text-align: left; vertical-align: top; }zF    th { position: sticky; top: 0; background: #181818; color: #ddd; }z    code { color: #d7f0ff; }z
  </style>z</head>z<body>z)  <h1>Save Selector Gate Pass Matrix</h1>z  <p>route r   z -&gt; r   z; predecessor pass samples r   r   r   z; zero-table pass samples r   r   z; party-slot in-range values r   r   z; runtime base proof required: r   z*; predecessor persistence proof required: r   z!; strict hotspot proof required: r   z; proofFound <code>r   z </code>; promotion status <code>r   z</code>.</p>z  <p>r   z</p>z  <h2>Failed Gates</h2>z  <ul>z</ul>z  <h2>Missing Evidence</h2>z  <h2>Evidence Refs</h2>z  <h2>Current Gates</h2>z  <table><thead><tr><th>gate</th><th>value</th><th>selection offset</th><th>table</th><th>branch target</th><th>fallthrough</th></tr></thead><tbody>z  </tbody></table>z  <h2>Save/Runtime Matrix</h2>z  <table><thead><tr><th>sample</th><th>selector</th><th>hypothesis</th><th>gate results</th><th>all gates fall through</th></tr></thead><tbody>z"  <h2>Party Slot Stat Summary</h2>z  <p>sample values z; in range z; out of range r   z; distinct values r   r   z.</p>z</body>z</html>)r   r4   r   r   r   )r   failed_gatesmissing_evidenceevidence_refsgate_rows_htmlr6   matrix_rows_htmlr   s           r   	html_pager   :  s   77 9: L ww -.  GG >* M Nz" 

S%5%<=> ?S_%;<= >S)C%D%KLM N;;s<012 3S):%;%BsCD ES);%<%CDE F		


 ./ 	
;;s:/0 1S_56 7;;s#4567 8;;/M0BCDE F,-. /	
	
 *+E99 222 	2 	#	2
 	Q2 	:2 	2 	r2 	12 	72 	:2 	G2 	f2 	t2 	Q2  	'!2" 	#2$ 	%2& 	'2( 	4)2* dkk'("345WT[[QYIZ=[<\ ]$$+,Z$[#\\_`g  iL  aM  `N N##*+W#X"YY\]d  fG  ^H  ]I I&&+,E&F%Gs5QcKdJe f((/0J(K'L M33:;`3a2b c**12N*O)P Q#L12 3""&++g6G.H"I!J,	X+2< GL12348=2> 	"?2@ e$A2B 	&C2D !"%(E2F 	#G2H u%I2J 	#K2L 	_M2N 
O2P 	Q2R 	)S2T 	ZU2V 
W2X 	Y2Z 	-[2\ e$678EJcDdCeetuz  |X  vY  uZ  Zl  mq  mx  mx  y}  yB  yB  CH  I\  C]  y^  m_  l`  `e  	f]2^ 	_2` 	a2b 	c2 2 2r   c                    |j                  dd       |dz  j                  t        j                  | dd      dz   d	       |d
z  j                  t	        |       d	       y )NT)parentsexist_okz#save_selector_gate_pass_matrix.jsonF   )ensure_asciiindentr   r   r   #save_selector_gate_pass_matrix.html)mkdir
write_textr   dumpsr   )r   out_dirs     r   write_outputsr     se    MM$M.44@@

7q9D@ A  44@@7AS^e@fr   c                 >   t        j                  t              } | j                  dt        t
        dz         | j                  dt        t
        dz         | j                  dt        t
        dz         | j                  d	t        t
               | j                         }t        t        |j                  i       t        |j                  i       t        |j                  g             }t        ||j                         t        d
|j                  dz          y )N)r   z--gate-sample-valuesr   )typedefaultz--predecessor-state-effectr   z--gate-pathsr   z	--out-dirz(wrote save selector gate pass matrix -> r   )argparseArgumentParser__doc__add_argumentr   r   
parse_argsr   r   r{   rK   r5   r   r   print)parserargsr   s      r   mainr     s    $$9F
.T3IpCpq
44O|I|}
T3A`;`a
$<D$))2.$//4$//2&G
 '4<<(	4T\\Di5i4j
klr   __main__)r
   r   r   r   returnr   )r   
str | Noner   
int | None)r   r  r   r  )r5   
list[dict]r   r  )rK   rX   r   r  )r[   r  r   zdict[str, list[dict]])r6   rX   rf   z	list[int]r   rX   )r{   rX   r|   r  r   r  )r{   rX   r   rX   )NNN)r{   dict | NonerK   r  r5   zlist[dict] | Noner   rX   )r   r  r   r   )r   rX   r   r   )r   rX   r   r   r   None)r   r  )$r   
__future__r   r   r   r   pathlibr   typingr   __file__resolver   ROOTr   r   r   r   r   r   r   r   r"   r=   rM   r^   ri   r   r   r   r   r   r   r   r   __name__r!   r   r   <module>r     s&   Q "      H~''*
Ul		$  % ! <G
 B`
 4Q"  86()0
 '+,0$(4#4)4 "4 
	4nJZWt 25 gm  zF r   