inky-engine 3.0.3

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
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
//! Fast-path report: every speed path the engine can take, ON or OFF, and for each OFF the setting that gated it.
//!
//! The gate functions here are the predicates the engine itself calls when it picks kernels (`prefill_tc_attn`,
//! the decode attention choice, the tail trim, the grouped MoE decode, ...), so the report cannot drift from what
//! runs: change a gate and both the kernel choice and the report move together. [`report`] evaluates them for one
//! configuration ([`Inputs`]), which needs no GPU and no model weights, only their types. See
//! `docs/fast-path-audit.md` for the audit behind each entry.

use crate::gguf::*;

/// Why a fast path is off.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OffKind {
    /// An explicit switch that names this path turned it off (`INK_NO_TC_ATTN`, `--no-kv-stitch`, ...).
    OptOut,
    /// Off by default because it measured slower; turning it on is an experiment arm.
    Default,
    /// Another setting, the mode or the hardware rules it out (`--exact`, `--kv8`, no tensor units).
    Mode,
    /// Nobody has written the kernel or the wiring for this combination or weight format yet.
    Missing,
}

impl OffKind {
    pub const fn name(self) -> &'static str {
        match self {
            OffKind::OptOut => "opt_out",
            OffKind::Default => "default_off",
            OffKind::Mode => "mode",
            OffKind::Missing => "missing",
        }
    }
}

/// One gate's verdict for a configuration.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Gate {
    On,
    Off(OffKind, &'static str),
}

impl Gate {
    pub const fn is_on(self) -> bool {
        matches!(self, Gate::On)
    }
}

/// Metal 4 tensor (MPP) kernels: `--no-mpp`, `INKY_DISABLE_MPP`, `INK_NO_TENSOR`, or a tuning without them.
pub const fn mpp_gate(no_mpp_flag: bool, disable_mpp_env: bool, no_tensor_env: bool, tuning_use_mpp: bool) -> Gate {
    if no_mpp_flag {
        Gate::Off(OffKind::OptOut, "--no-mpp")
    } else if disable_mpp_env {
        Gate::Off(OffKind::OptOut, "INKY_DISABLE_MPP")
    } else if no_tensor_env {
        Gate::Off(OffKind::OptOut, "INK_NO_TENSOR")
    } else if !tuning_use_mpp {
        Gate::Off(OffKind::Mode, "this machine's tuning has no Metal 4 tensor kernels (use_mpp = false)")
    } else {
        Gate::On
    }
}

/// fp16 prefill GEMMs and the half-precision attention path: needs MPP, no `INK_NO_HGEMM`, and the tensor
/// accumulator layout probe (`Engine::layout_ok`) passing on this GPU/OS.
pub const fn hgemm_gate(use_mpp: bool, no_hgemm_env: bool, layout_ok: bool) -> Gate {
    if !use_mpp {
        Gate::Off(OffKind::Mode, "Metal 4 tensor kernels are off (mpp_tensor)")
    } else if no_hgemm_env {
        Gate::Off(OffKind::OptOut, "INK_NO_HGEMM")
    } else if !layout_ok {
        Gate::Off(OffKind::Mode, "the tensor accumulator layout probe failed on this GPU/OS")
    } else {
        Gate::On
    }
}

/// Tensor-core prefill attention (`k_attn_tc_fixed_b`, `k_attn_tc_fixed_blk`), every cache format.
pub const fn tc_prefill_attn_gate(hgemm: bool, exact: bool, no_tc_attn_env: bool) -> Gate {
    if !hgemm {
        Gate::Off(OffKind::Mode, "the fp16 path is off (hgemm)")
    } else if exact {
        Gate::Off(OffKind::Mode, "--exact: prefill must write decode's bits")
    } else if no_tc_attn_env {
        Gate::Off(OffKind::OptOut, "INK_NO_TC_ATTN")
    } else {
        Gate::On
    }
}

/// Why tensor-core decode is off by default under `--kv4`: the M5 defaultgate measurement.
pub const TC_DEC_KV4_DEFAULT_OFF: &str = "off by default under --kv4: it fails the M5 defaultgate (long1600:dec0 KL 2.09 vs \
limit 0.5, max_abs 16.9 vs 6.0; with INK_TC_ATTN_DEC=0 mean KL 0.095, worst 0.450, max_abs 4.90, as v3.0.2; Stella at \
241e1355); INK_TC_ATTN_DEC=1 forces it on";

/// Tensor-core decode attention (`k_attn_tc_dec`, `_solo`, `k_attn_tc_grp_dec`, `k_attn_tc_sparse_dec`): on by
/// default for FP16 and KV8 since #268's M5 W24 control (+6.2% decode rows/s over the simdgroup KV8 decode); off by
/// default for KV4, which fails the M5 defaultgate with it ([`TC_DEC_KV4_DEFAULT_OFF`]). `setting` is
/// `INK_TC_ATTN_DEC`: `None` unset (the format's default), `Some(true)` forces it on in every format, `Some(false)`
/// is the explicit opt-out. `INK_NO_TC_ATTN` opts out of tensor-core attention as a whole, prefill and decode alike.
pub const fn tc_decode_attn_gate(hgemm: bool, exact: bool, no_tc_attn_env: bool, setting: Option<bool>, kv4: bool) -> Gate {
    if let Some(false) = setting {
        return Gate::Off(OffKind::OptOut, "INK_TC_ATTN_DEC=0");
    }
    if !hgemm {
        Gate::Off(OffKind::Mode, "the fp16 path is off (hgemm)")
    } else if exact {
        Gate::Off(OffKind::Mode, "--exact: decode attention stays on the deterministic simdgroup kernels")
    } else if no_tc_attn_env {
        Gate::Off(OffKind::OptOut, "INK_NO_TC_ATTN")
    } else if setting.is_none() && kv4 {
        Gate::Off(OffKind::Default, TC_DEC_KV4_DEFAULT_OFF)
    } else {
        Gate::On
    }
}

/// Process-wide exposure counters: proof that an on-by-default path actually ran (`/metrics`
/// `fast_path_*_total`). Counted where the engine encodes the dispatch, so a path the report calls on but no step
/// reached stays at 0.
pub struct Exposure {
    /// tensor-core decode attention dispatches (`k_attn_tc_dec`, `_solo`, `k_attn_tc_grp_dec`, `k_attn_tc_sparse_dec`)
    pub tc_decode_attn: std::sync::atomic::AtomicU64,
    /// tensor-core prefill attention dispatches (`k_attn_tc_fixed_b`, `k_attn_tc_fixed_blk`)
    pub tc_prefill_attn: std::sync::atomic::AtomicU64,
    /// tensor-core prefill attention dispatches from a library compiled with `TC_ATT_EXP2`
    pub tc_exp2: std::sync::atomic::AtomicU64,
    /// tensor-core prefill attention dispatches from a library compiled with `TC_ATT_LAZY_RESCALE`
    pub tc_lazy_rescale: std::sync::atomic::AtomicU64,
    /// full-attention prefill passes that ran sparse (`SparsePrefillStats::sparse_passes`)
    pub sparse_prefill_passes: std::sync::atomic::AtomicU64,
    /// the loaded library has the `TC_ATT_EXP2` / `TC_ATT_LAZY_RESCALE` defines (set when `into_engine_mode` builds it)
    pub exp2_compiled: std::sync::atomic::AtomicBool,
    pub lazy_rescale_compiled: std::sync::atomic::AtomicBool,
}

pub static EXPOSURE: Exposure = Exposure {
    tc_decode_attn: std::sync::atomic::AtomicU64::new(0),
    tc_prefill_attn: std::sync::atomic::AtomicU64::new(0),
    tc_exp2: std::sync::atomic::AtomicU64::new(0),
    tc_lazy_rescale: std::sync::atomic::AtomicU64::new(0),
    sparse_prefill_passes: std::sync::atomic::AtomicU64::new(0),
    exp2_compiled: std::sync::atomic::AtomicBool::new(false),
    lazy_rescale_compiled: std::sync::atomic::AtomicBool::new(false),
};

/// Count one dispatch of kernel `pso` in [`EXPOSURE`] (a prefix compare; nothing for other kernels).
#[inline]
pub fn count_dispatch(pso: &str) {
    use std::sync::atomic::Ordering::Relaxed;
    let Some(rest) = pso.strip_prefix("k_attn_tc_") else { return };
    if rest.starts_with("fixed") {
        EXPOSURE.tc_prefill_attn.fetch_add(1, Relaxed);
        if EXPOSURE.exp2_compiled.load(Relaxed) {
            EXPOSURE.tc_exp2.fetch_add(1, Relaxed);
        }
        if EXPOSURE.lazy_rescale_compiled.load(Relaxed) {
            EXPOSURE.tc_lazy_rescale.fetch_add(1, Relaxed);
        }
    } else {
        EXPOSURE.tc_decode_attn.fetch_add(1, Relaxed);
    }
}

/// Last-layer tail trim, configuration part. Per step ([`tail_trim_step`]) it also needs a prefill step that is not
/// verify; then each span longer than `TAIL_MIN_T` is trimmed ([`tail_trim_start`]), one span in place, several
/// through `TailPlan` (compact rows).
pub const fn tail_trim_gate(hgemm: bool, tail: bool) -> Gate {
    if !hgemm {
        Gate::Off(OffKind::Mode, "the fp16 path is off (hgemm)")
    } else if !tail {
        Gate::Off(OffKind::OptOut, "INK_NO_TAIL")
    } else {
        Gate::On
    }
}

/// Rows of a span the last layer's query side keeps when the span is trimmed. The first three see the post-conv
/// state instead of their real predecessors and the next three inherit that through the FFN post-conv, so rows
/// `>= t - 2` are exact: the final row (logits) and the last three rows of both branch outputs (conv states).
pub const TAIL_ROWS: usize = 8;
/// A span is trimmed only when it is longer than this.
pub const TAIL_MIN_T: usize = 16;

/// Last-layer tail trim on mixed steps (`INK_MIXED_TAIL_TRIM`, on by default): a mixed step's prefill spans trim their
/// last layer like a prefill step's, and its leading one-row decode rows keep their row, at the same compact row as
/// their batch row (`TailPlan::for_step`). Needs the tail trim itself and mixed steps.
pub const fn mixed_tail_trim_gate(hgemm: bool, tail: bool, mixed_steps: bool, mixed_tail_trim: bool) -> Gate {
    match tail_trim_gate(hgemm, tail) {
        Gate::On => {}
        Gate::Off(kind, why) => return Gate::Off(kind, why),
    }
    if !mixed_steps {
        Gate::Off(OffKind::OptOut, "INK_MIXED_STEPS=0")
    } else if !mixed_tail_trim {
        Gate::Off(OffKind::OptOut, "INK_MIXED_TAIL_TRIM=0")
    } else {
        Gate::On
    }
}

