inky-engine 2.0.1

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
use super::super::*;
use super::ScratchDir;
use crate::engine::{Engine, Lane, Span};
use crate::prefix::PrefixMatch;
use crate::tokenizer::Tokenizer;
use objc2_metal::MTLCommandBuffer;

// Run a serving lane through the actual paged prefill kernels. Fixed-size chunks give
// the cold comparison the same floating-point reduction order at every shared position.
fn prefill(eng: &Engine, cache: &mut ServeBlockCache, tokens: &[u32]) -> (usize, Vec<u32>) {
    let lane = Lane::new_blocked(eng, eng.max_ctx);
    let run = eng.on(&lane);
    let mut state = LaneBlockState::default();
    let matched = cache.match_and_bind(
        &mut eng.block_pool().borrow_mut(), &mut lane.block_table().borrow_mut(), &mut state, tokens,
    );
    let start = match matched {
        Some((pos, cs)) => { run.set_cs(&cs); pos }
        None => { run.reset(); 0 }
    };
    run.set_tokens(0, tokens);
    let mut pos = start;
    while pos < tokens.len() {
        let target = effective_pf_target(pos, tokens.len());
        let count = (target - pos).min(2 * BLOCK).min(eng.chunk);
        cache.ensure_span_blocks(
            &mut eng.block_pool().borrow_mut(), &mut lane.block_table().borrow_mut(), pos, count,
        ).unwrap();
        let cb = eng.gpu.cmd();
        eng.encode_spans(&cb, &[Span { lane: &lane, p0: pos, t: count }], pos + count == tokens.len(), false);
        cb.commit();
        crate::serve::wait_committed_step(&cb, "spill model regression").unwrap();
        cache.finish_prefill_span(
            &mut eng.block_pool().borrow_mut(), &mut lane.block_table().borrow_mut(),
            &mut state, tokens, pos, count, || run.get_cs(),
        );
        pos += count;
    }
    let row: Vec<_> = eng.logits().iter().map(|x| {
        assert!(x.is_finite(), "model produced nonfinite logits at prompt length {}", tokens.len());
        x.to_bits()
    }).collect();
    cache.release_lane(&mut eng.block_pool().borrow_mut(), &mut lane.block_table().borrow_mut(), &mut state);
    (start, row)
}

fn assert_same_logits(cached: &[u32], cold: &[u32]) {
    assert!(!cold.is_empty());
    assert_eq!(cached.len(), cold.len());
    for (token, (a, b)) in cached.iter().zip(cold).enumerate() {
        assert_eq!(a, b, "different logits at vocabulary token {token}: {} vs {}", f32::from_bits(*a), f32::from_bits(*b));
    }
}

#[test]
#[ignore = "requires an M5 Metal device and local Inkling-2-Mini GGUF"]
fn restored_long_prefix_and_early_fork_match_cold_logits() {
    let path = std::env::var("INKY_TEST_MODEL").unwrap_or_else(|_| crate::default_model());
    let eng = Engine::load(&path, 2048);
    eng.ensure_batch(2 * BLOCK);
    let kvb = eng.block_pool().borrow().full.kvb();
    *eng.block_pool().borrow_mut() = BlockPools::gpu(&eng.gpu.dev, 20, 20, kvb);
    let tokenizer = Tokenizer::load(&eng.g);
    let base = tokenizer.encode(" A blue moon rises above the river.", false);
    let other = tokenizer.encode("Bitter winter winds shake these walls.", false);
    assert!(!base.is_empty() && !other.is_empty() && base[0] != other[0]);
    let boundary = WINDOW + BLOCK;
    let long: Vec<u32> = base.iter().copied().cycle().take(boundary + 1).collect();
    let filler: Vec<u32> = other.iter().copied().cycle().take(6 * BLOCK + 1).collect();
    let mut fork = long[..BLOCK].to_vec();
    fork.extend(other.iter().copied().cycle().take(BLOCK + 17));
    assert_ne!(fork[BLOCK], long[BLOCK]);

    let dir = ScratchDir::new("m5-restore-fork");
    let mut cache = ServeBlockCache::with_spill(SpillStore::open(&dir.0, 512 * 1024 * 1024).unwrap());
    let (first, cold_long) = prefill(&eng, &mut cache, &long);
    assert_eq!(first, 0);
    assert_eq!(cache.peek_match_len(&eng.block_pool().borrow(), &long), boundary);

    // The disjoint prompt exceeds the remaining Full slots, forcing the LRU start to disk.
    assert_eq!(prefill(&eng, &mut cache, &filler).0, 0);
    assert_eq!(cache.peek_match_len(&eng.block_pool().borrow(), &long), 0);
    assert!(cache.stats().starts_spilled > 0);
    let writes = cache.spill_store().unwrap().stats().writes_committed;
    assert!(writes > 0);
    let reads_before = cache.spill_store().unwrap().stats().reads_hit;
    let restores_before = cache.stats().starts_restored;
    let (start, restored) = prefill(&eng, &mut cache, &long);
    assert_eq!(start, boundary);
    assert_eq!(cache.stats().starts_restored, restores_before + 1);
    let reads = cache.spill_store().unwrap().stats().reads_hit - reads_before;
    assert!(reads >= (boundary / BLOCK + WINDOW / BLOCK + 1) as u64, "expected all Full and Window blocks and recurrent state from SSD");
    assert_same_logits(&restored, &cold_long);

    let root = cache.tree.deepest_start(&long).ids[0];
    assert!(cache.tree.handle(root).unwrap().window().is_none());
    let dedups = cache.stats().shared_dedups;
    let (start, warm_fork) = prefill(&eng, &mut cache, &fork);
    assert_eq!(start, 0);
    assert!(cache.stats().shared_dedups > dedups);
    assert!(cache.tree.handle(root).unwrap().window().is_some());
    cache.shutdown(&mut eng.block_pool().borrow_mut());

    // This fresh cache has no retained handles or spill files for the independent branch run.
    let mut cold = ServeBlockCache::new();
    let (start, cold_fork) = prefill(&eng, &mut cold, &fork);
    assert_eq!(start, 0);
    assert_same_logits(&warm_fork, &cold_fork);
    cold.shutdown(&mut eng.block_pool().borrow_mut());
    super::assert_zero_pool_leaks(&eng.block_pool().borrow());
    eprintln!("SSD restore at {boundary} tokens: {writes} committed block writes, {reads} verified reads, {} logits matched for both restored prefix and early fork", cold_fork.len());
}

fn fnv1a_logits(mut h: u64, row: &[f32]) -> u64 {
    for &x in row {
        assert!(x.is_finite(), "non-finite logit in FNV-1a hash");
        h = (h ^ u64::from(x.to_bits())).wrapping_mul(0x100000001b3);
    }
    h
}

fn softcap_logit(x: f32, cap: f32) -> f32 {
    if cap > 0.0 { cap * (x / cap).tanh() } else { x }
}

