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
//! Issue #727 (spill and restore on reclaim): copy one physical agent slot of
//! a multi-slot [`HybridKvCache`] to host memory and restore it into any slot
//! index.
//!
//! Every per-slot buffer keeps the slot on its outermost axis, and none of a
//! slot's bytes depend on the slot index (the ADR-063 slot-independence gate
//! proves a request is bitwise equal in every slot). A spill copies exactly
//! the slot's observable state:
//!
//! - each full-attention layer and the MTP block: rows `0..cursor` of every
//!   head of the TQ codes/norms or F32 K/V, plus its independent live cursor.
//! - each DeltaNet layer: the slot's region of both physical conv buffers and
//!   both physical recurrent buffers, plus the slot's ping-pong parity. The
//!   restored slot then holds the same bytes in the same roles, so its next
//!   read and write see exactly what the source slot would have seen.
//! - the slot's graft-region length. The graft rows sit below the cursors
//!   and are copied with them.
//!
//! Rows at or above a cursor are unobservable and are not copied. The
//! per-position DeltaNet capture buffers are scratch inside one speculative
//! transaction; spill and restore refuse to run while capture is active,
//! which it never is between requests.
//!
//! Storage is host `Vec<u8>` filled by CPU `memcpy` over the shared-storage
//! Metal buffers: the same access the slot-anchor checkpoint uses at the same
//! admission point. The caller must not have GPU work in flight on the slot.

use anyhow::{anyhow, Context, Result};
use mlx_native::MlxBuffer;

use super::{
    copy_slot_region_in, copy_slot_region_out, FullAttnKvSlot, HybridKvCache,
    HybridKvSlotAnchor, SlotStateLineage,
};
use crate::inference::kv_slot_rows::{read_rows, write_rows, SlotRows};
use crate::serve::multi_seq_kv::SlotId;

/// Cursor-visible state of one full-attention block (a layer or the MTP
/// block) for one slot.
#[cfg_attr(test, derive(PartialEq, Eq))]
struct SpilledAttention {
    cursor: u32,
    /// Rows `0..cursor` of every head in [`attention_buffers`] order.
    rows: Vec<Vec<u8>>,
}

/// One DeltaNet layer's state for one slot.
#[cfg_attr(test, derive(PartialEq, Eq))]
struct SpilledLinear {
    pp_flipped: bool,
    /// The slot's region of each buffer, in [`linear_buffers`] order.
    regions: Vec<Vec<u8>>,
}

/// Host copy of one physical slot's complete observable cache state. See the
/// module documentation for what it holds.
#[cfg_attr(test, derive(PartialEq, Eq))]
pub struct HybridKvSlotSpill {
    lineage: SlotStateLineage,
    full_attn: Vec<SpilledAttention>,
    mtp: Option<SpilledAttention>,
    linear_attn: Vec<SpilledLinear>,
    graft_len: u32,
}

/// A fully preflighted restore retaining exclusive access to its target cache
/// until application. Pairing owners may validate their other image before
/// consuming this plan; no target bytes/cursors have been restored yet.
pub(crate) struct HybridKvSlotSpillRestorePlan<'cache, 'image> {
    cache: &'cache mut HybridKvCache,
    spill: &'image HybridKvSlotSpill,
    slot_idx: usize,
    n_seqs: usize,
}

/// A successful replacement holds the cache exclusively until all associated
/// checkpoints have been rehomed; no intervening reset/replacement can stale
/// the proof that their append-only rows were copied.
pub(crate) struct HybridKvSlotSpillRestoreReceipt<'cache, 'image> {
    cache: &'cache mut HybridKvCache,
    spill: &'image HybridKvSlotSpill,
    slot: SlotId,
}

impl HybridKvSlotSpillRestoreReceipt<'_, '_> {
    pub(crate) fn rebind_anchor(&self, anchor: &mut HybridKvSlotAnchor) -> Result<()> {
        self.spill.validate_anchor(anchor)?;
        anchor.lineage = self.cache.slot_state_lineage(self.slot)?;
        Ok(())
    }
}

impl HybridKvSlotSpill {
    fn validate_anchor(&self, anchor: &HybridKvSlotAnchor) -> Result<()> {
        anyhow::ensure!(anchor.lineage == self.lineage,
            "slot spill: carried anchor source lineage differs");
        anyhow::ensure!(anchor.graft_len == self.graft_len,
            "slot spill: carried anchor graft identity differs");
        anyhow::ensure!(
            anchor.full_attn_current_len.len() == self.full_attn.len()
                && anchor.full_attn_current_len.iter().zip(&self.full_attn)
                    .all(|(&saved, block)| saved <= block.cursor),
            "slot spill: carried anchor exceeds copied full-attention rows"
        );
        match (anchor.mtp_current_len, self.mtp.as_ref()) {
            (Some(saved), Some(block)) if saved <= block.cursor => {}
            (None, None) => {}
            _ => anyhow::bail!("slot spill: carried anchor exceeds copied MTP rows"),
        }
        Ok(())
    }

