hf2q 0.1.33

Pure Rust CLI for converting HuggingFace models to hardware-optimized formats and serving them over an OpenAI-compatible API on Apple Silicon
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
//! Issue #727: admission decides spill/restore by longest prefix, and a
//! reclaimed conversation is restored bitwise into whatever slot it is
//! granted on its return. The shared store's own tests are in
//! `slot_spill_tests.rs`.

use mlx_native::MlxDevice;

use super::super::slot_spill::{plan_reclaim, ReclaimPlan, SlotSpillStore, VictimSpill};
use super::super::{Qwen35PromptAnchor, Qwen35RetainedPrefix, Qwen35SlotPreference, SlotId};
use super::{
    qwen35_best_ledger_match, reclaim_qwen35_slot, spill_reclaimed_qwen35_slot,
    Qwen35SlotSpillStore,
};
use crate::inference::models::qwen35::kv_cache::HybridKvCache;
use crate::inference::models::qwen35::{default_layer_types, Qwen35Config, Qwen35Variant};
use crate::serve::api::engine_qwen35::anchor_store::Qwen35AnchorStore;
use super::super::{InflightBatchedScheduler, PromptCache, Qwen35KvGuard, Qwen35Slot};
use crate::serve::scheduler::Scheduler;

fn preference(cached_tokens: usize, anchor: bool) -> Qwen35SlotPreference {
    Qwen35SlotPreference {
        slot: SlotId(0),
        cached_tokens,
        restore_prompt_anchor: anchor,
        use_prefill_logits: false,
    }
}

/// The shared reclaim plan at Qwen's types.
fn qwen_plan(
    in_place: Option<Qwen35SlotPreference>,
    spill_match: Option<(usize, Qwen35SlotPreference)>,
    prompt_tokens: &[u32],
    victim_retained: &[u32],
    victim_has_ledger: bool,
) -> ReclaimPlan<usize, Qwen35SlotPreference> {
    plan_reclaim(
        in_place,
        spill_match,
        prompt_tokens,
        victim_retained,
        victim_has_ledger,
    )
}

#[test]
fn reclaim_plan_spills_only_discarded_state_and_restores_only_longer_matches() {
    let live = preference(30, false);
    let anchor = preference(12, true);
    let spill = |tokens| Some((3, preference(tokens, false)));
    // The occupant: stable anchor 0..12, then the assistant header 12..14,
    // reasoning and answer up to 30.
    let occupant: Vec<u32> = (0..30).collect();
    let other: Vec<u32> = (500..520).collect();
    let mut continuation: Vec<u32> = occupant[..14].to_vec();
    continuation.extend([900, 901, 902]);
    let mut fork: Vec<u32> = occupant[..12].to_vec();
    fork.extend([700, 701]);
    let mut extended = occupant.clone();
    extended.push(31);

    // Cold admission into an occupied slot: move its ledger into the store.
    let plan = qwen_plan(None, None, &other, &occupant, true);
    assert_eq!((plan.restore, plan.victim), (None, VictimSpill::Move));
    // Cold admission into an empty slot spills nothing.
    let plan = qwen_plan(None, None, &other, &[], false);
    assert_eq!(plan.victim, VictimSpill::Keep);
    // A live-tail resume keeps the slot's conversation.
    let plan = qwen_plan(Some(live), None, &extended, &occupant, true);
    assert_eq!((plan.restore, plan.victim), (None, VictimSpill::Keep));
    // The occupant's own next turn or retry rewinds to its stable anchor but
    // shares the assistant header beyond it: no copy.
    let plan = qwen_plan(Some(anchor), None, &continuation, &occupant, true);
    assert_eq!(plan.victim, VictimSpill::Keep);
    // A request that starts new content exactly at the anchor (a fork, or
    // another conversation sharing the anchor) would discard the occupant's
    // tail: copy the ledger, the anchor stays in place for this request.
    let plan = qwen_plan(Some(anchor), None, &fork, &occupant, true);
    assert_eq!(plan.victim, VictimSpill::Copy);
    // No tail beyond the anchor: nothing to lose.
    let plan = qwen_plan(Some(anchor), None, &fork, &occupant[..12], true);
    assert_eq!(plan.victim, VictimSpill::Keep);

    // A spill restores only when it resumes strictly more tokens.
    let plan = qwen_plan(Some(anchor), spill(16), &continuation, &occupant, true);
    assert_eq!(plan.restore, spill(16));
    assert_eq!(plan.victim, VictimSpill::Move);
    // A spill matching no more than the live tail (30 tokens) stays stored.
    let plan = qwen_plan(Some(live), spill(30), &extended, &occupant, true);
    assert_eq!((plan.restore, plan.victim), (None, VictimSpill::Keep));
    let plan = qwen_plan(None, spill(8), &other, &[], false);
    assert_eq!((plan.restore, plan.victim), (spill(8), VictimSpill::Keep));
}

#[test]
fn ledger_match_is_longest_prefix_then_newest() {
    let prompt: Vec<u32> = (1..=20).collect();
    let other: Vec<u32> = (100..120).collect();
    // Newest first: index 2 is newest.
    let candidates = [
        (2, &prompt[..8], Some(&prompt[..4])),
        (1, &prompt[..12], Some(&prompt[..4])),
        (0, &prompt[..12], Some(&prompt[..4])),
    ];
    let (index, best) = qwen35_best_ledger_match(candidates, &prompt).expect("match");
    assert_eq!(
        (index, best.cached_tokens),
        (1, 12),
        "longest, newest on ties"
    );
    assert!(!best.restore_prompt_anchor);

    // A full-prompt anchor beats a shorter live tail and reuses its logits.
    let candidates = [(0, &prompt[..15], None), (1, &other[..], Some(&prompt[..]))];
    let (index, best) = qwen35_best_ledger_match(candidates, &prompt).expect("match");
    assert_eq!((index, best.cached_tokens), (1, 20));
    assert!(best.restore_prompt_anchor && best.use_prefill_logits);

    // A live tail must be a strict prefix; unrelated ledgers never match.
    assert!(qwen35_best_ledger_match([(0, &prompt[..], None)], &prompt).is_none());
    assert!(qwen35_best_ledger_match([(0, &other[..5], Some(&other[..3]))], &prompt).is_none());
}

/// Two full-attention layers, two DeltaNet layers, no MTP.
fn tiny_cfg() -> Qwen35Config {
    Qwen35Config {
        variant: Qwen35Variant::Dense,
        hidden_size: 64,
        num_hidden_layers: 4,
        num_attention_heads: 2,
        num_key_value_heads: 2,
        head_dim: 32,
        linear_num_key_heads: 2,
        linear_num_value_heads: 4,
        linear_key_head_dim: 8,
        linear_value_head_dim: 8,
        linear_conv_kernel_dim: 4,
        full_attention_interval: 2,
        layer_types: default_layer_types(4, 2),
        partial_rotary_factor: 0.25,
        rope_theta: 1e7,
        rotary_dim: 8,
        mrope_section: [2, 2, 2, 2],
        mrope_interleaved: true,
        rms_norm_eps: 1e-6,
        max_position_embeddings: 4096,
        vocab_size: 256,
        attn_output_gate: true,
        mtp_num_hidden_layers: 0,
        mtp_use_dedicated_embeddings: true,
        intermediate_size: Some(128),
        moe: None,
    }
}

fn set_cursor(cache: &mut HybridKvCache, slot: SlotId, cursor: u32) {
    for block in &mut cache.full_attn {
        block.current_len[slot.0 as usize] = cursor;
    }
}