/// Returns `(argmax_cand, argmax_ref, kl_ref_to_cand)` over softcapped logits (`KL(P_ref || P_cand)`).
fn kl_and_argmax(cand_raw: &[f32], ref_raw: &[f32], cap: f32) -> (usize, usize, f64) {
    assert_eq!(cand_raw.len(), ref_raw.len());
    let mut max_c = f64::NEG_INFINITY;
    let mut max_r = f64::NEG_INFINITY;
    let mut arg_c = 0usize;
    let mut arg_r = 0usize;
    let cand: Vec<f64> = cand_raw
        .iter()
        .enumerate()
        .map(|(i, &x)| {
            let v = f64::from(softcap_logit(x, cap));
            if v > max_c {
                max_c = v;
                arg_c = i;
            }
            v
        })
        .collect();
    let rref: Vec<f64> = ref_raw
        .iter()
        .enumerate()
        .map(|(i, &x)| {
            let v = f64::from(softcap_logit(x, cap));
            if v > max_r {
                max_r = v;
                arg_r = i;
            }
            v
        })
        .collect();
    let lse_c = max_c + cand.iter().map(|&v| (v - max_c).exp()).sum::<f64>().ln();
    let lse_r = max_r + rref.iter().map(|&v| (v - max_r).exp()).sum::<f64>().ln();
    let kl: f64 = rref
        .iter()
        .zip(&cand)
        .map(|(&rv, &cv)| {
            let log_p = rv - lse_r;
            let log_q = cv - lse_c;
            log_p.exp() * (log_p - log_q)
        })
        .sum();
    (arg_c, arg_r, kl.max(0.0))
}

