coremlit 0.1.2

Safe, synchronous CoreML runtime for macOS (CPU/GPU/Neural Engine) with opt-in on-device multimodal pipelines: speech (Whisper STT, forced alignment, speaker diarization, Silero VAD), AudioSet sound-event tagging, and audio/text/image embeddings (CLAP, granite, SigLIP)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
//! Numerical-guard gate over every shipped CoreML graph.
//!
//! # The defect class
//!
//! A model graph contains a numerically-guarded op — `log`, `sqrt`,
//! `rsqrt`, a normalization, or a pooling divide — whose guard epsilon is
//! **smaller than fp16's smallest subnormal, `2^-24` ≈ 5.96e-8**. In an
//! fp32 conversion the guard survives. Executed in fp16 it **rounds to
//! zero**, the guard goes inert, and the op saturates or divides by zero.
//!
//! The failures are silent, systematic (bit-identical run to run), and
//! surface only on the ANE/GPU paths that actually compute in fp16 —
//! which is every path by default, because
//! [`ComputeUnits::default()`][coremlit::ComputeUnits] is
//! `All`. A model's *declared* MIL dtype is therefore **not** protection:
//! the pre-repair FluidInference `wespeaker.mlmodelc` was fp32 end-to-end in
//! its MIL and still collapsed to a cosine of 0.035 when the same fp32
//! artifact was loaded `CpuOnly → All` (issue #15; the shipping artifact now
//! carries the repaired `0x1p-24` guards). This gate consequently holds
//! **every** graph to the fp16 floor, whatever dtype it declares.
//!
//! # Why a graph gate and not an output check
//!
//! The graph is the only place the defect is *legible*. Downstream it
//! looks like a slightly-worse DER or a word timing that drifted — a
//! quality regression, not a bug. Three separate crates shipped this and
//! none of their output-level tests caught it. `model.mil` is plain text
//! and states the epsilon literally; this gate reads it and does arithmetic
//! on it. No inference, no models needed to test the checker itself.
//!
//! # What this asserts
//!
//! - Every `.mlmodelc` discovered under `Models/` is parsed — a **walk**,
//!   never a hardcoded list, so a newly-converted or newly-added model is
//!   covered the moment it lands.
//! - Every guard site's *effective* floor (the op's own `epsilon =` plus
//!   any provable lower bound on its input, from an `add`/`clip`/`maximum`
//!   guard) is compared against `2^-24`.
//! - Findings must match [`KNOWN_DEFECTS`] **exactly**. An unpinned model
//!   that grows a vanishing guard fails; a pinned one that is quietly
//!   *repaired* also fails, so a fix cannot land un-noticed either.
//! - Every site is CLASSIFIED into one of three [`GuardBand`]s and the census is
//!   reported with any failure. Only [`GuardBand::Inert`] fails; the two
//!   surviving bands are told apart rather than collapsed (see below).
//! - Every `batch_norm` whose `variance` is a CONSTANT has that constant read
//!   out of the bundle's weight blob, and the channels that are exactly `0.0` in
//!   fp16 are pinned in [`LOAD_BEARING_NORMS`] — in both directions. Those
//!   channels are guarded by the epsilon and by nothing else.
//! - A `.mlmodelc` with no readable `model.mil` is a hard failure; a pinned
//!   defect that has disappeared from an otherwise-present vendor tree is a hard
//!   failure; a constant `variance` the blob reader cannot read is a hard
//!   failure; and — the vendor manifest — an EXPECTED vendor directory that is
//!   missing entirely is a hard failure too, so deleting a whole vendor cannot
//!   silently disable all of its pins (the per-pin check alone only fired when
//!   the vendor dir still existed). Nothing silently skips.
//!
//! # The two SURVIVING bands, and why the threshold stays at `2^-24`
//!
//! `2^-24` is fp16's smallest SUBNORMAL; `2^-14` ≈ 6.10e-5 its smallest NORMAL.
//! A constant between them is representable only as a subnormal, and hardware
//! that flushed subnormals to zero would make it inert exactly as if it were
//! below `2^-24`. [`FP16_MIN_NORMAL`] used to sit here as a DEAD constant whose
//! doc comment said as much, with no test behind it — the file asserting a
//! hazard it never checked.
//!
//! It is not a small band. Over the 37 staged graphs the sweep audits 1 240
//! guard sites: **4 normal, 1 217 subnormal-only, 19 inert** — and the 19 are
//! exactly [`KNOWN_DEFECTS`]. Raising the threshold to the normal floor would
//! fail 98 % of the tree, including whisper-mel's `add(x, 0x1p-24)` — the file's
//! own clean control — and every issue-#15 REPAIR, which were cut to `0x1p-24`
//! precisely. If the band were inert those repairs would be worthless.
//!
//! So it was MEASURED, on the one artifact where the band is load-bearing:
//! `lid/SpeechBrainECAPAVoxLingua107.mlmodelc`, whose 33 `batch_norm` epsilons
//! are all `0x1.5p-17` = 1.0014e-5 (subnormal-only) and whose stored
//! `running_var` is exactly `0.0` in fp16 for 159 of its 19 968 channels — so
//! `sqrt(variance + epsilon)` there is `sqrt(epsilon)` and nothing else. The
//! graph was re-emitted with only those epsilon constants changed and run on
//! `CpuOnly`, `CpuAndGpu`, `CpuAndNeuralEngine` and `All`, over three inputs:
//!
//! - `0x0p+0` — **107 of 107 NaN on every arm.** The falsifier, red: the guard
//!   really is the only thing holding those channels up.
//! - `0x1.5p-17` (shipping) and `0x1p-24` (fp16's SMALLEST subnormal, this
//!   gate's own floor) — 107 of 107 finite on every arm, same top-1.
//! - `0x1p-24`, `0x1p-23`, `0x1p-20`, `0x1p-15`, `0x1p-14` — five DISTINCT
//!   outputs, so the value is consulted at full fp16 resolution, not flushed.
//! - `0x1p-25` is refused at load (`not within range of type: fp16`), so the
//!   `2^-24` floor is the type's own boundary, enforced by the runtime.
//!
//! `MLComputePlan` places 29 of those 33 `batch_norm` ops on the ANE under the
//! default `All`. The threshold therefore stays at `2^-24`; the band is
//! classified and REPORTED, not failed.
//!
//! This does **not** contradict the `lid/` [`KNOWN_DEFECTS`] note's failed
//! repair (1), where an explicit `+6e-8` on a `log` was measured to flush on a
//! static-shape ANE recompilation. The difference is structural and is the
//! rule worth carrying forward: a `batch_norm`'s `variance` and `epsilon` are
//! BOTH constants, so their sum is folded before any fp16 kernel runs, whereas
//! a `log`'s guarded operand is a runtime tensor and its `+ eps` is a real fp16
//! kernel add. Only the second is exposed to flush-to-zero. What has NOT been
//! measured is a static-shape recompilation of these `batch_norm`s; the tools
//! to produce one (coremltools) are not part of this repository's test
//! environment.
//!
//! # Coverage boundary (`COREMLIT_FP16_SWEEP_VENDORS`)
//!
//! By default the sweep requires EVERY vendor named by a [`KNOWN_DEFECTS`] or
//! [`LOAD_BEARING_NORMS`] pin to be present. CI runs it once per `model-tests` SHARD, and each shard stages
//! only its own kit's part of the tree (per MODELS_LOCK), so each names exactly
//! what it stages — `vadkit,speakerkit` for the speaker shard,
//! `whisperkit-coreml,vadkit` for whisper, `vadkit,lid` for lid, and so on —
//! narrowing the manifest EXPLICITLY. That works because the per-pin check
//! fires on `root.join(vendor).is_dir()`: in a whisper-only shard
//! `Models/speakerkit/` does not exist, so its five pins are skipped rather
//! than reported missing, while the manifest still refuses a vendor the shard
//! DID stage and then lost.
//!
//! The real coverage is therefore the UNION across shards, and the union is
//! pinned rather than assumed: `ci_fp16_sweep_shards_cover_every_pinned_vendor`
//! in `tests/whisper/models_lock.rs` fails if a vendor pinned by EITHER register
//! is swept by no shard, and fails if a shard stages a vendor tree it does not
//! sweep. Today that union proves the whisper mel, granite norm, vadkit STFT,
//! CED, CLAP and SigLIP graphs are clean controls, and that the FIVE
//! `speakerkit/` defect pins, the ONE `lid/` defect pin and the ONE `lid/`
//! [`LOAD_BEARING_NORMS`] pin still hold in BOTH directions. It still CANNOT verify the `alignkit` and `argmax-speakerkit`
//! pins — no shard downloads those models — so full pin verification (every
//! [`KNOWN_DEFECTS`] entry) remains a local/dev gate needing the complete
//! `Models/` tree; that gap is recorded by name as `UNSTAGED_DEFECT_VENDORS`
//! in the same test. The override is fail-closed — absence of it requires ALL
//! pinned vendors — so narrowing coverage is always an explicit, reviewable
//! act in ci.yml, never the silent side effect of a deleted directory, which is
//! the whole point of the manifest.
//!
//! When no DOWNLOADED model tree is on disk the sweep is `ignored`, never a
//! green `ok` over zero models (see `build.rs`). "Downloaded" excludes the one
//! model this repository commits — the `vadkit` VAD artifact — because a
//! checkout always has it, and un-ignoring the sweep on that alone would put
//! every fresh clone under the fail-closed manifest above and fail it for
//! vendors nobody fetched. The committed VAD graph is still swept wherever the
//! cfg is on — EVERY `model-tests` shard names `vadkit` in its manifest, so
//! deleting the vendored artifact fails all seven on every PR — and its single
//! guard site is pinned hermetically by `accepts_vadkits_stft_sqrt_guard`
//! regardless.
//!
//! The parser tests below are hermetic and always run: they pin the checker
//! against verbatim excerpts of the real known-bad and known-good graphs, so
//! the gate itself cannot rot into something that always passes.

// The workspace-root anchor, FOUND by searching upward for the `[workspace]`
// manifest rather than counted in `../` hops — see its module doc.
#[path = "support/workspace_root.rs"]
#[allow(dead_code)]
mod workspace_root;

use std::{
  collections::{BTreeMap, BTreeSet},
  env, fs,
  io::{self, Read, Seek, SeekFrom},
  path::{Path, PathBuf},
};

/// fp16's smallest subnormal, `2^-24`. An epsilon below this is not
/// representable in fp16 and rounds to zero — the guard becomes inert.
const FP16_MIN_SUBNORMAL: f64 = 5.960_464_477_539_063e-8;

/// fp16's smallest *normal*, `2^-14` ≈ 6.10e-5. The boundary between the two
/// SURVIVING bands (see [`GuardBand`]), **not** a second failure threshold —
/// the module docs carry the measurement that keeps it from being one.
const FP16_MIN_NORMAL: f64 = 6.103_515_625e-5;

/// Which fp16 band a guard's effective floor lands in.
///
/// Three bands rather than a bare pass/fail, because two of them survive and
/// they do not survive the same way, and because the difference is exactly the
/// thing this file used to assert without checking: [`FP16_MIN_NORMAL`] sat
/// here as a dead constant whose doc comment claimed subnormal guards were at
/// risk while no test looked at the band at all. It is a classification now, so
/// the claim is either measured or visible.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum GuardBand {
  /// `>= 2^-14` — an ordinary fp16 number, immune to any flush-to-zero.
  Normal,
  /// `[2^-24, 2^-14)` — representable, but ONLY as an fp16 subnormal. Almost
  /// the whole tree lives here (see the module docs' census); MEASURED to be
  /// honoured, and classified apart so that stays a measurement.
  SubnormalOnly,
  /// `< 2^-24` — not representable in fp16 at all. The constant rounds to zero,
  /// the guard goes inert, and the sweep FAILS.
  Inert,
}

impl GuardBand {
  /// The band an effective floor lands in.
  fn of(effective: f64) -> Self {
    if effective >= FP16_MIN_NORMAL {
      GuardBand::Normal
    } else if effective >= FP16_MIN_SUBNORMAL {
      GuardBand::SubnormalOnly
    } else {
      GuardBand::Inert
    }
  }

  /// Stable label — it appears in the census, in every failure message, and
  /// inside the [`LOAD_BEARING_NORMS`] pins, so it is API, not decoration.
  fn label(self) -> &'static str {
    match self {
      GuardBand::Normal => "normal",
      GuardBand::SubnormalOnly => "subnormal-only",
      GuardBand::Inert => "inert",
    }
  }
}

// ---------------------------------------------------------------------------
// MIL parsing
//
// Hand-rolled over MIL's fixed one-statement-per-line shape, mirroring
// `coremlit/tests/whisper/models_lock.rs`'s hand-rolled lock reader: no parser
// dependency for a grammar this small and this fixed.
//
//   tensor<fp16, [1, 2999, 29]> var_849_cast_fp16 =
//       log(epsilon = var_849_epsilon_0, x = var_849_softmax_cast_fp16)
//       [name = tensor<string, []>("op_849_cast_fp16")];
//
// TWO SPELLINGS OF THAT SHAPE, not one. Through coremltools 8 every
// declaration was written as a tensor type, rank-0 scalars included
// (`tensor<fp16, []> eps = const()[.., val = tensor<fp16, []>(0x1p-24)]`).
// coremltools 9 / MIL `program(1.3)` writes a scalar's type BARE, on both the
// declaration and the `val` attribute:
//
//   fp16 var_23_to_fp16 = const()[name = string("op_23_to_fp16"),
//                                 val = fp16(0x1.5p-17)];
//
// A `tensor<`-only reader sees no statement there at all, so EVERY scalar
// const of such a graph — every epsilon among them — stays out of
// [`Graph::consts`] and every guard site resolves to nothing. That was not a
// quiet under-report, which is why it was found: the sites land in
// [`Graph::unresolved`] and the sweep fails loudly (36 unresolvable guard
// statements and zero sites over the 162 KB VoxLingua107 graph). Both
// spellings are read below, and one graph mixes them freely — the same file
// writes `tensor<fp16, [1, 107]>` for a tensor and `fp32` for a scalar.
// ---------------------------------------------------------------------------

/// MIL's scalar (rank-0) type names, as coremltools 9 writes them BARE at the
/// head of a statement and inside a `const`'s `val = TY(..)` attribute. Only
/// these introduce a statement: any other leading token (`func`, `program(..)`,
/// `[buildInfo`, `{`, `}`) is not one, exactly as before. A closed vocabulary
/// rather than "any identifier followed by a space", so a wrapped line or a
/// future header cannot be mistaken for a declaration.
const MIL_SCALAR_TYPES: &[&str] = &[
  "bool", "string", "fp16", "fp32", "fp64", "int8", "int16", "int32", "int64", "uint8", "uint16",
  "uint32", "uint64",
];

/// The bare scalar type heading a coremltools-9 statement (`fp16 v = ..`), with
/// the rest of the line. `None` when the line does not start with one —
/// including every line of a coremltools-8 graph, where a scalar is spelled
/// `tensor<TY, []>` and this arm never fires.
fn bare_scalar_head(line: &str) -> Option<(&str, &str)> {
  let (ty, rest) = line.split_once(' ')?;
  MIL_SCALAR_TYPES.contains(&ty).then_some((ty, rest))
}

/// One parsed MIL statement: `tensor<DTYPE, [..]> VAR = OP(ARGS)[ATTRS];`
struct Stmt {
  dtype: String,
  op: String,
  args: String,
  /// The trailing `[name = .., val = ..]` attribute list, kept verbatim.
  ///
  /// Scalar `const`s are resolved to a number at parse time, but a WEIGHT
  /// const's value is not in the text at all — it is a `BLOBFILE(path, offset)`
  /// into the bundle's `weights/weight.bin`. Keeping the attributes is what
  /// lets [`Graph::audit`] hand a `batch_norm`'s `variance` operand to the
  /// sweep as a [`BlobRef`], so the quantity a guard protects can be READ
  /// rather than assumed.
  attrs: String,
}

/// A parsed graph: scalar constants resolved to values, plus every
/// variable's producing statement.
struct Graph {
  consts: BTreeMap<String, f64>,
  producers: BTreeMap<String, Stmt>,
  /// Statement lines that NAME a guarded op (see [`GUARD_LOOKING_OPS`]) but
  /// did not parse into a resolvable [`Stmt`]. Completeness accounting: a
  /// guard the reader cannot read is a hole, not a pass. [`Graph::audit`]
  /// carries these forward and the sweep fails with the line quoted, so a
  /// re-conversion that emits a guard in syntax this hand-rolled reader does
  /// not yet handle can never masquerade as a clean sweep — the exact way a
  /// partial parse used to stay GREEN with one recognized guard beside a new
  /// vanishing one.
  unresolved: Vec<String>,
}

/// Parses a hex float literal (`0x1p-149`, `0x1.5798eep-27`, `0x0p+0`).
///
/// `f64::from_str` does not accept hex floats, and every epsilon that
/// matters in these graphs is written in exactly that form.
fn parse_hex_float(s: &str) -> Option<f64> {
  let s = s.trim();
  let (neg, s) = match s.strip_prefix('-') {
    Some(rest) => (true, rest),
    None => (false, s.strip_prefix('+').unwrap_or(s)),
  };
  let s = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X"))?;
  let (mantissa, exponent) = s.split_once(['p', 'P'])?;
  let (int_part, frac_part) = mantissa.split_once('.').unwrap_or((mantissa, ""));
  if int_part.is_empty() && frac_part.is_empty() {
    return None;
  }

  let mut value = 0.0_f64;
  for c in int_part.chars() {
    value = value * 16.0 + f64::from(c.to_digit(16)?);
  }
  let mut scale = 1.0 / 16.0;
  for c in frac_part.chars() {
    value += f64::from(c.to_digit(16)?) * scale;
    scale /= 16.0;
  }

  let exp: i32 = exponent.parse().ok()?;
  value *= 2.0_f64.powi(exp);
  Some(if neg { -value } else { value })
}

/// Parses a MIL scalar literal — hex float first, then decimal.
fn parse_scalar(tok: &str) -> Option<f64> {
  let tok = tok.trim();
  if tok.contains("0x") || tok.contains("0X") {
    return parse_hex_float(tok);
  }
  tok.parse::<f64>().ok()
}

/// Splits `a = 1, b = tensor<int32, [1]>([2])` on depth-0 commas.
fn split_args(args: &str) -> Vec<&str> {
  let (mut out, mut depth, mut start) = (Vec::new(), 0_i32, 0_usize);
  for (i, c) in args.char_indices() {
    match c {
      '(' | '[' | '<' => depth += 1,
      ')' | ']' | '>' => depth -= 1,
      ',' if depth == 0 => {
        out.push(args[start..i].trim());
        start = i + 1;
      }
      _ => {}
    }
  }
  let tail = args[start..].trim();
  if !tail.is_empty() {
    out.push(tail);
  }
  out
}

/// Value of the `key = value` argument named `key`, if present.
fn arg<'a>(args: &'a str, key: &str) -> Option<&'a str> {
  split_args(args).into_iter().find_map(|pair| {
    let (k, v) = pair.split_once('=')?;
    (k.trim() == key).then(|| v.trim())
  })
}

/// The op names that make a statement *guard-looking*. If the reader cannot
/// fully parse a statement whose op is one of these, the sweep fails rather
/// than dropping it silently: it may be a numerically-guarded op emitted in
/// syntax this hand-rolled reader does not yet handle — exactly what a new
/// coremltools re-conversion can produce. Covers the guard SITES (`log`,
/// `rsqrt`, `sqrt`, `real_div`, the norms — `instance_norm`, `layer_norm`,
/// `batch_norm`, `l2_norm`) AND the floor-contributing ops a site's guard is
/// resolved through (`add`, `clip`, `maximum`, `softmax`), because an unreadable
/// `clip` can make a `sqrt` guard vanish just as silently as an unreadable
/// `sqrt`. `exp` is included as the containment op the folded-log audit reasons
/// about. `l2_norm` is whole-token matched, so `reduce_l2_norm` — a bare L2
/// reduction that carries no `epsilon` — never trips it. The check is dormant on
/// today's tree (every guard statement parses) and arms only when a re-conversion
/// changes the shape of one — the bias is deliberately toward a loud review over
/// a silent drop.
const GUARD_LOOKING_OPS: &[&str] = &[
  "log",
  "rsqrt",
  "sqrt",
  "real_div",
  "instance_norm",
  "layer_norm",
  "batch_norm",
  "l2_norm",
  "add",
  "clip",
  "maximum",
  "softmax",
  "exp",
];

/// The kwarg spellings that name a numerical-stability guard *directly on an op*
/// (as opposed to a floor contributed by a separate `add`/`clip`/`maximum`).
/// CoreML MIL spells it `epsilon` on every guarded op it emits — `log`, `rsqrt`,
/// the norms, `l2_norm`. Any op carrying one of these that no specific
/// [`Graph::audit`] arm recognizes is still a guard the sweep must not drop: the
/// vocabulary-independent catch-all surfaces it as unresolved. A one-element
/// slice on purpose — extend it here if a future MIL op guards under a different
/// name — kept a named set so the catch-all reads as "a guard we don't model",
/// not a bare string check.
const EPSILON_KWARGS: &[&str] = &["epsilon"];

/// True when `b` can appear inside a MIL identifier.
fn is_ident_byte(b: u8) -> bool {
  b.is_ascii_alphanumeric() || b == b'_'
}