    /// Compare physical continuation state, excluding the deliberately changed
    /// cache/slot lineage. Transport authorization is tested separately.
    #[cfg(test)]
    pub(crate) fn observable_state_eq(&self, other: &Self) -> bool {
        self.full_attn == other.full_attn && self.mtp == other.mtp
            && self.linear_attn == other.linear_attn && self.graft_len == other.graft_len
    }

    pub(crate) fn validate_logical_token_boundary(&self, tokens: usize) -> Result<()> {
        let physical = tokens.checked_add(self.graft_len as usize)
            .ok_or_else(|| anyhow!("Qwen spill token cursor overflow"))?;
        anyhow::ensure!(self.full_attn.iter().all(|block| block.cursor as usize == physical),
            "Qwen spill target cursor does not match its retained token boundary");
        Ok(())
    }
    /// Host bytes owned by this spill.
    pub fn total_bytes(&self) -> usize {
        let attention = self
            .full_attn
            .iter()
            .chain(self.mtp.iter())
            .flat_map(|block| block.rows.iter())
            .map(Vec::len);
        let linear = self
            .linear_attn
            .iter()
            .flat_map(|layer| layer.regions.iter())
            .map(Vec::len);
        attention.chain(linear).sum::<usize>() + std::mem::size_of::<SlotStateLineage>()
    }
}

/// The K/V buffers of one block in a fixed order: TQ codes/norms, then F32.
fn attention_buffers(block: &FullAttnKvSlot) -> Vec<&MlxBuffer> {
    let mut buffers = Vec::with_capacity(6);
    if let Some(tq) = &block.tq {
        buffers.extend([&tq.k_packed, &tq.k_norms, &tq.v_packed, &tq.v_norms]);
    }
    buffers.extend(block.k.as_ref());
    buffers.extend(block.v.as_ref());
    buffers
}

fn attention_buffers_mut(block: &mut FullAttnKvSlot) -> Vec<&mut MlxBuffer> {
    let mut buffers = Vec::with_capacity(6);
    if let Some(tq) = block.tq.as_mut() {
        buffers.extend([
            &mut tq.k_packed,
            &mut tq.k_norms,
            &mut tq.v_packed,
            &mut tq.v_norms,
        ]);
    }
    buffers.extend(block.k.as_mut());
    buffers.extend(block.v.as_mut());
    buffers
}

const LINEAR_BUFFER_NAMES: [&str; 4] = [
    "conv_state",
    "conv_state_scratch",
    "recurrent",
    "recurrent_scratch",
];

fn linear_buffers(layer: &super::LinearAttnStateSlot) -> [&MlxBuffer; 4] {
    [
        &layer.conv_state,
        &layer.conv_state_scratch,
        &layer.recurrent,
        &layer.recurrent_scratch,
    ]
}

fn linear_buffers_mut(layer: &mut super::LinearAttnStateSlot) -> [&mut MlxBuffer; 4] {
    [
        &mut layer.conv_state,
        &mut layer.conv_state_scratch,
        &mut layer.recurrent,
        &mut layer.recurrent_scratch,
    ]
}

fn block_cursor(block: &FullAttnKvSlot, slot_idx: usize, name: &str) -> Result<u32> {
    block
        .current_len
        .get(slot_idx)
        .copied()
        .ok_or_else(|| anyhow!("slot spill ({name}): cursor missing for slot {slot_idx}"))
}

fn spill_attention(
    block: &FullAttnKvSlot,
    slot_idx: usize,
    n_seqs: usize,
    name: &str,
) -> Result<SpilledAttention> {
    let cursor = block_cursor(block, slot_idx, name)?;
    let rows = attention_buffers(block)
        .into_iter()
        .enumerate()
        .map(|(index, buffer)| {
            read_rows(
                buffer,
                slot_idx,
                n_seqs,
                cursor as usize,
                &format!("{name} buffer {index}"),
            )
        })
        .collect::<Result<_>>()?;
    Ok(SpilledAttention { cursor, rows })
}

