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,
}
}
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)));
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);
let plan = qwen_plan(None, None, &other, &occupant, true);
assert_eq!((plan.restore, plan.victim), (None, VictimSpill::Move));
let plan = qwen_plan(None, None, &other, &[], false);
assert_eq!(plan.victim, VictimSpill::Keep);
let plan = qwen_plan(Some(live), None, &extended, &occupant, true);
assert_eq!((plan.restore, plan.victim), (None, VictimSpill::Keep));
let plan = qwen_plan(Some(anchor), None, &continuation, &occupant, true);
assert_eq!(plan.victim, VictimSpill::Keep);
let plan = qwen_plan(Some(anchor), None, &fork, &occupant, true);
assert_eq!(plan.victim, VictimSpill::Copy);
let plan = qwen_plan(Some(anchor), None, &fork, &occupant[..12], true);
assert_eq!(plan.victim, VictimSpill::Keep);
let plan = qwen_plan(Some(anchor), spill(16), &continuation, &occupant, true);
assert_eq!(plan.restore, spill(16));
assert_eq!(plan.victim, VictimSpill::Move);
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();
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);
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);
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());
}
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;
}
}
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;
}
}
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;
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");
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());
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];
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");
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());
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_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));
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");
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");
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();
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();
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);
}
}