/// The guard op *called* in `line`, if any: a `NAME(` where NAME is in
/// [`GUARD_LOOKING_OPS`] and stands as a whole token — not the tail of a
/// longer identifier such as `catalog(` or `log_softmax(`. Used only on
/// statement lines that FAILED to parse, to tell a completeness hole (a
/// guard we must not lose) from a benign non-guard op we never audited.
fn guard_op_in(line: &str) -> Option<&'static str> {
  let bytes = line.as_bytes();
  GUARD_LOOKING_OPS.iter().copied().find(|&op| {
    let mut from = 0;
    while let Some(rel) = line[from..].find(op) {
      let i = from + rel;
      let after = i + op.len();
      let before_ok = i == 0 || !is_ident_byte(bytes[i - 1]);
      if before_ok && bytes.get(after) == Some(&b'(') {
        return true;
      }
      from = i + 1;
    }
    false
  })
}

/// A fully-parsed statement: its variable, producing op, and (when the op
/// is a scalar `const`) the resolved value. Payload of
/// [`ParseOutcome::Parsed`].
struct Parsed {
  var: String,
  stmt: Stmt,
  const_val: Option<f64>,
}

/// The outcome of reading one physical line as a MIL statement.
enum ParseOutcome {
  /// Not a `tensor<...>` statement line at all — skipped, as before.
  NotStatement,
  /// A fully-parsed statement: its variable, producing op, and (when the op
  /// is a scalar `const`) the resolved value.
  Parsed(Parsed),
  /// A `tensor<...>` statement line that did not parse. Carries the guard op
  /// it appears to call, if any — `Some` is a completeness hole.
  Unparsed(Option<&'static str>),
}

/// Reads one trimmed line. Any statement — in EITHER type spelling, `tensor<..>`
/// or a bare [`MIL_SCALAR_TYPES`] head — that does not parse is reported as
/// [`ParseOutcome::Unparsed`], never silently skipped, so a guard emitted in
/// unhandled syntax is surfaced, not lost.
fn parse_stmt_line(line: &str) -> ParseOutcome {
  // From a recognized type head onward the line IS a statement; any failure to
  // parse is Unparsed, and a completeness hole iff the raw line names a guard
  // op. Declared before the head split so an unclosed `tensor<` stays a
  // statement we could not read rather than degrading to "not a statement".
  let unparsed = || ParseOutcome::Unparsed(guard_op_in(line));

  let (dtype, rest) = if let Some(rest) = line.strip_prefix("tensor<") {
    // `fp16, [1, 2999, 29]> var = op(args)[attrs];` — shapes never nest angle
    // brackets, so the first `>` closes the tensor type.
    let Some((ty, rest)) = rest.split_once('>') else {
      return unparsed();
    };
    (ty.split(',').next().unwrap_or("").trim().to_string(), rest)
  } else if let Some((ty, rest)) = bare_scalar_head(line) {
    // coremltools 9: `fp16 var = op(args)[attrs];`. The dtype is the head
    // itself, so a scalar's `Finding::render` reads `log/fp16` exactly as the
    // tensor spelling's does.
    (ty.to_string(), rest)
  } else {
    return ParseOutcome::NotStatement;
  };

  let Some((var, rest)) = rest.split_once('=') else {
    return unparsed();
  };
  let var = var.trim();
  if var.is_empty() || !var.chars().all(|c| c.is_alphanumeric() || c == '_') {
    return unparsed();
  }

  let rest = rest.trim();
  let Some(open) = rest.find('(') else {
    return unparsed();
  };
  let op = rest[..open].trim().to_string();

  // Balanced scan for the op's argument list.
  let mut depth = 0_i32;
  let mut close = None;
  for (i, c) in rest[open..].char_indices() {
    match c {
      '(' => depth += 1,
      ')' => {
        depth -= 1;
        if depth == 0 {
          close = Some(open + i);
          break;
        }
      }
      _ => {}
    }
  }
  let Some(close) = close else {
    // The op name is already in hand — classify by it directly rather than
    // re-scanning, so a guard call with an unbalanced arg list is caught.
    let guard = GUARD_LOOKING_OPS
      .iter()
      .copied()
      .find(|&g| g == op.as_str());
    return ParseOutcome::Unparsed(guard);
  };
  let args = rest[open + 1..close].to_string();
  let attrs = rest[close + 1..].trim().to_string();

  let const_val = (op == "const").then(|| const_scalar(&attrs)).flatten();

  ParseOutcome::Parsed(Parsed {
    var: var.to_string(),
    stmt: Stmt {
      dtype,
      op,
      args,
      attrs,
    },
    const_val,
  })
}

/// Reads a MIL program into constants, producers, and — critically — the
/// guard-looking statements it could NOT read (see [`Graph::unresolved`]).
fn parse_mil(text: &str) -> Graph {
  let mut consts = BTreeMap::new();
  let mut producers = BTreeMap::new();
  let mut unresolved = Vec::new();

  for line in text.lines() {
    let line = line.trim();
    match parse_stmt_line(line) {
      ParseOutcome::NotStatement => {}
      ParseOutcome::Parsed(Parsed {
        var,
        stmt,
        const_val,
      }) => {
        if let Some(value) = const_val {
          consts.insert(var.clone(), value);
        }
        producers.insert(var, stmt);
      }
      ParseOutcome::Unparsed(Some(op)) => {
        unresolved.push(format!("unreadable `{op}` statement: {line}"));
      }
      ParseOutcome::Unparsed(None) => {}
    }
  }

  Graph {
    consts,
    producers,
    unresolved,
  }
}

/// Extracts a scalar `const`'s value from its attribute list:
/// `[name = .., val = tensor<fp32, []>(0x1p-149)]`, or its coremltools-9
/// spelling `[name = .., val = fp32(0x1p-149)]`. Non-scalar constants (weights,
/// shapes) have a non-empty shape and are deliberately ignored, in both
/// spellings — `val = tensor<fp16, [1024]>(BLOBFILE(..))` has no bare form.
fn const_scalar(attrs: &str) -> Option<f64> {
  let val = attrs.find("val")?;
  let open = attrs[val..].find("(")? + val;
  let head = attrs[val..open].replace(' ', "");
  // `tensor<TY, []>` — a rank-0 tensor — or the bare `TY`. The bare arm reads
  // only what follows the LAST `val=`: `attrs.find("val")` can land inside a
  // name (`"..._validate_indices_0"`, `"interval"`), and the tensor arm's
  // substring test tolerates that, so the added arm must too or it would
  // narrow what already parses.
  let scalar_tensor = head.contains(",[]>");
  let bare_scalar = head
    .rsplit_once("val=")
    .is_some_and(|(_, ty)| MIL_SCALAR_TYPES.contains(&ty));
  if !(scalar_tensor || bare_scalar) {
    return None;
  }
  let close = attrs[open..].find(')')? + open;
  parse_scalar(&attrs[open + 1..close])
}

// ---------------------------------------------------------------------------
// Weight blobs
//
// A guard is only worth what it guards. `epsilon >= 2^-24` says the CONSTANT is
// representable; it says nothing about whether the quantity beside it can be
// zero. For most guard shapes that quantity is a runtime tensor and the gate
// rightly makes no claim — but `batch_norm` is different: MIL passes its
// `variance` as an OPERAND, and in every graph here that operand is a constant
// stored in the bundle's own `weights/weight.bin`. So it can be read, and the
// question "is this epsilon the ONLY thing between the graph and 1/sqrt(0)"
// has an answer that is a fact about the artifact rather than a guess.
//
// The blob format is coremltools' `blob_file_format`: a 24-byte metadata record
// at the offset the MIL names, then the payload wherever that record points.
//
//   0x00  uint32  sentinel = 0xdeadbeef
//   0x04  uint32  dtype (1 = fp16, 2 = fp32)
//   0x08  uint64  payload size in BYTES
//   0x10  uint64  payload offset
//
// The sentinel is checked, and every failure to read is a HOLE — the same rule
// the MIL reader follows. A variance this reader cannot read means the guard's
// worth is unknown, which is not the same as the guard being fine.
// ---------------------------------------------------------------------------

/// The 4-byte sentinel every blob metadata record begins with.
const BLOB_SENTINEL: u32 = 0xdead_beef;
/// `blob_metadata`'s dtype code for fp16.
const BLOB_DTYPE_FP16: u32 = 1;
/// `blob_metadata`'s dtype code for fp32.
const BLOB_DTYPE_FP32: u32 = 2;
/// Refuse to allocate for a payload larger than this. A corrupt or
/// misinterpreted metadata record can name an arbitrary `size`; the largest
/// constant in the tree is a few tens of MiB, so a cap well above it turns a
/// misread into a named failure instead of an out-of-memory abort.
const BLOB_MAX_BYTES: u64 = 512 * 1024 * 1024;

/// Where a non-scalar constant's bytes live: a bundle-relative path and the
/// byte offset of its blob METADATA record (not of the payload).
struct BlobRef {
  path: String,
  offset: u64,
}

/// The [`BlobRef`] in a `const`'s attribute list, if its value is a weight blob.
///
/// Both spellings, exactly as the two `const_scalar` arms handle both:
/// coremltools 8 writes `BLOBFILE(path = tensor<string, []>("…"), offset =
/// tensor<uint64, []>(64))`, coremltools 9 writes `BLOBFILE(path = string("…"),
/// offset = uint64(618752))`. The path is the first quoted string after
/// `BLOBFILE(` and the offset the first parenthesised integer after `offset`,
/// which both spellings satisfy without the reader having to model either.
fn blob_ref(attrs: &str) -> Option<BlobRef> {
  let rest = &attrs[attrs.find("BLOBFILE(")? + "BLOBFILE(".len()..];
  let open_quote = rest.find('"')?;
  let close_quote = open_quote + 1 + rest[open_quote + 1..].find('"')?;
  let path = rest[open_quote + 1..close_quote].to_string();

  let after = &rest[close_quote..];
  let offset_key = after.find("offset")?;
  let open = offset_key + after[offset_key..].find('(')?;
  let close = open + after[open..].find(')')?;
  let offset = after[open + 1..close].trim().parse().ok()?;
  Some(BlobRef { path, offset })
}

/// Reads a weight blob and narrows it to fp16 — the precision the guard is
/// judged at, whatever the blob declares.
///
/// `Err` is a completeness HOLE, never a skip: an unreadable variance means the
/// gate cannot say what the epsilon beside it is worth.
fn read_blob_as_fp16(bundle: &Path, blob: &BlobRef) -> Result<Vec<half::f16>, String> {
  let rel = blob.path.strip_prefix("@model_path/").unwrap_or(&blob.path);
  let path = bundle.join(rel);
  let mut file = fs::File::open(&path).map_err(|e| format!("open {}: {e}", path.display()))?;

  let mut meta = [0_u8; 24];
  file
    .seek(SeekFrom::Start(blob.offset))
    .and_then(|_| file.read_exact(&mut meta))
    .map_err(|e| {
      format!(
        "read blob metadata at offset {} of {}: {e}",
        blob.offset,
        path.display()
      )
    })?;
  let word = |at: usize| u32::from_le_bytes(meta[at..at + 4].try_into().expect("4 bytes"));
  let long = |at: usize| u64::from_le_bytes(meta[at..at + 8].try_into().expect("8 bytes"));

  let sentinel = word(0);
  if sentinel != BLOB_SENTINEL {
    return Err(format!(
      "blob metadata at offset {} of {} begins {sentinel:#010x}, not the {BLOB_SENTINEL:#010x} \
       sentinel — the offset or the blob layout is not what this reader assumes",
      blob.offset,
      path.display()
    ));
  }
  let dtype = word(4);
  let width = match dtype {
    BLOB_DTYPE_FP16 => 2_u64,
    BLOB_DTYPE_FP32 => 4,
    other => {
      return Err(format!(
        "blob at offset {} of {} declares dtype {other}, which this reader does not narrow to \
         fp16 (it knows {BLOB_DTYPE_FP16} = fp16 and {BLOB_DTYPE_FP32} = fp32)",
        blob.offset,
        path.display()
      ));
    }
  };
  let size = long(8);
  if size > BLOB_MAX_BYTES || size % width != 0 {
    return Err(format!(
      "blob at offset {} of {} declares a {size}-byte payload, which is not a sane multiple of \
       its {width}-byte element",
      blob.offset,
      path.display()
    ));
  }
  let mut raw = vec![0_u8; usize::try_from(size).map_err(|e| format!("{size} bytes: {e}"))?];
  file
    .seek(SeekFrom::Start(long(16)))
    .and_then(|_| file.read_exact(&mut raw))
    .map_err(|e| {
      format!(
        "read {size} bytes of payload at offset {} of {}: {e}",
        long(16),
        path.display()
      )
    })?;

  Ok(match dtype {
    BLOB_DTYPE_FP16 => raw
      .as_chunks::<2>()
      .0
      .iter()
      .map(|c| half::f16::from_le_bytes(*c))
      .collect(),
    // Narrowed, not read as-is: an fp32 constant executed in fp16 IS its fp16
    // rounding, which is the whole premise of this gate.
    _ => raw
      .as_chunks::<4>()
      .0
      .iter()
      .map(|c| half::f16::from_f32(f32::from_le_bytes(*c)))
      .collect(),
  })
}

/// A `batch_norm` whose `variance` operand resolved to a CONSTANT — the one
/// guard shape in this tree where the guarded quantity is pinned in the
/// artifact and can therefore be counted.
struct ConstVarianceNorm {
  var: String,
  dtype: String,
  eps: f64,
  blob: BlobRef,
}

impl Graph {
  /// Resolves a token to a constant value, if it is one.
  fn value(&self, tok: Option<&str>) -> Option<f64> {
    let tok = tok?;
    parse_scalar(tok).or_else(|| self.consts.get(tok).copied())
  }

  /// Resolves a token to a constant scalar, following `cast` producers. A
  /// fp16 conversion routinely emits a guard constant as `const → cast` — an
  /// fp32 literal cast to fp16 before it reaches an `add`/`maximum`/`clip`
  /// guard operand — and the bare [`Graph::value`] stops at the `cast`, so the
  /// guard's floor silently vanishes (the exact `const(1e-8) → cast →
  /// add(count, eps) → real_div` hole a re-conversion can open). Tries the
  /// direct literal/const first — identical to [`Graph::value`] on today's
  /// tree, where every guard constant is a direct literal — then follows a
  /// `cast` chain to its constant source. Depth-capped like [`Graph::floor`].
  fn const_through_cast(&self, tok: Option<&str>, depth: u8) -> Option<f64> {
    let tok = tok?;
    if let Some(v) = self.value(Some(tok)) {
      return Some(v);
    }
    if depth > 6 {
      return None;
    }
    match self.producers.get(tok) {
      Some(stmt) if stmt.op == "cast" => self.const_through_cast(arg(&stmt.args, "x"), depth + 1),
      _ => None,
    }
  }

  /// Follows `cast` producers to the ultimate non-`cast` producing statement of
  /// `tok`, with the SAME bounded traversal [`Graph::floor`] and
  /// [`Graph::const_through_cast`] use (depth-capped at 6). A fp16 conversion
  /// routinely interposes a `cast` between a floor-contributing guard op and the
  /// site it guards (`add → cast → real_div`), so inspecting only the immediate
  /// producer would miss the guard.
  fn producer_through_cast(&self, tok: Option<&str>, depth: u8) -> Option<&Stmt> {
    let tok = tok?;
    if depth > 6 {
      return None;
    }
    match self.producers.get(tok) {
      Some(stmt) if stmt.op == "cast" => {
        self.producer_through_cast(arg(&stmt.args, "x"), depth + 1)
      }
      other => other,
    }
  }

  /// True when `operand`'s producer — followed through any `cast` chain — is a
  /// floor-contributing GUARD op (`add`/`maximum`/`clip`) whose floor
  /// nonetheless did NOT resolve: the graph structurally intends a floor here
  /// but its constant is unreadable even through casts, so it is a hole to
  /// surface, not "no claim". The `cast` chain is followed with the SAME bounded
  /// traversal [`Graph::floor`] uses (shared [`Graph::producer_through_cast`]);
  /// [`Graph::floor`] itself recursively unwraps `cast`, so a `dynamic → add →
  /// cast → real_div` divisor reaches the `add` when the floor is resolved — the
  /// unresolved check must reach it too, or the site contributes neither a
  /// finding nor a hole and simply vanishes. Kept distinct from a genuinely
  /// dynamic input (no producer, or a non-guard producer like
  /// `real_div`/`sqrt`/`mul`/`reduce_*`/`scatter`), which stays silent: that is
  /// what lets the shipped embedders' `sqrt(real_div(..))` std sites and every
  /// `x / <dynamic>` divide avoid flooding the sweep with false holes while a
  /// `count + <dynamic>` guard the reader cannot read is still caught (see the
  /// `sqrt`/`real_div` arms of [`Graph::audit`]).
  fn unreadable_floor_guard(&self, operand: Option<&str>) -> bool {
    self
      .producer_through_cast(operand, 0)
      .is_some_and(|stmt| matches!(stmt.op.as_str(), "add" | "maximum" | "clip"))
  }

  /// The provable lower bound on the tensor `var`, and where it comes from.
  ///
  /// Returns `None` when nothing constant bounds it — a dynamic value this
  /// gate deliberately makes no claim about, rather than guessing.
  fn floor(&self, var: Option<&str>, depth: u8) -> Option<(f64, String)> {
    let var = var?;
    if depth > 6 {
      return None;
    }
    let stmt = self.producers.get(var)?;
    match stmt.op.as_str() {
      "const" => self.consts.get(var).map(|v| (*v, format!("const({v:e})"))),
      // `x + eps` — the classic explicit guard. The constant operand is
      // resolved through any `cast` (a fp16 conversion casts an fp32 literal
      // before adding it), not just direct literals/consts — see
      // [`Graph::const_through_cast`].
      "add" => ["y", "x"]
        .iter()
        .find_map(|k| self.const_through_cast(arg(&stmt.args, k), 0))
        .map(|c| (c, format!("add(+{c:e})"))),
      "clip" => self
        .const_through_cast(arg(&stmt.args, "alpha"), 0)
        .map(|lo| (lo, format!("clip(alpha={lo:e})"))),
      "maximum" => ["y", "x"]
        .iter()
        .find_map(|k| self.const_through_cast(arg(&stmt.args, k), 0))
        .map(|c| (c, format!("maximum({c:e})"))),
      // A softmax output can underflow to exactly 0 in fp16 long before
      // the log's epsilon is ever added — the decomposed-log_softmax trap.
      "softmax" => Some((0.0, "softmax->log".to_string())),
      "cast" => self.floor(arg(&stmt.args, "x"), depth + 1),
      _ => None,
    }
  }