/// Fill `slot`'s region of every buffer with a seed-distinct pattern.
fn plant(cache: &mut HybridKvCache, slot: SlotId, seed: usize) {
    let n_seqs = cache.n_seqs as usize;
    let fill = |buffer: &mut mlx_native::MlxBuffer, index: usize| {
        let region = buffer.byte_len() / n_seqs;
        let start = slot.0 as usize * region;
        let bytes = buffer.as_mut_slice::<u8>().expect("cache bytes");
        for (offset, byte) in bytes[start..start + region].iter_mut().enumerate() {
            *byte = ((seed * 29 + index * 13 + offset) % 251) as u8;
        }
    };
    let mut index = 0;
    for block in &mut cache.full_attn {
        let tq = block.tq.as_mut().expect("TQ cache");
        for buffer in [
            &mut tq.k_packed,
            &mut tq.k_norms,
            &mut tq.v_packed,
            &mut tq.v_norms,
        ] {
            fill(buffer, index);
            index += 1;
        }
    }
    for linear in &mut cache.linear_attn {
        for buffer in [
            &mut linear.conv_state,
            &mut linear.conv_state_scratch,
            &mut linear.recurrent,
            &mut linear.recurrent_scratch,
        ] {
            fill(buffer, index);
            index += 1;
        }
        linear.pp_flipped[slot.0 as usize] = seed % 2 == 1;
    }
}

/// Conversation A in `slot`: an anchor at `anchor_len` tokens, then a live
/// tail up to `tokens.len()`.
fn seat_conversation(
    cache: &mut HybridKvCache,
    slot: SlotId,
    tokens: &[u32],
    anchor_len: usize,
    seed: usize,
) -> (Qwen35RetainedPrefix, Qwen35AnchorStore) {
    plant(cache, slot, seed);
    set_cursor(cache, slot, anchor_len as u32);
    let kv = cache
        .snapshot_slot_anchor(slot, anchor_len)
        .expect("anchor checkpoint");
    set_cursor(cache, slot, tokens.len() as u32);
    let retained = Qwen35RetainedPrefix {
        tokens: tokens.to_vec(),
        spec: None,
        draft_prefix: Default::default(),
    };
    let mut anchors = Qwen35AnchorStore::new(4).expect("test anchor store");
    anchors
        .stage(
            seed as u64,
            Qwen35PromptAnchor {
                id: 0,
                request: 0,
                prompt_tokens: tokens[..anchor_len].to_vec(),
                kv,
                prefill_logits: vec![0.25; 8],
                vision_fingerprint: None,
                spec: None,
                draft: None,
                discard_only: false,
                draft_prefix: Default::default(),
            },
        )
        .expect("stage anchor");
    anchors.commit(seed as u64, false).expect("commit anchor");
    (retained, anchors)
}

#[test]
fn copied_spill_and_live_prefix_share_full_parent_until_the_final_owner_releases() {
    use crate::inference::models::qwen35::carry_memory::CarryOwners;
    use crate::serve::api::engine_qwen35::Qwen35SpecPrefixBoundary;
    use mlx_native::DType;
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let Ok(device) = MlxDevice::new() else { return };
    let mut cache = HybridKvCache::new_with_options(&tiny_cfg(), &device, 32, 2, true).unwrap();
    let (mut retained, mut anchors) = seat_conversation(
        &mut cache, SlotId(0), &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 6, 1,
    );
    let parent = device.alloc_buffer(8 * 64 * 4, DType::F32, vec![8, 64]).unwrap();
    let backing_bytes = parent.byte_len() as u64;
    // Different slots/windows of one padded joint parent, not logical rows.
    let active = parent.slice_view(7 * 64 * 4, 64);
    retained.spec = Some(Qwen35SpecPrefixBoundary {
        token_count: 10, pending_target_hidden: parent.slice_view(64 * 4, 64),
    });
    drop(parent);
    let mut store = Qwen35SlotSpillStore::new(1 << 30, 8);
    super::spill_qwen35_victim(
        &cache, &mut store, SlotId(0), &mut retained, &mut anchors, VictimSpill::Copy,
        None,
    ).expect("spill copied state");
    assert_eq!(store.len(), 1);
    assert!(store.resident_bytes() > backing_bytes, "full host KV/ledger payload stays charged");
    let mut joined = CarryOwners::default();
    joined.include(&active);
    joined.include(&retained.spec.as_ref().unwrap().pending_target_hidden);
    super::include_carry_owners(&store, &mut joined);
    assert_eq!(joined.bytes(), backing_bytes);
    let replacement = device.alloc_buffer(3 * 64 * 4, DType::F32, vec![3, 64]).unwrap();
    retained.spec = Some(Qwen35SpecPrefixBoundary {
        token_count: 10, pending_target_hidden: replacement.slice_view(2 * 64 * 4, 64),
    });
    drop(active);
    drop(joined);
    let mut replaced = CarryOwners::default();
    replaced.include(&retained.spec.as_ref().unwrap().pending_target_hidden);
    super::include_carry_owners(&store, &mut replaced);
    assert_eq!(replaced.bytes(), backing_bytes + replacement.byte_len() as u64);
    drop(replaced);
    drop(store);
    let mut remaining = CarryOwners::default();
    remaining.include(&retained.spec.as_ref().unwrap().pending_target_hidden);
    assert_eq!(remaining.bytes(), replacement.byte_len() as u64);
}

#[test]
fn reclaimed_conversation_is_spilled_then_restored_bitwise_into_its_granted_slot() {
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let device = MlxDevice::new().expect("Metal device");
    let mut cache = HybridKvCache::new_with_options(&tiny_cfg(), &device, 32, 3, true)
        .expect("three-slot cache");
    let mut retained: Vec<Qwen35RetainedPrefix> =
        (0..3).map(|_| Qwen35RetainedPrefix::default()).collect();
    let mut anchors: Vec<Qwen35AnchorStore> = (0..3)
        .map(|_| Qwen35AnchorStore::new(4).expect("test anchor store"))
        .collect();
    let mut store: Qwen35SlotSpillStore = SlotSpillStore::new(1 << 30, 8);

    let a: Vec<u32> = (1..=10).collect();
    (retained[0], anchors[0]) = seat_conversation(&mut cache, SlotId(0), &a, 6, 1);
    let a_state = cache.spill_slot(SlotId(0)).expect("reference copy of A");

    // A cold request C is granted A's idle slot: A moves into the store.
    let c = [50u32, 51, 52];
    let granted = reclaim_qwen35_slot(
        &mut cache,
        &mut store,
        SlotId(0),
        &mut retained[0],
        &mut anchors[0],
        None,
        &c,
        None,
        None,
        None,
        false,
    )
    .expect("cold reclaim");
    assert_eq!(granted, None, "C stays cold");
    assert_eq!(store.len(), 1);
    assert!(retained[0].is_empty() && anchors[0].is_empty());

    // C runs in slot 0 and overwrites it.
    cache.reset_for_slot(SlotId(0)).expect("cold reset");
    plant(&mut cache, SlotId(0), 2);
    set_cursor(&mut cache, SlotId(0), 4);
    retained[0].tokens = vec![50, 51, 52, 53];

    // A returns with one more turn and is granted the empty slot 2.
    let mut a_turn: Vec<u32> = a.clone();
    a_turn.extend([11, 12]);
    let granted = reclaim_qwen35_slot(
        &mut cache,
        &mut store,
        SlotId(2),
        &mut retained[2],
        &mut anchors[2],
        None,
        &a_turn,
        None,
        None,
        None,
        false,
    )
    .expect("restore A");
    assert_eq!(
        granted,
        Some(Qwen35SlotPreference {
            slot: SlotId(2),
            cached_tokens: 10,
            restore_prompt_anchor: false,
            use_prefill_logits: false,
        }),
        "A resumes its live tail in slot 2"
    );
    assert!(store.is_empty(), "a restored spill leaves the store");
    assert_eq!(retained[2].tokens, a);
    assert_eq!(
        anchors[2]
            .deepest()
            .map(|anchor| anchor.prompt_tokens.as_slice()),
        Some(&a[..6])
    );
    assert!(
        cache.spill_slot(SlotId(2)).expect("restored A").observable_state_eq(&a_state),
        "slot 2 holds A's state bitwise"
    );
    assert_eq!(retained[0].tokens, vec![50, 51, 52, 53], "C is untouched");

    // D shares A's anchor and rewinds slot 2 to it: A's tail is copied out
    // while the anchor stays in place for D.
    let mut d = a[..6].to_vec();
    d.push(99);
    let in_place = Some(Qwen35SlotPreference {
        slot: SlotId(2),
        cached_tokens: 6,
        restore_prompt_anchor: true,
        use_prefill_logits: false,
    });
    let granted = reclaim_qwen35_slot(
        &mut cache,
        &mut store,
        SlotId(2),
        &mut retained[2],
        &mut anchors[2],
        in_place,
        &d,
        None,
        None,
        None,
        false,
    )
    .expect("anchor reclaim");
    assert_eq!(granted, in_place);
    assert_eq!(store.len(), 1);
    assert_eq!(retained[2].tokens, a, "the slot ledger is unchanged");
    assert!(!anchors[2].is_empty());

    // A's own next turn also rewinds slot 2 to the anchor, but it shares the
    // tokens after it (the assistant header): no copy is taken.
    let mut continuation = a[..8].to_vec();
    continuation.push(77);
    let granted = reclaim_qwen35_slot(
        &mut cache,
        &mut store,
        SlotId(2),
        &mut retained[2],
        &mut anchors[2],
        in_place,
        &continuation,
        None,
        None,
        None,
        false,
    )
    .expect("continuation keeps its slot");
    assert_eq!(granted, in_place);
    assert_eq!(store.len(), 1, "a continuation copies nothing");

    // A returns again, granted slot 1: its copied tail is restored.
    a_turn.push(13);
    let granted = reclaim_qwen35_slot(
        &mut cache,
        &mut store,
        SlotId(1),
        &mut retained[1],
        &mut anchors[1],
        None,
        &a_turn,
        None,
        None,
        None,
        false,
    )
    .expect("restore A again");
    assert_eq!(granted.map(|preference| preference.cached_tokens), Some(10));
    assert!(store.is_empty());
    assert!(cache.spill_slot(SlotId(1)).expect("restored A").observable_state_eq(&a_state));

    // An embedding request takes slot 1 over: A is spilled again.
    spill_reclaimed_qwen35_slot(
        &cache,
        &mut store,
        SlotId(1),
        &mut retained[1],
        &mut anchors[1],
        None,
    ).expect("spill embedding victim");
    assert_eq!(store.len(), 1);
    assert!(retained[1].is_empty() && anchors[1].is_empty());
}