#[test]
#[ignore = "requires an M5 Metal device and local Inkling-2-Mini GGUF"]
fn kv4_wht_m5_non_regression_kl_fp16_cs_spill_and_sabotage_gate() {
    use crate::blocks::{
        BlockIndex, BlockKind, BlockPools, KvMode, KVB_KV4, KV4_FULL_STRIDE, KV4_ROW_BYTES, KV4_WINDOW_STRIDE,
    };
    use crate::spill::SpillError;

    let path = std::env::var("INKY_TEST_MODEL").unwrap_or_else(|_| crate::default_model());
    let haiku: Vec<u32> = include_str!("../../../../ref/haiku.tokens")
        .split_whitespace()
        .map(|s| s.parse::<u32>().expect("haiku token"))
        .collect();
    let long_toks: Vec<u32> = include_str!("../../../../ref/long.tokens")
        .split_whitespace()
        .map(|s| s.parse::<u32>().expect("long token"))
        .collect();
    assert_eq!(haiku.len(), 61);
    assert_eq!(long_toks.len(), 2403);

    // Two 288-token natural prose streams sharing a 256-token (`4 * BLOCK`) sealed prefix, then diverging
    // coherently for 32 tokens + 8 decode steps (`lanes = 2 <= 4`).
    let shared_len = 4 * BLOCK;
    let tail_len = 32usize;
    let dec_steps = 8usize;

    // ---- 1. Bit-exact FP16 non-regression vs unmodified `main` (`f3e062fb45528c1c5f38ebfee36f1b21b449e7fb`)
    //         + capture exact FP16 reference logits (one model loaded at a time, `-c <= 4096`, `lanes <= 2`).
    let (fp16_haiku_rows, fp16_dec_rows, prompt_a, seq_a, prompt_b, seq_b, softcap) = {
        let eng = Engine::load_with_mode(&path, 4096, KvMode::Fp16, 4096).expect("load FP16 engine");
        assert!(eng.hgemm, "FP16 engine must use fast hgemm tensor path on M5");
        let cap = eng.effective_sampler_softcap(0);
        eng.ensure_batch(4096);
        let tok = Tokenizer::load(&eng.g);
        let shared_prose = tok.encode(
            "In modern high-throughput language model serving on unified-memory Apple Silicon GPUs, key-value cache capacity and memory bandwidth govern both maximum concurrency and per-token decode latency. Because attention reads historical key and value states on every generated token, compressing each head vector from sixteen-bit floating point down to four bits nearly quadruples the resident prefix cache capacity within the same physical memory budget. Applying a randomized Walsh-Hadamard transform before four-bit Gaussian Lloyd-Max quantization spreads channel outliers uniformly across all one hundred twenty-eight head dimensions so that a single half-precision root-mean-square scale per head row preserves attention inner products with minimal Kullback-Leibler divergence across long multi-turn conversations, tool-use transcripts, and shared system prompts. Furthermore, rotating query vectors into the Walsh-Hadamard domain once per head allows split-K decode kernels to compute inner products directly against unpacked four-bit codewords without performing an inverse butterfly per historical key, while accumulating weighted rotated values across splits requires only a single inverse transform during the final head combine stage. When combined with paged sixty-four-token block allocation, prefix-tree deduplication, and lazy solid-state spill storage, a single workstation serves deep concurrent agentic workflows without recomputing shared context.",
            false,
        );
        assert!(shared_prose.len() >= shared_len, "shared_prose only had {} tokens", shared_prose.len());
        let branch_a = tok.encode(
            " First, folding the per-head key mean into the attention sink removes static direct-current bias prior to quantization, sharpening retrieval accuracy across every full-attention layer in the recurrent stack and keeping multi-step decode distributions closely aligned with exact half-precision baselines.",
            false,
        );
        let branch_b = tok.encode(
            "\n\nTo summarize the architectural trade-offs clearly: first, memory bandwidth limits decode latency on unified-memory GPUs; second, caching sealed prefix blocks across multi-turn sessions eliminates redundant prefill work; third, Walsh-Hadamard rotation spreads outlier channels evenly before quantization.",
            false,
        );
        assert!(branch_a.len() >= tail_len && branch_b.len() >= tail_len);
        let mut prompt_a = shared_prose[..shared_len].to_vec();
        prompt_a.extend_from_slice(&branch_a[..tail_len]);
        let mut prompt_b = shared_prose[..shared_len].to_vec();
        prompt_b.extend_from_slice(&branch_b[..tail_len]);
        assert_ne!(prompt_a[shared_len], prompt_b[shared_len]);

        // 1a. `decode haiku` golden hash (`cfb2e3a0c3da77ba` on M5 Pro & M5 Max).
        let lane = Lane::new(&eng);
        let run = eng.on(&lane);
        run.set_tokens(0, &haiku);
        run.reserve(4096, false);
        run.reset();
        let mut h_haiku = 0xcbf29ce484222325u64;
        let mut rows_haiku = Vec::with_capacity(haiku.len());
        for pos in 0..haiku.len() {
            let cb = eng.gpu.cmd();
            run.encode_step(&cb, pos, true, false);
            cb.commit();
            crate::metal::wait_completed(&cb, "fp16 haiku", pos).expect("fp16 haiku step");
            let lg = eng.logits().to_vec();
            h_haiku = fnv1a_logits(h_haiku, &lg);
            rows_haiku.push(lg);
        }
        assert_eq!(
            h_haiku, 0xcfb2_e3a0_c3da_77ba,
            "FP16 `decode haiku` logit hash drifted from main (`0xcfb2e3a0c3da77ba`): got 0x{h_haiku:016x}"
        );

        // 1b. `prefill+decode long` (`INK_PF=1500`) golden hash (`b9d2bd3f3ab65de0` on M5 Pro & M5 Max).
        run.set_tokens(0, &long_toks);
        run.reserve(4096, false);
        run.reset();
        let pf = 1500usize;
        let cbp = eng.gpu.cmd();
        run.encode_prefill(&cbp, 0, pf, true, false);
        cbp.commit();
        crate::metal::wait_completed(&cbp, "fp16 long prefill", 0).expect("fp16 long prefill");
        let mut h_long_pf = fnv1a_logits(0xcbf29ce484222325u64, &eng.logits());
        for pos in pf..long_toks.len() {
            let cb = eng.gpu.cmd();
            run.encode_step(&cb, pos, true, false);
            cb.commit();
            crate::metal::wait_completed(&cb, "fp16 long decode", pos).expect("fp16 long decode");
            h_long_pf = fnv1a_logits(h_long_pf, &eng.logits());
        }
        assert_eq!(
            h_long_pf, 0xb9d2_bd3f_3ab6_5de0,
            "FP16 `INK_PF=1500 long` logit hash drifted from main (`0xb9d2bd3f3ab65de0`): got 0x{h_long_pf:016x}"
        );

        // 1c. Exact FP16 reference logits + on-policy greedy decode tokens for the 2-lane 288-token + 8-step scenario.
        let mut dec_rows = Vec::with_capacity(2 * dec_steps);
        let mut seqs = Vec::with_capacity(2);
        for prompt in [&prompt_a, &prompt_b] {
            let plen = prompt.len();
            let mut full_seq = prompt.clone();
            run.set_tokens(0, &full_seq);
            run.reserve(4096, false);
            run.reset();
            let mut p0 = 0usize;
            for &chunk_len in &[128usize, 128, tail_len] {
                let cb0 = eng.gpu.cmd();
                eng.encode_spans(&cb0, &[Span { lane: &lane, p0, t: chunk_len }], p0 + chunk_len == plen, false);
                cb0.commit();
                crate::metal::wait_completed(&cb0, "fp16 ref prefill", p0).expect("fp16 ref prefill");
                p0 += chunk_len;
            }
            let first_next = eng
                .logits()
                .iter()
                .enumerate()
                .fold((0usize, f32::NEG_INFINITY), |b, (i, &x)| if x > b.1 { (i, x) } else { b })
                .0 as u32;
            full_seq.push(first_next);
            run.set_tokens(plen, &[first_next]);
            for step in 0..dec_steps {
                let pos = plen + step;
                let cb = eng.gpu.cmd();
                run.encode_step(&cb, pos, true, false);
                cb.commit();
                crate::metal::wait_completed(&cb, "fp16 ref decode", step).expect("fp16 ref decode");
                let lg = eng.logits().to_vec();
                if step + 1 < dec_steps {
                    let nxt = lg
                        .iter()
                        .enumerate()
                        .fold((0usize, f32::NEG_INFINITY), |b, (i, &x)| if x > b.1 { (i, x) } else { b })
                        .0 as u32;
                    full_seq.push(nxt);
                    run.set_tokens(pos + 1, &[nxt]);
                }
                dec_rows.push(lg);
            }
            seqs.push(full_seq);
        }
        let seq_b = seqs.pop().unwrap();
        let seq_a = seqs.pop().unwrap();
        (rows_haiku, dec_rows, prompt_a, seq_a, prompt_b, seq_b, cap)
    };

    // ---- 2. Bit-exact `--kv8` non-regression vs unmodified `main` (`93e09ccb61ac49f6` on M5 Pro & M5 Max).
    {
        let eng8 = Engine::load_with_mode(&path, 4096, KvMode::Kv8, 512).expect("load KV8 engine");
        let lane = Lane::new(&eng8);
        let run = eng8.on(&lane);
        run.set_tokens(0, &haiku);
        run.reserve(4096, false);
        run.reset();
        let mut h_kv8 = 0xcbf29ce484222325u64;
        let mut perturbed_first = None;
        let mut kv8_match = 0usize;
        let mut kv8_kls = Vec::with_capacity(haiku.len());
        for (pos, ref_row) in fp16_haiku_rows.iter().enumerate() {
            let cb = eng8.gpu.cmd();
            run.encode_step(&cb, pos, true, false);
            cb.commit();
            crate::metal::wait_completed(&cb, "kv8 haiku", pos).expect("kv8 haiku step");
            let lg = eng8.logits();
            if perturbed_first.is_none() {
                let mut sab = lg.to_vec();
                sab[0] = f32::from_bits(sab[0].to_bits() ^ 1);
                perturbed_first = Some(fnv1a_logits(0xcbf29ce484222325u64, &sab));
            }
            h_kv8 = fnv1a_logits(h_kv8, &lg);
            let (ac, ar, kl) = kl_and_argmax(&lg, ref_row, softcap);
            if ac == ar {
                kv8_match += 1;
            }
            kv8_kls.push(kl);
        }
        kv8_kls.sort_by(|a, b| a.partial_cmp(b).unwrap());
        eprintln!(
            "[kv8-m5-ref] single-stream haiku vs FP16: argmax {kv8_match}/{}, median KL {:.6}, p95 KL {:.6}, worst KL {:.6}",
            haiku.len(),
            kv8_kls[kv8_kls.len() / 2],
            kv8_kls[(kv8_kls.len() * 95) / 100],
            kv8_kls[kv8_kls.len() - 1],
        );
        assert_eq!(
            h_kv8, 0x93e0_9ccb_61ac_49f6,
            "KV8 `decode haiku` logit hash drifted from main (`0x93e09ccb61ac49f6`): got 0x{h_kv8:016x}"
        );
        assert_ne!(perturbed_first.unwrap(), fnv1a_logits(0xcbf29ce484222325u64, &fp16_haiku_rows[0]));
    }

    // ---- 3. Live `--kv4` (`WHT-KV4` + Key DC-mean sink fold + exact FP32 retained `cs` + `SpillStore` + sabotage controls).
    {
        use crate::blocks::{metal_in_slot_byte_offset_mode, Kv};

        assert_eq!(KV4_ROW_BYTES, 66);
        assert_eq!(KvMode::Kv4.stride_bytes(BlockKind::Full), KV4_FULL_STRIDE);
        assert_eq!(KvMode::Kv4.stride_bytes(BlockKind::Window), KV4_WINDOW_STRIDE);
        assert_eq!(KV4_FULL_STRIDE, 540_672);
        assert_eq!(KV4_WINDOW_STRIDE, 2_703_360);

        let eng4 = Engine::load_with_mode(&path, 4096, KvMode::Kv4, 512).expect("load KV4 engine");
        assert!(eng4.kv4 && !eng4.kv8);
        assert_eq!(eng4.kv_mode(), KvMode::Kv4);
        assert!(eng4.hgemm, "--kv4 must keep fast fp16 hgemm tensor path active on M5");
        let kv4_digest = eng4.kv4_codec_digest();
        assert_eq!(eng4.kv4_dc_table_bytes().len(), Engine::KV4_DC_TABLE_BYTES);
        assert!(
            eng4.kv4_dc_table_bytes().iter().any(|&b| b != 0),
            "calibrated K_DC_ROT table must be non-zero on real GGUF weights"
        );
        eng4.ensure_batch(512);
        eng4.ensure_dbatch(2);

        // 3a. Single-stream `--kv4` vs exact FP16 on `haiku` (61 steps) + CPU-vs-GPU `WHT-KV4` encoder parity.
        let lane = Lane::new(&eng4);
        let run = eng4.on(&lane);
        run.set_tokens(0, &haiku);
        run.reserve(4096, false);
        run.reset();
        let mut haiku_match = 0usize;
        let mut asst_match = 0usize;
        let mut haiku_kls = Vec::with_capacity(haiku.len());
        let mut asst_kls = Vec::new();
        for (pos, ref_row) in fp16_haiku_rows.iter().enumerate() {
            let cb = eng4.gpu.cmd();
            run.encode_step(&cb, pos, true, false);
            cb.commit();
            crate::metal::wait_completed(&cb, "kv4 haiku", pos).expect("kv4 haiku step");
            let (ac, ar, kl) = kl_and_argmax(&eng4.logits(), ref_row, softcap);
            if ac == ar {
                haiku_match += 1;
            }
            if pos >= 23 {
                if ac == ar {
                    asst_match += 1;
                }
                asst_kls.push(kl);
            }
            haiku_kls.push(kl);
        }
        let haiku_kl_mean = haiku_kls.iter().sum::<f64>() / (haiku.len() as f64);
        haiku_kls.sort_by(|a, b| a.partial_cmp(b).unwrap());
        let haiku_kl_median = haiku_kls[haiku_kls.len() / 2];
        let haiku_kl_worst = haiku_kls[haiku_kls.len() - 1];
        let asst_n = asst_kls.len();
        let asst_kl_mean = asst_kls.iter().sum::<f64>() / (asst_n as f64);
        let asst_kl_worst = asst_kls.iter().copied().fold(0.0f64, f64::max);
        eprintln!(
            "[kv4-m5-gate] single-stream haiku vs FP16 (hgemm={}): all={haiku_match}/{} (median KL {haiku_kl_median:.6}, mean KL {haiku_kl_mean:.6}, worst KL {haiku_kl_worst:.6}) | assistant={asst_match}/{asst_n} (mean KL {asst_kl_mean:.6}, worst KL {asst_kl_worst:.6})",
            eng4.hgemm,
            haiku.len(),
        );
        assert!(haiku_match >= 58, "KV4 haiku argmax match too low: {haiku_match}/{}", haiku.len());
        assert_eq!(asst_match, asst_n, "KV4 haiku assistant span must match 100% argmax: {asst_match}/{asst_n}");
        assert!(haiku_kl_median < 0.01, "KV4 haiku median KL too high: {haiku_kl_median}");
        assert!(asst_kl_mean < 0.02, "KV4 haiku assistant mean KL too high: {asst_kl_mean}");

        // 3b. Exact FP32-input CPU-vs-GPU `WHT-KV4` encoder parity across 8 layers (`[0, 5, 6, 11, 17, 23, 35, 47]`:
        //     4 SWA + 4 Full across all 3 loop passes) and 8 positions (`1,024` 66-byte rows = `131,072` nibbles):
        //     verifies `k_kvprep_b == k_kvprep_b_blk == k_kvprep_dec` 66/66 byte-exact AND `kv4_pack_row_cpu` fed the
        //     exact pre-quantization FP32 `k` & `v` vectors achieves `max_sc_ulp == 0` and exact nibbles; plus checks
        //     real-prompt `pos = 0` `768/768` (`48` passes × `2` planes × `8` heads) prefill == decode parity AND
        //     verifies `calibrate_kv4_dc_mean` surfaces GPU command-buffer errors cleanly without leaving partial DC state.
        {
            let saved_dc = eng4.kv4_dc_table_bytes().to_vec();
            crate::metal::inject_wait_failure("kv4 dc calibration", 1);
            let cal_err = eng4.calibrate_kv4_dc_mean().expect_err("injected calibration failure on pass 1 must return Err");
            crate::metal::clear_wait_failure();
            assert!(
                cal_err.to_string().contains("kv4 dc calibration pass 1"),
                "unexpected calibration error: {cal_err}"
            );
            assert!(
                eng4.kv4_dc_table_bytes().iter().all(|&b| b == 0),
                "failed calibration pass must zero K_DC_ROT rather than leaving partial pass-0 data"
            );
            eng4.set_kv4_dc_table_bytes(&saved_dc);
            assert_eq!(eng4.kv4_codec_digest(), kv4_digest);
            eng4.ensure_batch(512);
            eng4.ensure_dbatch(2);
        }

        let (parity_rows, byte_exact_rows, exact_nibbles, max_sc_ulp) =
            eng4.verify_kv4_multi_layer_fp32_encoder_parity(&[0, 5, 6, 11, 17, 23, 35, 47], 8);
        let total_nibbles = parity_rows * 128;
        eprintln!(
            "[kv4-m5-gate] multi-layer FP32-input CPU vs GPU WHT-KV4 parity (8 layers x 8 pos): byte_exact_rows={byte_exact_rows}/{parity_rows} ({:.2}%), exact_nibbles={exact_nibbles}/{total_nibbles} ({:.4}%), max_sc_ulp={max_sc_ulp}",
            100.0 * (byte_exact_rows as f64) / (parity_rows as f64),
            100.0 * (exact_nibbles as f64) / (total_nibbles as f64),
        );
        assert_eq!(parity_rows, 1024);
        assert_eq!(byte_exact_rows, 1024, "FP32-input CPU vs GPU WHT-KV4 rows must be 100% byte-exact");
        assert_eq!(exact_nibbles, total_nibbles, "FP32-input CPU vs GPU WHT-KV4 nibbles must be 100% exact");
        assert_eq!(max_sc_ulp, 0, "FP32-input CPU vs GPU KV4 fp16 scale must have 0 ULP diff");

        *eng4.block_pool().borrow_mut() = BlockPools::gpu_mode(&eng4.gpu.dev, 10, 10, KvMode::Kv4);
        assert_eq!(eng4.block_pool().borrow().full.kvb(), KVB_KV4);
        assert_eq!(eng4.block_pool().borrow().full.stride_bytes(), KV4_FULL_STRIDE);
        assert_eq!(eng4.block_pool().borrow().window.stride_bytes(), KV4_WINDOW_STRIDE);
        {
            let mut tmp_cache = ServeBlockCache::new();
            let lane_pf0 = Lane::new_blocked(&eng4, 128);
            let mut st_pf0 = LaneBlockState::default();
            eng4.on(&lane_pf0).reset();
            eng4.on(&lane_pf0).set_tokens(0, &haiku[..1]);
            tmp_cache
                .ensure_span_blocks(&mut eng4.block_pool().borrow_mut(), &mut lane_pf0.block_table().borrow_mut(), 0, 1)
                .unwrap();
            let cb_pf = eng4.gpu.cmd();
            eng4.encode_spans(&cb_pf, &[Span { lane: &lane_pf0, p0: 0, t: 1 }], false, false);
            cb_pf.commit();
            crate::metal::wait_completed(&cb_pf, "kv4 pos0 prefill", 0).expect("kv4 pos0 prefill");
            let pf_win_slot = lane_pf0.block_table().borrow().get(BlockKind::Window, BlockIndex::new(0)).unwrap().unwrap().slot();
            let pf_full_slot = lane_pf0.block_table().borrow().get(BlockKind::Full, BlockIndex::new(0)).unwrap().unwrap().slot();

            let lane_dec0 = Lane::new_blocked(&eng4, 128);
            let mut st_dec0 = LaneBlockState::default();
            eng4.on(&lane_dec0).reset();
            eng4.on(&lane_dec0).set_tokens(0, &haiku[..1]);
            tmp_cache
                .ensure_span_blocks(&mut eng4.block_pool().borrow_mut(), &mut lane_dec0.block_table().borrow_mut(), 0, 1)
                .unwrap();
            let cb_dec = eng4.gpu.cmd();
            eng4.encode_decode(&cb_dec, &[Span { lane: &lane_dec0, p0: 0, t: 1 }], false, false);
            cb_dec.commit();
            crate::metal::wait_completed(&cb_dec, "kv4 pos0 decode", 0).expect("kv4 pos0 decode");
            let dec_win_slot = lane_dec0.block_table().borrow().get(BlockKind::Window, BlockIndex::new(0)).unwrap().unwrap().slot();
            let dec_full_slot = lane_dec0.block_table().borrow().get(BlockKind::Full, BlockIndex::new(0)).unwrap().unwrap().slot();

            {
                let pools = eng4.block_pool().borrow();
                for (kind, n_passes, pf_s, dec_s) in [
                    (BlockKind::Window, crate::blocks::WINDOW_PASSES as u32, pf_win_slot, dec_win_slot),
                    (BlockKind::Full, crate::blocks::FULL_PASSES as u32, pf_full_slot, dec_full_slot),
                ] {
                    let pf_bytes = pools.of(kind).slot_bytes(pf_s).unwrap();
                    let dec_bytes = pools.of(kind).slot_bytes(dec_s).unwrap();
                    for p in 0..n_passes {
                        for plane in [Kv::Key, Kv::Value] {
                            for g in 0..crate::engine::NKV as u32 {
                                let off = metal_in_slot_byte_offset_mode(kind, KvMode::Kv4, p, plane, g, 0).unwrap() as usize;
                                assert_eq!(
                                    &pf_bytes[off..off + 66],
                                    &dec_bytes[off..off + 66],
                                    "GPU k_kvprep_b_blk vs k_kvprep_dec mismatch at {kind:?} pass={p} plane={plane:?} g={g}"
                                );
                            }
                        }
                    }
                }
            }
            eprintln!("[kv4-m5-gate] real-prompt pos=0 GPU prefill==decode parity: 768/768 66B rows exact");
            tmp_cache.release_lane(&mut eng4.block_pool().borrow_mut(), &mut lane_pf0.block_table().borrow_mut(), &mut st_pf0);
            tmp_cache.release_lane(&mut eng4.block_pool().borrow_mut(), &mut lane_dec0.block_table().borrow_mut(), &mut st_dec0);
            tmp_cache.shutdown(&mut eng4.block_pool().borrow_mut());
        }

        // 3c. Cold `--kv4` baseline on `seq_a` & `seq_b` (no cache hit, no spill):
        //     capture exact `f32::to_bits()` across all 16 decode rows so we can assert **100% bit-for-bit equality**
        //     (`16/16` exact bit-identity, `KL == 0.0`) after SSD `SpillStore` eviction/restore + warm RAM prefix sharing!
        let mut cold_kv4_dec_rows = Vec::with_capacity(2 * dec_steps);
        for full_seq in [&seq_a, &seq_b] {
            let plen = shared_len + tail_len;
            run.set_tokens(0, full_seq);
            run.reserve(4096, false);
            run.reset();
            let mut p0 = 0usize;
            for &chunk_len in &[128usize, 128, tail_len] {
                let cb0 = eng4.gpu.cmd();
                eng4.encode_spans(&cb0, &[Span { lane: &lane, p0, t: chunk_len }], false, false);
                cb0.commit();
                crate::metal::wait_completed(&cb0, "kv4 cold prefill", p0).expect("kv4 cold prefill");
                p0 += chunk_len;
            }
            for step in 0..dec_steps {
                let cb = eng4.gpu.cmd();
                eng4.encode_decode(&cb, &[Span { lane: &lane, p0: plen + step, t: 1 }], true, false);
                cb.commit();
                crate::metal::wait_completed(&cb, "kv4 cold decode", step).expect("kv4 cold decode");
                cold_kv4_dec_rows.push(eng4.span_logits(0).to_vec());
            }
        }

        // 3d. Paged Layer 3 `ServeBlockCache` + `SpillStore` (`KvMode::Kv4`, exact `3,833,856` B FP32 `cs`,
        //     stamped with SHA-256 over the `98,304` B `K_DC_ROT` table):
        //     seal 256-token prefix, evict to SSD via filler prompt, restore from SSD into Lane A,
        //     bind Lane B from warm RAM cache, decode 8 multi-lane steps, and assert **100% bit-for-bit equality**
        //     against cold `--kv4`!
        *eng4.block_pool().borrow_mut() = BlockPools::gpu_mode(&eng4.gpu.dev, 10, 10, KvMode::Kv4);
        let dir = ScratchDir::new("m5-kv4-spill");
        let model_fp = eng4.g.fingerprint_u64() ^ u64::from_le_bytes(kv4_digest[0..8].try_into().unwrap());
        let store = SpillStore::open_with_kv4_digest(&dir.0, 256 * 1024 * 1024, kv4_digest).unwrap();
        let mut cache = ServeBlockCache::with_spill_compat(store, None, model_fp);

        // Turn 1: prefill `prompt_a` (seals 4 blocks = 256 tokens with exact 3.66 MiB FP32 `cs`).
        let (first_match, cold_prefill_a_bits) = prefill(&eng4, &mut cache, &prompt_a);
        assert_eq!(first_match, 0);
        assert_eq!(cache.peek_match_len(&eng4.block_pool().borrow(), &prompt_a), shared_len);
        let tip_id = cache.tree.deepest_start(&prompt_a).ids.last().copied().expect("sealed start id");
        let retained_cs_bytes = cache.starts.get(&tip_id).expect("retained start").cs.len();
        assert_eq!(retained_cs_bytes, Engine::cs_image_bytes());
        assert_eq!(retained_cs_bytes, 3_833_856, "KV4 retained cs must stay exact 3,833,856-byte FP32");

        // Evict Turn 1's 4 Full blocks + exact FP32 `cs` to SSD `SpillStore` using an independent 7-block (`449`-token) filler prompt.
        let filler: Vec<u32> = long_toks[1400..1400 + 7 * BLOCK + 1].to_vec();
        assert_eq!(prefill(&eng4, &mut cache, &filler).0, 0);
        assert_eq!(cache.peek_match_len(&eng4.block_pool().borrow(), &prompt_a), 0);
        assert!(cache.stats().starts_spilled >= 1, "expected KV4 start to spill to SSD");
        assert!(dir.0.join("kv4.mode").is_file(), "expected kv4.mode stamp in spill dir");

        // Restore the 256-token prefix + exact 3.66 MiB FP32 `cs` from SSD into Lane A, and bind Lane B from warm RAM cache!
        let lane_a = Lane::new_blocked(&eng4, 1024);
        let lane_b = Lane::new_blocked(&eng4, 1024);
        let mut st_a = LaneBlockState::default();
        let mut st_b = LaneBlockState::default();

        let matched_a = cache
            .match_and_bind(&mut eng4.block_pool().borrow_mut(), &mut lane_a.block_table().borrow_mut(), &mut st_a, &prompt_a)
            .expect("SSD restore match for lane A");
        assert_eq!(matched_a.0, shared_len);
        assert_eq!(matched_a.1.len(), Engine::cs_image_bytes());
        assert!(cache.stats().starts_restored >= 1);
        eng4.on(&lane_a).set_cs(&matched_a.1);
        eng4.on(&lane_a).set_tokens(0, &seq_a);

        let matched_b = cache
            .match_and_bind(&mut eng4.block_pool().borrow_mut(), &mut lane_b.block_table().borrow_mut(), &mut st_b, &prompt_b)
            .expect("RAM shared-prefix match for lane B");
        assert_eq!(matched_b.0, shared_len);
        assert_eq!(matched_b.1.len(), Engine::cs_image_bytes());
        assert_eq!(matched_b.1, matched_a.1, "warm RAM cs must match SSD-restored FP32 cs bit-for-bit");
        eng4.on(&lane_b).set_cs(&matched_b.1);
        eng4.on(&lane_b).set_tokens(0, &seq_b);

        // Prefill the divergent 32-token tails `[256..288)` together in one batched Layer 3 prefill step.
        cache
            .ensure_span_blocks(&mut eng4.block_pool().borrow_mut(), &mut lane_a.block_table().borrow_mut(), shared_len, tail_len)
            .unwrap();
        cache
            .ensure_span_blocks(&mut eng4.block_pool().borrow_mut(), &mut lane_b.block_table().borrow_mut(), shared_len, tail_len)
            .unwrap();
        {
            let cb = eng4.gpu.cmd();
            eng4.encode_spans(
                &cb,
                &[
                    Span { lane: &lane_a, p0: shared_len, t: tail_len },
                    Span { lane: &lane_b, p0: shared_len, t: tail_len },
                ],
                true,
                false,
            );
            cb.commit();
            crate::serve::wait_committed_step(&cb, "kv4 2-lane tail prefill").unwrap();
        }
        let warm_prefill_a_bits: Vec<u32> = eng4.span_logits(0).iter().map(|x| x.to_bits()).collect();
        assert_same_logits(&warm_prefill_a_bits, &cold_prefill_a_bits);

        cache.finish_prefill_span(
            &mut eng4.block_pool().borrow_mut(),
            &mut lane_a.block_table().borrow_mut(),
            &mut st_a,
            &prompt_a,
            shared_len,
            tail_len,
            || eng4.on(&lane_a).get_cs(),
        );
        cache.finish_prefill_span(
            &mut eng4.block_pool().borrow_mut(),
            &mut lane_b.block_table().borrow_mut(),
            &mut st_b,
            &prompt_b,
            shared_len,
            tail_len,
            || eng4.on(&lane_b).get_cs(),
        );

        // Run 8 concurrent 2-lane paged decode steps (`k_attn_grp_dec` on shared 256-token blocks + `k_attn_dec_solo` on tail).
        let mut l3_dec_rows_a = Vec::with_capacity(dec_steps);
        let mut l3_dec_rows_b = Vec::with_capacity(dec_steps);
        for step in 0..dec_steps {
            let pos = prompt_a.len() + step;
            cache
                .ensure_span_blocks(&mut eng4.block_pool().borrow_mut(), &mut lane_a.block_table().borrow_mut(), pos, 1)
                .unwrap();
            cache
                .ensure_span_blocks(&mut eng4.block_pool().borrow_mut(), &mut lane_b.block_table().borrow_mut(), pos, 1)
                .unwrap();
            let cb = eng4.gpu.cmd();
            eng4.encode_decode(
                &cb,
                &[Span { lane: &lane_a, p0: pos, t: 1 }, Span { lane: &lane_b, p0: pos, t: 1 }],
                true,
                false,
            );
            cb.commit();
            crate::serve::wait_committed_step(&cb, "kv4 2-lane decode").unwrap();
            cache.finish_decode_span(&mut eng4.block_pool().borrow_mut(), &mut lane_a.block_table().borrow_mut(), &mut st_a, pos);
            cache.finish_decode_span(&mut eng4.block_pool().borrow_mut(), &mut lane_b.block_table().borrow_mut(), &mut st_b, pos);
            l3_dec_rows_a.push(eng4.span_logits(0).to_vec());
            l3_dec_rows_b.push(eng4.span_logits(1).to_vec());
        }

        let mut paged_match = 0usize;
        let mut paged_kl_sum = 0.0f64;
        let mut paged_kl_worst = 0.0f64;
        for (step, row_a) in l3_dec_rows_a.iter().enumerate() {
            let row_a_bits: Vec<u32> = row_a.iter().map(|x| x.to_bits()).collect();
            let cold_a_bits: Vec<u32> = cold_kv4_dec_rows[step].iter().map(|x| x.to_bits()).collect();
            assert_same_logits(&row_a_bits, &cold_a_bits);
            let (ac, ar, kl) = kl_and_argmax(row_a, &fp16_dec_rows[step], softcap);
            if ac == ar {
                paged_match += 1;
            } else {
                let mut ref_idx: Vec<(usize, f32)> = fp16_dec_rows[step].iter().copied().enumerate().collect();
                ref_idx.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
                eprintln!(
                    "[kv4-m5-gate]   lane_a step={step} mismatch: kv4_top1={ac} (logit={:.5}) vs fp16_top1={ar} (logit={:.5}), fp16_top2={} (logit={:.5}, fp16_gap={:.5}), KL={kl:.6}",
                    row_a[ac],
                    fp16_dec_rows[step][ar],
                    ref_idx[1].0,
                    ref_idx[1].1,
                    ref_idx[0].1 - ref_idx[1].1,
                );
            }
            paged_kl_sum += kl;
            paged_kl_worst = paged_kl_worst.max(kl);
        }
        for (step, row_b) in l3_dec_rows_b.iter().enumerate() {
            let row_b_bits: Vec<u32> = row_b.iter().map(|x| x.to_bits()).collect();
            let cold_b_bits: Vec<u32> = cold_kv4_dec_rows[dec_steps + step].iter().map(|x| x.to_bits()).collect();
            assert_same_logits(&row_b_bits, &cold_b_bits);
            let (ac, ar, kl) = kl_and_argmax(row_b, &fp16_dec_rows[dec_steps + step], softcap);
            if ac == ar {
                paged_match += 1;
            } else {
                let ref_row = &fp16_dec_rows[dec_steps + step];
                let mut ref_idx: Vec<(usize, f32)> = ref_row.iter().copied().enumerate().collect();
                ref_idx.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
                eprintln!(
                    "[kv4-m5-gate]   lane_b step={step} mismatch: kv4_top1={ac} (logit={:.5}) vs fp16_top1={ar} (logit={:.5}), fp16_top2={} (logit={:.5}, fp16_gap={:.5}), KL={kl:.6}",
                    row_b[ac],
                    ref_row[ar],
                    ref_idx[1].0,
                    ref_idx[1].1,
                    ref_idx[0].1 - ref_idx[1].1,
                );
            }
            paged_kl_sum += kl;
            paged_kl_worst = paged_kl_worst.max(kl);
        }
        let total_paged = 2 * dec_steps;
        let paged_kl_mean = paged_kl_sum / (total_paged as f64);
        eprintln!(
            "[kv4-m5-gate] SSD-restored + warm RAM KV4 vs cold KV4: {total_paged}/{total_paged} (100.0%) EXACT bit-for-bit logit equality (0 ULP diff, KL == 0.0)"
        );
        eprintln!(
            "[kv4-m5-gate] Layer3 ServeBlockCache+SpillStore 2-lane decode vs FP16: argmax {paged_match}/{total_paged} ({:.1}%), mean KL {paged_kl_mean:.6}, worst KL {paged_kl_worst:.6}, cs_f32_bytes={retained_cs_bytes}",
            100.0 * (paged_match as f64) / (total_paged as f64),
        );
        assert!(paged_match >= 15, "KV4 Layer3 paged argmax match too low: {paged_match}/{total_paged}");
        assert!(paged_kl_mean < 0.03, "KV4 Layer3 paged mean KL too high: {paged_kl_mean}");
        assert!(paged_kl_worst < 0.08, "KV4 Layer3 paged worst KL too high: {paged_kl_worst}");

        // ---- 4. Three targeted sabotage negative controls (all run with `dry_state = true` against clean state):
        //      4a. Swap hi/lo nibbles `b.rotate_left(4)` across `lane_sab`'s blocks while keeping every `fp16` RMS scale `sc` intact!
        let sab_pos = prompt_a.len() + dec_steps - 1;
        // First capture clean `dry_state = true` baseline at `sab_pos` before any mutation.
        // Wait: `lane_a` already advanced `cs` through `sab_pos` on step 7; let's re-bind `lane_a` cleanly to `shared_len`
        // or snapshot `lane_a`'s `cs` before step 7? Even better: `cold_prefill_a` on a fresh `lane_sab`!
        {
            let lane_sab = Lane::new_blocked(&eng4, 1024);
            let mut st_sab = LaneBlockState::default();
            let matched_sab = cache
                .match_and_bind(&mut eng4.block_pool().borrow_mut(), &mut lane_sab.block_table().borrow_mut(), &mut st_sab, &prompt_a)
                .expect("warm match for sabotage lane");
            eng4.on(&lane_sab).set_cs(&matched_sab.1);
            eng4.on(&lane_sab).set_tokens(0, &seq_a);
            cache
                .ensure_span_blocks(&mut eng4.block_pool().borrow_mut(), &mut lane_sab.block_table().borrow_mut(), shared_len, tail_len)
                .unwrap();
            {
                let cb = eng4.gpu.cmd();
                eng4.encode_spans(&cb, &[Span { lane: &lane_sab, p0: shared_len, t: tail_len }], false, false);
                cb.commit();
                crate::metal::wait_completed(&cb, "sabotage tail prefill", 0).expect("sabotage tail prefill");
            }
            cache
                .ensure_span_blocks(&mut eng4.block_pool().borrow_mut(), &mut lane_sab.block_table().borrow_mut(), prompt_a.len(), 1)
                .unwrap();

            // Baseline clean dry decode at `pos = prompt_a.len()` (`step = 0`, must match `l3_dec_rows_a[0]` bit-for-bit!).
            {
                let cb = eng4.gpu.cmd();
                eng4.encode_decode(&cb, &[Span { lane: &lane_sab, p0: prompt_a.len(), t: 1 }], true, true);
                cb.commit();
                crate::metal::wait_completed(&cb, "sabotage clean dry baseline", 0).expect("sabotage clean dry baseline");
            }
            let clean_step0 = eng4.span_logits(0).to_vec();
            let clean_step0_bits: Vec<u32> = clean_step0.iter().map(|x| x.to_bits()).collect();
            let ref_step0_bits: Vec<u32> = l3_dec_rows_a[0].iter().map(|x| x.to_bits()).collect();
            assert_same_logits(&clean_step0_bits, &ref_step0_bits);

            // Sabotage Control 4a: Swap hi/lo nibbles `(b >> 4) | (b << 4)` in `lane_sab`'s private tail block (`BlockIndex(4)`)
            // while leaving all `fp16` RMS scales `sc` (`+64..+66`) 100% untouched!
            let tail_bi = BlockIndex::new((shared_len / BLOCK) as u32);
            let mut saved_tail_blocks = Vec::new();
            {
                let mut pools = eng4.block_pool().borrow_mut();
                for kind in [BlockKind::Full, BlockKind::Window] {
                    let entry = lane_sab.block_table().borrow().get(kind, tail_bi).unwrap().unwrap();
                    let slot_bytes = pools.of_mut(kind).slot_bytes_mut(entry.slot()).unwrap();
                    saved_tail_blocks.push((kind, entry.slot(), slot_bytes.to_vec()));
                    for row_chunk in slot_bytes.as_chunks_mut::<{ KV4_ROW_BYTES as usize }>().0 {
                        for b in &mut row_chunk[..64] {
                            *b = (*b).rotate_left(4);
                        }
                        // `row_chunk[64..66]` (`fp16` scale `sc`) intentionally left intact!
                    }
                }
            }
            {
                let cb = eng4.gpu.cmd();
                eng4.encode_decode(&cb, &[Span { lane: &lane_sab, p0: prompt_a.len(), t: 1 }], true, true);
                cb.commit();
                crate::metal::wait_completed(&cb, "sabotage 4a nibble swap", 0).expect("sabotage 4a nibble swap");
            }
            let sab_nibble_logits = eng4.span_logits(0).to_vec();
            let (sab_nib_ac, clean_ac, sab_nib_kl) = kl_and_argmax(&sab_nibble_logits, &clean_step0, softcap);
            eprintln!(
                "[kv4-m5-gate] sabotage 4a (hi/lo nibble swap, sc intact): clean_argmax={clean_ac}, sab_argmax={sab_nib_ac}, KL={sab_nib_kl:.6}"
            );
            assert!(
                sab_nib_kl > 0.05 || sab_nib_ac != clean_ac,
                "hi/lo nibble-swap sabotage was NOT detected: sab_nib_kl={sab_nib_kl}, sab_nib_ac={sab_nib_ac}"
            );
            // Restore clean tail block bytes and verify exact recovery before running Sabotage 4b!
            {
                let mut pools = eng4.block_pool().borrow_mut();
                for (kind, slot, orig) in saved_tail_blocks {
                    pools.of_mut(kind).slot_bytes_mut(slot).unwrap().copy_from_slice(&orig);
                }
            }

            // Sabotage Control 4b: Zero `K_DC_ROT` (`98,304` B) in `eng4.pb` at attention time AFTER all 288 keys
            // were DC-centered during prefill — omitting the `-<qp, mu_rot>` sink fold MUST spike KL!
            let orig_dc = eng4.kv4_dc_table_bytes().to_vec();
            eng4.set_kv4_dc_table_bytes(&vec![0u8; Engine::KV4_DC_TABLE_BYTES]);
            {
                let cb = eng4.gpu.cmd();
                eng4.encode_decode(&cb, &[Span { lane: &lane_sab, p0: prompt_a.len(), t: 1 }], true, true);
                cb.commit();
                crate::metal::wait_completed(&cb, "sabotage 4b zeroed K_DC_ROT", 0).expect("sabotage 4b zeroed K_DC_ROT");
            }
            let sab_dc_logits = eng4.span_logits(0).to_vec();
            eng4.set_kv4_dc_table_bytes(&orig_dc);
            let (sab_dc_ac, _, sab_dc_kl) = kl_and_argmax(&sab_dc_logits, &clean_step0, softcap);
            eprintln!(
                "[kv4-m5-gate] sabotage 4b (zeroed K_DC_ROT at attention after centered write): clean_argmax={clean_ac}, sab_argmax={sab_dc_ac}, KL={sab_dc_kl:.6}"
            );
            assert!(
                sab_dc_kl > 0.02 || sab_dc_ac != clean_ac,
                "zeroed K_DC_ROT attention sabotage was NOT detected: sab_dc_kl={sab_dc_kl}, sab_dc_ac={sab_dc_ac}"
            );

            // Sabotage Control 4c: Invert nibbles (`^= 0xFF`) and overwrite `fp16` RMS scale `sc` (`+64..+66`)
            // with `half(-32.0)` (`0xD000`) across `lane_sab`'s private tail blocks!
            {
                let mut pools = eng4.block_pool().borrow_mut();
                for kind in [BlockKind::Full, BlockKind::Window] {
                    let entry = lane_sab.block_table().borrow().get(kind, tail_bi).unwrap().unwrap();
                    let slot_bytes = pools.of_mut(kind).slot_bytes_mut(entry.slot()).unwrap();
                    for row_chunk in slot_bytes.as_chunks_mut::<{ KV4_ROW_BYTES as usize }>().0 {
                        for b in &mut row_chunk[..64] {
                            *b ^= 0xFF;
                        }
                        row_chunk[64..66].copy_from_slice(&0xD000u16.to_le_bytes());
                    }
                }
            }
            {
                let cb = eng4.gpu.cmd();
                eng4.encode_decode(&cb, &[Span { lane: &lane_sab, p0: prompt_a.len(), t: 1 }], true, true);
                cb.commit();
                crate::metal::wait_completed(&cb, "sabotage 4c inverted nibbles + scale", 0)
                    .expect("sabotage 4c inverted nibbles + scale");
            }
            let sab_scale_logits = eng4.span_logits(0).to_vec();
            let (sab_sc_ac, _, sab_sc_kl) = kl_and_argmax(&sab_scale_logits, &clean_step0, softcap);
            eprintln!(
                "[kv4-m5-gate] sabotage 4c (inverted nibbles + fp16 scale -32.0): clean_argmax={clean_ac}, sab_argmax={sab_sc_ac}, KL={sab_sc_kl:.6}"
            );
            assert!(
                sab_sc_kl > 0.25 || sab_sc_ac != clean_ac,
                "inverted-nibbles + scale -32.0 sabotage was NOT detected: sab_sc_kl={sab_sc_kl}, sab_sc_ac={sab_sc_ac}"
            );

            cache.release_lane(&mut eng4.block_pool().borrow_mut(), &mut lane_sab.block_table().borrow_mut(), &mut st_sab);
        }
        let _ = sab_pos;

        cache.release_lane(&mut eng4.block_pool().borrow_mut(), &mut lane_a.block_table().borrow_mut(), &mut st_a);
        cache.release_lane(&mut eng4.block_pool().borrow_mut(), &mut lane_b.block_table().borrow_mut(), &mut st_b);
        cache.shutdown(&mut eng4.block_pool().borrow_mut());
        drop(cache);
        super::assert_zero_pool_leaks(&eng4.block_pool().borrow());

        // Reopening the `--kv4` spill directory after shutdown in FP16, KV8, OR `--kv4` with a mismatched
        // `K_DC_ROT` digest must fail closed with `SpillError::ModeMismatch`, while reopening with the
        // matching `kv4_digest` succeeds cleanly!
        assert!(matches!(
            SpillStore::open_with_mode(&dir.0, 256 * 1024 * 1024, KvMode::Fp16),
            Err(SpillError::ModeMismatch { .. })
        ));
        assert!(matches!(
            SpillStore::open_with_mode(&dir.0, 256 * 1024 * 1024, KvMode::Kv8),
            Err(SpillError::ModeMismatch { .. })
        ));
        let mut mutated_digest = kv4_digest;
        mutated_digest[0] ^= 0x01;
        assert!(matches!(
            SpillStore::open_with_kv4_digest(&dir.0, 256 * 1024 * 1024, mutated_digest),
            Err(SpillError::ModeMismatch { .. })
        ));
        let reopened_ok = SpillStore::open_with_kv4_digest(&dir.0, 256 * 1024 * 1024, kv4_digest).unwrap();
        assert_eq!(reopened_ok.kvb(), KVB_KV4);
        drop(reopened_ok);

        // And `open_or_rotate_stale` (`inky serve` boot path) moves the stale spill directory aside intact
        // to `<spill-dir>.stale-<unix_ts>` and boots a clean empty `SpillStore` instead of exiting 2!
        let (fresh_store, rot) =
            SpillStore::open_or_rotate_stale(&dir.0, 256 * 1024 * 1024, KvMode::Kv4, Some(mutated_digest)).unwrap();
        let rot = rot.expect("digest mismatch must trigger stale spill rotation");
        assert_eq!(fresh_store.kvb(), KVB_KV4);
        assert!(rot.moved_to.exists(), "rotated stale spill dir must exist intact");
        let preserved = SpillStore::open_with_kv4_digest(&rot.moved_to, 256 * 1024 * 1024, kv4_digest).unwrap();
        assert_eq!(preserved.kvb(), KVB_KV4);
        drop(preserved);
        drop(fresh_store);
        let _ = std::fs::remove_dir_all(&rot.moved_to);
    }
}