  /// Every guard site in the graph, in a stable order, together with every
  /// guard-looking statement the audit could not fully resolve. A non-empty
  /// [`Audit::unresolved`] is a hard sweep failure: an epsilon this reader
  /// cannot resolve is a hole (the guard is unreadable), never a silent pass.
  fn audit(&self) -> Audit {
    let mut found = Vec::new();
    // Parser-level holes (unreadable statement shapes) carry through; audit-
    // level holes (a recognized site whose epsilon will not resolve) join
    // them below.
    let mut unresolved = self.unresolved.clone();
    let mut const_variance_norms = Vec::new();
    for (var, stmt) in &self.producers {
      let eps_kwarg = self.value(arg(&stmt.args, "epsilon"));
      // A `batch_norm` is the only op here that takes its `variance` as an
      // OPERAND rather than computing it — `layer_norm`/`instance_norm` derive
      // theirs from `x` at runtime and carry no such argument. When that
      // operand is a constant, what the epsilon is worth is a readable fact
      // about the artifact, so hand it to the sweep, which has the bundle
      // path. A constant this reader cannot turn into a [`BlobRef`] is a HOLE,
      // exactly like an unreadable epsilon: the guard's worth is unknown.
      let variance_const = self
        .producer_through_cast(arg(&stmt.args, "variance"), 0)
        .filter(|producer| producer.op == "const");
      if let ("batch_norm", Some(eps), Some(producer)) =
        (stmt.op.as_str(), eps_kwarg, variance_const)
      {
        match blob_ref(&producer.attrs) {
          Some(blob) => const_variance_norms.push(ConstVarianceNorm {
            var: var.clone(),
            dtype: stmt.dtype.clone(),
            eps,
            blob,
          }),
          // A rank-0 `variance` is not a thing MIL emits, but a constant whose
          // value this reader can neither locate in the blob nor read as a
          // scalar is unreadable, not absent.
          None if const_scalar(&producer.attrs).is_none() => {
            unresolved.push(format!(
              "unreadable constant `variance` on batch_norm/{} {var}: {}",
              stmt.dtype, producer.attrs
            ));
          }
          None => {}
        }
      }
      let site = match stmt.op.as_str() {
        // `log` and `rsqrt` always carry an `epsilon` in CoreML MIL, so they
        // are always guard sites — including when that epsilon has already
        // been folded to a literal `0x0p+0`. An epsilon that will NOT resolve
        // is a hole (we cannot read the guard), not a site to fold to zero.
        "log" | "rsqrt" => match eps_kwarg {
          Some(eps) => {
            let (floor, guard) = self
              .floor(arg(&stmt.args, "x"), 0)
              .unwrap_or((0.0, "-".into()));
            Some((eps, floor, guard))
          }
          None => {
            unresolved.push(unresolved_site(var, stmt));
            None
          }
        },
        // A normalization's epsilon is its whole guard: `instance_norm`,
        // `layer_norm` and `batch_norm` add it inside `sqrt(variance + eps)`, and
        // `l2_norm` does the same inside `sqrt(sum(x^2) + eps)` — so the stored
        // epsilon rounding to zero in fp16 is a divide-by-zero at the norm just as
        // for the others, and the effective floor is the epsilon itself. The op
        // prefix in `Finding::render` distinguishes `l2_norm` from the
        // batch/layer/instance norms; the guard semantics are identical.
        // Unresolvable means the guard is unreadable, not absent — the site must
        // FAIL the audit, not vanish from it (the old `eps_kwarg.map(...)` dropped
        // it silently).
        "instance_norm" | "layer_norm" | "batch_norm" | "l2_norm" => match eps_kwarg {
          Some(e) => Some((e, 0.0, "norm".into())),
          None => {
            unresolved.push(unresolved_site(var, stmt));
            None
          }
        },
        // `sqrt` has no epsilon: it is a guard site only when something
        // constant floors its input. A genuinely dynamic input is no claim,
        // not a hole — its guard, if any, lives in a floor-contributing op
        // whose own unreadability is caught at parse time. But a
        // floor-contributing GUARD op (`add`/`maximum`/`clip`) whose constant
        // will NOT resolve — even through a `cast` — IS a hole: the graph
        // structurally intends a floor here and the reader cannot read it, so
        // it must FAIL the audit, not `.map`-drop into silence (the
        // `const(1e-8) → cast → add → sqrt` shape a re-conversion can emit).
        "sqrt" => match self.floor(arg(&stmt.args, "x"), 0) {
          Some((f, g)) => Some((0.0, f, g)),
          None => {
            if self.unreadable_floor_guard(arg(&stmt.args, "x")) {
              unresolved.push(unresolved_site(var, stmt));
            }
            None
          }
        },
        // A divide is a guard site when its DIVISOR is const-floored —
        // the `x / (n + eps)` pooling shape. An unreadable floor guard on the
        // divisor is a hole for the same reason as `sqrt` above; a divisor with
        // no readable floor and no guard-op producer is a genuinely dynamic
        // divide, which stays "no claim".
        "real_div" => match self.floor(arg(&stmt.args, "y"), 0) {
          Some((f, g)) => Some((0.0, f, format!("denom:{g}"))),
          None => {
            if self.unreadable_floor_guard(arg(&stmt.args, "y")) {
              unresolved.push(unresolved_site(var, stmt));
            }
            None
          }
        },
        // Vocabulary-independent completeness catch-all (BEFORE the wildcard). Any
        // op no arm above recognized that still carries an `epsilon` kwarg (see
        // [`EPSILON_KWARGS`]) is a numerical guard whose exact semantics this audit
        // does not model — a re-conversion can emit a brand-new epsilon-bearing op,
        // or a known one this reader was never taught (the `l2_norm` hole was
        // exactly this). It must NOT drop through the `_ => None` wildcard the way a
        // recognized-but-unguarded op does: surface it as unresolved so the sweep
        // fails loudly, exactly like an unreadable guard statement. Resolvable or
        // not, an epsilon we cannot attribute to modeled semantics is a hole.
        _ if EPSILON_KWARGS.iter().any(|k| arg(&stmt.args, k).is_some()) => {
          unresolved.push(unresolved_site(var, stmt));
          None
        }
        _ => None,
      };
      if let Some((eps, floor, guard)) = site {
        found.push(Finding {
          op: stmt.op.clone(),
          dtype: stmt.dtype.clone(),
          var: var.clone(),
          eps,
          floor,
          guard,
        });
      }
    }
    Audit {
      findings: found,
      unresolved,
      const_variance_norms,
    }
  }
}

/// The result of auditing a graph: every resolved guard site, plus every
/// guard-looking statement that could not be fully read. Completeness lives
/// here — a non-empty `unresolved` is a hard sweep failure, so a partial
/// parse can never report a clean fp16 sweep.
struct Audit {
  findings: Vec<Finding>,
  unresolved: Vec<String>,
  /// Every `batch_norm` whose `variance` is a constant in the bundle's weight
  /// blob. Carried out of the text-only audit so [`sweep_tree`] — which knows
  /// the bundle path — can read it; the hermetic parser tests stay file-free.
  const_variance_norms: Vec<ConstVarianceNorm>,
}

/// A one-line completeness failure for a recognized guard site whose epsilon
/// did not resolve to a constant — the statement quoted so the hole is
/// actionable (which op, which var, and the arguments as read).
fn unresolved_site(var: &str, stmt: &Stmt) -> String {
  format!(
    "unresolvable epsilon on {}/{} {var}: {}({})",
    stmt.op, stmt.dtype, stmt.op, stmt.args
  )
}

/// One numerically-guarded op, with the guard resolved to a number.
struct Finding {
  op: String,
  dtype: String,
  var: String,
  /// The op's own `epsilon =` argument (0.0 when it has none).
  eps: f64,
  /// The provable lower bound on the guarded input / divisor.
  floor: f64,
  guard: String,
}

impl Finding {
  /// What the guard is actually worth. The op's own `eps` and the preceding
  /// floor are TWO independently-materialized constants — `log(x + eps)` with
  /// `x` bounded below by an `add`/`clip`/`maximum` guard is two SEPARATE
  /// constants in the graph, each rounded to fp16 on its own. So the guard
  /// survives iff AT LEAST ONE of them clears the fp16 floor: the effective
  /// floor is their MAX, not their sum. Summing them is wrong — two constants
  /// each below `2^-24` BOTH round to zero independently, so their fp16 "sum"
  /// never materializes (nothing proves CoreML folds them into a single
  /// constant before lowering, e.g. `add(x, 0x1p-25)` feeding `log(eps =
  /// 0x1p-25)` would falsely "survive" at `2^-24` while both halves vanish).
  /// whisper-mel's clean pattern is `add(x, 0x1p-24)` with `log(eps = 0)`: the
  /// `eps = 0` contributes nothing and the add's `2^-24` survives on its own, so
  /// the MAX keeps mel clean.
  fn effective(&self) -> f64 {
    self.eps.max(self.floor)
  }

  /// Which fp16 band this guard's effective floor lands in.
  fn band(&self) -> GuardBand {
    GuardBand::of(self.effective())
  }

  /// The gate. A guard survives iff its effective floor — the MAX of the op's
  /// own epsilon and the preceding floor, each an independent fp16 constant — is
  /// at or above fp16's smallest subnormal; anything below rounds to zero and
  /// the guard goes inert.
  ///
  /// Survival is the [`GuardBand::Inert`] question and nothing more. The
  /// remaining two bands both survive, and the module docs carry the
  /// measurement that says so — the distinction is REPORTED, never failed.
  fn survives_fp16(&self) -> bool {
    self.band() != GuardBand::Inert
  }

  /// A `softmax` feeding a `log` is a decomposed `log_softmax`. Even with
  /// a surviving epsilon it is lossy: the softmax output underflows to 0
  /// in fp16 *before* the log ever adds the epsilon, so the true log-prob
  /// is clamped at `log(eps)` instead of computed. A fused, stable
  /// `log_softmax` (`x - logsumexp(x)`) never materializes the underflow.
  fn is_decomposed_log_softmax(&self) -> bool {
    self.op == "log" && self.guard == "softmax->log"
  }

  /// Stable one-line rendering — this is what [`KNOWN_DEFECTS`] pins, so
  /// any drift in op, dtype, guard shape, or epsilon fails the gate.
  fn render(&self) -> String {
    format!(
      "{}/{} guard={} eff={:e}",
      self.op,
      self.dtype,
      self.guard,
      self.effective()
    )
  }
}

// ---------------------------------------------------------------------------
// The pins
// ---------------------------------------------------------------------------

/// A model we knowingly still ship with an inert fp16 guard.
struct KnownDefect {
  /// Path relative to `Models/`.
  path: &'static str,
  /// Every vanishing guard site, rendered by [`Finding::render`], sorted.
  ///
  /// Pinned in BOTH directions on purpose: a new vanishing site fails the
  /// gate, and so does a *repair*. A model quietly re-converted with a
  /// healthy epsilon must not slip by unnoticed — the fix has to be seen,
  /// the pin deleted, and the parity goldens re-cut deliberately.
  sites: &'static [&'static str],
  /// What breaks, and why it is still here.
  note: &'static str,
}

/// Every fp16-vanishing guard in the tree. Each entry is a defect, not an
/// exemption.
///
/// The sweep that created this gate found ten sites across nine models. TWO of
/// those models — the two the speakerkit pipeline SHIPS — have since been
/// replaced by guard-repaired re-conversions (issue #15) and their pins are
/// gone: `speakerkit/pyannote_segmentation` no longer contains a `log` op at
/// all, and `speakerkit/wespeaker` (the fp32 shipping embedder) carries its
/// three pooling divisor guards at `0x1p-24`, the fp16 floor. Every other pin
/// below still stands, including the ones whose re-conversions exist but are
/// NOT adopted (see the `wespeaker_v2` note, and `alignkit/base960h_aligner`).
const KNOWN_DEFECTS: &[KnownDefect] = &[
  KnownDefect {
    path: "alignkit/base960h_aligner.mlmodelc",
    sites: &["log/fp16 guard=softmax->log eff=1.401298464324817e-45"],
    note: "Decomposed log-softmax; eps 0x1p-149 rounds to 0 in fp16. `emissions` IS the log \
           output, so ANE log(0) -> ~-45440 lands directly in the shipped tensor: 16.7% of \
           output cells corrupted, word timings shifted up to 881 ms.",
  },
  KnownDefect {
    path: "speakerkit/Segmentation.mlmodelc",
    sites: &["log/fp32 guard=softmax->log eff=1.401298464324817e-45"],
    note: "Same source model and same coremltools default epsilon as pyannote_segmentation; the \
           fp32 artifact merely KEEPS 0x1p-149 rather than folding it to zero. That is fp32's \
           smallest subnormal — it survives fp32 arithmetic and nothing else. Loaded under the \
           default ComputeUnits::All it is demoted to fp16 on the ANE and vanishes exactly like \
           its fp16 sibling.",
  },
  KnownDefect {
    path: "speakerkit/wespeaker_v2.mlmodelc",
    // THREE identical divisor guards, one per attentive-stat pooling division
    // (the weighted mean and the two divisions feeding the weighted variance /
    // `std`). Listed thrice, not deduped: the multiplicity is the blast radius
    // (finding 5).
    sites: &[
      "real_div/fp32 guard=denom:add(+9.99999993922529e-9) eff=9.99999993922529e-9",
      "real_div/fp32 guard=denom:add(+9.99999993922529e-9) eff=9.99999993922529e-9",
      "real_div/fp32 guard=denom:add(+9.99999993922529e-9) eff=9.99999993922529e-9",
    ],
    note: "Attentive-stat pooling divides by `count + 1e-8` at THREE sites (the weighted mean \
           and the two divisions behind the weighted variance/std). 1e-8 is 0.168x fp16's \
           smallest subnormal, so on the ANE all three divisor guards are zero. This is the int8 \
           embedder issue #15 RETIRED from shipping (its per-tensor palettization silently \
           collapses 8-speaker audio — tests/speaker/model_io.rs's DECISION); it stays on disk \
           as the tested sibling the factorial record runs on, guards unrepaired. The published \
           re-conversion is NOT adopted for it: that artifact is also a RE-PALETTIZATION \
           (different LUTs), and it moves clip 14's int8 ANE arm from 0.8178 % to 1.4860 % DER. \
           The fp32 `wespeaker.mlmodelc` the pipeline ships instead carries these SAME pooling \
           guards repaired to 0x1p-24 — which is why the shipping embedder has no entry here.",
  },
  KnownDefect {
    path: "speakerkit/wespeaker_int8.mlmodelc",
    sites: &[
      "real_div/fp32 guard=denom:add(+9.99999993922529e-9) eff=9.99999993922529e-9",
      "real_div/fp32 guard=denom:add(+9.99999993922529e-9) eff=9.99999993922529e-9",
      "real_div/fp32 guard=denom:add(+9.99999993922529e-9) eff=9.99999993922529e-9",
    ],
    note: "Same three-site pooling epsilon as wespeaker_v2.mlmodelc (byte-identical artifact).",
  },
  KnownDefect {
    path: "speakerkit/PLDA.mlmodelc",
    // TWO sqrt-of-clipped-value guards, each clipped to 1e-12 (finding 5).
    sites: &[
      "sqrt/fp32 guard=clip(alpha=9.999999960041972e-13) eff=9.999999960041972e-13",
      "sqrt/fp32 guard=clip(alpha=9.999999960041972e-13) eff=9.999999960041972e-13",
    ],
    note: "Normalization clips to 1e-12 before `sqrt` at TWO sites, then divides by it. 1e-12 is \
           1.7e-5x fp16's smallest subnormal, so IF these ops are lowered to fp16 the clip floor \
           becomes zero, giving sqrt(0) and a divide by zero. That premise is UNTESTED: this sweep \
           reads the MIL text STATICALLY, nothing loads these graphs, and no run has observed \
           their actual placement or whether ComputeUnits::All demotes them. THIS finding is why \
           the runtime projects with diaric's f64 `PldaTransform` (weights `include_bytes!`d, host \
           arithmetic, no compute-unit demotion) instead of the CoreML PLDA the same model repo \
           ships — see `Extraction::into_offline_input`. The graph arrives with the vendor tree \
           whatever this crate decides, so the pin stays: it is what forces a re-conversion that \
           repairs the epsilon to be SEEN, rather than leaving the rejection as folklore a future \
           contributor would have to rediscover.",
  },
  KnownDefect {
    path: "speakerkit/PldaRho.mlmodelc",
    sites: &[
      "sqrt/fp32 guard=clip(alpha=9.999999960041972e-13) eff=9.999999960041972e-13",
      "sqrt/fp32 guard=clip(alpha=9.999999960041972e-13) eff=9.999999960041972e-13",
    ],
    note: "Same two-site 1e-12 clip floor as PLDA.mlmodelc, unloaded for the same reason.",
  },
  KnownDefect {
    path: "argmax-speakerkit/speaker_segmenter/pyannote-v3/W32A32/SpeakerSegmenter.mlmodelc",
    sites: &["log/fp16 guard=softmax->log eff=0e0"],
    note: "Vendored from argmax. Epsilon already folded to 0x0p+0, and the graph is fp16 \
           DESPITE the W32A32 directory name. Contained, not silent-clean: the saturated log \
           feeds an `exp` that maps it back toward 0 before any shipped output, and the winning \
           powerset class never underflows, so `speaker_probs`/`speaker_ids` survive. The guard \
           is still inert — pinned so a re-vendored graph cannot widen the blast radius unseen.",
  },
  KnownDefect {
    path: "argmax-speakerkit/speaker_segmenter/pyannote-v3/W8A16/SpeakerSegmenter.mlmodelc",
    sites: &["log/fp16 guard=softmax->log eff=1.401298464324817e-45"],
    note: "Same graph as the W32A32 variant with the epsilon left at 0x1p-149 instead of folded \
           to zero — identically inert in fp16, identically contained by the downstream `exp`.",
  },
  KnownDefect {
    path: "lid/SpeechBrainECAPAVoxLingua107.mlmodelc",
    sites: &["log/fp16 guard=softmax->log eff=1.401298464324817e-45"],
    note: "The THIRD instance of this class, after alignkit/base960h_aligner and \
           speakerkit/Segmentation: a decomposed log-softmax at the classifier tail, guarded by \
           fp32's smallest subnormal (0x1p-149) against an fp16 log whose floor is 2^-24 ~ 6e-8. \
           TODAY IT COSTS NOTHING, AND THE REASON IS THAT THE EPSILON IS NEVER CONSULTED. The \
           shipped graph is FLEXIBLE-SHAPE, and on every current backend — All, ANE, GPU, CpuOnly \
           — the softmax->log pair executes as one fused, higher-precision log-softmax. Measured \
           on both census clips, all four arms: 107 of 107 rows finite, no saturation, the tail \
           reaching -37.27 (a probability of 6.5e-17, NINE orders below fp16's smallest subnormal \
           — a number the fp16 grid cannot hold, which is the proof the log is not being taken in \
           fp16), and sum(exp) = 0.994-1.000. `Error::NonFiniteOutput` cannot fire. The epsilon is \
           dead code. THE TRIGGER THAT ARMS IT IS STATIC SHAPES — exactly what a re-conversion \
           would do to put this tail on the ANE. Recompiled with fixed input dims the fusion is \
           gone, and every entry whose true log-prob is below ln(2^-24) = -16.635 becomes ANE \
           log(0) = -45440.0. On the 13 s anchor clip that is 105 of 107 entries, starting at RANK \
           2, and the fp64 reference agrees exactly on WHICH 105. Top-1 survives essentially \
           intact (-0.009842 against an fp64 truth of -0.010195, delta 3.5e-4) and so does top-2, \
           so the blast radius is confidence-gated: on a flat 3 s clip it is 0 of 107. -45440.0 is \
           FINITE, so nothing upstack notices — the door's non-finite guard stays silent, \
           `LanguageScore::probability` reads 0.0, and `identify(k >= 3)` fills ranks 2+ by \
           ascending model column, the order `RankedScore` breaks ties in. TWO OBVIOUS REPAIRS ARE \
           ALREADY KNOWN NOT TO WORK — measured on that static ANE arm, and recorded here because \
           without it the first of them looks correct AND appears to succeed. (1) A `HEALTHY` fp16 \
           EPSILON — an explicit +6e-8, the whisper-mel discipline the issue-#15 \
           speakerkit re-conversions used — does NOT survive: the ANE flushes subnormals and the output is -45440.0, \
           unchanged. A floor that does survive must be at least 6.1e-5, fp16's smallest NORMAL, \
           which clamps the whole tail at -9.7 and is uselessly coarse. (2) The PYANNOTE-STYLE `x \
           - logsumexp(x)` rewrite also fails on the ANE at this graph's logit range: exp(~23) \
           overflows fp16 inside the reduce and the output comes back as raw logits (max +22.86, \
           sum(exp) 8.6e9) — worse than the defect. The ONLY verified ANE-safe tail is an fp32 \
           ISLAND: the final softmax+log excluded from the fp16 pass (8 CPU ops, 2 unit \
           transitions, latency unchanged at ~23.6 ms), which reproduces the flexible graph's full \
           finite tail (-37.28) on the ANE. Pinned unrepaired because the shipping artifact is \
           flexible-shape and the guard is therefore inert; the pin is what makes the arming event \
           impossible to miss, since a re-conversion to static shapes cannot land without this \
           entry changing.",
  },
];

// ---------------------------------------------------------------------------
// The second register: where a surviving guard is the ONLY guard
// ---------------------------------------------------------------------------

/// One `batch_norm` whose stored `variance` holds channels that are exactly
/// `0.0` once narrowed to fp16.
///
/// Those channels have nothing else. `batch_norm` computes
/// `gamma * (x - mean) / sqrt(variance + epsilon) + beta`, so with
/// `variance == 0` the epsilon is the entire denominator: drop it and the site
/// computes `1/sqrt(0)`. That is not a hypothesis either — see
/// [`LOAD_BEARING_NORMS`], where the measurement is recorded.
struct ZeroVarianceSite {
  dtype: String,
  eps: f64,
  channels: usize,
  zeros: usize,
}

impl ZeroVarianceSite {
  /// Stable one-line rendering — this is what [`LOAD_BEARING_NORMS`] pins, so
  /// a changed epsilon, a changed BAND, a changed width or a changed number of
  /// zero channels all fail the gate.
  fn render(&self) -> String {
    format!(
      "batch_norm/{} eps={:e} band={} zero={}/{}",
      self.dtype,
      self.eps,
      GuardBand::of(self.eps).label(),
      self.zeros,
      self.channels
    )
  }
}

/// An artifact where a surviving epsilon is the ONLY protection some channel
/// has — the second thing this file pins, beside [`KNOWN_DEFECTS`].
///
/// [`KNOWN_DEFECTS`] answers "is the constant representable in fp16".
/// This answers the question that one cannot: "and is there anything else
/// holding the site up". A guard can clear `2^-24` by three orders of magnitude
/// and still be the single point of failure for a channel whose variance is
/// zero, and the gate had no way to see that.
///
/// Pinned in BOTH directions, like [`KnownDefect::sites`] and like
/// `CHECKSUMLESS_KITS` in `tests/whisper/models_lock.rs`: a NEW artifact with
/// zero-variance channels fails as an unpinned finding, a pinned artifact whose
/// rows change fails, and a pinned artifact that is REPAIRED — its zero
/// channels gone — fails too, so the entry cannot outlive its cause.
struct LoadBearingNorm {
  /// Path relative to `Models/`.
  path: &'static str,
  /// Every zero-variance `batch_norm`, rendered by
  /// [`ZeroVarianceSite::render`], sorted. A multiset, like
  /// [`KnownDefect::sites`]: two same-signature layers are two sites.
  sites: &'static [&'static str],
  /// Constant-variance channels in the whole graph, and how many of them are
  /// exactly zero in fp16. The denominator is pinned too, so a re-conversion
  /// that changes the model's widths cannot leave the numerator looking
  /// unchanged.
  channels: usize,
  zero_channels: usize,
  /// What is measured, and what it would take to arm it.
  note: &'static str,
}