fn attention_spill_bytes(
    block: &FullAttnKvSlot,
    cursor: u32,
    n_seqs: usize,
    name: &str,
) -> Result<usize> {
    attention_buffers(block)
        .into_iter()
        .map(|buffer| SlotRows::of(buffer, n_seqs, name)?.spilled_len(cursor as usize, name))
        .sum()
}

fn validate_attention(
    block: &FullAttnKvSlot,
    spilled: &SpilledAttention,
    slot_idx: usize,
    n_seqs: usize,
    name: &str,
) -> Result<()> {
    block_cursor(block, slot_idx, name)?;
    let buffers = attention_buffers(block);
    anyhow::ensure!(
        buffers.len() == spilled.rows.len(),
        "slot spill ({name}): spill holds {} K/V buffers, cache holds {} (TQ/F32 mode mismatch)",
        spilled.rows.len(),
        buffers.len()
    );
    for (index, (buffer, rows)) in buffers.into_iter().zip(&spilled.rows).enumerate() {
        let expected =
            SlotRows::of(buffer, n_seqs, name)?.spilled_len(spilled.cursor as usize, name)?;
        anyhow::ensure!(
            rows.len() == expected,
            "slot spill ({name} buffer {index}): spilled {} bytes, cache geometry needs {expected}",
            rows.len()
        );
    }
    Ok(())
}

fn restore_attention(
    block: &mut FullAttnKvSlot,
    spilled: &SpilledAttention,
    slot_idx: usize,
    n_seqs: usize,
    name: &str,
) -> Result<()> {
    for (index, (buffer, rows)) in attention_buffers_mut(block)
        .into_iter()
        .zip(&spilled.rows)
        .enumerate()
    {
        write_rows(
            rows,
            buffer,
            slot_idx,
            n_seqs,
            spilled.cursor as usize,
            &format!("{name} buffer {index}"),
        )?;
    }
    block.commit_written_rows(slot_idx, spilled.cursor);
    // A replacement owns only the rows it copied, not the previous
    // destination conversation's incidental initialized high water.
    block.initialized_len[slot_idx] = spilled.cursor;
    Ok(())
}