/// The engine's per-step tail-trim predicate for a step of `n_spans` spans whose first `n_dec` are one-row decode
/// rows: [`tail_trim_gate`], on a step with a prefill span (a decode step has one row per span) that is not verify
/// (it needs every row's logits). A mixed step (`0 < n_dec < n_spans`) also needs `mixed_tail_trim`
/// (`INK_MIXED_TAIL_TRIM`). Any number of spans.
pub const fn tail_trim_step(hgemm: bool, tail: bool, mixed_tail_trim: bool, n_dec: usize, n_spans: usize, verify: bool) -> bool {
    tail_trim_gate(hgemm, tail).is_on() && n_dec < n_spans && (n_dec == 0 || mixed_tail_trim) && !verify
}

/// Local first row of a span's last-layer query side: `t - TAIL_ROWS` for a span longer than `TAIL_MIN_T`, else 0.
pub const fn tail_trim_start(t: usize) -> usize {
    if t > TAIL_MIN_T {
        t - TAIL_ROWS
    } else {
        0
    }
}

/// One LM-head GEMM for every logits row of a multi-span prefill step ([`span_logits_batch_step`]), instead of one
/// GEMM per span that reads the whole output matrix each time. The f32 fallback keeps its matrix-vector per span.
pub const fn batched_span_logits_gate(hgemm: bool, per_span_env: bool) -> Gate {
    if !hgemm {
        Gate::Off(OffKind::Mode, "the fp16 path is off (hgemm): the f32 LM head is one matrix-vector product per span")
    } else if per_span_env {
        Gate::Off(OffKind::OptOut, "INK_PER_SPAN_LOGITS=1")
    } else {
        Gate::On
    }
}

/// The engine's per-step predicate: [`batched_span_logits_gate`] on a prefill step with more than one span that
/// reads logits. One span writes its own logits row (`ar.logits`); decode and verify have their own heads.
pub const fn span_logits_batch_step(hgemm: bool, per_span: bool, spans: usize, wanted: usize) -> bool {
    batched_span_logits_gate(hgemm, per_span).is_on() && spans > 1 && wanted > 0
}

/// Separate split-attention combine pass (`serve` refuses to start without it).
pub const fn sep_comb_gate(sep_comb: bool) -> Gate {
    if sep_comb {
        Gate::On
    } else {
        Gate::Off(OffKind::OptOut, "INK_FUSE_COMB")
    }
}

/// Router top-k fused into the router pass.
pub const fn fused_topk_gate(sep_topk: bool) -> Gate {
    if sep_topk {
        Gate::Off(OffKind::OptOut, "INK_SEP_TOPK")
    } else {
        Gate::On
    }
}

/// Shared-K/V grouped decode attention (`k_attn_grp_dec`).
pub const fn grouped_decode_attn_gate(no_grp_dec: bool) -> Gate {
    if no_grp_dec {
        Gate::Off(OffKind::OptOut, "INK_NO_GRP_DEC")
    } else {
        Gate::On
    }
}

/// Right-sized single-read grouped MoE decode (`k_moe_dec_sg4/sg8`), configuration part (per step it also needs
/// `Engine::want_decode_sized`).
pub const fn grouped_moe_decode_gate(hgemm: bool, old_moe_dec_env: bool) -> Gate {
    if !hgemm {
        Gate::Off(OffKind::Mode, "the fp16 path is off (hgemm)")
    } else if old_moe_dec_env {
        Gate::Off(OffKind::OptOut, "INK_OLD_MOE_DEC")
    } else {
        Gate::On
    }
}

/// Multi-token grouped tiles of the grouped MoE decode (`INK_NO_GRP_MOE` falls back to `cnt = 1` tiles).
pub const fn grouped_moe_tiles_gate(no_grp_moe: bool) -> Gate {
    if no_grp_moe {
        Gate::Off(OffKind::OptOut, "INK_NO_GRP_MOE")
    } else {
        Gate::On
    }
}

/// Decode-sized dense fp16 GEMMs (`Engine::gemm_h_dec`), configuration part.
pub const fn decode_gemm_gate(old_moe_dec_env: bool) -> Gate {
    if old_moe_dec_env {
        Gate::Off(OffKind::OptOut, "INK_OLD_MOE_DEC")
    } else {
        Gate::On
    }
}

/// Decode's fixed-cost cuts (`INK_DEC_FIXED_COST`, on by default, #297): one `k_mix_wave` dispatch for every job of a
/// mixer, the 4 KiB-ring sg4 dense decode GEMMs, and the format-specialised kernel for a uniform multi-segment GEMM
/// (fused QKV). Bit-identical to the opt-out.
pub const fn dec_fixed_cost_gate(dec_fixed_cost: bool) -> Gate {
    if dec_fixed_cost {
        Gate::On
    } else {
        Gate::Off(OffKind::OptOut, "INK_DEC_FIXED_COST=0")
    }
}

/// Layers per command buffer of a chunked plain decode step (`INK_CB_CHUNK`, [`cb_chunk_layers`]) when the variable
/// is unset: the GPU starts on the first layers while the CPU encodes the rest (`Engine::encode_decode_chunked`).
pub const CB_CHUNK_DEFAULT: usize = 8;

/// `INK_CB_CHUNK`: unset is [`CB_CHUNK_DEFAULT`]; `0` opts out (one command buffer per decode step, as before); any
/// other layer count commits every that many layers. Anything else is an error naming the variable.
pub fn cb_chunk_layers(value: Option<&str>) -> Result<usize, String> {
    match value {
        None => Ok(CB_CHUNK_DEFAULT),
        Some(v) => v.parse().map_err(|_| format!("INK_CB_CHUNK={v:?} is not a layer count")),
    }
}

/// Chunked plain decode commits (`INK_CB_CHUNK`, on by default): the same kernels in the same queue order, so the
/// logits are bit-identical (`inky dbatch` with `INK_DB_CHUNK` checks every row).
pub const fn chunked_decode_commits_gate(cb_chunk: usize) -> Gate {
    if cb_chunk > 0 {
        Gate::On
    } else {
        Gate::Off(OffKind::OptOut, "INK_CB_CHUNK=0")
    }
}

/// Parallel CPU sampling (`INK_PARALLEL_CPU_SAMPLE`, on by default): the decode rows of a step that take neither GPU
/// sampling path draw on scoped threads, each with its own lane's sampler, so the tokens are the serial ones.
pub const fn parallel_cpu_sample_gate(parallel_cpu_sample: bool) -> Gate {
    if parallel_cpu_sample {
        Gate::On
    } else {
        Gate::Off(OffKind::OptOut, "INK_PARALLEL_CPU_SAMPLE=0")
    }
}

/// Concurrent batched mixer jobs (`k_mix_b_*`).
pub const fn batched_mix_gate(old_mixb_env: bool) -> Gate {
    if old_mixb_env {
        Gate::Off(OffKind::OptOut, "INK_OLD_MIXB")
    } else {
        Gate::On
    }
}

/// 16 query rows per tensor-core attention threadgroup (`prefill_attn_grid`); `--full-attn-budget` drops to 1.
pub const fn tc_attn_row_blocks_gate(full_attn_budget: bool) -> Gate {
    if full_attn_budget {
        Gate::Off(OffKind::Missing, "--full-attn-budget: one query row per threadgroup")
    } else {
        Gate::On
    }
}

/// Why the implicit sparse decode configuration is disabled for this mode.
pub const fn default_sparse_topk_dropped_by(exact: bool, full_attn_budget: bool, kv8: bool) -> Option<Gate> {
    if exact {
        Some(Gate::Off(OffKind::Mode, "--exact: sparse retrieval is approximate"))
    } else if full_attn_budget {
        Some(Gate::Off(OffKind::Mode, "--full-attn-budget: one far-key pruning scheme at a time"))
    } else if kv8 {
        Some(Gate::Off(OffKind::Default, "off by default for KV8: M5 70K sparse decode K128/A16 failed KL \
            (p99.9 0.09239 vs 0.05, 5 positions above 0.05, allowed 0); --sparse-topk K opts in"))
    } else {
        None
    }
}

/// The resolved engine setting and the command-line choice determine the startup report.
fn sparse_topk_gate(i: &Inputs) -> Gate {
    if i.sparse_topk {
        return Gate::On;
    }
    let implicit_kv8 = i.kv8 && !i.serve.no_sparse_topk;
    match default_sparse_topk_dropped_by(i.exact, i.full_attn_budget, implicit_kv8) {
        Some(g) => g,
        None => Gate::Off(OffKind::OptOut, "--sparse-topk off"),
    }
}

/// Sparse top-k prefill attention (`INK_SPARSE_PREFILL`, `src/engine/sparse_prefill.rs`), for query blocks past
/// `INK_SPARSE_PREFILL_MIN_CTX` (65,536 tokens by default, the `--sparse-min-ctx` default): off by default, measured
/// slower and over the long-context KL limit on the M5 ([`SPARSE_PREFILL_DEFAULT_OFF`]); `INK_SPARSE_PREFILL=1` opts in. It needs tensor-core prefill attention (the masked kernel is
/// `k_attn_tc_fixed_blk`), the `--sparse-topk` block sketches and no `--full-attn-budget`. `Engine::encode_spans`
/// calls this per span pass with that step's `tc_attn`; a span past the floor that it turns away runs dense and
/// counts a fallback. The report gives a missing prerequisite the kind of that prerequisite's own gate.
pub const SPARSE_PREFILL_DEFAULT_OFF: &str = "off by default: on the M5 (Stella, e8bca79d, 70K production-model probe; \
72 sparse passes, 27.2% of causal blocks kept, no dense fallbacks) it was slower (prefill 62.2 s vs 54.0 s dense) and \
failed long-context KL (mean 0.01314 vs limit 0.01, max 0.58772 at token 70052 vs limit 0.10, 6 positions over 0.05); \
INK_SPARSE_PREFILL=1 opts in";

pub const fn sparse_prefill_gate(on_env: bool, tc_prefill_attn: bool, sparse_topk: bool, full_attn_budget: bool) -> Gate {
    if !on_env {
        Gate::Off(OffKind::Default, SPARSE_PREFILL_DEFAULT_OFF)
    } else if !tc_prefill_attn {
        Gate::Off(OffKind::Mode, "tensor-core prefill attention is off (tc_prefill_attn): the mask lives in that kernel")
    } else if !sparse_topk {
        Gate::Off(OffKind::Mode, "--sparse-topk is off: no block sketches to select by")
    } else if full_attn_budget {
        Gate::Off(OffKind::Mode, "--full-attn-budget: one far-key pruning scheme at a time")
    } else {
        Gate::On
    }
}