#[test]
fn a_spill_above_the_budget_is_not_stored_and_the_victim_goes_cold() {
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let device = MlxDevice::new().expect("Metal device");
    let mut cache =
        HybridKvCache::new_with_options(&tiny_cfg(), &device, 32, 2, true).expect("two-slot cache");
    let a: Vec<u32> = (1..=10).collect();
    let (mut retained, mut anchor) = seat_conversation(&mut cache, SlotId(0), &a, 6, 1);
    let mut store: Qwen35SlotSpillStore = SlotSpillStore::new(1024, 8);
    let granted = reclaim_qwen35_slot(
        &mut cache,
        &mut store,
        SlotId(0),
        &mut retained,
        &mut anchor,
        None,
        &[7, 7, 7],
        None,
        None,
        None,
        false,
    )
    .expect("cold reclaim");
    assert_eq!(granted, None);
    assert!(store.is_empty(), "a 1 KiB budget cannot hold the slot");
    // The ledger stays for admission's ordinary cold clear.
    assert_eq!(retained.tokens, a);
}

fn paired_parent(
    cache: &mut HybridKvCache,
    runtime: &mut crate::inference::spec_decode::dflash2::runtime::DFlash2Runtime,
    device: &MlxDevice,
    slot: SlotId,
    tokens: &[u32],
) -> (Qwen35RetainedPrefix, Qwen35AnchorStore) {
    runtime.test_bind_lane_checkpoint_tokens(slot.0 as usize, tokens).unwrap();
    let image = std::sync::Arc::new(runtime.snapshot_lane_checkpoint(device, slot.0 as usize).unwrap());
    let (mut retained, old) = seat_conversation(cache, slot, tokens, tokens.len(), 9);
    retained.draft_prefix = crate::serve::api::engine_qwen35::Qwen35DraftPrefix::Maintained;
    let mut anchor = old.deepest().unwrap().clone();
    anchor.draft = Some(image);
    anchor.draft_prefix = retained.draft_prefix;
    let mut store = Qwen35AnchorStore::new(1).unwrap();
    store.stage(1, anchor).unwrap();
    store.commit(1, false).unwrap();
    (retained, store)
}

#[test]
fn paired_restore_and_cancellation_recover_wrapped_parents_without_touching_peers() {
    use crate::inference::spec_decode::dflash2::runtime::DFlash2Runtime;
    use crate::serve::api::engine_qwen35::anchor_store::{
        recover_cancelled_prefix, restore_committed_anchor, AnchorRecovery,
    };
    use crate::serve::api::engine_supervisor::EngineSupervisor;
    use crate::inference::models::qwen35::kv_cache::LaRestoreRoute;
    fn active_linear(cache: &HybridKvCache, slot: SlotId) -> Vec<Vec<u8>> {
        let mut active = Vec::with_capacity(cache.linear_attn.len() * 2);
        for layer in &cache.linear_attn {
            let buffers = if layer.pp_flipped[slot.0 as usize] {
                [&layer.conv_state_scratch, &layer.recurrent_scratch]
            } else {
                [&layer.conv_state, &layer.recurrent]
            };
            for buffer in buffers {
                let bytes = buffer.byte_len() / cache.n_seqs as usize;
                let start = slot.0 as usize * bytes;
                active.push(buffer.as_slice::<u8>().unwrap()[start..start + bytes].to_vec());
            }
        }
        active
    }
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let Ok(device) = MlxDevice::new() else { return };
    let supervisor = EngineSupervisor::new();
    for parent_len in [7, 19] {
        let mut cache = HybridKvCache::new_with_options(&tiny_cfg(), &device, 64, 3, true).unwrap();
        cache.set_la_restore_route(LaRestoreRoute::Gpu);
        let mut runtime = DFlash2Runtime::test_for_lane_checkpoints(&device, 3, 8).unwrap();
        let parent: Vec<u32> = (100..100 + parent_len).collect();
        let prediction: Vec<u32> = (100..110 + parent_len).collect();
        let (mut retained, mut anchors) =
            paired_parent(&mut cache, &mut runtime, &device, SlotId(0), &parent);
        let parent_active = active_linear(&cache, SlotId(0));
        let parent_draft = runtime.test_lane_checkpoint_bits(0).unwrap();
        let id = anchors.deepest().unwrap().id;
        plant(&mut cache, SlotId(1), 33);
        set_cursor(&mut cache, SlotId(1), 5);
        runtime.test_bind_lane_checkpoint_tokens(1, &[90, 91, 92, 93, 94]).unwrap();
        let peer_target = cache.spill_slot(SlotId(1)).unwrap();
        let peer_draft = runtime.test_lane_checkpoint_bits(1).unwrap();

        runtime.test_bind_lane_checkpoint_tokens(0, &prediction).unwrap();
        set_cursor(&mut cache, SlotId(0), prediction.len() as u32);
        assert!(!runtime.align_lane_prefix(0, &parent), "wrapped rewind must need the owned image");
        // Snapshot captures only the active DeltaNet buffers; canonical
        // restoration writes them to main and publishes parity=false. Compare
        // full physical state with the independent Host restore from exactly
        // this prediction state, not the parent's old ping-pong layout.
        let mut reference = HybridKvCache::new_with_options(&tiny_cfg(), &device, 64, 3, true).unwrap();
        let prediction_target = cache.spill_slot(SlotId(0)).unwrap();
        let mut reference_anchor = anchors.anchor(id).unwrap().kv.clone();
        let transfer = reference.plan_slot_spill_restore(SlotId(0), &prediction_target).unwrap();
        transfer.validate_anchor(&reference_anchor).unwrap();
        let receipt = transfer.apply().unwrap();
        receipt.rebind_anchor(&mut reference_anchor).unwrap();
        drop(receipt);
        reference.set_la_restore_route(LaRestoreRoute::Host);
        let target_plan = reference.plan_slot_anchor_restore(
            SlotId(0), &reference_anchor).unwrap();
        reference.apply_slot_anchor_restore(target_plan).unwrap();
        let expected_target = reference.spill_slot(SlotId(0)).unwrap();
        restore_committed_anchor(&mut cache, SlotId(0), &mut anchors, id,
            &supervisor, Some((&device, &mut runtime))).unwrap();
        assert!(cache.spill_slot(SlotId(0)).unwrap().observable_state_eq(&expected_target));
        assert_eq!(active_linear(&cache, SlotId(0)), parent_active);
        assert_eq!(cache.sequence_len_for_slot(SlotId(0)).unwrap() as usize, parent.len());
        assert_eq!(runtime.test_lane_checkpoint_bits(0).unwrap(), parent_draft);
        assert!(runtime.align_lane_prefix(0, &parent));

        runtime.test_bind_lane_checkpoint_tokens(0, &prediction).unwrap();
        set_cursor(&mut cache, SlotId(0), prediction.len() as u32);
        let mut pending = anchors.deepest().unwrap().clone();
        pending.prompt_tokens = prediction.clone();
        pending.kv = cache.snapshot_slot_anchor(SlotId(0), prediction.len()).unwrap();
        pending.draft = Some(std::sync::Arc::new(runtime.snapshot_lane_checkpoint(&device, 0).unwrap()));
        anchors.stage(2, pending).unwrap();
        let prediction_target = cache.spill_slot(SlotId(0)).unwrap();
        let mut reference_anchor = anchors.anchor(id).unwrap().kv.clone();
        let transfer = reference.plan_slot_spill_restore(SlotId(0), &prediction_target).unwrap();
        transfer.validate_anchor(&reference_anchor).unwrap();
        let receipt = transfer.apply().unwrap();
        receipt.rebind_anchor(&mut reference_anchor).unwrap();
        drop(receipt);
        let target_plan = reference.plan_slot_anchor_restore(
            SlotId(0), &reference_anchor).unwrap();
        reference.apply_slot_anchor_restore(target_plan).unwrap();
        let expected_cancel_target = reference.spill_slot(SlotId(0)).unwrap();
        let recovery = recover_cancelled_prefix(&mut cache, SlotId(0), 2, &mut anchors,
            &mut retained.tokens, &mut retained.spec, false, &supervisor,
            Some((&device, &mut runtime)), &mut retained.draft_prefix).unwrap();
        assert_eq!(recovery, AnchorRecovery::Restored { rank: 0, tokens: parent.len() });
        assert_eq!(retained.tokens, parent);
        assert!(anchors.pending().is_none());
        assert_eq!(runtime.test_lane_checkpoint_bits(0).unwrap(), parent_draft);
        assert!(cache.spill_slot(SlotId(0)).unwrap().observable_state_eq(&expected_cancel_target));
        assert_eq!(active_linear(&cache, SlotId(0)), parent_active);
        assert_eq!(cache.sequence_len_for_slot(SlotId(0)).unwrap() as usize, parent.len());
        assert!(runtime.align_lane_prefix(0, &parent));
        assert!(cache.spill_slot(SlotId(1)).unwrap() == peer_target);
        assert_eq!(runtime.test_lane_checkpoint_bits(1).unwrap(), peer_draft);
    }
}