impl HybridKvCache {
    fn validate_spill_anchors<'a>(
        &self, slot: SlotId, anchors: impl Iterator<Item = &'a HybridKvSlotAnchor>,
    ) -> Result<()> {
        for anchor in anchors {
            self.validate_slot_anchor_identity(slot, anchor)?;
            self.validate_anchor_restore(
                slot, anchor.linear_image.as_ref().context("slot spill: anchor image missing")?,
                &anchor.full_attn_current_len, anchor.mtp_current_len,
            )?;
            // Initialized high water alone cannot prove an old branch's rows
            // remain valid. Serving supplies only its current ledger members.
            anyhow::ensure!(
                anchor.full_attn_current_len.iter().zip(&self.full_attn)
                    .all(|(&saved, block)| saved <= block.current_len[slot.0 as usize]),
                "slot spill: carried anchor exceeds the proven live full-attention prefix"
            );
            anyhow::ensure!(
                match (anchor.mtp_current_len, self.mtp_slot.as_ref()) {
                    (Some(saved), Some(block)) => saved <= block.current_len[slot.0 as usize],
                    (None, None) => true,
                    _ => false,
                },
                "slot spill: carried anchor exceeds the proven live MTP prefix"
            );
        }
        Ok(())
    }

    fn slot_spill_index(&self, slot: SlotId, operation: &str) -> Result<usize> {
        let slot_idx = slot.0 as usize;
        anyhow::ensure!(
            slot_idx < self.n_seqs as usize,
            "{operation}: slot {} outside n_seqs={}",
            slot.0,
            self.n_seqs
        );
        anyhow::ensure!(
            !self.la_capture_active(),
            "{operation}: DeltaNet capture is active; a slot can only move between transactions"
        );
        Ok(slot_idx)
    }

    /// Host bytes [`Self::spill_slot`] would copy for `slot`, without copying.
    #[cfg(test)]
    pub(crate) fn slot_spill_bytes(&self, slot: SlotId) -> Result<usize> {
        self.slot_spill_bytes_with_anchors(slot, std::iter::empty())
    }

    pub(crate) fn slot_spill_bytes_with_anchors<'a>(
        &self, slot: SlotId,
        anchors: impl Iterator<Item = &'a HybridKvSlotAnchor>,
    ) -> Result<usize> {
        let slot_idx = self.slot_spill_index(slot, "slot_spill_bytes")?;
        let n_seqs = self.n_seqs as usize;
        self.validate_spill_anchors(slot, anchors)?;
        let mut total = std::mem::size_of::<SlotStateLineage>();
        for (layer, block) in self.full_attn.iter().enumerate() {
            let cursor = block_cursor(block, slot_idx, "slot_spill_bytes")?;
            total += attention_spill_bytes(
                block, cursor, n_seqs, &format!("full_attn[{layer}]"))?;
        }
        if let Some(mtp) = &self.mtp_slot {
            let cursor = block_cursor(mtp, slot_idx, "slot_spill_bytes MTP")?;
            total += attention_spill_bytes(mtp, cursor, n_seqs, "mtp")?;
        }
        for (layer, linear) in self.linear_attn.iter().enumerate() {
            for (buffer, name) in linear_buffers(linear).into_iter().zip(LINEAR_BUFFER_NAMES) {
                anyhow::ensure!(
                    buffer.byte_len() % n_seqs == 0,
                    "slot_spill_bytes: linear_attn[{layer}].{name} is not split by slot"
                );
                total += buffer.byte_len() / n_seqs;
            }
        }
        Ok(total)
    }

    /// Copy `slot`'s complete observable state to host memory. The cache is
    /// not modified.
    #[cfg(test)]
    pub(crate) fn spill_slot(&self, slot: SlotId) -> Result<HybridKvSlotSpill> {
        self.spill_slot_with_anchors(slot, std::iter::empty())
    }

    /// `anchors` must be the caller's current, non-tombstoned token-ledger
    /// members. A raw initialized high water is not a deeper-prefix proof.
    pub(crate) fn spill_slot_with_anchors<'a>(
        &self, slot: SlotId,
        anchors: impl Iterator<Item = &'a HybridKvSlotAnchor>,
    ) -> Result<HybridKvSlotSpill> {
        let slot_idx = self.slot_spill_index(slot, "spill_slot")?;
        let n_seqs = self.n_seqs as usize;
        self.validate_spill_anchors(slot, anchors)?;
        let full_attn = self
            .full_attn
            .iter()
            .enumerate()
            .map(|(layer, block)| {
                spill_attention(block, slot_idx, n_seqs, &format!("full_attn[{layer}]"))
            })
            .collect::<Result<_>>()?;
        let mtp = self
            .mtp_slot
            .as_ref()
            .map(|mtp| {
                spill_attention(mtp, slot_idx, n_seqs, "mtp")
            })
            .transpose()?;
        let linear_attn = self
            .linear_attn
            .iter()
            .enumerate()
            .map(|(layer, linear)| {
                let pp_flipped = *linear.pp_flipped.get(slot_idx).ok_or_else(|| {
                    anyhow!("spill_slot: linear_attn[{layer}] parity missing for slot {slot_idx}")
                })?;
                let regions = linear_buffers(linear)
                    .into_iter()
                    .zip(LINEAR_BUFFER_NAMES)
                    .map(|(buffer, name)| {
                        copy_slot_region_out(
                            buffer,
                            slot_idx,
                            n_seqs,
                            &format!("linear_attn[{layer}].{name}"),
                        )
                    })
                    .collect::<Result<_>>()?;
                Ok(SpilledLinear {
                    pp_flipped,
                    regions,
                })
            })
            .collect::<Result<_>>()?;
        let graft_len = *self
            .graft_len
            .get(slot_idx)
            .ok_or_else(|| anyhow!("spill_slot: graft length missing for slot {slot_idx}"))?;
        Ok(HybridKvSlotSpill {
            lineage: self.slot_state_lineage(slot)?,
            full_attn,
            mtp,
            linear_attn,
            graft_len,
        })
    }

    #[cfg(test)]
    pub(crate) fn restore_slot_spill(
        &mut self, slot: SlotId, spill: &HybridKvSlotSpill,
    ) -> Result<()> {
        self.plan_slot_spill_restore(slot, spill)?.apply().map(|_| ())
    }

    /// Preflight every source region and reserve target backing without
    /// restoring any cursor or semantic state. The returned plan owns the
    /// cache borrow, so its checked geometry cannot change before application.
    pub(crate) fn plan_slot_spill_restore<'cache, 'image>(
        &'cache mut self,
        slot: SlotId,
        spill: &'image HybridKvSlotSpill,
    ) -> Result<HybridKvSlotSpillRestorePlan<'cache, 'image>> {
        let slot_idx = self.slot_spill_index(slot, "restore_slot_spill")?;
        let n_seqs = self.n_seqs as usize;
        let required = spill.full_attn.iter().chain(spill.mtp.iter())
            .map(|block| block.cursor).max().unwrap_or(0);
        // SlotRows validates against actual backing, not the logical limit.
        self.ensure_fa_backing(required as usize)?;
        anyhow::ensure!(
            spill.full_attn.len() == self.full_attn.len(),
            "restore_slot_spill: spill holds {} full-attention layers, cache holds {}",
            spill.full_attn.len(),
            self.full_attn.len()
        );
        anyhow::ensure!(
            spill.linear_attn.len() == self.linear_attn.len(),
            "restore_slot_spill: spill holds {} DeltaNet layers, cache holds {}",
            spill.linear_attn.len(),
            self.linear_attn.len()
        );
        for (layer, (block, spilled)) in self.full_attn.iter().zip(&spill.full_attn).enumerate() {
            validate_attention(
                block,
                spilled,
                slot_idx,
                n_seqs,
                &format!("full_attn[{layer}]"),
            )?;
        }
        match (self.mtp_slot.as_ref(), spill.mtp.as_ref()) {
            (Some(mtp), Some(spilled)) => {
                validate_attention(mtp, spilled, slot_idx, n_seqs, "mtp")?
            }
            (None, None) => {}
            _ => anyhow::bail!("restore_slot_spill: MTP presence differs between spill and cache"),
        }
        for (layer, (linear, spilled)) in
            self.linear_attn.iter().zip(&spill.linear_attn).enumerate()
        {
            anyhow::ensure!(
                slot_idx < linear.pp_flipped.len(),
                "restore_slot_spill: linear_attn[{layer}] parity missing for slot {slot_idx}"
            );
            anyhow::ensure!(
                spilled.regions.len() == LINEAR_BUFFER_NAMES.len(),
                "restore_slot_spill: linear_attn[{layer}] spill holds {} regions",
                spilled.regions.len()
            );
            for ((buffer, name), region) in linear_buffers(linear)
                .into_iter()
                .zip(LINEAR_BUFFER_NAMES)
                .zip(&spilled.regions)
            {
                anyhow::ensure!(
                    buffer.byte_len() % n_seqs == 0 && region.len() == buffer.byte_len() / n_seqs,
                    "restore_slot_spill: linear_attn[{layer}].{name} spilled {} bytes, slot region is {}",
                    region.len(),
                    buffer.byte_len() / n_seqs
                );
            }
        }
        anyhow::ensure!(
            slot_idx < self.graft_len.len(),
            "restore_slot_spill: graft length missing for slot {slot_idx}"
        );
        Ok(HybridKvSlotSpillRestorePlan { cache: self, spill, slot_idx, n_seqs })
    }
}