/// `INK_TC_EXP2` (`TC_ATT_EXP2` in `prefill.metal`): the tensor-core prefill softmax in log2 units, `exp2` for `exp`.
/// An inexact reordering of the float math, so KV8 only (`--kv8` promises no bits; FP16 and KV4 keep theirs); the
/// switch is off by default (it fails the M5 confident-KL bound, see the reason) and `INK_TC_EXP2=1` opts in under
/// `--kv8`. `tc_softmax_defines` in `engine.rs` compiles
/// the define exactly when this is on with `tc_prefill_attn = true`; the report also names tensor-core prefill
/// attention being off, when the define would sit in kernels that never run.
pub const fn tc_exp2_gate(on_env: bool, kv8: bool, tc_prefill_attn: bool) -> Gate {
    tc_softmax_reorder_gate(
        on_env,
        kv8,
        tc_prefill_attn,
        "off by default: under --kv8 it fails the M5 TC-vs-simdgroup confident-KL bound (two confident positions \
         at KL ~0.0019 vs 1e-4; with both reorderings off worst 0.017 vs the scalar reference 0.061, 48/48 top-1; \
         Stella at 241e1355); INK_TC_EXP2=1 opts in under --kv8",
    )
}

/// `INK_TC_LAZY_RESCALE` (`TC_ATT_LAZY_RESCALE`): a row's reference max moves only when the tile max passes it by more
/// than 8, so most tiles skip the `O *= alpha` pass. Inexact, KV8 only, off by default (M5 confident-KL bound),
/// `INK_TC_LAZY_RESCALE=1` opts in, as [`tc_exp2_gate`].
pub const fn tc_lazy_rescale_gate(on_env: bool, kv8: bool, tc_prefill_attn: bool) -> Gate {
    tc_softmax_reorder_gate(
        on_env,
        kv8,
        tc_prefill_attn,
        "off by default: under --kv8 it fails the M5 TC-vs-simdgroup confident-KL bound (step 17 KL 0.01277 vs \
         1e-4; with both reorderings off worst 0.017 vs the scalar reference 0.061, 48/48 top-1; Stella at \
         241e1355); INK_TC_LAZY_RESCALE=1 opts in under --kv8",
    )
}

/// Off outside KV8 is the cache format's rule, not a lost path: FP16 and KV4 promise their softmax order. It is
/// reported as `default_off`, which the policy accepts, so a default FP16/KV4 serve starts under
/// `INK_REQUIRE_FAST_PATHS=1`.
const fn tc_softmax_reorder_gate(on_env: bool, kv8: bool, tc_prefill_attn: bool, default_off: &'static str) -> Gate {
    if !kv8 {
        Gate::Off(OffKind::Default, "KV8 only: FP16 and KV4 keep the exact softmax order")
    } else if !on_env {
        Gate::Off(OffKind::Default, default_off)
    } else if !tc_prefill_attn {
        Gate::Off(OffKind::Mode, "tensor-core prefill attention is off (tc_prefill_attn): the reordering lives in that kernel")
    } else {
        Gate::On
    }
}

/// Approximate Zero-RoPE K/V stitching across turns and cartridges.
pub const fn kv_stitch_gate(kv_stitch: bool, exact: bool) -> Gate {
    if kv_stitch {
        Gate::On
    } else if exact {
        Gate::Off(OffKind::Mode, "--exact: stitched K/V is approximate")
    } else {
        Gate::Off(OffKind::OptOut, "--no-kv-stitch")
    }
}

/// Attention projections as the GGUF's GEMMs alone. `INK_LORA` (an experiment arm) adds a runtime LoRA beside
/// q / k / v / o: two more dispatches after each projection group (`Engine::lora_apply`), every other path kept.
pub const fn attn_proj_plain_gate(lora: bool) -> Gate {
    if lora {
        Gate::Off(OffKind::OptOut, "INK_LORA: y += scale * B (A x) beside q/k/v/o, two extra dispatches per projection group")
    } else {
        Gate::On
    }
}

/// Mixed prefill+decode steps (`INK_MIXED_STEPS`, on by default): when a prefill step runs while decoders wait,
/// the decoders ride it as leading 1-token rows. Under speculative verify (`--dspark`, `INK_PROMPT_LOOKUP`) a rider
/// decodes one plain token in the mixed step and verifies on decode steps; per step a runnable LoopCD lane plans
/// homogeneous steps (`allow_mixed` in `serve.rs`).
pub const fn mixed_steps_gate(mixed_steps: bool) -> Gate {
    if mixed_steps {
        Gate::On
    } else {
        Gate::Off(OffKind::OptOut, "INK_MIXED_STEPS=0")
    }
}

/// Prefill spans run through their start-point checkpoints (`serve/checkpoint.rs`): the step keeps the conv state
/// at each checkpoint inside a span instead of ending the span there, so a prompt's last partial block rides the
/// body's step. `INK_PREFILL_CKPT_SPLIT=1` restores the split.
pub const fn prefill_through_checkpoints_gate(ckpt_split_env: bool) -> Gate {
    if ckpt_split_env {
        Gate::Off(OffKind::OptOut, "INK_PREFILL_CKPT_SPLIT=1")
    } else {
        Gate::On
    }
}

/// Why `/v1/messages` thinking echo is off by default: the matched M5 pair.
pub const MESSAGES_ECHO_THINKING_DEFAULT_OFF: &str = "off by default: on a matched M5 pair (Stella) the echo ran (messages_thinking_echoed_total 0 -> 1) but the prompt \
grew 7,783 -> 8,014 tokens with the restored prefix unchanged at 7,680, fresh rows 103 -> 334, TTFT 120 -> 209 ms, and \
the visible answers were byte-identical: cost with no reuse or answer benefit shown; INK_MESSAGES_ECHO_THINKING=1 opts in";

/// `/v1/messages` renders inky's own signed thinking blocks back into the prompt, so the next turn meets the lane's
/// kept K/V to the end of the previous reply. Off by default ([`MESSAGES_ECHO_THINKING_DEFAULT_OFF`]): sent
/// thinking blocks are dropped, as before #239. `INK_MESSAGES_ECHO_THINKING=1` opts in.
pub const fn messages_echo_thinking_gate(echo_thinking: bool) -> Gate {
    if echo_thinking {
        Gate::On
    } else {
        Gate::Off(OffKind::Default, MESSAGES_ECHO_THINKING_DEFAULT_OFF)
    }
}

/// Retained start points are evicted by demonstrated reuse per byte under the card lease (`EvictionRank` in
/// `serve/block_cache.rs`); `INK_RETAIN_LRU=1` evicts by plain LRU, as before.
pub const fn retain_reuse_rank_gate(retain_lru: bool) -> Gate {
    if retain_lru {
        Gate::Off(OffKind::OptOut, "INK_RETAIN_LRU=1")
    } else {
        Gate::On
    }
}

/// Serve-side settings the engine cannot see; `serve` fills them from its options ([`ServeFlags::default`] is
/// `inky serve`'s default).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ServeFlags {
    /// The operator explicitly selected `--no-sparse-topk`.
    pub no_sparse_topk: bool,
    /// `INK_MIXED_STEPS` (default on).
    pub mixed_steps: bool,
    /// A speculative verify runtime: `--dspark` or `INK_PROMPT_LOOKUP=1`.
    pub spec_verify: bool,
    /// `INK_MESSAGES_ECHO_THINKING` (default off).
    pub echo_thinking: bool,
    /// `INK_RETAIN_LRU` (default off: reuse ranking on).
    pub retain_lru: bool,
}

impl Default for ServeFlags {
    fn default() -> ServeFlags {
        ServeFlags {
            no_sparse_topk: false,
            mixed_steps: true,
            spec_verify: false,
            echo_thinking: crate::engine::switches::default_of("INK_MESSAGES_ECHO_THINKING"),
            retain_lru: crate::engine::switches::default_of("INK_RETAIN_LRU"),
        }
    }
}

/// Environment switches the report reads. The engine reads the same names at load or step time.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct EnvFlags {
    pub disable_mpp: bool,
    pub no_tensor: bool,
    pub no_hgemm: bool,
    pub no_tc_attn: bool,
    /// `INK_TC_ATTN_DEC`: `None` unset (on for FP16/KV8, off for KV4), `Some(true)` forced on, `Some(false)` the
    /// explicit opt-out.
    pub tc_attn_dec: Option<bool>,
    pub old_moe_dec: bool,
    pub old_moe_rg: bool,
    pub old_mixb: bool,
    pub generic_moe: bool,
    pub tc_exp2: bool,
    pub tc_lazy_rescale: bool,
    pub prefill_ckpt_split: bool,
    pub per_span_logits: bool,
    /// `INK_MIXED_TAIL_TRIM` (default on).
    pub mixed_tail_trim: bool,
    /// `INK_PARALLEL_CPU_SAMPLE` (default on).
    pub parallel_cpu_sample: bool,
    /// `INK_CB_CHUNK` layers per decode command buffer ([`cb_chunk_layers`]; unset [`CB_CHUNK_DEFAULT`], `0` off).
    /// A value serve refuses reads as the default here.
    pub cb_chunk: usize,
    /// `INK_DEC_FIXED_COST` (default on).
    pub dec_fixed_cost: bool,
}

/// Every switch unset: each at its default (`engine::switches::SWITCHES`).
impl Default for EnvFlags {
    fn default() -> EnvFlags {
        EnvFlags::read(|_| None)
    }
}

impl EnvFlags {
    /// Read through `get` (the process environment in production): every name is a `0`/`1` switch
    /// (`engine::switches`), unset taking its default.
    pub fn read(get: impl Fn(&str) -> Option<String>) -> EnvFlags {
        let on = |name: &str| crate::engine::switches::value(name, get(name).as_deref());
        EnvFlags {
            disable_mpp: on("INKY_DISABLE_MPP"),
            no_tensor: on("INK_NO_TENSOR"),
            no_hgemm: on("INK_NO_HGEMM"),
            no_tc_attn: on("INK_NO_TC_ATTN"),
            tc_attn_dec: crate::engine::switches::setting("INK_TC_ATTN_DEC", get("INK_TC_ATTN_DEC").as_deref()),
            old_moe_dec: on("INK_OLD_MOE_DEC"),
            old_mixb: on("INK_OLD_MIXB"),
            generic_moe: on("INK_GENERIC_MOE"),
            tc_exp2: on("INK_TC_EXP2"),
            tc_lazy_rescale: on("INK_TC_LAZY_RESCALE"),
            prefill_ckpt_split: on("INK_PREFILL_CKPT_SPLIT"),
            old_moe_rg: on("INK_OLD_MOE_RG"),
            per_span_logits: on("INK_PER_SPAN_LOGITS"),
            mixed_tail_trim: on("INK_MIXED_TAIL_TRIM"),
            parallel_cpu_sample: on("INK_PARALLEL_CPU_SAMPLE"),
            cb_chunk: cb_chunk_layers(get("INK_CB_CHUNK").as_deref()).unwrap_or(CB_CHUNK_DEFAULT),
            dec_fixed_cost: on("INK_DEC_FIXED_COST"),
        }
    }
    pub fn from_process() -> EnvFlags {
        Self::read(|name| std::env::var_os(name).map(|v| v.to_string_lossy().into_owned()))
    }
}