/// Every artifact in the tree whose epsilon is load-bearing. ONE, today.
///
/// The census that produced it swept all 37 staged graphs: 1 240 guard sites,
/// of which 4 are [`GuardBand::Normal`], 1 217 [`GuardBand::SubnormalOnly`] and
/// 19 [`GuardBand::Inert`] (those 19 are exactly [`KNOWN_DEFECTS`]). Of the
/// 285 `batch_norm` sites, every one has a constant `variance`, and every one
/// of those variances is bounded away from zero — whisper's 246 are all exactly
/// `1.0`, CED's 4 sit at 244–448 and CLAP's 2 at 564–1043 — except the LID
/// classifier's, below.
const LOAD_BEARING_NORMS: &[LoadBearingNorm] = &[LoadBearingNorm {
  path: "lid/SpeechBrainECAPAVoxLingua107.mlmodelc",
  sites: &[
    "batch_norm/fp16 eps=1.0013580322265625e-5 band=subnormal-only zero=1/1024",
    "batch_norm/fp16 eps=1.0013580322265625e-5 band=subnormal-only zero=144/6144",
    "batch_norm/fp16 eps=1.0013580322265625e-5 band=subnormal-only zero=4/1024",
    "batch_norm/fp16 eps=1.0013580322265625e-5 band=subnormal-only zero=4/3072",
    "batch_norm/fp16 eps=1.0013580322265625e-5 band=subnormal-only zero=6/1024",
  ],
  channels: 19_968,
  zero_channels: 159,
  note: "SpeechBrain's ECAPA carries PyTorch's BatchNorm1d default epsilon, 1e-5, rounded to \
           fp16 as 0x1.5p-17 = 1.0014e-5 — 168x fp16's smallest subnormal, but 0.164x its \
           smallest NORMAL, so it exists only as a subnormal. Across the 33 `batch_norm` sites \
           the artifact's own `running_var` blobs hold 19 968 channels, of which 159 are exactly \
           0.0 in fp16 (0.80 %), spread over five layers — 144 of them in `asp_bn`, the 6 144-wide \
           statistics-pooling norm feeding the embedding. Those 159 channels are guarded by the \
           epsilon and by nothing else. MEASURED, on this exact artifact (SHA-pinned by \
           tests/lid/common/mod.rs), by re-emitting the graph with the two epsilon constants \
           changed and running all four ComputeUnits arms on three inputs: at 0x0p+0 every arm \
           returns 107 of 107 NaN — the falsifier, red, so the guard is genuinely load-bearing; \
           at the SHIPPING 0x1.5p-17, and at 0x1p-24 (fp16's SMALLEST subnormal, the gate's own \
           floor), every arm returns 107 of 107 finite log-probabilities with the same top-1, and \
           0x1p-24 / 0x1p-23 / 0x1p-20 / 0x1p-15 / 0x1p-14 each give a DISTINCT output, so the \
           value is being consulted at full fp16 resolution rather than flushed. MLComputePlan \
           places 29 of the 33 `batch_norm` ops on the ANE under the default `All`. So the \
           subnormal is honoured here, and the reason is structural: `variance` and `epsilon` are \
           BOTH constants, so `variance + epsilon` is folded before any fp16 kernel runs — unlike \
           the `log` epsilon pinned for this same artifact in KNOWN_DEFECTS, whose guarded operand \
           is a runtime tensor and which the ANE was measured to flush. Pinned unrepaired because \
           the guard holds; the pin is what makes a re-conversion that drops, folds or re-rounds \
           this epsilon — or one that clamps `running_var` and removes the exposure — impossible \
           to land unseen.",
}];

/// Every path either register pins, so the sweep can require it to be present.
fn pinned_paths() -> BTreeSet<&'static str> {
  KNOWN_DEFECTS
    .iter()
    .map(|d| d.path)
    .chain(LOAD_BEARING_NORMS.iter().map(|d| d.path))
    .collect()
}

// ---------------------------------------------------------------------------
// Hermetic parser tests — no models, always run.
//
// These are the gate's can-it-fail proof, kept permanently executable:
// every snippet below is a VERBATIM excerpt of a real shipped `model.mil`.
// ---------------------------------------------------------------------------

/// `Models/alignkit/base960h_aligner.mlmodelc/model.mil`, lines 800-803.
const ALIGNKIT_LOG_SOFTMAX: &str = r#"
            tensor<int32, []> var_847 = const()[name = tensor<string, []>("op_847"), val = tensor<int32, []>(-1)];
            tensor<fp16, [1, 2999, 29]> var_849_softmax_cast_fp16 = softmax(axis = var_847, x = linear_73_cast_fp16)[name = tensor<string, []>("op_849_softmax_cast_fp16")];
            tensor<fp32, []> var_849_epsilon_0 = const()[name = tensor<string, []>("op_849_epsilon_0"), val = tensor<fp32, []>(0x1p-149)];
            tensor<fp16, [1, 2999, 29]> var_849_cast_fp16 = log(epsilon = var_849_epsilon_0, x = var_849_softmax_cast_fp16)[name = tensor<string, []>("op_849_cast_fp16")];
"#;

/// `speakerkit/pyannote_segmentation.mlmodelc/model.mil` lines 137-139 **as
/// shipped before the issue-#15 re-conversion** — the shipped graph now ends
/// `reduce_log_sum_exp` → `sub` and carries no `log` at all. Retained verbatim:
/// this is the exact pre-repair tail whose inert `log(epsilon = 0)` saturated
/// `segments` to −45440 on the ANE, and the parser must keep catching it if it
/// ever reappears from a re-conversion. It did NOT cause the 8-speaker
/// clip-09 collapse — the factorial attributes that to the int8 EMBEDDER
/// (swapping only the segmentation conversion left the collapse unchanged;
/// `tests/speaker/model_io.rs`, "Clip 09"). Conflating the two defects is the
/// attribution error the factorial exists to prevent.
const SPEAKERKIT_SEG_FP16: &str = r#"
            tensor<fp16, [1, 589, 7]> var_231_softmax_cast_fp16 = softmax(axis = var_230, x = linear_2_cast_fp16)[name = tensor<string, []>("op_231_softmax_cast_fp16")];
            tensor<fp16, []> var_231_epsilon_0_to_fp16 = const()[name = tensor<string, []>("op_231_epsilon_0_to_fp16"), val = tensor<fp16, []>(0x0p+0)];
            tensor<fp16, [1, 589, 7]> var_231_cast_fp16 = log(epsilon = var_231_epsilon_0_to_fp16, x = var_231_softmax_cast_fp16)[name = tensor<string, []>("op_231_cast_fp16")];
"#;

/// The pre-repair FluidInference `wespeaker.mlmodelc/model.mil`, lines
/// 4444-4450 — the exact text that shipped until issue #15. The adopted
/// FinDIT-Studio re-conversion raises this constant (and its `op_5807` twin)
/// from `0x1.5798eep-27` (1e-8) to `0x1p-24` and leaves every other byte of
/// the graph and all weights identical; the retired int8 siblings
/// (`wespeaker_v2`/`wespeaker_int8`) still carry it — see their
/// [`KNOWN_DEFECTS`] notes. Kept verbatim so the parser keeps catching this
/// pattern if a re-conversion ever reintroduces it.
const WESPEAKER_POOLING: &str = r#"
            tensor<fp32, []> var_5790 = const()[name = tensor<string, []>("op_5790"), val = tensor<fp32, []>(0x1.5798eep-27)];
            tensor<fp32, [3, 1]> v1 = add(x = var_5789, y = var_5790)[name = tensor<string, []>("v1")];
            tensor<fp32, [3, 2560]> mean = real_div(x = var_5794, y = v1)[name = tensor<string, []>("mean")];
"#;

/// `Models/whisperkit-coreml/openai_whisper-tiny/MelSpectrogram.mlmodelc/model.mil`,
/// lines 46-49. The one graph in the workspace that got this right — and
/// note it did so with an explicit `add`, not with the `log`'s own
/// epsilon, which is a literal `0x0p+0` here too.
const WHISPER_MEL: &str = r#"
            tensor<fp16, []> var_41_to_fp16 = const()[name = tensor<string, []>("op_41_to_fp16"), val = tensor<fp16, []>(0x1p-24)];
            tensor<fp16, [80, 3000]> mel_spec_cast_fp16 = add(x = mel_spec_1_cast_fp16, y = var_41_to_fp16)[name = tensor<string, []>("mel_spec_cast_fp16")];
            tensor<fp16, []> log_0_epsilon_0_to_fp16 = const()[name = tensor<string, []>("log_0_epsilon_0_to_fp16"), val = tensor<fp16, []>(0x0p+0)];
            tensor<fp16, [80, 3000]> log_0_cast_fp16 = log(epsilon = log_0_epsilon_0_to_fp16, x = mel_spec_cast_fp16)[name = tensor<string, []>("log_0_cast_fp16")];
"#;

/// The SECOND clean control (design spec §4 fp16 lens; vendor `vadkit`).
/// `Models/vadkit/silero-vad-unified-256ms-v6.2.1.mlmodelc/model.mil`,
/// lines 120-127 — the STFT power-to-magnitude of the FluidInference unified
/// Silero VAD graph. `sqrt(real^2 + imag^2 + 0x1p-24)`: the same discipline as
/// whisper's mel above, an explicit `add(x, 0x1p-24)` at exactly fp16's
/// smallest subnormal, this time feeding a `sqrt` rather than a `log`. Silero
/// VAD is why `vadkit` joins the sweep: the graph is `Mixed(Float16, Float32)`
/// and repeats this guarded `sqrt` at all eight STFT sites, so the sweep must
/// prove they SURVIVE (they do) rather than assume it. The graph carries no
/// `log`, `rsqrt`, `real_div` or norm anywhere, and its output is a noisy-OR of
/// sigmoids bounded in `[0, 1]`, so there is no vanishing-guard site to pin —
/// `vadkit` is a clean vendor with NO `KNOWN_DEFECTS` entry, exactly like
/// whisper-mel. Pinning this excerpt keeps the checker's "a `sqrt` floored by a
/// surviving `add` is clean" reading from rotting into a false finding (or a
/// missed one, if the add's constant were ever misread).
const VADKIT_STFT_SQRT: &str = r#"
            tensor<fp16, []> var_201_promoted_to_fp16 = const()[name = tensor<string, []>("op_201_promoted_to_fp16"), val = tensor<fp16, []>(0x1p+1)];
            tensor<fp16, [1, 129, 4]> var_227_cast_fp16 = pow(x = var_222_cast_fp16, y = var_201_promoted_to_fp16)[name = tensor<string, []>("op_227_cast_fp16")];
            tensor<fp16, []> var_201_promoted_1_to_fp16 = const()[name = tensor<string, []>("op_201_promoted_1_to_fp16"), val = tensor<fp16, []>(0x1p+1)];
            tensor<fp16, [1, 129, 4]> var_228_cast_fp16 = pow(x = var_225_cast_fp16, y = var_201_promoted_1_to_fp16)[name = tensor<string, []>("op_228_cast_fp16")];
            tensor<fp16, [1, 129, 4]> var_229_cast_fp16 = add(x = var_227_cast_fp16, y = var_228_cast_fp16)[name = tensor<string, []>("op_229_cast_fp16")];
            tensor<fp16, []> var_230_to_fp16 = const()[name = tensor<string, []>("op_230_to_fp16"), val = tensor<fp16, []>(0x1p-24)];
            tensor<fp16, [1, 129, 4]> var_231_cast_fp16 = add(x = var_229_cast_fp16, y = var_230_to_fp16)[name = tensor<string, []>("op_231_cast_fp16")];
            tensor<fp16, [1, 129, 4]> input_3_cast_fp16 = sqrt(x = var_231_cast_fp16)[name = tensor<string, []>("input_3_cast_fp16")];
"#;

/// clapkit's converted CLAP graphs are CLEAN — the second clean control beside
/// whisper's mel. Verbatim excerpts of the real shipped graphs:
/// `Models/clapkit/clap_audio.mlmodelc/model.mil` lines 12/15 (the input
/// `batch_norm`, `epsilon = 0x1.5p-17 ≈ 1.001e-5`) and
/// `Models/clapkit/clap_text.mlmodelc/model.mil` lines 46/47 (the embeddings
/// `layer_norm`, `epsilon = 0x1p-24`, RoBERTa's `1e-12` source eps auto-raised by
/// the fp16 conversion to exactly the audit floor). The audio graph carries 29
/// more `layer_norm`s at the same `0x1.5p-17` and the text graph 24 more at
/// `0x1p-24`; both eps tiers clear `2^-24` (the text tier inclusively), and
/// neither graph has any `log`/`sqrt`/`rsqrt`/`real_div` — L2-norm is kept OUT of
/// the graphs, so the rsqrt-guard class is absent by construction. This snippet
/// is the models-independent proof that clapkit's conversion guard shape audits
/// clean; the live sweep covers every site when `Models/clapkit/` is present.
const CLAPKIT_NORMS_CLEAN: &str = r#"
            tensor<fp16, []> var_7_to_fp16 = const()[name = tensor<string, []>("op_7_to_fp16"), val = tensor<fp16, []>(0x1.5p-17)];
            tensor<fp16, [1, 64, 1001, 1]> normalized_input_features_cast_fp16 = batch_norm(beta = audio_model_audio_encoder_batch_norm_bias_to_fp16, epsilon = var_7_to_fp16, gamma = audio_model_audio_encoder_batch_norm_weight_to_fp16, mean = audio_model_audio_encoder_batch_norm_running_mean_to_fp16, variance = audio_model_audio_encoder_batch_norm_running_var_to_fp16, x = input_1_cast_fp16)[name = tensor<string, []>("normalized_input_features_cast_fp16")];
            tensor<fp16, []> var_23_to_fp16 = const()[name = tensor<string, []>("op_23_to_fp16"), val = tensor<fp16, []>(0x1p-24)];
            tensor<fp16, [1, 512, 768]> input_5_cast_fp16 = layer_norm(axes = input_5_axes_0, beta = text_model_embeddings_LayerNorm_bias_to_fp16, epsilon = var_23_to_fp16, gamma = text_model_embeddings_LayerNorm_weight_to_fp16, x = input_3_cast_fp16)[name = tensor<string, []>("input_5_cast_fp16")];
"#;

/// The clapkit text `layer_norm` with its epsilon halved to `0x1p-25` (exactly
/// half the fp16 floor) — the mutation a re-conversion would introduce if it
/// dropped the eps below the floor. It MUST be caught as a vanishing `norm`
/// finding, proving the clean control above is not vacuously green.
const CLAPKIT_NORM_VANISHING_MUTANT: &str = r#"
            tensor<fp16, []> var_23_to_fp16 = const()[name = tensor<string, []>("op_23_to_fp16"), val = tensor<fp16, []>(0x1p-25)];
            tensor<fp16, [1, 512, 768]> input_5_cast_fp16 = layer_norm(axes = input_5_axes_0, beta = text_model_embeddings_LayerNorm_bias_to_fp16, epsilon = var_23_to_fp16, gamma = text_model_embeddings_LayerNorm_weight_to_fp16, x = input_3_cast_fp16)[name = tensor<string, []>("input_5_cast_fp16")];
"#;

/// granite's converted ModernBERT graph is CLEAN — the third norm-only clean
/// control beside clapkit's. Verbatim excerpts of the real shipped graph
/// `Models/embedkit-granite/granite-97m-multilingual-r2/granite_97m_512.mlmodelc/model.mil`
/// lines 17-18 (the embeddings `layer_norm`, `epsilon = 0x1.5p-17 ≈ 1.001e-5`)
/// and lines 106-107 (a transformer-layer `layer_norm` at the same eps). The
/// graph carries 25 `layer_norm`s, ALL at `0x1.5p-17` (well above the fp16 floor
/// `2^-24`), and NO `log`/`sqrt`/`rsqrt`/`real_div` anywhere — L2-norm is kept
/// OUT of the graph (applied in Rust), so the rsqrt-guard class is absent by
/// construction, exactly like clapkit. This snippet is the models-independent
/// proof that granite's conversion guard shape audits clean; the live sweep
/// covers every site when `Models/embedkit-granite/` is present.
const GRANITE_NORMS_CLEAN: &str = r#"
            tensor<fp16, []> var_42_to_fp16 = const()[name = tensor<string, []>("op_42_to_fp16"), val = tensor<fp16, []>(0x1.5p-17)];
            tensor<fp16, [1, 512, 384]> input_5_cast_fp16 = layer_norm(axes = input_5_axes_0, epsilon = var_42_to_fp16, gamma = embeddings_norm_weight_to_fp16, x = input_3_cast_fp16)[name = tensor<string, []>("input_5_cast_fp16")];
            tensor<fp16, []> var_95_to_fp16 = const()[name = tensor<string, []>("op_95_to_fp16"), val = tensor<fp16, []>(0x1.5p-17)];
            tensor<fp16, [1, 512, 384]> input_15_cast_fp16 = layer_norm(axes = input_15_axes_0, epsilon = var_95_to_fp16, gamma = layers_0_mlp_norm_weight_to_fp16, x = input_13_cast_fp16)[name = tensor<string, []>("input_15_cast_fp16")];
"#;

/// The granite embeddings `layer_norm` with its epsilon halved to `0x1p-25`
/// (exactly half the fp16 floor) — the mutation a re-conversion would introduce
/// if it dropped the eps below the floor. It MUST be caught as a vanishing `norm`
/// finding, proving the clean control above is not vacuously green.
const GRANITE_NORM_VANISHING_MUTANT: &str = r#"
            tensor<fp16, []> var_42_to_fp16 = const()[name = tensor<string, []>("op_42_to_fp16"), val = tensor<fp16, []>(0x1p-25)];
            tensor<fp16, [1, 512, 384]> input_5_cast_fp16 = layer_norm(axes = input_5_axes_0, epsilon = var_42_to_fp16, gamma = embeddings_norm_weight_to_fp16, x = input_3_cast_fp16)[name = tensor<string, []>("input_5_cast_fp16")];
"#;

/// siglip's converted SigLIP2 graphs are CLEAN — the fourth norm-only control
/// beside clapkit's and granite's. Verbatim excerpts of the real shipped graphs
/// `Models/siglip2-naflex/…/siglip2_vision_512.mlmodelc/model.mil` (an encoder
/// `layer_norm`, `epsilon = 0x1.1p-20 ≈ 1.013e-6`, source eps 1e-6 rounded to
/// fp16) and `…/siglip2_text_64.mlmodelc/model.mil` (the first text encoder
/// `layer_norm` at the same eps). The vision graph carries 26 `layer_norm`s and
/// the text graph 25, ALL at `0x1.1p-20` — ~17× above the fp16 floor `2^-24` — and
/// NEITHER graph has any `log`/`sqrt`/`rsqrt`/`real_div` (L2-norm is applied in
/// Rust, so the rsqrt-guard class is absent by construction, exactly like clapkit
/// and granite). This snippet is the models-independent proof that siglip's
/// conversion guard shape audits clean; the live sweep covers every site when
/// `Models/siglip2-naflex/` is present.
const SIGLIP_NORMS_CLEAN: &str = r#"
            tensor<fp16, []> var_63_to_fp16 = const()[name = tensor<string, []>("op_63_to_fp16"), val = tensor<fp16, []>(0x1.1p-20)];
            tensor<fp16, [1, 512, 768]> input_7_cast_fp16 = layer_norm(axes = input_7_axes_0, beta = encoder_layers_0_layer_norm2_bias_to_fp16, epsilon = var_63_to_fp16, gamma = encoder_layers_0_layer_norm2_weight_to_fp16, x = input_5_cast_fp16)[name = tensor<string, []>("input_7_cast_fp16")];
            tensor<fp16, []> var_11_to_fp16 = const()[name = tensor<string, []>("op_11_to_fp16"), val = tensor<fp16, []>(0x1.1p-20)];
            tensor<fp16, [1, 64, 768]> hidden_states_1_cast_fp16 = layer_norm(axes = hidden_states_1_axes_0, beta = text_model_encoder_layers_0_layer_norm1_bias_to_fp16, epsilon = var_11_to_fp16, gamma = text_model_encoder_layers_0_layer_norm1_weight_to_fp16, x = input_3_cast_fp16)[name = tensor<string, []>("hidden_states_1_cast_fp16")];
"#;

/// The siglip text `layer_norm` with its epsilon halved to `0x1p-25` (exactly half
/// the fp16 floor) — the mutation a re-conversion would introduce if it dropped the
/// eps below the floor. It MUST be caught as a vanishing `norm` finding, proving
/// the clean control above is not vacuously green.
const SIGLIP_NORM_VANISHING_MUTANT: &str = r#"
            tensor<fp16, []> var_11_to_fp16 = const()[name = tensor<string, []>("op_11_to_fp16"), val = tensor<fp16, []>(0x1p-25)];
            tensor<fp16, [1, 64, 768]> hidden_states_1_cast_fp16 = layer_norm(axes = hidden_states_1_axes_0, beta = text_model_encoder_layers_0_layer_norm1_bias_to_fp16, epsilon = var_11_to_fp16, gamma = text_model_encoder_layers_0_layer_norm1_weight_to_fp16, x = input_3_cast_fp16)[name = tensor<string, []>("hidden_states_1_cast_fp16")];
"#;

/// Two INDEPENDENT sub-threshold guard constants on ONE `log` site: an
/// `add(x, 0x1p-25)` floor feeding a `log(eps = 0x1p-25)`. Each constant is
/// `2^-25` — exactly HALF fp16's smallest subnormal — so each rounds to zero in
/// fp16 on its own and the guard is inert. Their SUM is exactly `2^-24`, at the
/// floor: an `effective = eps + floor` rule marks this "surviving" and masks a
/// real vanishing guard, even though nothing proves CoreML folds the two
/// materialized constants into one before lowering. The MAX rule — each constant
/// must clear the floor on its own — correctly flags it. `WHISPER_MEL` with BOTH
/// its constants halved (and thus the exact boundary the summing rule got wrong).
const TWO_HALF_SUBNORMAL_GUARDS: &str = r#"
            tensor<fp16, []> half_add_c = const()[name = tensor<string, []>("half_add_c"), val = tensor<fp16, []>(0x1p-25)];
            tensor<fp16, [80, 3000]> half_guarded = add(x = feat_in, y = half_add_c)[name = tensor<string, []>("half_guarded")];
            tensor<fp16, []> half_log_eps = const()[name = tensor<string, []>("half_log_eps"), val = tensor<fp16, []>(0x1p-25)];
            tensor<fp16, [80, 3000]> half_log = log(epsilon = half_log_eps, x = half_guarded)[name = tensor<string, []>("half_log")];