#[test]
fn paired_restore_preflight_is_read_only_and_partial_failure_invalidates_both_images() {
    use crate::inference::spec_decode::dflash2::runtime::DFlash2Runtime;
    use crate::serve::api::engine_qwen35::anchor_store::{restore_committed_anchor, AnchorRestoreFault};
    use crate::serve::api::engine_supervisor::EngineSupervisor;
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let Ok(device) = MlxDevice::new() else { return };
    let mut cache = HybridKvCache::new_with_options(&tiny_cfg(), &device, 64, 2, true).unwrap();
    let mut runtime = DFlash2Runtime::test_for_lane_checkpoints(&device, 2, 8).unwrap();
    let parent: Vec<u32> = (1..=19).collect();
    let prediction: Vec<u32> = (1..=29).collect();
    let (_, mut anchors) = paired_parent(&mut cache, &mut runtime, &device, SlotId(0), &parent);
    let id = anchors.deepest().unwrap().id;
    runtime.test_bind_lane_checkpoint_tokens(0, &prediction).unwrap();
    set_cursor(&mut cache, SlotId(0), prediction.len() as u32);
    let before_target = cache.spill_slot(SlotId(0)).unwrap();
    let before_draft = runtime.test_lane_checkpoint_bits(0).unwrap();
    let supervisor = EngineSupervisor::new();
    // A same-length foreign binding must fail before the target restore writes.
    anchors.deepest_mut().unwrap().prompt_tokens[0] += 1;
    assert!(restore_committed_anchor(&mut cache, SlotId(0), &mut anchors, id,
        &supervisor, Some((&device, &mut runtime))).is_err());
    assert!(cache.spill_slot(SlotId(0)).unwrap() == before_target);
    assert_eq!(runtime.test_lane_checkpoint_bits(0).unwrap(), before_draft);
    assert!(!anchors.is_poisoned() && anchors.open_transaction().is_none());
    anchors.deepest_mut().unwrap().prompt_tokens.clone_from(&parent);
    anchors.restore_fault = Some(AnchorRestoreFault::PostCommit);
    assert!(restore_committed_anchor(&mut cache, SlotId(0), &mut anchors, id,
        &supervisor, Some((&device, &mut runtime))).is_err());
    assert!(anchors.is_poisoned() && anchors.is_empty() && anchors.open_transaction().is_none());
    assert_eq!(runtime.lane_lengths()[0], 0);
    assert!(!runtime.align_lane_prefix(0, &parent));
}

#[test]
fn target_only_restore_refuses_unfinalized_context_without_consuming_completion() {
    use crate::inference::spec_decode::dflash2::{
        forward::prepare_decode_positions, runtime::DFlash2Runtime,
    };
    use crate::serve::api::engine_qwen35::anchor_store::{
        restore_committed_anchor, DFlash2CheckpointIncompatible,
    };
    use crate::serve::api::engine_supervisor::EngineSupervisor;
    use mlx_native::KernelRegistry;
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let Ok(device) = MlxDevice::new() else { return };
    let ring_bits = |runtime: &DFlash2Runtime| {
        runtime.workspace.ring_keys.iter().chain(&runtime.workspace.ring_values)
            .map(|ring| ring.as_slice::<u16>().unwrap().to_vec()).collect::<Vec<_>>()
    };
    for detached in [false, true] {
        let mut cache = HybridKvCache::new_with_options(&tiny_cfg(), &device, 64, 2, true).unwrap();
        let (_, mut anchors) = seat_conversation(&mut cache, SlotId(0), &(1..=9).collect::<Vec<_>>(), 3, 9);
        let id = anchors.deepest().unwrap().id;
        assert!(anchors.deepest().unwrap().draft.is_none());
        let mut runtime = DFlash2Runtime::test_for_prefill_checkpoints(&device, 2, 256, 128).unwrap();
        runtime.workspace.captured_target_hidden.as_mut_slice::<f32>().unwrap().fill(0.125);
        prepare_decode_positions(&mut runtime.workspace, &runtime.config, &[0, 0]).unwrap();
        let counts = [1, 0];
        let mut registry = KernelRegistry::new();
        let submitted = if detached {
            runtime.submit_target_context_detached(&device, &mut registry, &counts)
        } else {
            runtime.submit_target_context(&device, &mut registry, &counts)
        }.unwrap();
        // Wait for the real producer, but leave its completion ownership external.
        assert!(runtime.snapshot_lane_checkpoint(&device, 0).is_err());
        let target = cache.spill_slot(SlotId(0)).unwrap();
        let peer = cache.spill_slot(SlotId(1)).unwrap();
        let draft = ring_bits(&runtime);
        let lengths = runtime.lane_lengths().to_vec();
        let supervisor = EngineSupervisor::new();
        let error = restore_committed_anchor(&mut cache, SlotId(0), &mut anchors, id,
            &supervisor, Some((&device, &mut runtime))).unwrap_err();
        assert!(error.downcast_ref::<DFlash2CheckpointIncompatible>().is_some());
        assert!(cache.spill_slot(SlotId(0)).unwrap() == target);
        assert!(cache.spill_slot(SlotId(1)).unwrap() == peer);
        assert_eq!(ring_bits(&runtime), draft);
        assert_eq!(runtime.lane_lengths(), lengths.as_slice());
        assert!(!anchors.is_poisoned() && anchors.open_transaction().is_none());
        assert!(anchors.anchor(id).is_some() && supervisor.is_healthy());
        runtime.finish_target_context(submitted, &counts, !detached).unwrap();
        runtime.record_lane_tokens(0, &[7]).unwrap();
        assert_eq!(runtime.lane_lengths()[0], 1);
        restore_committed_anchor(&mut cache, SlotId(0), &mut anchors, id,
            &supervisor, Some((&device, &mut runtime))).unwrap();
        assert_eq!(cache.sequence_len_for_slot(SlotId(0)).unwrap(), 3);
        assert_eq!(runtime.lane_lengths()[0], 0);
        assert!(cache.spill_slot(SlotId(1)).unwrap() == peer);
        assert!(!anchors.is_poisoned() && supervisor.is_healthy());
    }
}