/// Everything the report depends on: the engine's resolved settings, the serve options and the expert formats.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Inputs {
    pub no_mpp_flag: bool,
    pub tuning_use_mpp: bool,
    /// Engine `use_mpp` after load.
    pub use_mpp: bool,
    /// Engine `hgemm` after load (and the `layout_ok` fallback).
    pub hgemm: bool,
    pub exact: bool,
    pub kv4: bool,
    pub kv8: bool,
    pub sep_comb: bool,
    pub sep_topk: bool,
    pub tail: bool,
    pub no_grp_dec: bool,
    pub no_grp_moe: bool,
    pub full_attn_budget: bool,
    pub sparse_topk: bool,
    /// `INK_SPARSE_PREFILL` as the engine parsed it at load.
    pub sparse_prefill: bool,
    pub kv_stitch: bool,
    /// a runtime LoRA adapter is loaded (`INK_LORA`)
    pub lora: bool,
    /// `(gate/up, down)` weight type of each layer's experts.
    pub expert_types: Vec<(u32, u32)>,
    pub env: EnvFlags,
    pub serve: ServeFlags,
}

impl Inputs {
    #[cfg(test)]
    /// The default `inky serve` configuration on an M5 (KV4, sparse top-k, stitching), Q4_K / Q8_0 experts.
    pub fn serve_default() -> Inputs {
        Inputs {
            no_mpp_flag: false,
            tuning_use_mpp: true,
            use_mpp: true,
            hgemm: true,
            exact: false,
            kv4: true,
            kv8: false,
            sep_comb: true,
            sep_topk: false,
            tail: true,
            no_grp_dec: false,
            no_grp_moe: false,
            full_attn_budget: false,
            sparse_topk: true,
            sparse_prefill: crate::engine::switches::default_of("INK_SPARSE_PREFILL"),
            kv_stitch: true,
            lora: false,
            expert_types: vec![(T_Q4_K, T_Q8_0); 2],
            env: EnvFlags::default(),
            serve: ServeFlags::default(),
        }
    }
}

impl crate::engine::Engine {
    /// The report inputs of this loaded engine, read the way the engine reads them: its resolved settings, the
    /// process environment, and the serve option it cannot see (`--kv-stitch`). `--no-mpp` is read from
    /// `DISABLE_MPP`, the switch `into_engine_mode` itself read when it chose `use_mpp`.
    pub fn fast_path_inputs(&self, kv_stitch: bool) -> Inputs {
        let (chip, mem) = crate::tuning::this_machine();
        Inputs {
            no_mpp_flag: crate::engine::DISABLE_MPP.load(std::sync::atomic::Ordering::Relaxed),
            tuning_use_mpp: crate::tuning::select(&chip, mem).use_mpp,
            use_mpp: self.use_mpp,
            hgemm: self.hgemm,
            exact: self.exact,
            kv4: self.kv4,
            kv8: self.kv8,
            sep_comb: self.sep_comb,
            sep_topk: self.sep_topk,
            tail: self.tail.get(),
            no_grp_dec: self.no_grp_dec.get(),
            no_grp_moe: self.no_grp_moe.get(),
            full_attn_budget: self.full_attn_budget().is_some(),
            sparse_topk: self.sparse_topk().is_some(),
            sparse_prefill: self.sparse_prefill().is_some(),
            kv_stitch,
            lora: !self.lora.is_empty(),
            expert_types: self.layers.iter().map(|l| (l.gu.ty, l.dn.ty)).collect(),
            env: EnvFlags::from_process(),
            serve: ServeFlags::default(),
        }
    }
}

/// One fast path's state.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FastPath {
    pub id: &'static str,
    pub what: &'static str,
    pub on: bool,
    pub kind: Option<OffKind>,
    pub reason: Option<String>,
}

/// Every fast path, in a fixed order.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Report {
    pub paths: Vec<FastPath>,
}

/// Every id the report can carry (`INK_FAST_PATH_OPT_OUT` accepts these).
pub const IDS: [&str; 31] = [
    "mpp_tensor",
    "hgemm",
    "tc_prefill_attn",
    "tc_decode_attn",
    "tail_trim",
    "mixed_tail_trim",
    "batched_span_logits",
    "sep_comb",
    "fused_topk",
    "grouped_decode_attn",
    "grouped_moe_decode",
    "grouped_moe_tiles",
    "decode_gemm",
    "batched_mix",
    "parallel_cpu_sample",
    "chunked_decode_commits",
    "dec_fixed_cost",
    "moe_prefill_specialised",
    "moe_decode_specialised",
    "moe_decode_rg",
    "tc_attn_row_blocks",
    "sparse_topk",
    "sparse_prefill",
    "kv_stitch",
    "attn_proj_plain",
    "tc_exp2",
    "tc_lazy_rescale",
    "mixed_steps",
    "prefill_through_checkpoints",
    "messages_echo_thinking",
    "retain_reuse_rank",
];

fn path(id: &'static str, what: &'static str, gate: Gate) -> FastPath {
    match gate {
        Gate::On => FastPath { id, what, on: true, kind: None, reason: None },
        Gate::Off(kind, why) => FastPath { id, what, on: false, kind: Some(kind), reason: Some(why.to_string()) },
    }
}

fn type_name(ty: u32) -> String {
    match ty {
        T_Q4_K => "Q4_K".into(),
        T_Q5_0 => "Q5_0".into(),
        T_Q6_K => "Q6_K".into(),
        T_Q8_0 => "Q8_0".into(),
        T_Q2_K => "Q2_K".into(),
        T_Q3_K => "Q3_K".into(),
        T_Q3_0 => "Q3_0".into(),
        T_NV4 => "NV4".into(),
        T_MX8 => "MX8".into(),
        T_BF16 => "BF16".into(),
        other => format!("type {other}"),
    }
}

/// Expert formats that take a generic kernel: `kernel(ty, situ)` is the engine's own selector, `generic` its
/// fallback name. `None` when every expert tensor has a specialised kernel.
fn generic_formats(types: &[(u32, u32)], kernel: impl Fn(u32, bool) -> &'static str, generic: &str) -> Option<String> {
    let mut hits: Vec<String> = Vec::new();
    for &(gu, dn) in types {
        for (ty, situ, part) in [(gu, true, "gate/up"), (dn, false, "down")] {
            if kernel(ty, situ) == generic {
                let s = format!("{part} {}", type_name(ty));
                if !hits.contains(&s) {
                    hits.push(s);
                }
            }
        }
    }
    (!hits.is_empty()).then(|| hits.join(", "))
}

/// `sparse_prefill` in the report: off for a missing prerequisite takes that prerequisite's kind, so an explicit
/// `INK_NO_TC_ATTN` or `--no-sparse-topk` stays an accepted opt-out and `--exact` stays a mode.
fn sparse_prefill_report_gate(i: &Inputs) -> Gate {
    let tc_prefill = tc_prefill_attn_gate(i.hgemm, i.exact, i.env.no_tc_attn);
    let sparse_topk = sparse_topk_gate(i);
    match sparse_prefill_gate(i.sparse_prefill, tc_prefill.is_on(), i.sparse_topk, i.full_attn_budget) {
        Gate::Off(OffKind::Mode, why) => {
            let kind = match (tc_prefill, sparse_topk) {
                (Gate::Off(kind, _), _) | (Gate::On, Gate::Off(kind, _)) => kind,
                (Gate::On, Gate::On) => OffKind::Mode,
            };
            Gate::Off(kind, why)
        }
        g => g,
    }
}

/// A path off as a mode because its prerequisite is off takes the prerequisite's kind (an explicit `INK_NO_TC_ATTN`
/// stays an accepted opt-out, `--exact` a mode).
fn inherit_mode(g: Gate, prerequisite: Gate) -> Gate {
    match (g, prerequisite) {
        (Gate::Off(OffKind::Mode, why), Gate::Off(kind, _)) => Gate::Off(kind, why),
        (g, _) => g,
    }
}