"#;

/// Two INDEPENDENT decomposed-`log_softmax` sites, distinct vars but an
/// identical vanishing signature — the multiset shape finding 5 is about, and
/// the exact one the live wespeaker_v2/PLDA graphs carry (3 and 2
/// same-signature sites; the shipping fp32 wespeaker's three were repaired,
/// issue #15). Both render to `log/fp16 guard=softmax->log eff=0e0`, so a `dedup` or
/// set would collapse them into one and hide the second defect under a green
/// pin. Synthesized from two copies of the real `SPEAKERKIT_SEG_FP16` shape.
const TWO_SITE_LOG_SOFTMAX: &str = r#"
            tensor<fp16, [1, 589, 7]> a_softmax_cast_fp16 = softmax(axis = a_axis, x = a_linear)[name = tensor<string, []>("a_softmax")];
            tensor<fp16, []> a_epsilon = const()[name = tensor<string, []>("a_epsilon"), val = tensor<fp16, []>(0x0p+0)];
            tensor<fp16, [1, 589, 7]> a_cast_fp16 = log(epsilon = a_epsilon, x = a_softmax_cast_fp16)[name = tensor<string, []>("a_log")];
            tensor<fp16, [1, 589, 7]> b_softmax_cast_fp16 = softmax(axis = b_axis, x = b_linear)[name = tensor<string, []>("b_softmax")];
            tensor<fp16, []> b_epsilon = const()[name = tensor<string, []>("b_epsilon"), val = tensor<fp16, []>(0x0p+0)];
            tensor<fp16, [1, 589, 7]> b_cast_fp16 = log(epsilon = b_epsilon, x = b_softmax_cast_fp16)[name = tensor<string, []>("b_log")];
"#;