#[test]
fn paired_anchor_quota_charges_ring_owner_once_and_never_stages_target_only() {
    use crate::inference::spec_decode::dflash2::runtime::DFlash2Runtime;
    use crate::serve::api::engine_qwen35::anchor_store::draft_owned_bytes;
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let Ok(device) = MlxDevice::new() else { return };
    let mut cache = HybridKvCache::new_with_options(&tiny_cfg(), &device, 32, 1, true).unwrap();
    let mut runtime = DFlash2Runtime::test_for_lane_checkpoints(&device, 1, 8).unwrap();
    let parent: Vec<u32> = (1..=7).collect();
    let (_, anchors) = paired_parent(&mut cache, &mut runtime, &device, SlotId(0), &parent);
    let anchor = anchors.deepest().unwrap().clone();
    let image_bytes = draft_owned_bytes(anchor.draft.as_ref().unwrap());
    let mut refused = Qwen35AnchorStore::new_with_quota(1, Some(anchor.owned_bytes() - 1)).unwrap();
    assert!(refused.stage(2, anchor.clone()).is_err());
    assert!(refused.is_empty());
    let mut exact = Qwen35AnchorStore::new_with_quota(1, Some(anchor.owned_bytes() * 2)).unwrap();
    exact.stage(1, anchor.clone()).unwrap();
    exact.commit(1, false).unwrap();
    exact.stage(2, anchor.clone()).unwrap();
    assert_eq!(exact.pending_owned().payload_image, 0,
        "a copied ledger retains the same target/draft owners, not another ring charge");
    assert!(exact.committed_owned().payload_image >= image_bytes);
    let mut owners = crate::inference::models::qwen35::carry_memory::CarryOwners::default();
    exact.include_carry_owners(&mut owners);
    assert!(owners.bytes() > 0, "the retained native draft image enters the carry census");
}

#[test]
fn a_deeper_live_spill_restores_its_own_draft_image_in_another_physical_slot() {
    use crate::inference::spec_decode::dflash2::runtime::DFlash2Runtime;
    use crate::serve::api::engine_qwen35::anchor_store::restore_committed_anchor;
    use crate::serve::api::engine_supervisor::EngineSupervisor;
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let Ok(device) = MlxDevice::new() else { return };
    let mut cache = HybridKvCache::new_with_options(&tiny_cfg(), &device, 64, 3, true).unwrap();
    let mut runtime = DFlash2Runtime::test_for_lane_checkpoints(&device, 3, 8).unwrap();
    let parent: Vec<u32> = (1..=6).collect();
    let live: Vec<u32> = (1..=19).collect();
    let (mut retained, mut anchors) =
        paired_parent(&mut cache, &mut runtime, &device, SlotId(0), &parent);
    let parent_draft = runtime.test_lane_checkpoint_bits(0).unwrap();
    runtime.test_bind_lane_checkpoint_tokens(0, &live).unwrap();
    set_cursor(&mut cache, SlotId(0), live.len() as u32);
    retained.tokens.clone_from(&live);
    let live_draft = runtime.test_lane_checkpoint_bits(0).unwrap();
    let live_target = cache.spill_slot(SlotId(0)).unwrap();
    runtime.test_bind_lane_checkpoint_tokens(1, &[901, 902, 903]).unwrap();
    let peer_draft = runtime.test_lane_checkpoint_bits(1).unwrap();
    let mut store = Qwen35SlotSpillStore::new(1 << 30, 8);
    reclaim_qwen35_slot(&mut cache, &mut store, SlotId(0), &mut retained, &mut anchors,
        None, &[700, 701], None, None, Some((&device, &mut runtime)), true).unwrap();
    let mut destination = Qwen35RetainedPrefix::default();
    let mut destination_anchors = Qwen35AnchorStore::new(1).unwrap();
    let mut next_turn = live.clone();
    next_turn.push(20);
    let preference = reclaim_qwen35_slot(&mut cache, &mut store, SlotId(2),
        &mut destination, &mut destination_anchors, None, &next_turn, None, None,
        Some((&device, &mut runtime)), true).unwrap().unwrap();
    assert_eq!(preference.cached_tokens, live.len());
    assert!(!preference.restore_prompt_anchor);
    assert_eq!(runtime.test_lane_checkpoint_bits(2).unwrap(), live_draft);
    assert!(cache.spill_slot(SlotId(2)).unwrap().observable_state_eq(&live_target));
    assert!(runtime.align_lane_prefix(2, &live));
    let id = destination_anchors.deepest().unwrap().id;
    restore_committed_anchor(&mut cache, SlotId(2), &mut destination_anchors, id,
        &EngineSupervisor::new(), Some((&device, &mut runtime))).unwrap();
    assert_eq!(runtime.test_lane_checkpoint_bits(2).unwrap(), parent_draft);
    assert!(runtime.align_lane_prefix(2, &parent));
    assert_eq!(runtime.test_lane_checkpoint_bits(1).unwrap(), peer_draft);
}

#[test]
fn a_live_draft_spill_must_fit_the_existing_budget_before_either_image_is_copied() {
    use crate::inference::spec_decode::dflash2::runtime::DFlash2Runtime;
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let Ok(device) = MlxDevice::new() else { return };
    let mut cache = HybridKvCache::new_with_options(&tiny_cfg(), &device, 64, 2, true).unwrap();
    let mut runtime = DFlash2Runtime::test_for_lane_checkpoints(&device, 2, 8).unwrap();
    let parent: Vec<u32> = (1..=6).collect();
    let live: Vec<u32> = (1..=19).collect();
    let (mut retained, mut anchors) =
        paired_parent(&mut cache, &mut runtime, &device, SlotId(0), &parent);
    runtime.test_bind_lane_checkpoint_tokens(0, &live).unwrap();
    set_cursor(&mut cache, SlotId(0), live.len() as u32);
    retained.tokens.clone_from(&live);
    let before_target = cache.spill_slot(SlotId(0)).unwrap();
    let before_draft = runtime.test_lane_checkpoint_bits(0).unwrap();
    let target_and_ledger = cache.slot_spill_bytes(SlotId(0)).unwrap()
        + super::ledger_bytes(&retained, &anchors);
    let mut store = Qwen35SlotSpillStore::new(target_and_ledger as u64, 8);
    reclaim_qwen35_slot(&mut cache, &mut store, SlotId(0), &mut retained, &mut anchors,
        None, &[700, 701], None, None, Some((&device, &mut runtime)), true).unwrap();
    assert!(store.is_empty(), "the target and old anchor fitting is not enough for a deeper live ring");
    assert_eq!(retained.tokens, live);
    assert!(cache.spill_slot(SlotId(0)).unwrap() == before_target);
    assert_eq!(runtime.test_lane_checkpoint_bits(0).unwrap(), before_draft);
    assert!(anchors.open_transaction().is_none());
}