impl<'cache, 'image> HybridKvSlotSpillRestorePlan<'cache, 'image> {
    pub(crate) fn validate_anchor(&self, anchor: &HybridKvSlotAnchor) -> Result<()> {
        self.spill.validate_anchor(anchor)?;
        anchor.linear_image.as_ref().context("slot spill: anchor image missing")?
            .validate_cache_layout(self.cache)
    }

    pub(crate) fn apply(self) -> Result<HybridKvSlotSpillRestoreReceipt<'cache, 'image>> {
        let Self { cache, spill, slot_idx, n_seqs } = self;
        // Invalidate every old destination checkpoint/plan even if a later
        // copy fails; only a completed receipt can authorize new checkpoints.
        cache.advance_slot_state_generation(slot_idx);

        for (layer, (block, spilled)) in cache.full_attn.iter_mut().zip(&spill.full_attn).enumerate()
        {
            restore_attention(
                block,
                spilled,
                slot_idx,
                n_seqs,
                &format!("full_attn[{layer}]"),
            )?;
        }
        if let (Some(mtp), Some(spilled)) = (cache.mtp_slot.as_mut(), spill.mtp.as_ref()) {
            restore_attention(mtp, spilled, slot_idx, n_seqs, "mtp")?;
        }
        for (layer, (linear, spilled)) in cache
            .linear_attn
            .iter_mut()
            .zip(&spill.linear_attn)
            .enumerate()
        {
            for ((buffer, name), region) in linear_buffers_mut(linear)
                .into_iter()
                .zip(LINEAR_BUFFER_NAMES)
                .zip(&spilled.regions)
            {
                copy_slot_region_in(
                    region,
                    buffer,
                    slot_idx,
                    n_seqs,
                    &format!("linear_attn[{layer}].{name}"),
                )?;
            }
            linear.pp_flipped[slot_idx] = spilled.pp_flipped;
        }
        cache.graft_len[slot_idx] = spill.graft_len;
        Ok(HybridKvSlotSpillRestoreReceipt { cache, spill, slot: SlotId(slot_idx as u32) })
    }
}

#[cfg(test)]
#[path = "slot_spill_tests.rs"]
mod tests;