/// One clean, surviving guard (whisper's mel `add(0x1p-24) -> log`) beside a
/// second `log` emitted in syntax this reader cannot parse — its argument
/// list left unbalanced, a stand-in for the unhandled shapes a new coremltools
/// re-conversion can produce. This is the partial-parse trap: the recognized
/// guard alone must NOT let the sweep report success while the unreadable
/// vanishing guard silently disappears. The audit is required to surface the
/// second statement as unresolved, not drop it.
const VALID_GUARD_PLUS_UNREADABLE_GUARD: &str = r#"
            tensor<fp16, []> ok_eps = const()[name = tensor<string, []>("ok_eps"), val = tensor<fp16, []>(0x1p-24)];
            tensor<fp16, [80, 3000]> ok_mel = add(x = ok_mel_1, y = ok_eps)[name = tensor<string, []>("ok_mel")];
            tensor<fp16, []> ok_log_eps = const()[name = tensor<string, []>("ok_log_eps"), val = tensor<fp16, []>(0x0p+0)];
            tensor<fp16, [80, 3000]> ok_log = log(epsilon = ok_log_eps, x = ok_mel)[name = tensor<string, []>("ok_log")];
            tensor<fp16, [1, 589, 7]> bad_softmax = softmax(axis = bad_axis, x = bad_linear)[name = tensor<string, []>("bad_softmax")];
            tensor<fp16, [1, 589, 7]> bad_log = log(epsilon = bad_eps, x = bad_softmax [name = tensor<string, []>("bad_log")];
"#;

/// A `batch_norm` whose `epsilon` names a var that is never defined as a
/// scalar const — the guard is present but unreadable. The old
/// `eps_kwarg.map(...)` dropped such a site silently (the `.map` short-circuits
/// on `None`); completeness requires it to FAIL the audit with the statement
/// quoted, exactly as a malformed parse does.
const NORM_WITH_UNRESOLVABLE_EPSILON: &str = r#"
            tensor<fp16, [1, 384, 1, 1500]> n_out = batch_norm(beta = n_beta, epsilon = n_eps_missing, gamma = n_gamma, mean = n_mean, variance = n_var, x = n_in)[name = tensor<string, []>("n_out")];
"#;

/// A pooling-divisor guard emitted as `const → cast → add → real_div` — the
/// shape a coremltools re-conversion produces when it casts the fp32 epsilon
/// literal to fp16 before adding it to the count. Every statement here parses,
/// so NOTHING is unresolved at parse time; the `1e-8` floor is reachable ONLY
/// by following the `cast` from the `add`'s operand to the const. Modeled on
/// the real `WESPEAKER_POOLING` `count + 1e-8` guard with a `cast` interposed
/// on the constant. Before the audit followed constants through `cast`,
/// `floor(add)` missed the cast-wrapped const, the `real_div` `.map`-dropped to
/// nothing, and this vanishing guard produced NEITHER a finding NOR an
/// unresolved hole — it simply disappeared while any other recognized guard
/// kept the sweep GREEN.
const CAST_WRAPPED_POOLING_DIVISOR: &str = r#"
            tensor<fp32, []> eps_fp32 = const()[name = tensor<string, []>("eps_fp32"), val = tensor<fp32, []>(0x1.5798eep-27)];
            tensor<fp16, []> eps_fp16 = cast(dtype = fp16, x = eps_fp32)[name = tensor<string, []>("eps_fp16")];
            tensor<fp16, [3, 1]> v1 = add(x = count_cast_fp16, y = eps_fp16)[name = tensor<string, []>("v1")];
            tensor<fp16, [3, 2560]> mean = real_div(x = numer_cast_fp16, y = v1)[name = tensor<string, []>("mean")];
"#;

/// The same pooling-divisor shape, but the epsilon is DYNAMIC — computed (a
/// `mul`), not a constant — so no `cast` chain reaches a literal. The `add`
/// still structurally guards the divisor (`count + <something>`), so its
/// unresolvable floor is a HOLE, not "no claim": the reader can see a guard it
/// cannot read, and must surface the `real_div` as unresolved rather than
/// `.map`-drop it into a silent pass. Contrast a genuinely dynamic divisor
/// produced by a NON-guard op — the shipped embedders' `x / real_div(..)` and
/// `sqrt(real_div(..))` std sites — which stays "no claim" and never lands
/// here.
const DYNAMIC_UNRESOLVABLE_DIVISOR: &str = r#"
            tensor<fp16, [3, 1]> dyn_eps = mul(x = a_cast_fp16, y = b_cast_fp16)[name = tensor<string, []>("dyn_eps")];
            tensor<fp16, [3, 1]> v1 = add(x = count_cast_fp16, y = dyn_eps)[name = tensor<string, []>("v1")];
            tensor<fp16, [3, 2560]> mean = real_div(x = numer_cast_fp16, y = v1)[name = tensor<string, []>("mean")];
"#;

/// The same dynamically-unresolvable `add`-guarded divisor, but with a `cast`
/// interposed before the `real_div` (`mul(dynamic) → add → cast → real_div`),
/// beside one clean, surviving guard (whisper's mel `add(0x1p-24) → log`). Every
/// statement parses, so nothing is unresolved at parse time; the `add`
/// structurally guards the divisor but its epsilon is a `mul` (dynamic), so no
/// floor resolves. `Graph::floor` recursively unwraps the `cast` to reach the
/// `add` — so the unresolved-detection MUST unwrap it too, or the site produces
/// NEITHER a finding NOR a hole and simply disappears while the clean guard
/// keeps the sweep green. This is the exact hole an `unreadable_floor_guard`
/// that inspects only the divisor's IMMEDIATE producer (the `cast`, whose op is
/// not a guard op) leaves open.
const CAST_WRAPPED_DYNAMIC_DIVISOR: &str = r#"
            tensor<fp16, []> ok_eps = const()[name = tensor<string, []>("ok_eps"), val = tensor<fp16, []>(0x1p-24)];
            tensor<fp16, [80, 3000]> ok_mel = add(x = ok_mel_1, y = ok_eps)[name = tensor<string, []>("ok_mel")];
            tensor<fp16, []> ok_log_eps = const()[name = tensor<string, []>("ok_log_eps"), val = tensor<fp16, []>(0x0p+0)];
            tensor<fp16, [80, 3000]> ok_log = log(epsilon = ok_log_eps, x = ok_mel)[name = tensor<string, []>("ok_log")];
            tensor<fp16, [3, 1]> dyn_eps = mul(x = a_cast_fp16, y = b_cast_fp16)[name = tensor<string, []>("dyn_eps")];
            tensor<fp16, [3, 1]> v1 = add(x = count_cast_fp16, y = dyn_eps)[name = tensor<string, []>("v1")];
            tensor<fp16, [3, 1]> v1_fp16 = cast(dtype = fp16, x = v1)[name = tensor<string, []>("v1_fp16")];
            tensor<fp16, [3, 2560]> mean = real_div(x = numer_cast_fp16, y = v1_fp16)[name = tensor<string, []>("mean")];
"#;

/// F2 (recognized vocabulary): a clean, surviving `log` guard (whisper's mel
/// `add(0x1p-24) → log`) beside an `l2_norm` whose `epsilon` vanishes in fp16.
/// `l2_norm(x, epsilon)` computes `x / sqrt(sum(x^2) + epsilon)` — the epsilon is
/// the whole divide guard, so `1e-8` (0.168× the fp16 floor) rounds to zero and
/// the norm can divide by zero, exactly like the batch/layer/instance norms.
/// Before `l2_norm` was in the vocabulary it fell to the `_ => None` wildcard and
/// produced NEITHER a finding NOR an unresolved hole, so a re-conversion adding a
/// safe `log` plus a vanishing `l2_norm` swept GREEN. It must now surface as a
/// vanishing FINDING while the `log` beside it still survives.
const L2_NORM_VANISHING: &str = r#"
            tensor<fp16, []> ok_eps = const()[name = tensor<string, []>("ok_eps"), val = tensor<fp16, []>(0x1p-24)];
            tensor<fp16, [80, 3000]> ok_mel = add(x = ok_mel_1, y = ok_eps)[name = tensor<string, []>("ok_mel")];
            tensor<fp16, []> ok_log_eps = const()[name = tensor<string, []>("ok_log_eps"), val = tensor<fp16, []>(0x0p+0)];
            tensor<fp16, [80, 3000]> ok_log = log(epsilon = ok_log_eps, x = ok_mel)[name = tensor<string, []>("ok_log")];
            tensor<fp32, []> l2_eps = const()[name = tensor<string, []>("l2_eps"), val = tensor<fp32, []>(0x1.5798eep-27)];
            tensor<fp16, [1, 256]> l2_out = l2_norm(epsilon = l2_eps, x = embed_cast_fp16)[name = tensor<string, []>("l2_out")];
"#;

/// F2 (the CLASS, not the op): an op this reader does NOT recognize that still
/// carries an `epsilon` kwarg. Its exact semantics are unmodeled, so the
/// vocabulary-independent catch-all must surface it as UNRESOLVED — never drop it
/// through the `_ => None` wildcard — so a brand-new epsilon-bearing op from a
/// future coremltools (or a known one this reader was never taught) cannot sweep
/// green beside a recognized guard. The op-independent twin of the `l2_norm` fix.
const EPSILON_BEARING_UNKNOWN_OP: &str = r#"
            tensor<fp16, []> mystery_eps = const()[name = tensor<string, []>("mystery_eps"), val = tensor<fp16, []>(0x1p-30)];
            tensor<fp16, [1, 256]> mystery_out = some_future_norm(epsilon = mystery_eps, x = in_cast_fp16)[name = tensor<string, []>("mystery_out")];
"#;

/// The coremltools-9 BARE-SCALAR dialect, and the vendor that brought it.
/// Verbatim excerpts of the real shipped
/// `Models/lid/SpeechBrainECAPAVoxLingua107.mlmodelc/model.mil`
/// (`program(1.3)`, coremltools 9.0): lines 32-33 (a `batch_norm` whose epsilon
/// const is declared `fp16 …` rather than `tensor<fp16, []> …`), 668-671 (the
/// attentive-stat `clip(0x1p-24) -> sqrt`, whose clip floor is TWO bare scalars),
/// and 771-773 (the classifier tail's decomposed `softmax -> log`).
///
/// Every epsilon in this graph is a bare scalar, so a `tensor<`-only reader
/// resolves NONE of them: the whole file audited to zero guard sites and 36
/// unresolved statements. All three guard shapes are kept together here because
/// the dialect is orthogonal to the shape — the same file writes tensors the old
/// way and scalars the new way — so the fixture proves the reader reads BOTH
/// spellings in one graph rather than having merely swapped one for the other.
const LID_ECAPA_SCALAR_DIALECT: &str = r#"
            fp16 var_23_to_fp16 = const()[name = string("op_23_to_fp16"), val = fp16(0x1.5p-17)];
            tensor<fp16, [1, 1024, ?]> input_7_cast_fp16 = batch_norm(beta = embedding_model_blocks_0_norm_norm_bias_to_fp16, epsilon = var_23_to_fp16, gamma = embedding_model_blocks_0_norm_norm_weight_to_fp16, mean = embedding_model_blocks_0_norm_norm_running_mean_to_fp16, variance = embedding_model_blocks_0_norm_norm_running_var_to_fp16, x = x_3_cast_fp16)[name = string("input_7_cast_fp16")];
            fp16 var_13_to_fp16 = const()[name = string("op_13_to_fp16"), val = fp16(0x1p-24)];
            fp16 const_37_to_fp16 = const()[name = string("const_37_to_fp16"), val = fp16(inf)];
            tensor<fp16, [?, 3072]> clip_0_cast_fp16 = clip(alpha = var_13_to_fp16, beta = const_37_to_fp16, x = var_835_cast_fp16)[name = string("clip_0_cast_fp16")];
            tensor<fp16, [?, 3072]> std_1_cast_fp16 = sqrt(x = clip_0_cast_fp16)[name = string("std_1_cast_fp16")];
            tensor<fp16, [1, 107]> x_act_softmax_cast_fp16 = softmax(axis = var_914, x = input_cast_fp16)[name = string("x_act_softmax_cast_fp16")];
            fp32 x_act_epsilon_0 = const()[name = string("x_act_epsilon_0"), val = fp32(0x1p-149)];
            tensor<fp16, [1, 107]> x_act_cast_fp16 = log(epsilon = x_act_epsilon_0, x = x_act_softmax_cast_fp16)[name = string("x_act_cast_fp16")];
"#;

/// The bare-scalar dialect with its `batch_norm` epsilon dropped from
/// `0x1.5p-17` to `0x1p-25` — exactly half the fp16 floor. It MUST be caught as
/// a vanishing `norm` finding, which is what proves the clean sites of
/// [`LID_ECAPA_SCALAR_DIALECT`] are clean because the reader RESOLVED a bare
/// scalar const, not because it silently failed to read one. (A merely-unread
/// epsilon would surface as an unresolved hole, which [`vanishing`] panics on;
/// this pins the value path too.)
const LID_SCALAR_NORM_VANISHING_MUTANT: &str = r#"
            fp16 var_23_to_fp16 = const()[name = string("op_23_to_fp16"), val = fp16(0x1p-25)];
            tensor<fp16, [1, 1024, ?]> input_7_cast_fp16 = batch_norm(beta = embedding_model_blocks_0_norm_norm_bias_to_fp16, epsilon = var_23_to_fp16, gamma = embedding_model_blocks_0_norm_norm_weight_to_fp16, mean = embedding_model_blocks_0_norm_norm_running_mean_to_fp16, variance = embedding_model_blocks_0_norm_norm_running_var_to_fp16, x = x_3_cast_fp16)[name = string("input_7_cast_fp16")];
"#;

/// Every non-statement line of the same graph, verbatim: the `program`/`buildInfo`
/// header, the brace, the `func` signature, and the block's return. None is a
/// declaration, and the bare-scalar arm must not decide otherwise — it is the arm
/// that most easily over-fires, since "a token, a space, the rest" describes most
/// lines in the file. (`[buildInfo …]` is elided in the middle only for width; the
/// leading token, which is all the reader looks at, is verbatim.)
const LID_NON_STATEMENT_LINES: &[&str] = &[
  "program(1.3)",
  r#"[buildInfo = dict<string, string>({{"coremltools-version", "9.0"}})]"#,
  "{",
  r#"    func main<ios18>(tensor<fp32, [1, ?, 60]> mel_features) [FlexibleShapeInformation = tuple<tuple<string, dict<string, tensor<int32, [?]>>>, tuple<string, dict<string, list<tensor<int32, [2]>, ?>>>>((("DefaultShapes", {{"mel_features", [1, 301, 60]}}), ("RangeDims", {{"mel_features", [[1, 1], [10, 3001], [60, 60]]}})))] {"#,
  "} -> (log_probabilities);",
  "}",
];

/// `Models/lid/SpeechBrainECAPAVoxLingua107.mlmodelc/model.mil`, lines 28-29 and
/// 32-33 — the first of its 33 `batch_norm` sites, with the two constants the
/// census reads: the `variance` operand's `BLOBFILE` reference and the shared
/// epsilon. Verbatim, offsets included, so the hermetic tests exercise the same
/// blob lookup the real sweep performs.
const LID_BATCH_NORM: &str = r#"
            tensor<fp16, [1024]> embedding_model_blocks_0_norm_norm_running_mean_to_fp16 = const()[name = string("embedding_model_blocks_0_norm_norm_running_mean_to_fp16"), val = tensor<fp16, [1024]>(BLOBFILE(path = string("@model_path/weights/weight.bin"), offset = uint64(616640)))];
            tensor<fp16, [1024]> embedding_model_blocks_0_norm_norm_running_var_to_fp16 = const()[name = string("embedding_model_blocks_0_norm_norm_running_var_to_fp16"), val = tensor<fp16, [1024]>(BLOBFILE(path = string("@model_path/weights/weight.bin"), offset = uint64(618752)))];
            fp16 var_23_to_fp16 = const()[name = string("op_23_to_fp16"), val = fp16(0x1.5p-17)];
            tensor<fp16, [1, 1024, ?]> input_7_cast_fp16 = batch_norm(beta = embedding_model_blocks_0_norm_norm_bias_to_fp16, epsilon = var_23_to_fp16, gamma = embedding_model_blocks_0_norm_norm_weight_to_fp16, mean = embedding_model_blocks_0_norm_norm_running_mean_to_fp16, variance = embedding_model_blocks_0_norm_norm_running_var_to_fp16, x = x_3_cast_fp16)[name = string("input_7_cast_fp16")];
"#;

/// The blob-metadata offset [`LID_BATCH_NORM`]'s `variance` const names.
const LID_VARIANCE_BLOB_OFFSET: u64 = 618_752;

/// The vanishing guard sites of an already-audited graph, rendered and sorted
/// as a **multiset** — duplicates PRESERVED. Two sites with the same signature
/// are two defects, not one: a `dedup`/set here would let a reconversion that
/// adds a second same-signature vanishing site collapse into the first and keep
/// a green pin while the blast radius grows (finding 5). The live tree already
/// carries this — wespeaker's attentive-stat pooling has THREE identical
/// `real_div` guards and PLDA/PldaRho two `sqrt` each — which is exactly why the
/// dedup was hiding real multiplicity.
///
/// Both the sweep and the hermetic parser tests route through here, so the
/// multiset property is exercised by the always-run tests, not merely asserted
/// against live models.
fn vanishing_sites(findings: &[Finding]) -> Vec<String> {
  let mut sites: Vec<String> = findings
    .iter()
    .filter(|f| !f.survives_fp16())
    .map(Finding::render)
    .collect();
  sites.sort();
  sites
}

/// The vanishing guard sites of a MIL program (parse + audit + multiset render).
/// Only `log`/`sqrt`/`rsqrt`/`real_div`/norm sites, not every op.
///
/// Panics if the audit left any guard-looking statement unresolved, so every
/// hermetic snippet that routes through here doubles as proof it parsed
/// completely — a dropped guard can never hide inside a merely-empty vanishing
/// list.
fn vanishing(mil: &str) -> Vec<String> {
  let audit = parse_mil(mil).audit();
  assert!(
    audit.unresolved.is_empty(),
    "audit left guard-looking statement(s) unresolved: {:?}",
    audit.unresolved
  );
  vanishing_sites(&audit.findings)
}

#[test]
fn threshold_is_fp16s_smallest_subnormal() {
  assert_eq!(
    FP16_MIN_SUBNORMAL,
    2.0_f64.powi(-24),
    "the gate's threshold must be exactly 2^-24"
  );
  assert_eq!(FP16_MIN_NORMAL, 2.0_f64.powi(-14));

  // Corroborate the threshold against a real fp16 rounding, so the
  // constant above cannot drift away from the format it claims to model.
  assert_eq!(
    half::f16::from_f64(2.0_f64.powi(-149)),
    half::f16::from_f64(0.0),
    "0x1p-149 must round to zero in fp16"
  );
  assert_eq!(half::f16::from_f64(1e-8), half::f16::from_f64(0.0));
  assert_eq!(half::f16::from_f64(1e-12), half::f16::from_f64(0.0));
  assert!(
    half::f16::from_f64(FP16_MIN_SUBNORMAL) > half::f16::from_f64(0.0),
    "2^-24 must be representable in fp16"
  );
}

#[test]
fn hex_float_literals_parse_exactly() {
  assert_eq!(parse_hex_float("0x1p-149"), Some(2.0_f64.powi(-149)));
  assert_eq!(parse_hex_float("0x0p+0"), Some(0.0));
  assert_eq!(parse_hex_float("0x1p-24"), Some(FP16_MIN_SUBNORMAL));
  // 1e-8 and 1e-12, as coremltools actually spells them.
  let eight = parse_hex_float("0x1.5798eep-27").expect("parses");
  assert!(
    (eight - 1e-8).abs() < 1e-15,
    "0x1.5798eep-27 ~= 1e-8, got {eight:e}"
  );
  let twelve = parse_hex_float("0x1.197998p-40").expect("parses");
  assert!(
    (twelve - 1e-12).abs() < 1e-19,
    "0x1.197998p-40 ~= 1e-12, got {twelve:e}"
  );
}

/// The gate must FAIL on the real alignkit graph. If this ever passes, the
/// checker has stopped checking.
#[test]
fn detects_the_alignkit_log_softmax_defect() {
  assert_eq!(
    vanishing(ALIGNKIT_LOG_SOFTMAX),
    ["log/fp16 guard=softmax->log eff=1.401298464324817e-45"],
    "alignkit's fp16 log(eps = 0x1p-149) must be caught"
  );

  let graph = parse_mil(ALIGNKIT_LOG_SOFTMAX);
  let audit = graph.audit();
  assert!(
    audit.unresolved.is_empty(),
    "the real alignkit excerpt must parse completely: {:?}",
    audit.unresolved
  );
  let log = audit
    .findings
    .iter()
    .find(|f| f.op == "log")
    .expect("a log site");
  assert!(!log.survives_fp16());
  assert!(
    log.is_decomposed_log_softmax(),
    "and it must be recognized as a decomposed log_softmax"
  );
}

/// The other face of the same defect: a divisor guard, not a log epsilon.
#[test]
fn detects_the_wespeaker_pooling_defect() {
  assert_eq!(
    vanishing(WESPEAKER_POOLING),
    ["real_div/fp32 guard=denom:add(+9.99999993922529e-9) eff=9.99999993922529e-9"],
    "wespeaker's `count + 1e-8` divisor guard must be caught even though \
     the graph declares fp32 — the ANE demotes it to fp16 regardless"
  );
}

/// And the already-folded-to-zero face.
#[test]
fn detects_the_speakerkit_segmentation_defect() {
  assert_eq!(
    vanishing(SPEAKERKIT_SEG_FP16),
    ["log/fp16 guard=softmax->log eff=0e0"],
    "an epsilon coremltools already folded to 0x0p+0 must be caught"
  );
}

/// The control. whisperkit's mel guards its `log` with an explicit
/// `add(x, 0x1p-24)` — exactly fp16's smallest subnormal — so it survives,
/// and the gate must say so. A checker that flagged this too would be
/// useless (everything fails, nobody looks).
#[test]
fn accepts_whisperkits_mel_guard() {
  assert_eq!(
    vanishing(WHISPER_MEL),
    Vec::<String>::new(),
    "whisper's mel add(x, 0x1p-24) is exactly at the fp16 floor and survives"
  );

  let graph = parse_mil(WHISPER_MEL);
  let audit = graph.audit();
  assert!(
    audit.unresolved.is_empty(),
    "the real whisper-mel excerpt must parse completely: {:?}",
    audit.unresolved
  );
  let log = audit
    .findings
    .iter()
    .find(|f| f.op == "log")
    .expect("a log site");
  assert_eq!(log.eps, 0.0, "the log's OWN epsilon is 0x0p+0 here");
  assert_eq!(
    log.floor, FP16_MIN_SUBNORMAL,
    "the guard is the preceding add, not the log's epsilon"
  );
  assert!(log.survives_fp16());
  assert!(
    !log.is_decomposed_log_softmax(),
    "it logs a mel spectrogram, not a softmax"
  );
}

/// The coremltools-9 dialect, read end to end: three guard sites in one graph,
/// every epsilon of them a BARE scalar const. Two survive and the third is the
/// pinned defect, so this excerpt exercises the reader's clean and dirty verdicts
/// at once — and, because [`vanishing`] refuses any unresolved statement, it
/// doubles as the proof that the `tensor<`-only reader's 36-hole failure is
/// closed rather than merely quieted.
#[test]
fn reads_the_coremltools_9_bare_scalar_dialect() {
  let graph = parse_mil(LID_ECAPA_SCALAR_DIALECT);

  // The values only a bare-scalar-aware reader can see. `inf` is here because
  // the clip's UPPER bound is one: a scalar literal that is not a hex float.
  assert_eq!(
    graph.consts.get("var_23_to_fp16").copied(),
    Some(1.0013580322265625e-5),
    "the batch_norm epsilon is declared `fp16 …`, not `tensor<fp16, []> …`"
  );
  assert_eq!(
    graph.consts.get("var_13_to_fp16").copied(),
    Some(FP16_MIN_SUBNORMAL)
  );
  assert_eq!(
    graph.consts.get("const_37_to_fp16").copied(),
    Some(f64::INFINITY)
  );
  assert_eq!(
    graph.consts.get("x_act_epsilon_0").copied(),
    Some(2.0_f64.powi(-149)),
    "and an fp32 scalar is spelled bare too, in the same graph as `tensor<fp16, [1, 107]>`"
  );

  assert_eq!(
    vanishing(LID_ECAPA_SCALAR_DIALECT),
    ["log/fp16 guard=softmax->log eff=1.401298464324817e-45"],
    "exactly one of the three sites vanishes: the classifier tail's decomposed \
     log-softmax. The batch_norm's 1.001e-5 and the clip's 0x1p-24 both clear the floor."
  );

  let audit = graph.audit();
  assert_eq!(
    audit.findings.len(),
    3,
    "batch_norm, sqrt and log — a reader that saw only `tensor<` statements found NONE of \
     them and reported three unresolved holes instead: {:?}",
    audit
      .findings
      .iter()
      .map(Finding::render)
      .collect::<Vec<_>>()
  );
  let sqrt = audit
    .findings
    .iter()
    .find(|f| f.op == "sqrt")
    .expect("a sqrt site");
  assert_eq!(
    sqrt.floor, FP16_MIN_SUBNORMAL,
    "the attentive-stat sqrt is floored by clip(alpha = 0x1p-24), read through a bare scalar"
  );
  assert!(sqrt.survives_fp16());
}

/// The falsifier for the test above: the same bare-scalar `batch_norm` with its
/// epsilon halved to `0x1p-25` must be CAUGHT. Without it, "clean" could mean
/// the reader resolved a healthy epsilon or that it resolved nothing at all in a
/// way the hole accounting happened to miss.
#[test]
fn a_vanishing_bare_scalar_epsilon_is_caught() {
  assert_eq!(
    vanishing(LID_SCALAR_NORM_VANISHING_MUTANT),
    ["batch_norm/fp16 guard=norm eff=2.9802322387695313e-8"],
    "a bare-scalar epsilon below the fp16 floor must fail exactly like a `tensor<fp16, []>` one"
  );
}

/// The over-fire side. The bare-scalar arm keys on "leading token, then a
/// space", which describes the graph's header and its function signature too —
/// so those must stay [`ParseOutcome::NotStatement`]. A header misread as a
/// declaration would add a junk producer and, worse, could be reported as an
/// unreadable guard (the `func` line names `tuple(`/`dict(`, and a future one
/// might name `log(`), failing every graph in the dialect for nothing.
#[test]
fn the_bare_scalar_arm_does_not_swallow_the_program_header() {
  for line in LID_NON_STATEMENT_LINES {
    assert!(
      matches!(parse_stmt_line(line.trim()), ParseOutcome::NotStatement),
      "not a declaration, and must not be read as one: {line}"
    );
  }
  assert_eq!(
    bare_scalar_head("fp16 var_23_to_fp16 = const()[]"),
    Some(("fp16", "var_23_to_fp16 = const()[]")),
    "…while a real scalar declaration still is one"
  );
  assert_eq!(
    bare_scalar_head("float16 v = const()[]"),
    None,
    "the vocabulary is closed: a near-miss type name is not a declaration"
  );
}

/// The second control. vadkit's Silero VAD graph guards its STFT
/// power-to-magnitude `sqrt` with an explicit `add(x, 0x1p-24)` — exactly
/// fp16's smallest subnormal — so it survives, and the gate must say so. A
/// `sqrt` floored by a surviving `add` is the clean counterpart of PLDA's
/// `clip(1e-12) -> sqrt` finding: the checker distinguishes them by the floor's
/// magnitude, and this pins that it reads the surviving one as clean. vadkit is
/// a clean vendor with no `KNOWN_DEFECTS` pin (see `VADKIT_STFT_SQRT`).
#[test]
fn accepts_vadkits_stft_sqrt_guard() {
  assert_eq!(
    vanishing(VADKIT_STFT_SQRT),
    Vec::<String>::new(),
    "vadkit's STFT add(x, 0x1p-24) -> sqrt is exactly at the fp16 floor and survives"
  );

  let graph = parse_mil(VADKIT_STFT_SQRT);
  let audit = graph.audit();
  assert!(
    audit.unresolved.is_empty(),
    "the real vadkit STFT excerpt must parse completely: {:?}",
    audit.unresolved
  );
  let sqrt = audit
    .findings
    .iter()
    .find(|f| f.op == "sqrt")
    .expect("a sqrt site");
  assert_eq!(sqrt.eps, 0.0, "sqrt carries no epsilon of its own");
  assert_eq!(
    sqrt.floor, FP16_MIN_SUBNORMAL,
    "the guard is the preceding add(0x1p-24), not any epsilon on the sqrt"
  );
  assert!(sqrt.survives_fp16());
}

/// clapkit's converted CLAP graphs are a CLEAN control (the second beside
/// whisper's mel): the audio `batch_norm`/`layer_norm` guards at `0x1.5p-17` and
/// the text `layer_norm` guards at `0x1p-24` all clear the fp16 floor (the text
/// tier inclusively), so the sweep must report clapkit clean. Its companion
/// mutant — the same text `layer_norm` with the epsilon halved to `0x1p-25` —
/// MUST be flagged, proving this control is not vacuously green.
#[test]
fn accepts_clapkit_conversion_norm_guards() {
  assert_eq!(
    vanishing(CLAPKIT_NORMS_CLEAN),
    Vec::<String>::new(),
    "clapkit's audio 0x1.5p-17 and text 0x1p-24 norm guards both survive fp16"
  );

  let audit = parse_mil(CLAPKIT_NORMS_CLEAN).audit();
  assert!(
    audit.unresolved.is_empty(),
    "the real clapkit norm excerpts must parse completely: {:?}",
    audit.unresolved
  );
  // Two norm findings (batch_norm + layer_norm), both surviving; no log/div guard
  // class present (L2-norm kept out of the graphs).
  assert_eq!(
    audit.findings.len(),
    2,
    "one batch_norm + one layer_norm site"
  );
  assert!(audit.findings.iter().all(|f| f.survives_fp16()));

  // Mutation proof: below-floor epsilon is caught, not silently swept green.
  assert_eq!(
    vanishing(CLAPKIT_NORM_VANISHING_MUTANT),
    ["layer_norm/fp16 guard=norm eff=2.9802322387695313e-8"],
    "a clapkit norm eps halved to 0x1p-25 (below the fp16 floor) must be flagged"
  );
}

/// granite's converted ModernBERT graph is a CLEAN control (the third norm-only
/// control beside clapkit's audio/text towers): all 25 `layer_norm` guards at
/// `0x1.5p-17` clear the fp16 floor, and no `log`/`sqrt`/`rsqrt`/`real_div` class
/// is present (L2-norm kept out of the graph), so the sweep must report granite
/// clean. Its companion mutant — the same embeddings `layer_norm` with the
/// epsilon halved to `0x1p-25` — MUST be flagged, proving this control is not
/// vacuously green.
#[test]
fn accepts_granite_conversion_norm_guards() {
  assert_eq!(
    vanishing(GRANITE_NORMS_CLEAN),
    Vec::<String>::new(),
    "granite's 0x1.5p-17 layer_norm guards all survive fp16"
  );

  let audit = parse_mil(GRANITE_NORMS_CLEAN).audit();
  assert!(
    audit.unresolved.is_empty(),
    "the real granite norm excerpts must parse completely: {:?}",
    audit.unresolved
  );
  // Two layer_norm findings, both surviving; no log/div/sqrt guard class present.
  assert_eq!(audit.findings.len(), 2, "two layer_norm sites");
  assert!(audit.findings.iter().all(|f| f.survives_fp16()));
  assert!(
    audit.findings.iter().all(|f| f.op == "layer_norm"),
    "granite carries only layer_norm guard sites"
  );

  // Mutation proof: below-floor epsilon is caught, not silently swept green.
  assert_eq!(
    vanishing(GRANITE_NORM_VANISHING_MUTANT),
    ["layer_norm/fp16 guard=norm eff=2.9802322387695313e-8"],
    "a granite norm eps halved to 0x1p-25 (below the fp16 floor) must be flagged"
  );
}

/// siglip's converted SigLIP2 towers are a CLEAN control (the fourth norm-only
/// control): both towers' `layer_norm` guards at `0x1.1p-20` clear the fp16 floor,
/// and no `log`/`sqrt`/`rsqrt`/`real_div` class is present (L2-norm kept out of the
/// graphs), so the sweep must report siglip clean. Its companion mutant — the text
/// `layer_norm` with the epsilon halved to `0x1p-25` — MUST be flagged, proving
/// this control is not vacuously green.
#[test]
fn accepts_siglip_conversion_norm_guards() {
  assert_eq!(
    vanishing(SIGLIP_NORMS_CLEAN),
    Vec::<String>::new(),
    "siglip's 0x1.1p-20 vision+text layer_norm guards all survive fp16"
  );

  let audit = parse_mil(SIGLIP_NORMS_CLEAN).audit();
  assert!(
    audit.unresolved.is_empty(),
    "the real siglip norm excerpts must parse completely: {:?}",
    audit.unresolved
  );
  // Two layer_norm findings (one per tower), both surviving; no log/div/sqrt class.
  assert_eq!(
    audit.findings.len(),
    2,
    "one vision + one text layer_norm site"
  );
  assert!(audit.findings.iter().all(|f| f.survives_fp16()));
  assert!(
    audit.findings.iter().all(|f| f.op == "layer_norm"),
    "siglip carries only layer_norm guard sites"
  );

  // Mutation proof: below-floor epsilon is caught, not silently swept green.
  assert_eq!(
    vanishing(SIGLIP_NORM_VANISHING_MUTANT),
    ["layer_norm/fp16 guard=norm eff=2.9802322387695313e-8"],
    "a siglip norm eps halved to 0x1p-25 (below the fp16 floor) must be flagged"
  );
}

/// F3: two independently-materialized guard constants, each `2^-25` (half fp16's
/// smallest subnormal), must NOT sum into a false "survives". Each rounds to zero
/// in fp16 on its own, so the site is a vanishing finding — the effective floor
/// is the MAX of the two, not their sum (which is exactly `2^-24` here and would
/// spuriously pass). MUTATION PROOF: reverting `Finding::effective` from
/// `eps.max(floor)` back to `eps + floor` makes the sum reach the floor, marks
/// the site surviving, empties `vanishing()`, and turns this assertion red.
#[test]
fn two_sub_threshold_guards_do_not_sum_into_survival() {
  assert_eq!(
    vanishing(TWO_HALF_SUBNORMAL_GUARDS),
    ["log/fp16 guard=add(+2.9802322387695313e-8) eff=2.9802322387695313e-8"],
    "add(0x1p-25) feeding log(eps=0x1p-25): each constant is half the fp16 floor \
     and rounds to zero on its own, so the guard vanishes — the two must not sum \
     past the floor"
  );

  // The companion mel control proves the MAX rule does not over-flag: mel's
  // surviving `add(0x1p-24)` with `log(eps = 0)` stays clean under the same rule.
  assert_eq!(
    vanishing(WHISPER_MEL),
    Vec::<String>::new(),
    "the MAX rule must keep whisper-mel clean (add's 2^-24 survives on its own)"
  );
}

/// Finding 5: two vanishing sites with the SAME signature must be TWO findings,
/// not deduped to one. This is the blast-radius multiplicity a `dedup`/set
/// silently hides (a reconversion that adds a second same-signature vanishing
/// site keeps a green pin while doubling the corrupted sites). Routes through
/// the same `vanishing` path the live sweep uses, so re-introducing a dedup in
/// [`vanishing_sites`] breaks this hermetically, before any model is loaded.
#[test]
fn same_signature_sites_are_a_multiset_not_a_set() {
  let sites = vanishing(TWO_SITE_LOG_SOFTMAX);
  assert_eq!(
    sites.len(),
    2,
    "two independent softmax->log sites must render as TWO findings, not collapse to one — got {sites:?}"
  );
  assert_eq!(
    sites[0], sites[1],
    "...and they share a signature, which is exactly what a set/dedup would fold away"
  );
  assert_eq!(sites[0], "log/fp16 guard=softmax->log eff=0e0");
}

/// Completeness (partial-parse face). A graph with ONE recognized, surviving
/// guard beside ONE guard in syntax the reader cannot parse must FAIL the
/// audit: the unreadable statement is surfaced, never dropped so the recognized
/// guard alone reports a clean sweep. This is the exact rot a re-conversion can
/// introduce — new coremltools, new MIL shape — and the reason the sweep audits
/// completeness, not merely the guards it happens to recognize. Mutating the
/// reader back to drop-silently (classifying every unparsed line as
/// non-guard) turns `unresolved` empty and this assertion red.
#[test]
fn a_partial_parse_fails_the_audit_never_reports_clean() {
  let audit = parse_mil(VALID_GUARD_PLUS_UNREADABLE_GUARD).audit();

  // The clean mel-style guard is still audited and still survives...
  assert!(
    audit
      .findings
      .iter()
      .any(|f| f.op == "log" && f.survives_fp16()),
    "the valid mel-style guard must still be audited and survive"
  );
  // ...but the unreadable second `log` is surfaced as a completeness hole,
  // not silently dropped: the audit is NOT clean, and it quotes the statement.
  assert!(
    !audit.unresolved.is_empty(),
    "an unreadable guard statement must fail the audit, not vanish — got no unresolved holes"
  );
  assert!(
    audit
      .unresolved
      .iter()
      .any(|u| u.contains("log") && u.contains("bad_log")),
    "the unresolved report must quote the offending `log` statement: {:?}",
    audit.unresolved
  );
}

/// Completeness (unresolvable-epsilon face). A recognized guard SITE
/// (`batch_norm`) whose epsilon does not resolve to a constant is a hole, not
/// an absence: the guard is unreadable. The old `eps_kwarg.map(...)`
/// short-circuited on `None` and dropped the site; it must now fail the audit
/// with the statement quoted. Reverting the norm arm to `eps_kwarg.map(...)`
/// turns `unresolved` empty and this assertion red.
#[test]
fn a_norm_with_an_unreadable_epsilon_is_a_hole_not_a_skip() {
  let audit = parse_mil(NORM_WITH_UNRESOLVABLE_EPSILON).audit();
  assert!(
    audit.findings.is_empty(),
    "an unresolvable-epsilon norm yields no resolved finding, got: {:?}",
    audit
      .findings
      .iter()
      .map(Finding::render)
      .collect::<Vec<_>>()
  );
  assert!(
    audit
      .unresolved
      .iter()
      .any(|u| u.contains("batch_norm") && u.contains("n_out")),
    "...but it must be reported unresolved, quoting the statement — not dropped: {:?}",
    audit.unresolved
  );
}

/// F2, recognized vocabulary: an `l2_norm` with a fp16-vanishing epsilon must
/// surface as a FINDING (a vanishing guard site), rendered like the other norms
/// but with an `l2_norm/` op prefix — beside a clean `log` that still survives.
/// Before `l2_norm` was in the vocabulary it fell to the `_ => None` wildcard and
/// produced NEITHER a finding NOR an unresolved hole: a re-conversion adding a
/// safe `log` plus a vanishing `l2_norm(epsilon = 1e-8)` swept GREEN. MUTATION
/// PROOF: dropping `l2_norm` from the norm arm sends it to the `epsilon`
/// catch-all → unresolved → `vanishing()` panics; dropping BOTH the arm and the
/// catch-all sends it to the wildcard → empty `vanishing()` → this assertion red.
#[test]
fn an_l2_norm_with_a_vanishing_epsilon_is_a_finding_not_a_wildcard_drop() {
  assert_eq!(
    vanishing(L2_NORM_VANISHING),
    ["l2_norm/fp16 guard=norm eff=9.99999993922529e-9"],
    "l2_norm's epsilon is its whole divide guard; 1e-8 rounds to zero in fp16 and \
     must surface as a vanishing finding, not drop through the wildcard"
  );
}

/// F2, the CLASS: an op the audit does not recognize that carries an `epsilon`
/// kwarg is a hole, not an absence — the vocabulary-independent catch-all must
/// FAIL the audit with the statement quoted, never drop it through the wildcard.
/// This is what stops a brand-new epsilon-bearing op (a future MIL op, or a known
/// one we forgot to teach) from sweeping green beside a recognized guard. MUTATION
/// PROOF: removing the `_ if EPSILON_KWARGS ...` catch-all arm sends the unknown
/// op to `_ => None` → `unresolved` empty → this assertion red.
#[test]
fn an_epsilon_bearing_unknown_op_is_a_hole_not_a_wildcard_drop() {
  let audit = parse_mil(EPSILON_BEARING_UNKNOWN_OP).audit();
  assert!(
    audit.findings.is_empty(),
    "an unrecognized op yields no resolved finding, got: {:?}",
    audit
      .findings
      .iter()
      .map(Finding::render)
      .collect::<Vec<_>>()
  );
  assert!(
    audit
      .unresolved
      .iter()
      .any(|u| u.contains("some_future_norm") && u.contains("mystery_out")),
    "an unknown op carrying an `epsilon` kwarg must be surfaced as unresolved, quoting the \
     statement — not dropped through the wildcard: {:?}",
    audit.unresolved
  );
}

/// Regression (completeness, cast-wrapped floor). A `const → cast → add →
/// real_div` divisor guard must surface its `1e-8` site in `vanishing()`,
/// exactly like the direct-const `WESPEAKER_POOLING`. Before the audit followed
/// constants through `cast`, this chain — every statement of which parses —
/// produced no finding and no unresolved hole: the vanishing guard disappeared
/// while any other recognized guard kept the sweep green. MUTATION PROOF:
/// reverting `Graph::floor`'s `add` arm from `const_through_cast` back to
/// `value` loses the cast-wrapped floor and turns this assertion red — the
/// pinned `real_div` site is no longer what `vanishing()` returns.
#[test]
fn follows_a_cast_wrapped_pooling_divisor_guard() {
  assert_eq!(
    vanishing(CAST_WRAPPED_POOLING_DIVISOR),
    ["real_div/fp16 guard=denom:add(+9.99999993922529e-9) eff=9.99999993922529e-9"],
    "a `count + cast(1e-8)` divisor guard must be caught THROUGH the cast, \
     rendering identically to the direct-const wespeaker pooling guard"
  );
}

/// Regression (completeness, dynamically-unresolvable floor). An `add`-guarded
/// divisor whose epsilon will not resolve to a constant — even through casts —
/// is a hole the audit must FAIL on, not a silent drop. The `real_div` here
/// divides by `count + <dynamic>`: structurally a guard, unreadable in value.
/// A genuinely dynamic divisor from a NON-guard op stays silent instead (see
/// `DYNAMIC_UNRESOLVABLE_DIVISOR`). MUTATION PROOF: reverting the `real_div`
/// arm from routing this to `unresolved` back to a bare `.map`-drop turns
/// `unresolved` empty and this assertion red.
#[test]
fn an_unresolvable_add_guarded_divisor_is_a_hole_not_a_drop() {
  let audit = parse_mil(DYNAMIC_UNRESOLVABLE_DIVISOR).audit();
  assert!(
    audit.findings.is_empty(),
    "an unresolvable divisor guard yields no resolved finding, got: {:?}",
    audit
      .findings
      .iter()
      .map(Finding::render)
      .collect::<Vec<_>>()
  );
  assert!(
    audit
      .unresolved
      .iter()
      .any(|u| u.contains("real_div") && u.contains("mean")),
    "the unreadable `add`-guarded divisor must be surfaced as unresolved, quoting \
     the statement — not dropped: {:?}",
    audit.unresolved
  );
}

/// Regression (completeness, cast-wrapped UNRESOLVED floor). A cast-wrapped,
/// dynamically-unresolvable `add`-guarded divisor (`mul → add → cast →
/// real_div`) beside a clean, surviving guard must FAIL the audit: the clean
/// guard must not mask the hole. `Graph::floor` unwraps the `cast` to reach the
/// `add` when resolving the floor, so the unresolved-detection must unwrap it
/// too — otherwise the `real_div` yields neither a finding nor an unresolved
/// hole and vanishes. MUTATION PROOF: reverting `unreadable_floor_guard` to
/// inspect only the divisor's IMMEDIATE producer (dropping the shared
/// `producer_through_cast` unwrap) makes it see the `cast` — whose op is not a
/// guard op — return false, push no unresolved, and this assertion goes red (the
/// audit reports clean while the guard silently disappears).
#[test]
fn follows_a_cast_before_an_unresolvable_divisor_guard() {
  let audit = parse_mil(CAST_WRAPPED_DYNAMIC_DIVISOR).audit();

  // The clean mel-style guard is still audited and still survives...
  assert!(
    audit
      .findings
      .iter()
      .any(|f| f.op == "log" && f.survives_fp16()),
    "the valid mel-style guard must still be audited and survive"
  );
  // ...but the cast-wrapped `add`-guarded divisor is surfaced as a hole,
  // quoting the `real_div` statement — not dropped so the clean guard alone
  // reports a clean sweep.
  assert!(
    audit
      .unresolved
      .iter()
      .any(|u| u.contains("real_div") && u.contains("mean")),
    "the cast-wrapped unresolvable divisor guard must be surfaced as unresolved, \
     quoting the statement — not dropped: {:?}",
    audit.unresolved
  );
}

/// The walk propagates I/O errors instead of flattening them into a silent
/// early return: a `read_dir` failure must never quietly shrink the sweep to
/// whatever happened to be readable. The old `let Ok(entries) = .. else
/// return` swallowed exactly this.
#[test]
fn discover_propagates_read_dir_errors() {
  let mut out = Vec::new();
  let missing = models_dir().join("__no_such_subtree_for_the_walk__");
  assert!(
    discover(&missing, &mut out).is_err(),
    "read_dir on a nonexistent path must return Err, not an empty Ok"
  );
  assert!(out.is_empty(), "a failed walk collects nothing");
}

// ---------------------------------------------------------------------------
// The sweep — runs iff `Models/` is on disk (see `build.rs`).
// ---------------------------------------------------------------------------

/// Workspace `Models/`, matching the other crates' test helpers.
fn models_dir() -> PathBuf {
  workspace_root::models_root()
}

/// Every `*.mlmodelc` under `root`, recursively. A walk, never a list.
///
/// Dot-directories are skipped: `huggingface-cli` leaves a
/// `.cache/huggingface/download/` tree of `.mlmodelc`-NAMED bookkeeping
/// directories that hold no `model.mil` (25 of them, against 26 real
/// models). They are download metadata, not shipped artifacts — and
/// treating them as models would make the "a .mlmodelc must have a
/// readable model.mil" hard failure fire on every machine that pulled the
/// argmax models from the Hub.
///
/// A `read_dir` failure or an unreadable directory entry PROPAGATES as an
/// `Err` rather than flattening into a silent early return — the walk must
/// never quietly shrink the sweep to whatever happened to be readable, which
/// is the same "fixture went missing, test went green" mode the pins guard
/// against.
fn discover(root: &Path, out: &mut Vec<PathBuf>) -> io::Result<()> {
  let entries = fs::read_dir(root)
    .map_err(|e| io::Error::new(e.kind(), format!("read_dir {}: {e}", root.display())))?;
  for entry in entries {
    let entry = entry
      .map_err(|e| io::Error::new(e.kind(), format!("dir entry under {}: {e}", root.display())))?;
    let path = entry.path();
    if !path.is_dir() {
      continue;
    }
    if entry.file_name().to_string_lossy().starts_with('.') {
      continue;
    }
    if path.extension().is_some_and(|e| e == "mlmodelc") {
      out.push(path);
    } else {
      discover(&path, out)?;
    }
  }
  Ok(())
}

/// The vendor prefix of a [`KNOWN_DEFECTS`] path
/// (`speakerkit/Foo.mlmodelc` -> `speakerkit`).
fn vendor_of(path: &str) -> &str {
  path.split('/').next().unwrap_or(path)
}

/// The vendors the sweep REQUIRES to be present (the vendor manifest). Default:
/// every vendor named by a [`KNOWN_DEFECTS`] **or** a [`LOAD_BEARING_NORMS`]
/// pin, so deleting a whole vendor FAILS the sweep instead of silently dropping
/// that vendor's pins. Fail-closed — absence of the override is the strictest
/// setting.
///
/// `COREMLIT_FP16_SWEEP_VENDORS` (comma-separated) OVERRIDES the manifest for a
/// deliberately-partial tree: CI's model job stages part of the tree (per
/// MODELS_LOCK) and names exactly that part, so there the sweep requires every
/// staged vendor and audits its graphs while the absent alignkit/argmax vendors
/// are the DOCUMENTED escape, not a silent skip. Narrowing coverage is thus an
/// explicit, reviewable act; the full pin verification remains a local/dev gate
/// (see the module docs' coverage boundary, which carries the current value).
///
/// A present-but-EMPTY override (`""`, whitespace, or only commas) is a HARD
/// ERROR, not an empty manifest — see [`vendor_manifest`].
fn expected_vendors() -> BTreeSet<String> {
  // `.ok()` folds both `VarError` variants to "unset" ⇒ the strict full manifest,
  // keeping a non-UTF-8 value fail-CLOSED; a present-but-empty UTF-8 value is the
  // fail-OPEN case `vendor_manifest` rejects.
  vendor_manifest(env::var("COREMLIT_FP16_SWEEP_VENDORS").ok().as_deref())
}

/// The vendor manifest for a raw `COREMLIT_FP16_SWEEP_VENDORS` value: `None` (the
/// variable is UNSET) ⇒ the full fail-closed manifest, every [`KNOWN_DEFECTS`]
/// vendor; `Some(raw)` ⇒ its comma-separated, trimmed, non-empty vendor names.
///
/// Split out of [`expected_vendors`] so the present-but-empty rejection is
/// exercised hermetically, without mutating a process-global env var that races
/// across the parallel test threads.
///
/// # Panics
/// If `raw` is `Some` but names no vendor (empty, whitespace-only, or only
/// commas/whitespace): such an override collapses to an EMPTY expected set, which
/// requires NO vendor and silently re-opens the whole-vendor-deletion escape the
/// manifest exists to close (codex r7 F3). The panic names the variable so a CI
/// expansion like `COREMLIT_FP16_SWEEP_VENDORS="$MAYBE_EMPTY"` fails loudly rather
/// than disabling the fail-closed default.
fn vendor_manifest(raw: Option<&str>) -> BTreeSet<String> {
  let Some(raw) = raw else {
    return pinned_paths()
      .into_iter()
      .map(|path| vendor_of(path).to_string())
      .collect();
  };
  let vendors: BTreeSet<String> = raw
    .split(',')
    .map(str::trim)
    .filter(|s| !s.is_empty())
    .map(String::from)
    .collect();
  assert!(
    !vendors.is_empty(),
    "COREMLIT_FP16_SWEEP_VENDORS is set to {raw:?} but names no vendor — a present-but-empty \
     override (empty, whitespace, or comma-only) would require NO vendor and silently re-open the \
     whole-vendor-deletion escape the manifest exists to close. Unset it to require every \
     KNOWN_DEFECTS vendor, or name the vendors to audit (e.g. whisperkit-coreml)."
  );
  vendors
}

/// The result of sweeping a tree: how many models and guard sites were audited,
/// and every failure found. An empty `failures` is a clean sweep.
struct SweepOutcome {
  models_len: usize,
  audited_sites: usize,
  /// How many audited sites landed in each [`GuardBand`], keyed by
  /// [`GuardBand::label`]. Reported with every failure so a red carries the
  /// census that explains it, and asserted non-vacuous by the sweep.
  bands: BTreeMap<&'static str, usize>,
  /// Constant `batch_norm` variance channels read out of the weight blobs, and
  /// how many are exactly zero in fp16.
  variance_channels: usize,
  zero_variance_channels: usize,
  failures: Vec<String>,
}

/// Sweeps every `.mlmodelc` under `root` and returns the outcome — factored out
/// of [`every_shipped_model_graph_survives_fp16`] so the vendor manifest is
/// exercised hermetically over synthetic trees, not only the real `Models/`.
///
/// `expected_vendors` is the manifest: each named vendor directory MUST exist
/// under `root` or a failure is recorded, so deleting an ENTIRE vendor can no
/// longer silently disable its pins (the old per-pin check only fired when the
/// vendor dir still existed, so a tree with just the clean whisper vendor swept
/// green with all ten speakerkit/alignkit/argmax pins quietly skipped). A pin
/// whose vendor is NOT in `expected_vendors` is allowed to be absent — the
/// deliberately-partial-tree escape (see [`expected_vendors`]) — but a pin missing
/// from a vendor that IS present still fails.
fn sweep_tree(root: &Path, expected_vendors: &BTreeSet<String>) -> io::Result<SweepOutcome> {
  let mut models = Vec::new();
  discover(root, &mut models)?;
  models.sort();

  let pins: BTreeMap<&str, &KnownDefect> = KNOWN_DEFECTS.iter().map(|d| (d.path, d)).collect();
  let load_bearing: BTreeMap<&str, &LoadBearingNorm> =
    LOAD_BEARING_NORMS.iter().map(|d| (d.path, d)).collect();
  let mut audited_sites = 0_usize;
  let mut bands: BTreeMap<&'static str, usize> = BTreeMap::new();
  let mut variance_channels = 0_usize;
  let mut zero_variance_channels = 0_usize;
  let mut failures = Vec::new();
  let mut seen = Vec::new();

  for model in &models {
    let rel = model
      .strip_prefix(root)
      .expect("discovered under root")
      .to_string_lossy()
      .replace('\\', "/");
    seen.push(rel.clone());

    // A model directory with no readable graph is a hard failure, never a skip —
    // recorded (not a panic) so the sweep still reports every other model.
    let mil = model.join("model.mil");
    let text = match fs::read_to_string(&mil) {
      Ok(text) => text,
      Err(e) => {
        failures.push(format!("{rel}: .mlmodelc has no readable model.mil ({e})"));
        continue;
      }
    };

    let Audit {
      findings,
      unresolved,
      const_variance_norms,
    } = parse_mil(&text).audit();

    // Completeness: a guard-looking statement the reader could not resolve is
    // a hole, not a pass. A PARTIAL parse — one recognized guard beside a new
    // vanishing one in syntax this reader does not handle — must fail the
    // sweep with the offending statement quoted, never slip through GREEN on
    // the strength of the one guard it happened to recognize.
    if !unresolved.is_empty() {
      failures.push(format!(
        "{rel}: {} guard-looking statement(s) the reader could not resolve — a partial parse \
         fails the sweep rather than dropping a guard. Re-convert with a readable guard or teach \
         the reader this shape:\n      {}",
        unresolved.len(),
        unresolved.join("\n      ")
      ));
    }

    // A parsed graph with zero guard sites is the parser having rotted — a hard
    // failure recorded (not a panic) so the sweep still reports every other model.
    if findings.is_empty() {
      failures.push(format!(
        "{rel}: parsed zero guard sites from a {} byte graph — the parser has rotted",
        text.len()
      ));
      continue;
    }
    audited_sites += findings.len();
    for finding in &findings {
      *bands.entry(finding.band().label()).or_default() += 1;
    }

    // What the artifact's own constants say the guards are WORTH. A
    // `batch_norm` whose stored variance holds fp16-zero channels is a site
    // whose epsilon is the whole denominator; an unreadable variance is a hole,
    // recorded like any other, never a silent pass.
    let mut zero_variance: Vec<String> = Vec::new();
    let mut model_channels = 0_usize;
    let mut model_zero_channels = 0_usize;
    for norm in &const_variance_norms {
      match read_blob_as_fp16(model, &norm.blob) {
        Ok(values) => {
          let zeros = values.iter().filter(|v| v.to_f32() == 0.0).count();
          model_channels += values.len();
          model_zero_channels += zeros;
          if zeros > 0 {
            zero_variance.push(
              ZeroVarianceSite {
                dtype: norm.dtype.clone(),
                eps: norm.eps,
                channels: values.len(),
                zeros,
              }
              .render(),
            );
          }
        }
        Err(e) => failures.push(format!(
          "{rel}: batch_norm {} declares a constant `variance` this reader could not read \
           ({e}). What its epsilon is worth depends on that tensor, so an unreadable one is a \
           hole, not a pass.",
          norm.var
        )),
      }
    }
    zero_variance.sort();
    variance_channels += model_channels;
    zero_variance_channels += model_zero_channels;

    // A MULTISET, not a set: duplicates are preserved so a second
    // same-signature vanishing site fails the pin instead of collapsing into the
    // first (finding 5). See `vanishing_sites`.
    let vanishing = vanishing_sites(&findings);

    // Even a SURVIVING epsilon does not make `softmax -> log` safe: the
    // softmax underflows to 0 in fp16 before the log adds it. Any such
    // composition must be pinned, whatever its epsilon.
    let decomposed: Vec<&Finding> = findings
      .iter()
      .filter(|f| f.is_decomposed_log_softmax() && f.survives_fp16())
      .collect();
    for f in decomposed {
      failures.push(format!(
        "{rel}: {} ({}) is a decomposed log_softmax. Its epsilon survives fp16, but the \
         softmax output underflows to 0 BEFORE the log adds it, clamping the true log-prob \
         at log(eps). Convert with a fused, stable log_softmax (x - logsumexp(x)).",
        f.var,
        f.render()
      ));
    }

    match pins.get(rel.as_str()) {
      Some(pin) => {
        let expected: Vec<String> = pin.sites.iter().map(|s| (*s).to_string()).collect();
        if vanishing != expected {
          if vanishing.is_empty() {
            failures.push(format!(
              "{rel}: PINNED KNOWN DEFECT IS FIXED.\n    was: {expected:?}\n    now: clean.\n    \
               If this model was re-converted, that is good news — but it must be seen: delete \
               its KNOWN_DEFECTS entry and re-cut the parity goldens deliberately.\n    Pin note: \
               {}",
              pin.note
            ));
          } else {
            failures.push(format!(
              "{rel}: pinned defect CHANGED.\n    expected: {expected:?}\n    found:    \
               {vanishing:?}\n    Pin note: {}",
              pin.note
            ));
          }
        }
      }
      None if !vanishing.is_empty() => {
        failures.push(format!(
          "{rel}: NEW fp16-vanishing guard in an unpinned model: {vanishing:?}\n    Every \
           epsilon here is below fp16's smallest subnormal ({FP16_MIN_SUBNORMAL:e}), so it \
           rounds to zero and the guard goes inert on the ANE/GPU. Re-convert with an epsilon \
           >= 2^-24, or pin it in KNOWN_DEFECTS with a note saying what breaks."
        ));
      }
      None => {}
    }

    // The second register, pinned in BOTH directions exactly as the first is.
    match load_bearing.get(rel.as_str()) {
      Some(pin) => {
        let expected: Vec<String> = pin.sites.iter().map(|s| (*s).to_string()).collect();
        // Rows AND totals in one comparison: the rows carry the sites whose
        // epsilon is the whole denominator, the totals carry the graph the
        // fraction is out of — including the zero-FREE norms no row mentions.
        if (&zero_variance, model_channels, model_zero_channels)
          != (&expected, pin.channels, pin.zero_channels)
        {
          failures.push(format!(
            "{rel}: pinned LOAD-BEARING epsilon sites CHANGED.\n    expected: {expected:?} over \
             {}/{} channels\n    found:    {zero_variance:?} over {model_zero_channels}/\
             {model_channels} channels\n    A zero-variance channel is guarded by its epsilon \
             and by nothing else, so this changing in EITHER direction is a change in what the \
             artifact depends on — a REPAIR included, which must be seen and the pin retired \
             deliberately. Pin note: {}",
            pin.zero_channels, pin.channels, pin.note
          ));
        }
      }
      None if !zero_variance.is_empty() => {
        failures.push(format!(
          "{rel}: NEW load-bearing epsilon in an unpinned model: {zero_variance:?}\n    These \
           `batch_norm` sites hold channels whose stored variance is exactly 0.0 in fp16, so \
           `sqrt(variance + epsilon)` reduces to `sqrt(epsilon)` and the epsilon is the entire \
           denominator. That can clear the {FP16_MIN_SUBNORMAL:e} floor and still be a single \
           point of failure. Measure what the site does with the epsilon set to zero, then pin \
           it in LOAD_BEARING_NORMS with that measurement."
        ));
      }
      None => {}
    }
  }

  // The vendor manifest (F3): every EXPECTED vendor directory must be present, or
  // deleting a whole vendor would silently disable ALL of its pins — the "fixture
  // went missing, test went green" mode one level up from a single missing model.
  // A tree carrying only the clean whisper vendor used to sweep green with every
  // speakerkit/alignkit/argmax pin skipped. `expected_vendors` is narrowed
  // explicitly for CI's partial tree; unset, it demands every pinned vendor.
  for vendor in expected_vendors {
    if !root.join(vendor).is_dir() {
      failures.push(format!(
        "expected vendor Models/{vendor}/ is MISSING — its pinned known-defect models cannot be \
         verified, and deleting an entire vendor must never silently disable its pins. Restore \
         the vendor tree, or narrow COREMLIT_FP16_SWEEP_VENDORS for a deliberately partial tree."
      ));
    }
  }

  // A pinned model that has disappeared from a vendor tree that IS present means
  // the pin can no longer be verified. Hard failure — the single-model face of
  // the same mode (the manifest above is the whole-vendor face). Over BOTH
  // registers, so deleting the one artifact LOAD_BEARING_NORMS pins cannot
  // quietly retire that pin either.
  for path in pinned_paths() {
    let vendor = vendor_of(path);
    if root.join(vendor).is_dir() && !seen.iter().any(|s| s == path) {
      failures.push(format!(
        "{path}: pinned model is MISSING, but Models/{vendor}/ is present. The pin cannot be \
         verified. Restore the model or remove the pin."
      ));
    }
  }

  Ok(SweepOutcome {
    models_len: models.len(),
    audited_sites,
    bands,
    variance_channels,
    zero_variance_channels,
    failures,
  })
}

#[cfg_attr(
  not(models_present),
  ignore = "no downloaded model tree on disk — nothing to sweep beyond the committed \
            vadkit artifact (build.rs)"
)]
#[test]
fn every_shipped_model_graph_survives_fp16() {
  let root = models_dir();
  assert!(
    root.is_dir(),
    "Models/ vanished between build and run: {}",
    root.display()
  );

  let outcome = sweep_tree(&root, &expected_vendors())
    .unwrap_or_else(|e| panic!("walking Models/ failed instead of silently skipping: {e}"));

  // Non-vacuity. A sweep that found nothing must never report `ok`.
  assert!(
    outcome.models_len > 0,
    "Models/ exists but contains no .mlmodelc — the sweep would be vacuous"
  );
  assert!(
    outcome.audited_sites > 0,
    "swept {} models and audited zero guard sites — vacuous",
    outcome.models_len
  );
  // The band census must ACCOUNT for every audited site. A classification that
  // silently dropped one would make the report a subset of the tree while still
  // looking like a census.
  assert_eq!(
    outcome.bands.values().sum::<usize>(),
    outcome.audited_sites,
    "the band census {:?} does not account for all {} audited sites",
    outcome.bands,
    outcome.audited_sites
  );

  assert!(
    outcome.failures.is_empty(),
    "fp16 guard sweep failed over {} models / {} guard sites (bands: {:?}; constant batch_norm \
     variance: {} of {} channels zero in fp16):\n\n{}\n",
    outcome.models_len,
    outcome.audited_sites,
    outcome.bands,
    outcome.zero_variance_channels,
    outcome.variance_channels,
    outcome.failures.join("\n\n")
  );
}