#[allow(clippy::too_many_arguments)]
fn actual_ordinary_turn(
    guard: &mut Qwen35KvGuard<'_>, scheduler: &mut InflightBatchedScheduler,
    slots: &mut [Option<Qwen35Slot>], retained: &mut [Qwen35RetainedPrefix],
    caches: &mut [PromptCache], anchors: &mut [Qwen35AnchorStore],
    prompt: &[u32], boundary: usize, cached: usize,
    supervisor: &crate::serve::api::engine_supervisor::EngineSupervisor,
) {
    use crate::serve::api::engine::{SamplingParams, SlotReply, Qwen35SlotWork};
    use crate::serve::api::engine_qwen35::{Qwen35DraftPrefix, Qwen35PrefillState};
    use crate::serve::api::engine_qwen35::decode_route_evidence::DFlash2Refusal;
    use crate::serve::scheduler::AdmitRequest;
    let handle = scheduler.admit(AdmitRequest {
        prompt_tokens: prompt.len() as u32, max_tokens: 2, kv_bytes_needed: 0,
        prompt_kv_bytes: 0, preferred_slot: Some(SlotId(0)),
    }).unwrap().handle.unwrap();
    assert_eq!(handle.slot_id, SlotId(0));
    let mut state = Qwen35PrefillState::begin(prompt.to_vec(), SamplingParams {
        max_tokens: 2, temperature: 0.0, seed: Some(7),
        stable_prompt_prefix_tokens: Some(boundary), ..SamplingParams::default()
    }, None, guard.kv.as_mut().unwrap(), handle.slot_id, cached, None, None, None,
        guard.model.hidden_size, None).unwrap();
    state.set_draft_prefix(if cached == 0 { Qwen35DraftPrefix::Maintained }
        else { retained[0].draft_prefix });
    state.set_request_exclusion(Some(DFlash2Refusal::NoJointConfiguration));
    state.set_discard_only_checkpoint(cached > 0 && anchors[0].keeps_live_parent());
    state.initialize_route_evidence(true);
    let (send, mut receive) = tokio::sync::oneshot::channel();
    slots[0] = Some((Qwen35SlotWork::Prefill(state), SlotReply::Unary(send), handle));
    let stats = std::sync::Arc::new(std::sync::Mutex::new(scheduler.stats()));
    while matches!(&slots[0], Some((Qwen35SlotWork::Prefill(_), _, _))) {
        if let Some(fatal) = super::super::advance_qwen35_prefill(
            guard, scheduler, slots, retained, caches, anchors, None, &stats,
            handle, 720, 0, supervisor) {
            panic!("ordinary-turn native prefill: {:#}", fatal.error);
        }
    }
    if !matches!(&slots[0], Some((Qwen35SlotWork::Decode(_), _, _))) {
        match receive.try_recv() {
            Ok(Err(error)) => panic!("ordinary-turn prefill failed: {error:#}"),
            Ok(Ok(done)) => panic!(
                "ordinary-turn prefill completed after {} tokens without decode",
                done.completion_tokens
            ),
            Err(error) => panic!("ordinary-turn prefill has no decode state or reply: {error}"),
        }
    }
    if let Some(fatal) = super::super::decode_batch_qwen35(
        guard, scheduler, slots, retained, caches, anchors, None,
        &[handle], 0, None, supervisor) {
        panic!("ordinary-turn native decode: {:#}", fatal.error);
    }
    let completion = receive.try_recv().expect("actual ordinary completion").unwrap();
    assert_eq!(completion.completion_tokens, 2);
    assert_eq!(completion.cached_tokens, cached);
    assert!(matches!(retained[0].draft_prefix,
        Qwen35DraftPrefix::TargetOnly(DFlash2Refusal::NoJointConfiguration)));
    assert!(slots[0].is_none() && supervisor.is_healthy());
}

#[test]
fn ordinary_tails_continue_ordinary_then_reenter_from_the_paired_ancestor_in_place_or_spilled() {
    use crate::inference::spec_decode::dflash2::runtime::DFlash2Runtime;
    use crate::inference::models::qwen35::prefill_prepared::{PrefillSwitches, SwitchesForTest};
    use crate::serve::api::engine::SamplingParams;
    use crate::serve::api::engine_qwen35::{
        Qwen35DraftPrefix, Qwen35PrefillState, Qwen35PrefillAdvance,
        anchor_store::restore_committed_anchor, prefill_fold_scheduler_tests::loaded_paired,
    };
    use crate::serve::api::engine_supervisor::EngineSupervisor;
    const PARENT: usize = 280;
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let Ok(device) = MlxDevice::new() else { return };
    let _switches = SwitchesForTest::set(PrefillSwitches {
        prepared: true, fold_cue: true, joint: false, wait_layers: 1, keep_fresh: false,
    });
    let mut reference = None;
    for reclaimed in [false, true] {
        let mut qwen = loaded_paired(&device);
        qwen.dflash2 = Some(DFlash2Runtime::test_for_prefill_checkpoints(
            &device, 2, 256, qwen.hidden_size).unwrap());
        qwen.persistent_kv_cache = Some(HybridKvCache::new_with_options(
            &qwen.model.cfg, &device, 512, 2, true).unwrap());
        let mut guard = Qwen35KvGuard::take(&mut qwen).unwrap();
        let mut scheduler = InflightBatchedScheduler::new(2, 2);
        let mut slots: Vec<Option<Qwen35Slot>> = vec![None, None];
        let mut retained = vec![Qwen35RetainedPrefix::default(); 2];
        let mut caches = vec![PromptCache::new(); 2];
        let mut anchors: Vec<_> = (0..2).map(|_| Qwen35AnchorStore::new(1).unwrap()).collect();
        let supervisor = EngineSupervisor::new();
        let first: Vec<u32> = (10..10 + PARENT as u32 + 16).collect();
        actual_ordinary_turn(&mut guard, &mut scheduler, &mut slots, &mut retained,
            &mut caches, &mut anchors, &first, PARENT, 0, &supervisor);
        let parent_id = anchors[0].deepest().unwrap().id;
        let mut second = retained[0].tokens.clone();
        second.extend(200..208);
        let cached = retained[0].len();
        actual_ordinary_turn(&mut guard, &mut scheduler, &mut slots, &mut retained,
            &mut caches, &mut anchors, &second, second.len() - 4, cached, &supervisor);
        assert_eq!(anchors[0].deepest().unwrap().id, parent_id);
        assert!(anchors[0].deepest().unwrap().draft_prefix.maintained());
        let live = retained[0].tokens.clone();
        assert!(live.len() > first.len());
        assert_eq!(guard.model.dflash2.as_ref().unwrap().lane_lengths()[0], first.len(),
            "ordinary decode/prefill must not pretend to have ingested the live tail");
        let mut prompt = live.clone();
        prompt.extend(300..308);
        let mut spills = Qwen35SlotSpillStore::new(1 << 30, 8);
        let destination = if reclaimed {
            spill_reclaimed_qwen35_slot(guard.kv.as_ref().unwrap(), &mut spills, SlotId(0),
                &mut retained[0], &mut anchors[0],
                Some((&device, guard.model.dflash2.as_mut().unwrap()))).unwrap();
            let (_, entry) = spills.newest_first().next().unwrap();
            assert!(entry.payload.live_draft.is_none(),
                "an excluded ordinary tail has no live draft image to snapshot");
            SlotId(1)
        } else { SlotId(0) };
        let peer = SlotId(1 - destination.0);
        plant(guard.kv.as_mut().unwrap(), peer, 53);
        set_cursor(guard.kv.as_mut().unwrap(), peer, 5);
        guard.model.dflash2.as_mut().unwrap().test_bind_lane_checkpoint_tokens(
            peer.0 as usize, &[901, 902, 903, 904, 905]).unwrap();
        let peer_target = guard.kv.as_ref().unwrap().spill_slot(peer).unwrap();
        let peer_draft = guard.model.dflash2.as_mut().unwrap()
            .test_lane_checkpoint_bits(peer.0 as usize).unwrap();
        let index = destination.0 as usize;
        let original = (!reclaimed).then_some(Qwen35SlotPreference {
            slot: destination, cached_tokens: live.len(), restore_prompt_anchor: false,
            use_prefill_logits: false,
        });
        let selected = reclaim_qwen35_slot(guard.kv.as_mut().unwrap(), &mut spills, destination,
            &mut retained[index], &mut anchors[index], original, &prompt, None, None,
            Some((&device, guard.model.dflash2.as_mut().unwrap())), true)
            .unwrap_or_else(|error| panic!(
                "reclaimed={reclaimed} destination={} selection: {error:#}", destination.0))
            .expect("paired ancestor selected");
        assert!(selected.restore_prompt_anchor);
        assert_eq!(selected.cached_tokens, PARENT, "replay only the suffix behind the maintained ancestor");
        let id = anchors[index].deepest_prefix_for_route(&prompt, None, None, true).unwrap().id;
        restore_committed_anchor(guard.kv.as_mut().unwrap(), destination, &mut anchors[index],
            id, &supervisor, Some((&device, guard.model.dflash2.as_mut().unwrap())))
            .unwrap_or_else(|error| panic!(
                "reclaimed={reclaimed} destination={} paired restore: {error:#}", destination.0));
        let mut state = Qwen35PrefillState::begin(prompt.clone(),
            SamplingParams { max_tokens: 2, temperature: 0.0, seed: Some(7),
                ..SamplingParams::default() }, None,
            guard.kv.as_mut().unwrap(), destination, selected.cached_tokens, None, None, None,
            guard.model.hidden_size, None).unwrap();
        state.set_draft_prefix(Qwen35DraftPrefix::Maintained);
        let Qwen35PrefillAdvance::Ready { state, prefill_logits, .. } = state.advance(
            guard.model, None, guard.kv.as_mut().unwrap(), 720, &supervisor, None)
            .unwrap_or_else(|error| panic!(
                "reclaimed={reclaimed} destination={} native suffix: {error:#}", destination.0)) else {
            panic!("the necessary suffix did not finish in its bounded native transaction");
        };
        assert_eq!(state.cached_prefix_tokens(), PARENT);
        assert!(state.draft_prefix().maintained());
        assert!(state.dflash2_readiness(guard.kv.as_ref().unwrap()).is_ok());
        assert!(guard.model.dflash2.as_mut().unwrap()
            .align_lane_prefix(index, &prompt));
        let runtime = guard.model.dflash2.as_mut().unwrap();
        runtime.prepare_lane_checkpoint_change(index).unwrap();
        let ring = runtime.test_lane_checkpoint_bits(index).unwrap();
        let generated = state.c2_generated_tokens().to_vec();
        let seed = *generated.last().expect("native prefill seed");
        let probe = guard.model.model.forward_gpu_last_logits(
            &[seed], &[prompt.len() as i32; 4], guard.kv.as_mut().unwrap(), destination).unwrap();
        let continuation = (prompt, generated,
            prefill_logits.iter().map(|value| value.to_bits()).collect::<Vec<_>>(),
            probe.iter().map(|value| value.to_bits()).collect::<Vec<_>>(), ring);
        if let Some(reference) = &reference {
            assert_eq!(&continuation, reference,
                "reclaimed continuation must match the real in-place ordinary→paired route");
        } else {
            reference = Some(continuation);
        }
        assert!(guard.kv.as_ref().unwrap().spill_slot(peer).unwrap() == peer_target);
        assert_eq!(guard.model.dflash2.as_mut().unwrap()
            .test_lane_checkpoint_bits(peer.0 as usize).unwrap(), peer_draft);
    }
}