/// The fast-path report for `i`.
pub fn report(i: &Inputs) -> Report {
    let env = i.env;
    let mut paths = vec![
        path("mpp_tensor", "Metal 4 tensor kernels", mpp_gate(i.no_mpp_flag, env.disable_mpp, env.no_tensor, i.tuning_use_mpp)),
    ];
    // `hgemm` as resolved; when it is off with MPP on and no INK_NO_HGEMM, the layout probe turned it off.
    let layout_ok = i.hgemm || !i.use_mpp || env.no_hgemm;
    paths.push(path("hgemm", "fp16 prefill GEMMs and half attention I/O", hgemm_gate(i.use_mpp, env.no_hgemm, layout_ok)));
    paths.push(path(
        "tc_prefill_attn",
        "tensor-core prefill attention",
        tc_prefill_attn_gate(i.hgemm, i.exact, env.no_tc_attn),
    ));
    paths.push(path(
        "tc_decode_attn",
        "tensor-core decode attention",
        tc_decode_attn_gate(i.hgemm, i.exact, env.no_tc_attn, env.tc_attn_dec, i.kv4),
    ));
    paths.push(path("tail_trim", "last-layer tail trim (prefill, one or many spans)", tail_trim_gate(i.hgemm, i.tail)));
    paths.push(path(
        "mixed_tail_trim",
        "last-layer tail trim on mixed steps (prefill spans trimmed, decode rows whole)",
        mixed_tail_trim_gate(i.hgemm, i.tail, i.serve.mixed_steps, env.mixed_tail_trim),
    ));
    paths.push(path(
        "batched_span_logits",
        "one LM-head GEMM for a multi-span prefill step's logits rows",
        batched_span_logits_gate(i.hgemm, env.per_span_logits),
    ));
    paths.push(path("sep_comb", "separate split-attention combine", sep_comb_gate(i.sep_comb)));
    paths.push(path("fused_topk", "router top-k fused into the router", fused_topk_gate(i.sep_topk)));
    paths.push(path("grouped_decode_attn", "shared-K/V grouped decode attention", grouped_decode_attn_gate(i.no_grp_dec)));
    paths.push(path(
        "grouped_moe_decode",
        "grouped single-read MoE decode",
        grouped_moe_decode_gate(i.hgemm, env.old_moe_dec),
    ));
    paths.push(path("grouped_moe_tiles", "multi-token grouped MoE decode tiles", grouped_moe_tiles_gate(i.no_grp_moe)));
    paths.push(path("decode_gemm", "decode-sized dense fp16 GEMMs", decode_gemm_gate(env.old_moe_dec)));
    paths.push(path("batched_mix", "concurrent batched mixer jobs", batched_mix_gate(env.old_mixb)));
    paths.push(path(
        "parallel_cpu_sample",
        "a step's CPU-sampled decode rows drawn on scoped threads (each lane's own RNG stream)",
        parallel_cpu_sample_gate(env.parallel_cpu_sample),
    ));
    paths.push(path(
        "chunked_decode_commits",
        "plain decode steps committed every INK_CB_CHUNK layers (GPU starts while the CPU encodes)",
        chunked_decode_commits_gate(env.cb_chunk),
    ));
    paths.push(path(
        "dec_fixed_cost",
        "decode fixed-cost cuts: one k_mix_wave per mixer, 4 KiB sg4 GEMM ring, specialised uniform multi-segment GEMMs",
        dec_fixed_cost_gate(env.dec_fixed_cost),
    ));
    // The prefill MoE kernels exist only on the fp16 path; there the selector is `moe_sg_kernel_for`.
    let prefill_moe = if !i.hgemm {
        path("moe_prefill_specialised", "format-specialised prefill MoE", Gate::Off(OffKind::Mode, "the fp16 path is off (hgemm)"))
    } else if env.generic_moe {
        path("moe_prefill_specialised", "format-specialised prefill MoE", Gate::Off(OffKind::OptOut, "INK_GENERIC_MOE"))
    } else {
        let generic = crate::engine::moe_sg_kernel_for(1, u32::MAX, true, false);
        match generic_formats(&i.expert_types, |ty, situ| crate::engine::moe_sg_kernel_for(1, ty, situ, false), generic) {
            None => path("moe_prefill_specialised", "format-specialised prefill MoE", Gate::On),
            Some(fmts) => FastPath {
                id: "moe_prefill_specialised",
                what: "format-specialised prefill MoE",
                on: false,
                kind: Some(OffKind::Missing),
                reason: Some(format!("no specialised prefill MoE kernel for experts {fmts}")),
            },
        }
    };
    paths.push(prefill_moe);
    let decode_moe = if !grouped_moe_decode_gate(i.hgemm, env.old_moe_dec).is_on() {
        path(
            "moe_decode_specialised",
            "format-specialised grouped MoE decode",
            Gate::Off(OffKind::Mode, "grouped MoE decode is off (grouped_moe_decode)"),
        )
    } else {
        let generic = crate::engine::moe_dec_sg4_kernel(u32::MAX, true);
        match generic_formats(&i.expert_types, crate::engine::moe_dec_sg4_kernel, generic) {
            None => path("moe_decode_specialised", "format-specialised grouped MoE decode", Gate::On),
            Some(fmts) => FastPath {
                id: "moe_decode_specialised",
                what: "format-specialised grouped MoE decode",
                on: false,
                kind: Some(OffKind::Missing),
                reason: Some(format!("no specialised decode MoE kernel for experts {fmts}")),
            },
        }
    };
    paths.push(decode_moe);
    // class 1 (1..=64 tokens per expert) of the grouped decode on the register-fed kernels (`Engine::moe_rg_on`)
    const RG_WHAT: &str = "register-fed MoE decode (1..=64 tokens per expert)";
    let rg = if !grouped_moe_decode_gate(i.hgemm, env.old_moe_dec).is_on() {
        path("moe_decode_rg", RG_WHAT, Gate::Off(OffKind::Mode, "grouped MoE decode is off (grouped_moe_decode)"))
    } else if env.old_moe_rg {
        path("moe_decode_rg", RG_WHAT, Gate::Off(OffKind::OptOut, "INK_OLD_MOE_RG"))
    } else {
        let none = |ty: u32, situ: bool| match crate::engine::moe_dec_rg_kernel(crate::engine::MOE_RG_NSG, ty, situ) {
            Some(_) => "",
            None => "-",
        };
        match generic_formats(&i.expert_types, none, "-") {
            None => path("moe_decode_rg", RG_WHAT, Gate::On),
            Some(fmts) => FastPath {
                id: "moe_decode_rg",
                what: RG_WHAT,
                on: false,
                kind: Some(OffKind::Missing),
                reason: Some(format!("no register-fed decode MoE kernel for experts {fmts}")),
            },
        }
    };
    paths.push(rg);
    paths.push(path(
        "tc_attn_row_blocks",
        "16 query rows per tensor-core attention threadgroup",
        tc_attn_row_blocks_gate(i.full_attn_budget),
    ));
    paths.push(path(
        "sparse_topk",
        "sparse top-k full attention past --sparse-min-ctx",
        sparse_topk_gate(i),
    ));
    paths.push(path(
        "sparse_prefill",
        "sparse top-k prefill attention past INK_SPARSE_PREFILL_MIN_CTX",
        sparse_prefill_report_gate(i),
    ));
    paths.push(path("kv_stitch", "stitched K/V reuse", kv_stitch_gate(i.kv_stitch, i.exact)));
    paths.push(path("attn_proj_plain", "attention projections without runtime-LoRA side kernels", attn_proj_plain_gate(i.lora)));
    let tc_prefill = tc_prefill_attn_gate(i.hgemm, i.exact, env.no_tc_attn);
    paths.push(path(
        "tc_exp2",
        "exp2 softmax in tensor-core prefill attention (inexact, KV8)",
        inherit_mode(tc_exp2_gate(env.tc_exp2, i.kv8, tc_prefill.is_on()), tc_prefill),
    ));
    paths.push(path(
        "tc_lazy_rescale",
        "lazy O rescale in tensor-core prefill attention (inexact, KV8)",
        inherit_mode(tc_lazy_rescale_gate(env.tc_lazy_rescale, i.kv8, tc_prefill.is_on()), tc_prefill),
    ));
    paths.push(path(
        "mixed_steps",
        "mixed prefill+decode steps (decoders ride prefill steps)",
        mixed_steps_gate(i.serve.mixed_steps),
    ));
    paths.push(path(
        "prefill_through_checkpoints",
        "prefill spans run through start-point checkpoints (no lone tail steps)",
        prefill_through_checkpoints_gate(env.prefill_ckpt_split),
    ));
    paths.push(path(
        "messages_echo_thinking",
        "/v1/messages renders inky's own thinking back (whole-reply prefix reuse)",
        messages_echo_thinking_gate(i.serve.echo_thinking),
    ));
    paths.push(path(
        "retain_reuse_rank",
        "retained starts evicted by reuse per byte under the card lease (not plain LRU)",
        retain_reuse_rank_gate(i.serve.retain_lru),
    ));
    Report { paths }
}

/// The `INK_REQUIRE_FAST_PATHS` policy: refuse to start when a path is off for a reason other than an explicit
/// opt-out naming it, a measured default, or an id listed in `INK_FAST_PATH_OPT_OUT`.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Policy {
    pub require: bool,
    pub opt_out: Vec<String>,
}

impl Policy {
    /// Read `INK_REQUIRE_FAST_PATHS` (`0` or `1`) and `INK_FAST_PATH_OPT_OUT` (comma-separated report ids).
    pub fn read(get: impl Fn(&str) -> Option<String>) -> Result<Policy, String> {
        let require = match get("INK_REQUIRE_FAST_PATHS").as_deref() {
            None | Some("") | Some("0") => false,
            Some("1") => true,
            Some(_) => return Err("INK_REQUIRE_FAST_PATHS must be 0 or 1".into()),
        };
        let mut opt_out = Vec::new();
        for id in get("INK_FAST_PATH_OPT_OUT").unwrap_or_default().split(',').map(str::trim).filter(|s| !s.is_empty()) {
            if !IDS.contains(&id) {
                return Err(format!("INK_FAST_PATH_OPT_OUT: unknown fast path {id:?} (known: {})", IDS.join(", ")));
            }
            opt_out.push(id.to_string());
        }
        Ok(Policy { require, opt_out })
    }
}

impl Report {
    #[cfg(test)]
    pub fn get(&self, id: &str) -> Option<&FastPath> {
        self.paths.iter().find(|p| p.id == id)
    }