// ---------------------------------------------------------------------------
// Hermetic vendor-manifest tests — synthetic Models/ trees, no real models.
// ---------------------------------------------------------------------------

/// A unique, self-cleaning temp directory for the hermetic sweep tests. No
/// `tempfile` dependency (coremlit's dev-deps are `half` only); removed on drop.
struct TempTree(PathBuf);

impl TempTree {
  fn new(tag: &str) -> Self {
    let uniq = format!(
      "coremlit_fp16_sweep_{tag}_{}_{}",
      std::process::id(),
      std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .expect("clock after epoch")
        .as_nanos()
    );
    let root = env::temp_dir().join(uniq);
    fs::create_dir_all(&root).expect("create temp tree");
    TempTree(root)
  }

  fn path(&self) -> &Path {
    &self.0
  }
}

impl Drop for TempTree {
  fn drop(&mut self) {
    let _ = fs::remove_dir_all(&self.0);
  }
}

/// Writes `mil` to `root/rel/model.mil`, creating parents — the hermetic sweep
/// tests build a synthetic `Models/` tree from the same verbatim MIL excerpts the
/// parser tests use.
fn write_model(root: &Path, rel: &str, mil: &str) {
  let dir = root.join(rel);
  fs::create_dir_all(&dir).expect("create model dir");
  fs::write(dir.join("model.mil"), mil).expect("write model.mil");
}