#[test]
fn pre_submission_vision_cancellation_preserves_target_only_live_prefix_and_peer_request() {
    use crate::inference::spec_decode::dflash2::runtime::DFlash2Runtime;
    use crate::serve::api::engine::{SamplingParams, SlotReply, Qwen35SlotWork};
    use crate::serve::api::engine_qwen35::{
        Qwen35DraftPrefix, Qwen35PrefillState, Qwen35VisionPrefillData,
        decode_route_evidence::DFlash2Refusal, prefill_fold_scheduler_tests::loaded,
    };
    use crate::serve::api::engine_supervisor::EngineSupervisor;
    use crate::serve::scheduler::AdmitRequest;
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let Ok(device) = MlxDevice::new() else { return };
    let mut qwen = loaded(&device);
    qwen.dflash2 = Some(DFlash2Runtime::test_for_lane_checkpoints(&device, 2, 8).unwrap());
    let mut cache = HybridKvCache::new_with_options(&tiny_cfg(), &device, 128, 2, true).unwrap();
    let prefix: Vec<u32> = (1..=10).collect();
    let (mut saved, old) = seat_conversation(&mut cache, SlotId(0), &prefix, 6, 17);
    saved.draft_prefix = Qwen35DraftPrefix::TargetOnly(DFlash2Refusal::Vision);
    let mut image = old.deepest().unwrap().clone();
    image.vision_fingerprint = Some([4; 32]);
    image.draft_prefix = saved.draft_prefix;
    let mut vision_anchor = Qwen35AnchorStore::new(1).unwrap();
    vision_anchor.stage(1, image).unwrap();
    vision_anchor.commit(1, false).unwrap();
    plant(&mut cache, SlotId(1), 27);
    set_cursor(&mut cache, SlotId(1), 5);
    qwen.dflash2.as_mut().unwrap().test_bind_lane_checkpoint_tokens(
        1, &[901, 902, 903, 904, 905]).unwrap();
    let target_before = cache.spill_slot(SlotId(0)).unwrap();
    let peer_before = cache.spill_slot(SlotId(1)).unwrap();
    let peer_draft = qwen.dflash2.as_mut().unwrap().test_lane_checkpoint_bits(1).unwrap();
    qwen.persistent_kv_cache = Some(cache);
    let mut guard = Qwen35KvGuard::take(&mut qwen).unwrap();
    let mut scheduler = InflightBatchedScheduler::new(2, 2);
    let admit = |scheduler: &mut InflightBatchedScheduler, slot, prompt_tokens| {
        scheduler.admit(AdmitRequest { prompt_tokens, max_tokens: 2, kv_bytes_needed: 0,
            prompt_kv_bytes: 0, preferred_slot: Some(slot) }).unwrap().handle.unwrap()
    };
    let handle = admit(&mut scheduler, SlotId(0), 12);
    let peer = admit(&mut scheduler, SlotId(1), 7);
    let mut prompt = prefix.clone();
    prompt.extend([11, 12]);
    let vision_positions =
        crate::inference::models::qwen35::spec_decode::positions_for_range(0, prompt.len());
    let mut state = Qwen35PrefillState::begin(prompt, SamplingParams {
        max_tokens: 2, vision_fingerprint: Some([4; 32]), ..SamplingParams::default()
    }, None, guard.kv.as_mut().unwrap(), handle.slot_id, prefix.len(), None, None,
        Some(Qwen35VisionPrefillData::new(Vec::new(), None, Some(vision_positions))),
        guard.model.hidden_size, None).unwrap();
    state.set_draft_prefix(saved.draft_prefix);
    state.set_request_exclusion(Some(DFlash2Refusal::Vision));
    state.initialize_route_evidence(true);
    let peer_state = Qwen35PrefillState::begin(vec![901, 902, 903, 904, 905, 906, 907],
        SamplingParams { max_tokens: 2, ..SamplingParams::default() }, None,
        guard.kv.as_mut().unwrap(), peer.slot_id, 5, None, None, None,
        guard.model.hidden_size, None).unwrap();
    let (send, receive) = tokio::sync::oneshot::channel();
    let (peer_send, _peer_receive) = tokio::sync::oneshot::channel();
    let mut slots = vec![
        Some((Qwen35SlotWork::Prefill(state), SlotReply::Unary(send), handle)),
        Some((Qwen35SlotWork::Prefill(peer_state), SlotReply::Unary(peer_send), peer)),
    ];
    drop(receive);
    let mut retained = vec![saved, Qwen35RetainedPrefix::default()];
    let mut anchors = vec![vision_anchor, Qwen35AnchorStore::new(1).unwrap()];
    let mut caches = vec![PromptCache::new(); 2];
    let stats = std::sync::Arc::new(std::sync::Mutex::new(scheduler.stats()));
    let supervisor = EngineSupervisor::new();
    if let Some(fatal) = super::super::advance_qwen35_prefill(
        &mut guard, &mut scheduler, &mut slots, &mut retained, &mut caches,
        &mut anchors, None, &stats, handle, 720, 0, &supervisor) {
        panic!("legitimate pre-GPU vision cancellation became fatal: {:#}", fatal.error);
    }
    assert_eq!(retained[0].tokens, prefix);
    assert!(matches!(retained[0].draft_prefix,
        Qwen35DraftPrefix::TargetOnly(DFlash2Refusal::Vision)));
    assert!(guard.kv.as_ref().unwrap().spill_slot(SlotId(0)).unwrap() == target_before);
    assert!(guard.kv.as_ref().unwrap().spill_slot(SlotId(1)).unwrap() == peer_before);
    assert_eq!(guard.model.dflash2.as_mut().unwrap().test_lane_checkpoint_bits(1).unwrap(), peer_draft);
    assert_eq!(guard.model.dflash2.as_ref().unwrap().lane_lengths()[0], 0);
    assert!(slots[0].is_none() && slots[1].is_some());
    assert_eq!(scheduler.stats().in_flight_slots, 1);
    assert!(supervisor.is_healthy());
}