    /// Paths that are off for a reason the policy does not accept: anything but an explicit opt-out naming the path
    /// or a measured default, unless the id is in `opt_out`.
    pub fn unaccepted<'a>(&'a self, policy: &Policy) -> Vec<&'a FastPath> {
        self.paths
            .iter()
            .filter(|p| !p.on)
            .filter(|p| !matches!(p.kind, Some(OffKind::OptOut | OffKind::Default)))
            .filter(|p| !policy.opt_out.iter().any(|o| o == p.id))
            .collect()
    }

    /// `/health` `fast_paths`: `{ id: { "on": bool, "kind": ..., "reason": ... } }` plus `off` and `unaccepted` counts.
    pub fn to_json(&self, policy: &Policy) -> serde_json::Value {
        let mut paths = serde_json::Map::new();
        for p in &self.paths {
            let mut o = serde_json::Map::new();
            o.insert("on".into(), serde_json::json!(p.on));
            if let Some(k) = p.kind {
                o.insert("kind".into(), serde_json::json!(k.name()));
            }
            if let Some(r) = &p.reason {
                o.insert("reason".into(), serde_json::json!(r));
            }
            paths.insert(p.id.into(), serde_json::Value::Object(o));
        }
        let unaccepted: Vec<&str> = self.unaccepted(policy).iter().map(|p| p.id).collect();
        serde_json::json!({
            "paths": paths,
            "off": self.paths.iter().filter(|p| !p.on).count(),
            "unaccepted": unaccepted,
            "require": policy.require,
            "opt_out": policy.opt_out,
        })
    }

    /// The startup block: one line per path, OFF lines with their reason, `!!` on the ones the policy does not accept.
    pub fn log_lines(&self, policy: &Policy) -> Vec<String> {
        let bad: Vec<&str> = self.unaccepted(policy).iter().map(|p| p.id).collect();
        let off = self.paths.iter().filter(|p| !p.on).count();
        let mut out = vec![format!(
            "[fast-paths] {} of {} on, {} off, {} off without an opt-out{}",
            self.paths.len() - off,
            self.paths.len(),
            off,
            bad.len(),
            if policy.require { " (INK_REQUIRE_FAST_PATHS=1)" } else { "" }
        )];
        for p in &self.paths {
            if p.on {
                out.push(format!("[fast-paths]    ON   {:<24} {}", p.id, p.what));
            } else {
                let mark = if bad.contains(&p.id) { "!!" } else { "  " };
                out.push(format!(
                    "[fast-paths] {mark} OFF  {:<24} {} -- {} ({})",
                    p.id,
                    p.what,
                    p.reason.as_deref().unwrap_or(""),
                    p.kind.map_or("", OffKind::name)
                ));
            }
        }
        if !bad.is_empty() && !policy.require {
            out.push(format!(
                "[fast-paths] WARNING: {} switched off by another setting: {}. Name them in INK_FAST_PATH_OPT_OUT to accept, INK_REQUIRE_FAST_PATHS=1 refuses to start",
                if bad.len() == 1 { "a fast path is" } else { "fast paths are" },
                bad.join(", ")
            ));
        }
        out
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn off(r: &Report, id: &str) -> (OffKind, String) {
        let p = r.get(id).unwrap_or_else(|| panic!("no {id}"));
        assert!(!p.on, "{id} should be off");
        (p.kind.unwrap(), p.reason.clone().unwrap())
    }

    fn on(r: &Report, id: &str) -> bool {
        r.get(id).unwrap_or_else(|| panic!("no {id}")).on
    }

    #[test]
    fn exposure_counts_tensor_core_attention_dispatches_by_family() {
        use std::sync::atomic::Ordering::Relaxed;
        let before = |c: &std::sync::atomic::AtomicU64| c.load(Relaxed);
        let (d0, p0) = (before(&EXPOSURE.tc_decode_attn), before(&EXPOSURE.tc_prefill_attn));
        for k in ["k_attn_tc_dec", "k_attn_tc_dec_solo", "k_attn_tc_grp_dec", "k_attn_tc_sparse_dec"] {
            count_dispatch(k);
        }
        for k in ["k_attn_tc_fixed_b", "k_attn_tc_fixed_blk"] {
            count_dispatch(k);
        }
        for k in ["k_attn", "k_attn_dec_solo", "k_attn_grp_dec", "k_attn_sparse_dec", "k_gemm_t"] {
            count_dispatch(k);
        }
        // other tests may dispatch concurrently, so at least these
        assert!(before(&EXPOSURE.tc_decode_attn) >= d0 + 4);
        assert!(before(&EXPOSURE.tc_prefill_attn) >= p0 + 2);
    }

    #[test]
    fn every_id_is_reported_once_in_order() {
        let r = report(&Inputs::serve_default());
        let ids: Vec<&str> = r.paths.iter().map(|p| p.id).collect();
        assert_eq!(ids, IDS);
    }

    #[test]
    fn serve_default_keeps_every_path_on_but_the_measured_defaults() {
        let r = report(&Inputs::serve_default());
        let (kind, why) = off(&r, "sparse_prefill");
        assert_eq!(kind, OffKind::Default, "sparse prefill is measured off by default");
        assert!(why.contains("70052") && why.contains("INK_SPARSE_PREFILL=1"), "{why}");
        // under the default KV4 cache: tensor-core decode is off by default (it fails the M5 defaultgate) and the
        // KV8-only softmax reorderings are off as the format's rule, beside sparse prefill; the policy accepts them
        let offs: Vec<&str> = r.paths.iter().filter(|p| !p.on).map(|p| p.id).collect();
        assert_eq!(offs, ["tc_decode_attn", "sparse_prefill", "tc_exp2", "tc_lazy_rescale", "messages_echo_thinking"]);
        let (kind, why) = off(&r, "tc_decode_attn");
        assert_eq!(kind, OffKind::Default);
        assert!(why.contains("defaultgate") && why.contains("INK_TC_ATTN_DEC=1"), "{why}");
        for id in ["tc_exp2", "tc_lazy_rescale"] {
            assert_eq!(off(&r, id).0, OffKind::Default, "{id}");
        }
        assert!(r.unaccepted(&Policy::default()).is_empty());
        // under --kv8 every path is on but the measured-off ones: sparse prefill and the two softmax reorderings
        let mut i = Inputs::serve_default();
        i.kv8 = true;
        i.kv4 = !i.kv8;
        let r = report(&i);
        let offs: Vec<&str> = r.paths.iter().filter(|p| !p.on).map(|p| p.id).collect();
        assert_eq!(offs, ["sparse_prefill", "tc_exp2", "tc_lazy_rescale", "messages_echo_thinking"]);
        assert!(r.unaccepted(&Policy::default()).is_empty());
    }

    #[test]
    fn sparse_prefill_is_measured_off_by_default_and_names_what_blocks_it_when_asked() {
        let mut i = Inputs::serve_default();
        assert!(!i.sparse_prefill, "INK_SPARSE_PREFILL defaults to off");
        let r = report(&i);
        assert_eq!(off(&r, "sparse_prefill"), (OffKind::Default, SPARSE_PREFILL_DEFAULT_OFF.into()));
        assert!(r.unaccepted(&Policy { require: true, opt_out: vec![] }).is_empty());
        // INK_SPARSE_PREFILL=1
        i.sparse_prefill = true;
        assert!(on(&report(&i), "sparse_prefill"));
        // a prerequisite switched off by its own opt-out is an accepted opt-out here too
        i.env.no_tc_attn = true;
        let (kind, why) = off(&report(&i), "sparse_prefill");
        assert_eq!(kind, OffKind::OptOut);
        assert!(why.contains("tc_prefill_attn"), "{why}");
        assert!(report(&i).unaccepted(&Policy { require: true, opt_out: vec![] }).is_empty());
        i.env.no_tc_attn = false;
        i.exact = true;
        assert_eq!(off(&report(&i), "sparse_prefill").0, OffKind::Mode, "--exact is a mode");
        i.exact = false;
        i.sparse_topk = false;
        let (kind, why) = off(&report(&i), "sparse_prefill");
        assert_eq!(kind, OffKind::OptOut, "--no-sparse-topk is the user's choice");
        assert!(why.contains("--sparse-topk"), "{why}");
        i.full_attn_budget = true;
        let (kind, why) = off(&report(&i), "sparse_prefill");
        assert_eq!(kind, OffKind::Mode);
        assert!(why.contains("--sparse-topk"), "{why}");
        i.sparse_topk = true;
        assert!(off(&report(&i), "sparse_prefill").1.contains("--full-attn-budget"));
    }

    #[test]
    fn tc_decode_is_on_by_default_for_kv8_and_fp16_off_for_kv4_and_switchable() {
        // (kv4, kv8): KV4, KV8, FP16
        for (kv4, kv8) in [(true, false), (false, true), (false, false)] {
            let mut i = Inputs::serve_default();
            i.kv8 = kv8;
            i.kv4 = kv4;
            let r = report(&i);
            assert!(on(&r, "tc_prefill_attn"), "kv4={kv4} kv8={kv8}: #234: KV8 prefill is on the tensor cores");
            if kv4 {
                assert_eq!(off(&r, "tc_decode_attn").0, OffKind::Default, "KV4: off by default (M5 defaultgate)");
            } else {
                assert!(on(&r, "tc_decode_attn"), "kv8={kv8}: on by default");
            }
            assert!(r.unaccepted(&Policy::default()).is_empty());
            // INK_TC_ATTN_DEC=0 is a named opt-out the policy accepts; =1 leaves it on (other values are refused
            // at startup, `switches::check`)
            i.env = EnvFlags::read(|name| (name == "INK_TC_ATTN_DEC").then(|| "0".to_string()));
            let r = report(&i);
            assert_eq!(off(&r, "tc_decode_attn"), (OffKind::OptOut, "INK_TC_ATTN_DEC=0".into()), "kv4={kv4} kv8={kv8}");
            assert!(on(&r, "tc_prefill_attn"), "kv8={kv8}: the decode opt-out leaves prefill alone");
            assert!(r.unaccepted(&Policy { require: true, opt_out: vec![] }).is_empty());
            for v in ["1"] {
                i.env = EnvFlags::read(|name| (name == "INK_TC_ATTN_DEC").then(|| v.to_string()));
                assert!(on(&report(&i), "tc_decode_attn"), "kv4={kv4} kv8={kv8}: INK_TC_ATTN_DEC={v:?} forces it on");
            }
        }
    }

    #[test]
    fn tc_softmax_reorderings_are_measured_off_kv8_opt_ins_and_stay_off_elsewhere() {
        for (id, env) in [("tc_exp2", "INK_TC_EXP2"), ("tc_lazy_rescale", "INK_TC_LAZY_RESCALE")] {
            assert!(!crate::engine::switches::default_of(env), "{env} is off by default (M5 confident-KL bound)");
            let mut i = Inputs::serve_default();
            i.kv8 = true;
            i.kv4 = !i.kv8;
            for v in [None, Some("0")] {
                i.env = EnvFlags::read(|name| if name == env { v.map(str::to_string) } else { None });
                let r = report(&i);
                let (kind, why) = off(&r, id);
                assert_eq!(kind, OffKind::Default, "{id} {v:?}: a measured default");
                assert!(why.contains("confident-KL") && why.contains(&format!("{env}=1")), "{id}: {why}");
                assert!(r.unaccepted(&Policy { require: true, opt_out: vec![] }).is_empty(), "{id}");
            }
            i.env = EnvFlags::read(|name| (name == env).then(|| "1".to_string()));
            assert!(on(&report(&i), id), "{id}: {env}=1 under --kv8 opts in");
            // outside KV8 it is off whatever the switch says, as the cache format's rule the policy accepts
            for v in [None, Some("1")] {
                i.env = EnvFlags::read(|name| if name == env { v.map(str::to_string) } else { None });
                i.kv8 = false;
                i.kv4 = !i.kv8;
                let r = report(&i);
                let (kind, why) = off(&r, id);
                assert_eq!(kind, OffKind::Default, "{id} {v:?}");
                assert!(why.contains("KV8 only"), "{id}: {why}");
                assert!(r.unaccepted(&Policy::default()).is_empty(), "{id} {v:?}");
                i.kv8 = true;
                i.kv4 = !i.kv8;
            }
            // tensor-core prefill attention off: named, with that switch's kind
            i.env = EnvFlags::read(|name| (name == env).then(|| "1".to_string()));
            i.env.no_tc_attn = true;
            let (kind, why) = off(&report(&i), id);
            assert_eq!(kind, OffKind::OptOut, "{id}");
            assert!(why.contains("tc_prefill_attn"), "{id}: {why}");
            i.env.no_tc_attn = false;
            i.exact = true;
            assert_eq!(off(&report(&i), id).0, OffKind::Mode, "{id}: --exact");
        }
    }

    #[test]
    fn tc_softmax_defines_follow_the_gates() {
        for bits in 0u32..8 {
            let b = |n: u32| bits & (1 << n) != 0;
            let (kv8, exp2, lazy) = (b(0), b(1), b(2));
            let d = crate::engine::tc_softmax_defines(kv8, exp2, lazy);
            assert_eq!(d.contains("#define TC_ATT_EXP2 1"), tc_exp2_gate(exp2, kv8, true).is_on());
            assert_eq!(d.contains("#define TC_ATT_LAZY_RESCALE 1"), tc_lazy_rescale_gate(lazy, kv8, true).is_on());
        }
    }

    #[test]
    fn exact_turns_off_tc_prefill_sparse_and_stitch_as_mode() {
        let mut i = Inputs::serve_default();
        i.exact = true;
        i.sparse_topk = false;
        i.kv_stitch = false;
        let r = report(&i);
        for id in ["tc_prefill_attn", "sparse_topk", "kv_stitch"] {
            let (kind, why) = off(&r, id);
            assert_eq!(kind, OffKind::Mode, "{id}");
            assert!(why.contains("--exact"), "{id}: {why}");
        }
        // tc decode is on by default, so --exact turns it off as a mode, like tc prefill
        let (kind, why) = off(&r, "tc_decode_attn");
        assert_eq!(kind, OffKind::Mode);
        assert!(why.contains("--exact"), "{why}");
        let ids: Vec<&str> = r.unaccepted(&Policy::default()).iter().map(|p| p.id).collect();
        assert_eq!(ids, ["tc_prefill_attn", "tc_decode_attn", "sparse_topk", "kv_stitch"]);
        let accepted = Policy { require: true, opt_out: ids.iter().map(|s| s.to_string()).collect() };
        assert!(r.unaccepted(&accepted).is_empty());
    }

    #[test]
    fn sparse_decode_default_and_explicit_choices_are_reported() {
        // --dspark no longer drops the default: the parser and the report call the same function
        assert!(default_sparse_topk_dropped_by(false, false, false).is_none());
        let i = Inputs::serve_default();
        assert!(on(&report(&i), "sparse_topk"));
        // without --exact or --full-attn-budget, sparse off can only be the user's own choice
        let mut i = Inputs::serve_default();
        i.sparse_topk = false;
        assert_eq!(off(&report(&i), "sparse_topk").0, OffKind::OptOut);
        i.kv4 = false;
        i.kv8 = true;
        let r = report(&i);
        let (kind, why) = off(&r, "sparse_topk");
        assert_eq!(kind, OffKind::Default);
        assert!(why.contains("0.09239"));
        assert!(r.unaccepted(&Policy::default()).iter().all(|p| p.id != "sparse_topk"));
        i.serve.no_sparse_topk = true;
        assert_eq!(off(&report(&i), "sparse_topk").0, OffKind::OptOut);
        i.serve.no_sparse_topk = false;
        i.sparse_topk = true;
        assert!(on(&report(&i), "sparse_topk"));
    }

    #[test]
    fn ink_lora_is_reported_as_an_accepted_opt_out_and_costs_no_other_path() {
        let mut i = Inputs::serve_default();
        i.lora = true;
        let r = report(&i);
        let (kind, why) = off(&r, "attn_proj_plain");
        assert_eq!(kind, OffKind::OptOut);
        assert!(why.contains("INK_LORA"), "{why}");
        // only the KV4 tc decode default, the KV8-only tc softmax switches and the LoRA arm itself are off; the
        // policy accepts them
        let offs: Vec<&str> = r.paths.iter().filter(|p| !p.on).map(|p| p.id).collect();
        assert_eq!(offs, ["tc_decode_attn", "sparse_prefill", "attn_proj_plain", "tc_exp2", "tc_lazy_rescale", "messages_echo_thinking"]);
        assert!(r.unaccepted(&Policy { require: true, opt_out: vec![] }).is_empty());
    }

    #[test]
    fn full_attn_budget_loses_row_blocks_and_sparse() {
        let mut i = Inputs::serve_default();
        i.full_attn_budget = true;
        i.sparse_topk = false;
        let r = report(&i);
        assert_eq!(off(&r, "tc_attn_row_blocks").0, OffKind::Missing);
        assert_eq!(off(&r, "sparse_topk").0, OffKind::Mode);
    }

    #[test]
    fn no_mpp_cascades_to_every_fp16_path() {
        let mut i = Inputs::serve_default();
        i.no_mpp_flag = true;
        i.use_mpp = false;
        i.hgemm = false;
        let r = report(&i);
        assert_eq!(off(&r, "mpp_tensor"), (OffKind::OptOut, "--no-mpp".into()));
        for id in ["hgemm", "tc_prefill_attn", "tail_trim", "mixed_tail_trim", "grouped_moe_decode", "moe_prefill_specialised", "moe_decode_specialised", "moe_decode_rg"] {
            assert_eq!(off(&r, id).0, OffKind::Mode, "{id}");
        }
    }

    #[test]
    fn batched_span_logits_needs_hgemm_several_spans_and_a_wanted_row() {
        assert!(batched_span_logits_gate(true, false).is_on());
        assert_eq!(batched_span_logits_gate(true, true), Gate::Off(OffKind::OptOut, "INK_PER_SPAN_LOGITS=1"));
        assert!(matches!(batched_span_logits_gate(false, false), Gate::Off(OffKind::Mode, _)));
        assert!(span_logits_batch_step(true, false, 2, 1));
        assert!(!span_logits_batch_step(true, false, 1, 1), "one span writes ar.logits");
        assert!(!span_logits_batch_step(true, false, 5, 0), "no span reads logits");
        assert!(!span_logits_batch_step(true, true, 5, 5));
        assert!(!span_logits_batch_step(false, false, 5, 5));
        let read = EnvFlags::read(|n| (n == "INK_PER_SPAN_LOGITS").then(|| "1".to_string()));
        assert!(read.per_span_logits);
        let mut i = Inputs::serve_default();
        assert!(report(&i).paths.iter().any(|p| p.id == "batched_span_logits" && p.on));
        i.env.per_span_logits = true;
        assert!(report(&i).paths.iter().any(|p| p.id == "batched_span_logits" && p.kind == Some(OffKind::OptOut)));
    }

    #[test]
    fn tail_trim_step_is_the_gate_on_prefill_and_mixed_steps() {
        for (hgemm, tail) in [(true, true), (true, false), (false, true), (false, false)] {
            let on = tail_trim_gate(hgemm, tail).is_on();
            for mixed_tail in [true, false] {
                assert_eq!(tail_trim_step(hgemm, tail, mixed_tail, 0, 3, false), on, "a prefill step");
                assert_eq!(tail_trim_step(hgemm, tail, mixed_tail, 0, 1, false), on, "a one-span prefill step");
                assert!(!tail_trim_step(hgemm, tail, mixed_tail, 3, 3, false), "a decode step");
                assert!(!tail_trim_step(hgemm, tail, mixed_tail, 0, 3, true), "verify needs every row");
                assert_eq!(tail_trim_step(hgemm, tail, mixed_tail, 2, 3, false), on && mixed_tail, "a mixed step");
                assert!(!tail_trim_step(hgemm, tail, mixed_tail, 2, 3, true));
            }
        }
        assert_eq!(tail_trim_start(1), 0);
        assert_eq!(tail_trim_start(TAIL_MIN_T), 0);
        assert_eq!(tail_trim_start(TAIL_MIN_T + 1), TAIL_MIN_T + 1 - TAIL_ROWS);
        assert_eq!(tail_trim_start(4096), 4096 - TAIL_ROWS);
    }

    #[test]
    fn layout_probe_failure_is_named() {
        let mut i = Inputs::serve_default();
        i.hgemm = false;
        let (kind, why) = off(&report(&i), "hgemm");
        assert_eq!(kind, OffKind::Mode);
        assert!(why.contains("layout"), "{why}");
        i.env.no_hgemm = true;
        assert_eq!(off(&report(&i), "hgemm"), (OffKind::OptOut, "INK_NO_HGEMM".into()));
    }

    #[test]
    fn dev_switches_are_named_opt_outs() {
        let mut i = Inputs::serve_default();
        i.env = EnvFlags::read(|name| {
            matches!(name, "INK_NO_TC_ATTN" | "INK_OLD_MOE_DEC" | "INK_OLD_MIXB" | "INK_GENERIC_MOE").then(|| "1".to_string())
        });
        i.no_grp_dec = true;
        i.no_grp_moe = true;
        i.tail = false;
        i.sep_topk = true;
        let r = report(&i);
        for (id, why) in [
            ("tc_prefill_attn", "INK_NO_TC_ATTN"),
            ("grouped_moe_decode", "INK_OLD_MOE_DEC"),
            ("decode_gemm", "INK_OLD_MOE_DEC"),
            ("batched_mix", "INK_OLD_MIXB"),
            ("moe_prefill_specialised", "INK_GENERIC_MOE"),
            ("grouped_decode_attn", "INK_NO_GRP_DEC"),
            ("grouped_moe_tiles", "INK_NO_GRP_MOE"),
            ("tail_trim", "INK_NO_TAIL"),
            ("fused_topk", "INK_SEP_TOPK"),
        ] {
            assert_eq!(off(&r, id), (OffKind::OptOut, why.to_string()), "{id}");
        }
        // INK_NO_TC_ATTN takes TC decode with it, and the report names that switch: it opts out of tensor-core
        // attention, prefill and decode alike
        assert_eq!(off(&r, "tc_decode_attn"), (OffKind::OptOut, "INK_NO_TC_ATTN".into()));
        // with both switches set, the one naming decode is reported
        i.env.tc_attn_dec = Some(false);
        assert_eq!(off(&report(&i), "tc_decode_attn"), (OffKind::OptOut, "INK_TC_ATTN_DEC=0".into()));
    }

    #[test]
    fn mixed_tail_trim_is_on_by_default_and_opts_out_by_name() {
        let mut i = Inputs::serve_default();
        assert!(EnvFlags::default().mixed_tail_trim, "on by default");
        assert!(on(&report(&i), "mixed_tail_trim"));
        i.env = EnvFlags::read(|n| (n == "INK_MIXED_TAIL_TRIM").then(|| "0".to_string()));
        assert!(!i.env.mixed_tail_trim);
        assert_eq!(off(&report(&i), "mixed_tail_trim"), (OffKind::OptOut, "INK_MIXED_TAIL_TRIM=0".into()));
        assert!(on(&report(&i), "tail_trim"), "the prefill steps' trim stays on");
        assert!(report(&i).unaccepted(&Policy::default()).is_empty());
        // its prerequisites name themselves
        let mut i = Inputs::serve_default();
        i.serve.mixed_steps = false;
        assert_eq!(off(&report(&i), "mixed_tail_trim"), (OffKind::OptOut, "INK_MIXED_STEPS=0".into()));
        let mut i = Inputs::serve_default();
        i.tail = false;
        assert_eq!(off(&report(&i), "mixed_tail_trim"), (OffKind::OptOut, "INK_NO_TAIL".into()));
        i.hgemm = false;
        assert_eq!(off(&report(&i), "mixed_tail_trim").0, OffKind::Mode);
    }

    #[test]
    fn mixed_steps_are_on_by_default_opt_out_by_name_and_on_under_speculative_verify() {
        let mut i = Inputs::serve_default();
        assert!(on(&report(&i), "mixed_steps"));
        i.serve.mixed_steps = false;
        assert_eq!(off(&report(&i), "mixed_steps"), (OffKind::OptOut, "INK_MIXED_STEPS=0".into()));
        assert!(report(&i).unaccepted(&Policy::default()).is_empty());
        // speculative verify mixes too (riders decode one plain token)
        i.serve = ServeFlags { spec_verify: true, ..ServeFlags::default() };
        assert!(on(&report(&i), "mixed_steps"));
    }

    #[test]
    fn prefill_through_checkpoints_is_on_and_the_split_is_a_named_opt_out() {
        let mut i = Inputs::serve_default();
        assert!(on(&report(&i), "prefill_through_checkpoints"));
        i.env = EnvFlags::read(|name| (name == "INK_PREFILL_CKPT_SPLIT").then(|| "1".to_string()));
        let r = report(&i);
        assert_eq!(off(&r, "prefill_through_checkpoints"), (OffKind::OptOut, "INK_PREFILL_CKPT_SPLIT=1".into()));
        assert!(r.unaccepted(&Policy::default()).is_empty());
        i.env = EnvFlags::read(|name| (name == "INK_PREFILL_CKPT_SPLIT").then(|| "0".to_string()));
        assert!(on(&report(&i), "prefill_through_checkpoints"));
    }

    #[test]
    fn dec_fixed_cost_is_on_by_default_and_opts_out_by_name() {
        let mut i = Inputs::serve_default();
        assert!(EnvFlags::default().dec_fixed_cost, "on by default");
        assert!(on(&report(&i), "dec_fixed_cost"));
        i.env = EnvFlags::read(|n| (n == "INK_DEC_FIXED_COST").then(|| "0".to_string()));
        assert_eq!(off(&report(&i), "dec_fixed_cost"), (OffKind::OptOut, "INK_DEC_FIXED_COST=0".into()));
        assert!(report(&i).unaccepted(&Policy::default()).is_empty());
    }

    #[test]
    fn chunked_decode_commits_are_on_by_default_and_opt_out_at_zero() {
        assert_eq!(cb_chunk_layers(None), Ok(CB_CHUNK_DEFAULT));
        assert!(CB_CHUNK_DEFAULT > 0);
        assert_eq!(cb_chunk_layers(Some("0")), Ok(0));
        assert_eq!(cb_chunk_layers(Some("4")), Ok(4));
        assert!(cb_chunk_layers(Some("yes")).unwrap_err().contains("INK_CB_CHUNK"));
        let mut i = Inputs::serve_default();
        assert_eq!(EnvFlags::default().cb_chunk, CB_CHUNK_DEFAULT, "on by default");
        assert!(on(&report(&i), "chunked_decode_commits"));
        i.env = EnvFlags::read(|n| (n == "INK_CB_CHUNK").then(|| "0".to_string()));
        assert_eq!(off(&report(&i), "chunked_decode_commits"), (OffKind::OptOut, "INK_CB_CHUNK=0".into()));
        assert!(report(&i).unaccepted(&Policy::default()).is_empty());
    }

    #[test]
    fn parallel_cpu_sample_is_on_by_default_and_opts_out_by_name() {
        let mut i = Inputs::serve_default();
        assert!(EnvFlags::default().parallel_cpu_sample, "on by default");
        assert!(on(&report(&i), "parallel_cpu_sample"));
        i.env = EnvFlags::read(|n| (n == "INK_PARALLEL_CPU_SAMPLE").then(|| "0".to_string()));
        assert_eq!(off(&report(&i), "parallel_cpu_sample"), (OffKind::OptOut, "INK_PARALLEL_CPU_SAMPLE=0".into()));
        assert!(report(&i).unaccepted(&Policy::default()).is_empty());
    }

    #[test]
    fn old_moe_rg_is_a_named_opt_out_under_grouped_decode() {
        let mut i = Inputs::serve_default();
        assert!(on(&report(&i), "moe_decode_rg"));
        i.env = EnvFlags::read(|name| (name == "INK_OLD_MOE_RG").then(|| "1".to_string()));
        assert_eq!(off(&report(&i), "moe_decode_rg"), (OffKind::OptOut, "INK_OLD_MOE_RG".into()));
        assert!(on(&report(&i), "grouped_moe_decode"));
        i.env = EnvFlags::read(|name| (name == "INK_OLD_MOE_RG").then(|| "0".to_string()));
        assert!(on(&report(&i), "moe_decode_rg"));
        i.env = EnvFlags::read(|name| (name == "INK_OLD_MOE_DEC").then(|| "1".to_string()));
        assert_eq!(off(&report(&i), "moe_decode_rg").0, OffKind::Mode);
    }

    #[test]
    fn retain_reuse_rank_is_on_and_lru_is_a_named_opt_out() {
        let mut i = Inputs::serve_default();
        assert!(on(&report(&i), "retain_reuse_rank"));
        i.serve.retain_lru = true;
        let r = report(&i);
        assert_eq!(off(&r, "retain_reuse_rank"), (OffKind::OptOut, "INK_RETAIN_LRU=1".into()));
        assert!(r.unaccepted(&Policy::default()).is_empty());
    }

    #[test]
    fn messages_echo_thinking_is_measured_off_by_default_and_1_opts_in() {
        let mut i = Inputs::serve_default();
        assert!(!i.serve.echo_thinking, "INK_MESSAGES_ECHO_THINKING defaults to off");
        let r = report(&i);
        let (kind, why) = off(&r, "messages_echo_thinking");
        assert_eq!(kind, OffKind::Default);
        assert!(why.contains("TTFT") && why.contains("INK_MESSAGES_ECHO_THINKING=1"), "{why}");
        assert!(r.unaccepted(&Policy { require: true, opt_out: vec![] }).is_empty());
        i.serve.echo_thinking = true;
        assert!(on(&report(&i), "messages_echo_thinking"));
    }

    #[test]
    fn expert_formats_without_specialised_kernels_are_named() {
        let mut i = Inputs::serve_default();
        i.expert_types = vec![(T_Q4_K, T_Q8_0), (T_NV4, T_NV4), (T_Q3_K, T_Q5_0)];
        let r = report(&i);
        let (kind, why) = off(&r, "moe_decode_specialised");
        assert_eq!(kind, OffKind::Missing);
        assert!(why.contains("gate/up NV4") && why.contains("down NV4") && why.contains("gate/up Q3_K"), "{why}");
        assert!(!why.contains("Q4_K") && !why.contains("Q8_0") && !why.contains("Q5_0"), "{why}");
        let (_, why) = off(&r, "moe_prefill_specialised");
        assert!(why.contains("Q3_K") && !why.contains("NV4"), "prefill has NV4 kernels: {why}");
        // the register-fed decode kernels: Q4_K, Q8_0, Q5_0 only (a layer's other parts keep the sg4 kernels)
        let (kind, why) = off(&r, "moe_decode_rg");
        assert_eq!(kind, OffKind::Missing);
        assert!(why.contains("gate/up NV4") && why.contains("down NV4") && why.contains("gate/up Q3_K"), "{why}");
        assert!(!why.contains("Q4_K") && !why.contains("Q8_0") && !why.contains("Q5_0"), "{why}");
        i.expert_types = vec![(T_Q4_K, T_Q8_0), (T_Q4_K, T_Q5_0)];
        assert!(on(&report(&i), "moe_decode_rg"));
        i.expert_types = vec![(T_MX8, T_MX8)];
        assert!(on(&report(&i), "moe_prefill_specialised"));
    }

    #[test]
    fn gates_agree_with_the_engine_predicates() {
        for bits in 0u32..16 {
            let b = |n: u32| bits & (1 << n) != 0;
            let (hgemm, exact, no_tc, kv4) = (b(0), b(1), b(2), b(3));
            assert_eq!(tc_prefill_attn_gate(hgemm, exact, no_tc).is_on(), crate::engine::prefill_tc_attn(hgemm, exact, no_tc));
            assert_eq!(hgemm_gate(b(0), b(1), b(2)).is_on(), crate::engine::Engine::resolve_effective_hgemm(b(0), b(1), b(2)));
            for (dec, v) in [(None, None), (Some(true), Some("1")), (Some(false), Some("0"))] {
                // decode: unset is on for FP16/KV8 and off for KV4; =1 forces on, =0 off; the prerequisites as prefill
                let want = crate::engine::prefill_tc_attn(hgemm, exact, no_tc) && dec.unwrap_or(!kv4);
                assert_eq!(tc_decode_attn_gate(hgemm, exact, no_tc, dec, kv4).is_on(), want, "kv4={kv4} {dec:?}");
                // `ArithKnobs::split_attn` and `tc_dec` derive from the same gate
                let get = |name: &str| match name {
                    "INK_NO_TC_ATTN" => no_tc.then(|| "1".to_string()),
                    "INK_TC_ATTN_DEC" => v.map(str::to_string),
                    _ => None,
                };
                assert_eq!(crate::engine::tc_dec_attn(hgemm, exact, kv4, get), want);
                assert_eq!(
                    crate::engine::split_attn(hgemm, exact, kv4, get),
                    crate::engine::prefill_tc_attn(hgemm, exact, no_tc) && !want
                );
            }
        }
    }

    #[test]
    fn policy_reads_and_validates() {
        let env = |pairs: &'static [(&'static str, &'static str)]| {
            move |name: &str| pairs.iter().find(|(k, _)| *k == name).map(|(_, v)| v.to_string())
        };
        assert_eq!(Policy::read(env(&[])).unwrap(), Policy::default());
        let p = Policy::read(env(&[("INK_REQUIRE_FAST_PATHS", "1"), ("INK_FAST_PATH_OPT_OUT", "sparse_topk, kv_stitch")])).unwrap();
        assert!(p.require);
        assert_eq!(p.opt_out, ["sparse_topk", "kv_stitch"]);
        assert!(Policy::read(env(&[("INK_REQUIRE_FAST_PATHS", "yes")])).unwrap_err().contains("0 or 1"));
        assert!(Policy::read(env(&[("INK_FAST_PATH_OPT_OUT", "tc_attn")])).unwrap_err().contains("unknown fast path"));
    }

    #[test]
    fn json_and_log_block_name_every_off_path() {
        let mut i = Inputs::serve_default();
        i.full_attn_budget = true;
        i.sparse_topk = false;
        let r = report(&i);
        let policy = Policy::default();
        let j = r.to_json(&policy);
        assert_eq!(j["paths"]["sparse_topk"]["on"], false);
        assert_eq!(j["paths"]["sparse_topk"]["kind"], "mode");
        assert_eq!(j["paths"]["tc_attn_row_blocks"]["kind"], "missing");
        assert_eq!(j["paths"]["tc_prefill_attn"]["on"], true);
        assert_eq!(j["paths"]["sparse_prefill"]["kind"], "default_off");
        assert_eq!(j["off"], 7);
        assert_eq!(j["unaccepted"], serde_json::json!(["tc_attn_row_blocks", "sparse_topk"]));
        let lines = r.log_lines(&policy);
        assert!(lines[0].contains("7 off, 2 off without an opt-out"), "{}", lines[0]);
        assert!(lines.iter().any(|l| l.contains("!! OFF  sparse_topk") && l.contains("--full-attn-budget")), "{lines:?}");
        assert!(lines.last().unwrap().contains("WARNING") && lines.last().unwrap().contains("sparse_topk"));
    }
}