/// Writes a synthetic `.mlmodelc` whose `variance` const resolves to a real
/// weight blob: `model.mil`, plus a `weights/weight.bin` carrying one
/// `blob_metadata` record at `offset` and `values` (as fp16) right after it.
///
/// The layout is the one [`read_blob_as_fp16`] reads, written independently
/// here from the same field order — so a test that passes proves the reader and
/// this writer agree about a format neither of them invented, and the verbatim
/// [`LID_BATCH_NORM`] offsets stay untouched.
fn write_model_with_variance(root: &Path, rel: &str, mil: &str, offset: u64, values: &[f32]) {
  write_model(root, rel, mil);
  let payload: Vec<u8> = values
    .iter()
    .flat_map(|v| half::f16::from_f32(*v).to_le_bytes())
    .collect();
  let data_at = offset + 24;
  let mut blob = vec![0_u8; usize::try_from(data_at).expect("test offset fits") + payload.len()];
  let at = usize::try_from(offset).expect("test offset fits");
  blob[at..at + 4].copy_from_slice(&BLOB_SENTINEL.to_le_bytes());
  blob[at + 4..at + 8].copy_from_slice(&BLOB_DTYPE_FP16.to_le_bytes());
  blob[at + 8..at + 16].copy_from_slice(&(payload.len() as u64).to_le_bytes());
  blob[at + 16..at + 24].copy_from_slice(&data_at.to_le_bytes());
  blob[usize::try_from(data_at).expect("test offset fits")..].copy_from_slice(&payload);

  let weights = root.join(rel).join("weights");
  fs::create_dir_all(&weights).expect("create weights dir");
  fs::write(weights.join("weight.bin"), blob).expect("write weight.bin");
}

/// 1 024 variances with `zeros` of them exactly zero — the shape
/// [`LID_BATCH_NORM`] declares.
fn variances_with_zeros(zeros: usize) -> Vec<f32> {
  (0..1024)
    .map(|i| if i < zeros { 0.0 } else { 1.0 })
    .collect()
}

/// The three bands must be three, and their boundaries must be the format's,
/// not a rounded restatement of it. Also pins the band of the three epsilons the
/// live tree actually contains, so "which band is this tree in" is answered by a
/// test rather than by a comment.
///
/// MUTATION PROOF: collapsing [`GuardBand::of`]'s two surviving arms into one
/// reds the `SubnormalOnly` assertions below.
#[test]
fn the_two_surviving_bands_are_classified_apart() {
  assert_eq!(GuardBand::of(FP16_MIN_NORMAL), GuardBand::Normal);
  assert_eq!(GuardBand::of(FP16_MIN_SUBNORMAL), GuardBand::SubnormalOnly);
  // The boundaries are half-open at the BOTTOM of each band: the smallest
  // representable step below either one drops a band.
  assert_eq!(
    GuardBand::of(FP16_MIN_NORMAL - FP16_MIN_SUBNORMAL),
    GuardBand::SubnormalOnly
  );
  assert_eq!(
    GuardBand::of(FP16_MIN_SUBNORMAL / 2.0),
    GuardBand::Inert,
    "half of the smallest subnormal is not representable in fp16"
  );
  assert_eq!(GuardBand::of(0.0), GuardBand::Inert);

  // And the labels, which the pins and the failure messages both spell out.
  assert_eq!(GuardBand::Normal.label(), "normal");
  assert_eq!(GuardBand::SubnormalOnly.label(), "subnormal-only");
  assert_eq!(GuardBand::Inert.label(), "inert");

  // The three epsilons the live tree carries, one per band. Every one of these
  // is a real value from a real staged graph, so the classification is anchored
  // to the tree rather than to invented numbers.
  //  - 1e-4, speakerkit/Embedding's pooling divisor guard  -> normal
  //  - 1e-5, the BatchNorm1d default, everywhere           -> subnormal-only
  //  - 1e-8, wespeaker's pooling guard (KNOWN_DEFECTS)     -> inert
  assert_eq!(
    GuardBand::of(1.000_165_939_331_054_7e-4),
    GuardBand::Normal,
    "speakerkit/Embedding's divisor guard is an ordinary fp16 number"
  );
  assert_eq!(
    GuardBand::of(1.001_358_032_226_562_5e-5),
    GuardBand::SubnormalOnly,
    "0x1.5p-17, PyTorch's BatchNorm1d default rounded to fp16, is 168x the smallest subnormal \
     and 0.164x the smallest NORMAL — it exists only as a subnormal"
  );
  assert_eq!(GuardBand::of(9.999_999_939_225_29e-9), GuardBand::Inert);
}

/// The blob reader, against a record this test writes itself. Proves the census
/// reads what the MIL POINTS AT rather than whatever happens to be at the head
/// of the file, and that an fp32 blob is narrowed rather than read as-is.
#[test]
fn a_variance_blob_is_read_from_the_offset_the_mil_names() {
  let tree = TempTree::new("blob_read");
  write_model_with_variance(
    tree.path(),
    "lid/probe.mlmodelc",
    LID_BATCH_NORM,
    LID_VARIANCE_BLOB_OFFSET,
    &[1.0, 0.0, 2.0],
  );
  let bundle = tree.path().join("lid/probe.mlmodelc");
  let blob = BlobRef {
    path: "@model_path/weights/weight.bin".to_string(),
    offset: LID_VARIANCE_BLOB_OFFSET,
  };
  let values = read_blob_as_fp16(&bundle, &blob).expect("the written blob reads back");
  assert_eq!(
    values.iter().map(|v| v.to_f32()).collect::<Vec<_>>(),
    [1.0, 0.0, 2.0]
  );

  // The offset is load-bearing: a record that is not there is a hole, named.
  let wrong = BlobRef {
    path: "@model_path/weights/weight.bin".to_string(),
    offset: 0,
  };
  let err = read_blob_as_fp16(&bundle, &wrong).expect_err("offset 0 holds no blob record");
  assert!(
    err.contains("sentinel"),
    "a bad offset must be reported as a missing sentinel, got {err:?}"
  );
}

/// The finding this whole register exists for: a `batch_norm` whose stored
/// variance holds fp16-zero channels is a site whose epsilon is the ENTIRE
/// denominator, and the sweep must say so — for a model no pin covers, loudly.
///
/// MUTATION PROOF: making the census skip zero counting (or dropping the
/// `None if !zero_variance.is_empty()` arm) empties `failures` and reds this.
#[test]
fn an_unpinned_load_bearing_epsilon_fails_the_sweep() {
  let tree = TempTree::new("load_bearing_new");
  write_model_with_variance(
    tree.path(),
    "vadkit/synthetic.mlmodelc",
    LID_BATCH_NORM,
    LID_VARIANCE_BLOB_OFFSET,
    &variances_with_zeros(7),
  );
  let expected = BTreeSet::from(["vadkit".to_string()]);

  let outcome = sweep_tree(tree.path(), &expected).expect("walk the temp tree");
  assert_eq!(
    outcome.zero_variance_channels, 7,
    "seven of the 1 024 stored variances are exactly zero in fp16"
  );
  assert_eq!(outcome.variance_channels, 1024);
  assert!(
    outcome.failures.iter().any(|f| {
      f.contains("NEW load-bearing epsilon")
        && f.contains("band=subnormal-only")
        && f.contains("zero=7/1024")
    }),
    "an unpinned zero-variance batch_norm must fail the sweep, naming the band and the count — \
     got {:?}",
    outcome.failures
  );
}

/// The other direction, and the one that keeps the register honest: a pinned
/// artifact whose zero-variance channels have GONE fails too. An exemption must
/// not outlive its cause — the same rule `CHECKSUMLESS_KITS` holds in
/// `tests/whisper/models_lock.rs`.
///
/// Uses the real pinned path with a graph whose variances are all NON-zero, so
/// the pin's five rows meet an empty finding: exactly what a re-conversion that
/// clamped `running_var` would produce. The synthetic graph also carries no
/// `log`, so the artifact's [`KNOWN_DEFECTS`] pin reports a second, unrelated
/// failure; the assertion below names the load-bearing one specifically.
#[test]
fn a_repaired_load_bearing_pin_fails_the_sweep() {
  let pin = LOAD_BEARING_NORMS
    .iter()
    .find(|p| p.path == "lid/SpeechBrainECAPAVoxLingua107.mlmodelc")
    .expect("the lid artifact is pinned");
  assert!(!pin.sites.is_empty(), "and it pins at least one site");

  let tree = TempTree::new("load_bearing_repaired");
  write_model_with_variance(
    tree.path(),
    pin.path,
    LID_BATCH_NORM,
    LID_VARIANCE_BLOB_OFFSET,
    &variances_with_zeros(0),
  );
  let expected = BTreeSet::from(["lid".to_string()]);

  let outcome = sweep_tree(tree.path(), &expected).expect("walk the temp tree");
  assert_eq!(
    outcome.zero_variance_channels, 0,
    "nothing is zero any more"
  );
  assert!(
    outcome
      .failures
      .iter()
      .any(|f| f.contains("pinned LOAD-BEARING epsilon sites CHANGED") && f.contains("REPAIR")),
    "a pinned load-bearing artifact whose zero-variance channels vanished must FAIL, so the \
     repair is seen and the pin retired deliberately — got {:?}",
    outcome.failures
  );
}

/// A constant `variance` the reader cannot read is a HOLE, never a pass: what
/// the epsilon beside it is worth depends on that tensor, and "could not look"
/// is not "looked and it was fine". The same rule the MIL reader follows for an
/// unreadable guard statement.
#[test]
fn an_unreadable_variance_blob_is_a_hole_not_a_skip() {
  let tree = TempTree::new("variance_hole");
  // The MIL is verbatim, so it points at offset 618 752 — and the bundle is
  // written with NO weights directory at all.
  write_model(tree.path(), "vadkit/synthetic.mlmodelc", LID_BATCH_NORM);
  let expected = BTreeSet::from(["vadkit".to_string()]);

  let outcome = sweep_tree(tree.path(), &expected).expect("walk the temp tree");
  assert!(
    outcome.failures.iter().any(|f| {
      f.contains("constant `variance` this reader could not read") && f.contains("weight.bin")
    }),
    "a missing weight blob must be reported as a hole naming the file — got {:?}",
    outcome.failures
  );
}

/// A norm that computes its own statistics makes NO claim here, and must not
/// produce a hole either. `layer_norm` and `instance_norm` carry no `variance`
/// operand at all — their variance is a runtime tensor — so the census is
/// silent about them, while the ordinary epsilon audit still covers them.
///
/// Without this, the census could be "complete" by flagging every norm in the
/// tree, which would be noise rather than a finding.
#[test]
fn a_norm_that_computes_its_own_variance_makes_no_claim() {
  for (label, mil) in [
    ("granite layer_norm", GRANITE_NORMS_CLEAN),
    ("clap layer_norm", CLAPKIT_NORMS_CLEAN),
    ("siglip layer_norm", SIGLIP_NORMS_CLEAN),
  ] {
    let audit = parse_mil(mil).audit();
    assert!(
      audit.const_variance_norms.is_empty(),
      "{label} has no constant `variance` operand, so the census must say nothing about it"
    );
    assert!(
      audit.unresolved.is_empty(),
      "{label} must not become a hole either: {:?}",
      audit.unresolved
    );
    assert!(!audit.findings.is_empty(), "{label} still has guard sites");
  }
}

/// Register hygiene, both registers: a path pinned twice would make the second
/// entry unreachable, and the sweep looks each path up in a map. Mirrors the
/// duplicate check `CHECKSUMLESS_KITS` carries in
/// `tests/whisper/models_lock.rs`.
#[test]
fn neither_register_pins_a_path_twice() {
  let defects: BTreeSet<&str> = KNOWN_DEFECTS.iter().map(|d| d.path).collect();
  assert_eq!(
    defects.len(),
    KNOWN_DEFECTS.len(),
    "KNOWN_DEFECTS pins a path twice; the second entry would be unreachable"
  );
  let bearing: BTreeSet<&str> = LOAD_BEARING_NORMS.iter().map(|d| d.path).collect();
  assert_eq!(
    bearing.len(),
    LOAD_BEARING_NORMS.len(),
    "LOAD_BEARING_NORMS pins a path twice; the second entry would be unreachable"
  );
  assert_eq!(
    pinned_paths(),
    defects.union(&bearing).copied().collect::<BTreeSet<&str>>(),
    "pinned_paths must be the union of both registers — it is what the vendor manifest and the \
     missing-model check are built from"
  );
  for pin in LOAD_BEARING_NORMS {
    assert!(
      !pin.sites.is_empty(),
      "{}: a LOAD_BEARING_NORMS entry with no sites pins nothing",
      pin.path
    );
    assert!(
      pin.zero_channels > 0 && pin.zero_channels <= pin.channels,
      "{}: {} of {} channels zero is not a coherent census",
      pin.path,
      pin.zero_channels,
      pin.channels
    );
    assert!(
      !pin.note.trim().is_empty(),
      "{}: the note is the declaration — an entry without one records nothing",
      pin.path
    );
  }
}

/// F3: deleting an entire vendor must FAIL the sweep, not silently skip its pins.
/// A partial tree — one clean model under `whisperkit-coreml`, but NO `speakerkit`
/// vendor — is exactly CI's partial download and the shape that used to let all
/// ten defect pins skip green (the old per-pin check fired only when the vendor
/// dir still existed). With `speakerkit` in the expected-vendor manifest, its
/// absence is a hard failure naming the vendor. MUTATION PROOF: deleting the
/// expected-vendor manifest loop in `sweep_tree` empties `failures` and this
/// assertion goes red.
#[test]
fn a_missing_pinned_vendor_fails_the_sweep_not_silently_skips() {
  let tree = TempTree::new("missing_vendor");
  // One clean, present model keeps the sweep non-vacuous...
  write_model(
    tree.path(),
    "whisperkit-coreml/openai_whisper-tiny/MelSpectrogram.mlmodelc",
    WHISPER_MEL,
  );
  // ...but a pinned vendor (`speakerkit`) is entirely absent from the tree.
  let expected = BTreeSet::from(["whisperkit-coreml".to_string(), "speakerkit".to_string()]);

  let outcome = sweep_tree(tree.path(), &expected).expect("walk the temp tree");
  assert!(
    outcome
      .failures
      .iter()
      .any(|f| f.contains("speakerkit") && f.contains("MISSING")),
    "a missing expected vendor must FAIL the sweep, naming the vendor — got {:?}",
    outcome.failures
  );
}

/// F3/F1 reconciliation, and the proof that the sweep SHARDS: a manifest naming
/// only clean vendors sweeps green over a tree that has only those vendors.
///
/// `expected_vendors = {whisperkit-coreml, embedkit-granite, vadkit}` is a
/// clean-control set carrying no [`KNOWN_DEFECTS`] pin: two vendors MODELS_LOCK
/// stages, plus `vadkit`, which no shard downloads because the artifact is
/// COMMITTED to the repository. A tree containing the clean whisper mel, the
/// clean granite norms and the real vadkit STFT guard sweeps green — every
/// expected vendor present and clean, with the PINNED vendors entirely absent.
///
/// That absence is the load-bearing part now that ci.yml runs one shard per
/// kit. Each shard stages only its own kit's tree, so `Models/speakerkit/` does
/// not exist in the whisper shard at all — and its five pins must be SKIPPED
/// there rather than reported missing, because the per-pin check fires on
/// `root.join(vendor).is_dir()`. This test is that behavior, exercised on a real
/// partial tree rather than assumed. The narrowed manifest does not demand the
/// pinned vendors; the fail-closed default demands them only when the override
/// is unset. The opposite direction — a vendor a shard DOES name going missing —
/// is [`a_missing_pinned_vendor_fails_the_sweep_not_silently_skips`], and the
/// cross-shard question of whether the UNION still covers every pin is
/// `ci_fp16_sweep_shards_cover_every_pinned_vendor` in
/// `tests/whisper/models_lock.rs`.
#[test]
fn the_ci_model_job_scope_sweeps_clean() {
  let tree = TempTree::new("ci_model_job_scope");
  write_model(
    tree.path(),
    "whisperkit-coreml/openai_whisper-tiny/MelSpectrogram.mlmodelc",
    WHISPER_MEL,
  );
  write_model(
    tree.path(),
    "embedkit-granite/granite-97m-multilingual-r2/granite_97m_512.mlmodelc",
    GRANITE_NORMS_CLEAN,
  );
  write_model(
    tree.path(),
    "vadkit/silero-vad-unified-256ms-v6.2.1.mlmodelc",
    VADKIT_STFT_SQRT,
  );
  let expected = BTreeSet::from([
    "whisperkit-coreml".to_string(),
    "embedkit-granite".to_string(),
    "vadkit".to_string(),
  ]);

  let outcome = sweep_tree(tree.path(), &expected).expect("walk the temp tree");
  assert!(
    outcome.failures.is_empty(),
    "the CI model job's scope must sweep clean (every expected vendor present + clean; the pins \
     are the documented escape) — got {:?}",
    outcome.failures
  );
  assert_eq!(outcome.models_len, 3, "all three synthetic models");
  assert!(
    outcome.audited_sites >= 3,
    "the mel log site, a granite norm site and vadkit's STFT sqrt were audited"
  );
}

/// codex r7 F3: a present-but-EMPTY `COREMLIT_FP16_SWEEP_VENDORS` must HARD-ERROR,
/// never collapse to an empty (require-nothing) manifest that silently re-opens
/// the whole-vendor-deletion escape. Exercised through the pure [`vendor_manifest`]
/// (no env mutation, which would race the parallel test threads): unset ⇒ the full
/// fail-closed set; a real override ⇒ exactly the named vendors, trimmed; and every
/// empty SHAPE — `""`, whitespace, comma-only, whitespace-and-commas — panics.
#[test]
fn an_empty_vendor_override_hard_errors_not_disables_the_manifest() {
  // Unset ⇒ exactly the pinned vendors (the fail-closed default).
  let full = vendor_manifest(None);
  assert_eq!(
    full,
    KNOWN_DEFECTS
      .iter()
      .map(|d| vendor_of(d.path).to_string())
      .collect::<BTreeSet<String>>(),
    "unset must yield every KNOWN_DEFECTS vendor"
  );
  assert!(!full.is_empty(), "the pinned-vendor manifest is non-empty");

  // A real override ⇒ exactly the named vendors, whitespace trimmed.
  assert_eq!(
    vendor_manifest(Some(" whisperkit-coreml , speakerkit ")),
    BTreeSet::from(["whisperkit-coreml".to_string(), "speakerkit".to_string()]),
    "a named override selects exactly those vendors"
  );

  // Every present-but-empty SHAPE must panic (naming the variable), not return an
  // empty set. Silence the panic hook so the expected messages do not spam the
  // log, collect any shape that slipped through, then restore the hook and assert.
  let prev = std::panic::take_hook();
  std::panic::set_hook(Box::new(|_| {}));
  let mut leaked: Vec<&str> = Vec::new();
  for bad in ["", "   ", ",", ", ", " , , "] {
    if std::panic::catch_unwind(|| vendor_manifest(Some(bad))).is_ok() {
      leaked.push(bad);
    }
  }
  std::panic::set_hook(prev);
  assert!(
    leaked.is_empty(),
    "these present-but-empty overrides returned a manifest instead of hard-erroring: {leaked:?}"
  );
}