#[test]
fn tombstoned_branch_handles_stay_dead_after_same_or_changed_token_regrowth_and_transport() {
    use crate::inference::kv_slot_rows::{read_rows, write_rows};
    use crate::serve::api::engine_qwen35::anchor_store::{
        restore_committed_anchor, DFlash2CheckpointIncompatible,
    };
    use crate::serve::api::engine_supervisor::EngineSupervisor;
    let _gpu = crate::inference::hf2q_gpu_test_lock();
    let Ok(device) = MlxDevice::new() else { return };
    for same_tokens in [true, false] {
        let mut cache = HybridKvCache::new_with_options(&tiny_cfg(), &device, 64, 2, true).unwrap();
        let original: Vec<u32> = (10..26).collect();
        let (mut retained, mut anchors) =
            seat_conversation(&mut cache, SlotId(0), &original, 3, 9);
        let parent_id = anchors.deepest().unwrap().id;
        for block in &mut cache.full_attn { block.commit_written_rows(0, original.len() as u32); }
        set_cursor(&mut cache, SlotId(0), 6);
        let mut child = anchors.deepest().unwrap().clone();
        child.prompt_tokens = original[..6].to_vec();
        child.kv = cache.snapshot_slot_anchor(SlotId(0), 6).unwrap();
        let old_id = anchors.stage(2, child).unwrap();
        anchors.commit(2, false).unwrap();
        set_cursor(&mut cache, SlotId(0), original.len() as u32);
        let old_ticket = anchors.ticket(old_id).unwrap();
        anchors.abort_transaction(old_ticket).unwrap();
        let packed = &cache.full_attn[0].tq.as_ref().unwrap().k_packed;
        let original_three = read_rows(packed, 0, 2, 3, "old prefix").unwrap();
        let original_six = read_rows(packed, 0, 2, 6, "old child").unwrap();
        let supervisor = EngineSupervisor::new();
        restore_committed_anchor(&mut cache, SlotId(0), &mut anchors, parent_id,
            &supervisor, None).unwrap();
        retained.tokens.truncate(3);
        assert!(anchors.anchor(old_id).is_none());
        assert!(anchors.ticket(old_id).is_err());

        for rows in [8usize, 20] {
            for block in &mut cache.full_attn {
                let tq = block.tq.as_mut().unwrap();
                for (index, buffer) in [
                    &mut tq.k_packed, &mut tq.k_norms, &mut tq.v_packed, &mut tq.v_norms,
                ].into_iter().enumerate() {
                    let mut bytes = read_rows(buffer, 0, 2, rows, "branch rows").unwrap();
                    let heads = buffer.shape()[1];
                    let row_bytes = bytes.len() / (heads * rows);
                    for head in 0..heads {
                        bytes[(head * rows + 3) * row_bytes..(head + 1) * rows * row_bytes]
                            .fill((index + rows + 17) as u8);
                    }
                    write_rows(&bytes, buffer, 0, 2, rows, "overwrite branch").unwrap();
                }
                block.commit_written_rows(0, rows as u32);
            }
            retained.tokens = if same_tokens {
                (10..10 + rows as u32).collect()
            } else {
                original[..3].iter().copied().chain(200..200 + rows as u32 - 3).collect()
            };
            let packed = &cache.full_attn[0].tq.as_ref().unwrap().k_packed;
            assert_eq!(read_rows(packed, 0, 2, 3, "preserved prefix").unwrap(), original_three);
            assert_ne!(read_rows(packed, 0, 2, 6, "overwritten child").unwrap(), original_six);
            assert!(cache.full_attn.iter().all(|block| block.initialized_len[0] >= rows as u32));
            assert!(anchors.validate_ticket(old_ticket).is_err());
            let before = cache.spill_slot(SlotId(0)).unwrap();
            assert!(restore_committed_anchor(&mut cache, SlotId(0), &mut anchors, old_id,
                &supervisor, None).is_err());
            assert!(cache.spill_slot(SlotId(0)).unwrap() == before,
                "same_tokens={same_tokens} rows={rows}: stale handle wrote before refusal");
        }
        let mut fresh = anchors.deepest().unwrap().clone();
        fresh.prompt_tokens = retained.tokens.clone();
        fresh.kv = cache.snapshot_slot_anchor(SlotId(0), retained.len()).unwrap();
        let fresh_id = anchors.stage(3, fresh).unwrap();
        anchors.commit(3, false).unwrap();
        let source_state = cache.spill_slot(SlotId(0)).unwrap();
        let mut invalid_retained = retained.clone();
        invalid_retained.tokens[0] ^= 1;
        let mut invalid_anchors = anchors.clone();
        let mut rejected = Qwen35SlotSpillStore::new(1 << 20, 8);
        let error = spill_reclaimed_qwen35_slot(&cache, &mut rejected, SlotId(0),
            &mut invalid_retained, &mut invalid_anchors, None).err().expect("invalid token prefix");
        assert!(error.downcast_ref::<DFlash2CheckpointIncompatible>().is_some());
        assert!(rejected.is_empty());
        assert!(cache.spill_slot(SlotId(0)).unwrap() == source_state);

        let mut prompt = retained.tokens.clone();
        prompt.push(240);
        let mut spills = Qwen35SlotSpillStore::new(1 << 20, 8);
        spill_reclaimed_qwen35_slot(&cache, &mut spills, SlotId(0),
            &mut retained, &mut anchors, None).unwrap();
        cache.reset_for_slot(SlotId(0)).unwrap();
        let peer = cache.spill_slot(SlotId(0)).unwrap();
        let mut destination = Qwen35RetainedPrefix::default();
        let mut destination_anchors = Qwen35AnchorStore::new(4).unwrap();
        let selected = reclaim_qwen35_slot(&mut cache, &mut spills, SlotId(1),
            &mut destination, &mut destination_anchors, None, &prompt, None, None,
            None, false).unwrap().unwrap();
        assert_eq!(selected.cached_tokens, 20);
        assert!(cache.spill_slot(SlotId(1)).unwrap().observable_state_eq(&source_state));
        assert_eq!(destination_anchors.committed().iter().map(|anchor| anchor.id)
            .collect::<Vec<_>>(), vec![parent_id, fresh_id]);
        assert!(destination_anchors.anchor(old_id).is_none());
        assert!(destination_anchors.validate_ticket(old_ticket).is_err());
        let before = cache.spill_slot(SlotId(1)).unwrap();
        assert!(restore_committed_anchor(&mut cache, SlotId(1), &mut destination_anchors,
            old_id, &supervisor, None).is_err());
        assert!(cache.spill_slot(SlotId(1)).unwrap() == before);
        restore_committed_anchor(&mut cache, SlotId(1), &mut destination_anchors,
            fresh_id, &supervisor, None).unwrap();
        restore_committed_anchor(&mut cache, SlotId(1), &mut destination_anchors,
            parent_id, &supervisor, None).unwrap();
        assert_eq!(cache.sequence_len_for_slot(SlotId(1)).unwrap(), 3);
        let packed = &cache.full_attn[0].tq.as_ref().unwrap().k_packed;
        assert_eq!(read_rows(packed, 1, 2, 3, "transported parent").unwrap(), original_three);
        assert!(cache.spill_slot(SlotId(0)).unwrap() == peer);
    }
}