inky-engine 3.0.1

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
//! Spills leave the scheduler thread: an eviction queues its blocks for the spill writer and returns, the blocks
//! stay held until their writes are collected, and a spill that does not land leaves the cold tier as it was.
//!
//! The writer here has no thread. Queued work runs when a test calls `run_spill_writer_for_test`, and the fake
//! disk charges each block write to the cache's test clock, so every wait in these tests is a counted one.

use super::super::*;
use super::{assert_zero_pool_leaks, fake_cs, retain_test_prompt, ScratchDir};
use crate::spill::{write_block_to_dir, SPILL_HEADER_LEN};

const MIB: u64 = 1 << 20;
/// What the fake disk takes for one block write.
const WRITE_MS: u64 = 5_000;

struct Rig {
    dir: ScratchDir,
    cache: ServeBlockCache,
    pools: BlockPools,
    tbl: BlockTable,
    st: LaneBlockState,
}

/// A `--kv8` pool (1 MiB `Full`, 5 MiB `Window` slots) over a scratch spill store, with the test clock at 1000 ms.
fn rig(name: &str, max_spill_bytes: u64, slots: usize) -> Rig {
    let dir = ScratchDir::new(name);
    let store = SpillStore::open_with_kvb(&dir.0, max_spill_bytes, 1).unwrap();
    let mut cache = ServeBlockCache::with_spill(store);
    cache.set_test_clock_ms(1_000);
    Rig {
        dir,
        cache,
        pools: BlockPools::with_capacities(slots, slots, 1).unwrap(),
        tbl: BlockTable::new(16).unwrap(),
        st: LaneBlockState::default(),
    }
}

impl Rig {
    /// Prefill `blocks` blocks of a prompt of its own and keep its prompt start, with the lane released.
    fn retain(&mut self, base: u32, blocks: usize, tag: u8) -> (Vec<u32>, SealedId) {
        let toks: Vec<u32> = (0..=(blocks * BLOCK) as u32).map(|i| base + i).collect();
        let tip = retain_test_prompt(&mut self.cache, &mut self.pools, &mut self.tbl, &mut self.st, &toks, tag);
        (toks, tip)
    }

    fn entries(&self, tip: SealedId) -> Vec<(BlockKind, BlockIndex, BlockEntry)> {
        self.cache.starts[&tip].entries.clone()
    }

    fn refs(&self, entries: &[(BlockKind, BlockIndex, BlockEntry)]) -> Vec<u32> {
        entries.iter().map(|&(kind, _, e)| self.pools.of(kind).record(e.slot()).unwrap().refs()).collect()
    }

    fn restore(&mut self, toks: &[u32]) -> Option<(usize, Vec<u8>)> {
        let bound = self.cache.match_and_bind(&mut self.pools, &mut self.tbl, &mut self.st, toks);
        self.cache.release_lane(&mut self.pools, &mut self.tbl, &mut self.st);
        bound
    }

    /// Let the writer finish everything queued and collect it, until it owes nothing.
    fn drain(&mut self) {
        loop {
            let ran = self.cache.run_spill_writer_for_test(usize::MAX);
            let collected = self.cache.poll_spill_writes(&mut self.pools);
            if ran == 0 && collected == 0 {
                break;
            }
        }
    }

    fn finish(mut self) {
        self.cache.shutdown(&mut self.pools);
        assert_zero_pool_leaks(&self.pools);
        assert!(self.dir.0.exists());
    }
}

/// On-disk bytes of a `--kv8` start of `blocks` blocks with a `fake_cs` state: its `Full` and `Window` files and
/// the state file.
fn start_file_bytes(blocks: u64) -> u64 {
    let header = SPILL_HEADER_LEN as u64;
    let (full, window) = (BlockKind::Full.stride_bytes(1).unwrap(), BlockKind::Window.stride_bytes(1).unwrap());
    blocks * (full + header + window + header) + header + fake_cs(0).len() as u64
}

fn key_of(start: &SpilledStart, kind: BlockKind) -> SpillKey {
    start.entries.iter().find(|(k, _, _)| *k == kind).expect("the start has a block of this kind").2
}

#[test]
fn an_eviction_queues_its_spill_and_never_waits_for_the_write() {
    let mut r = rig("spill-queue-not-wait", 64 * MIB, 4);
    r.cache.spill_by_hand_for_test(u64::MAX);
    r.cache.set_spill_write_cost_for_test(WRITE_MS);
    let (toks, tip) = r.retain(10_000, 1, 7);
    let entries = r.entries(tip);
    assert_eq!(r.refs(&entries), [1, 1], "one Full and one Window block, held by the start alone");

    assert!(r.cache.evict_start(&mut r.pools, tip));
    let s = r.cache.stats();
    assert_eq!((s.spill_writes_queued, s.spill_writes_pending, s.spill_starts_pending), (3, 3, 1));
    assert_eq!((s.starts_spilled, s.spill_starts_dropped), (0, 0));
    assert_eq!((s.evict_us_total, s.evict_us_max), (0, 0), "no write ran inside the eviction");
    assert_eq!(r.cache.spill_store().unwrap().stats().writes_committed, 0);
    // The start has left RAM, but the blocks its spill reads are still held: no lane can take them.
    assert_eq!(r.cache.retained_start_count(), 0);
    assert_eq!(r.refs(&entries), [1, 1]);
    assert!(r.cache.spill_writes_hold_blocks());
    assert_eq!(r.cache.poll_spill_writes(&mut r.pools), 0, "nothing has landed yet");

    // The writer does its 15 s of work on its own time.
    assert_eq!(r.cache.run_spill_writer_for_test(usize::MAX), 3);
    assert_eq!(r.cache.now_ms(), 1_000 + 3 * WRITE_MS);
    assert_eq!(r.refs(&entries), [1, 1], "a landed block stays held until its result is collected");
    assert_eq!(r.cache.poll_spill_writes(&mut r.pools), 3);
    let s = r.cache.stats();
    assert_eq!((s.starts_spilled, s.spill_starts_dropped, s.spill_starts_pending, s.spill_writes_pending), (1, 0, 0, 0));
    assert_eq!(s.spill_write_bytes_pending, 0);
    assert_eq!(r.refs(&entries), [0, 0], "collected: the blocks are free");
    assert!(!r.cache.spill_writes_hold_blocks());
    assert_eq!(r.cache.stats().evict_us_total, 0, "none of the 15 s was the scheduler's");

    // The index follows, also through the writer, and the spilled start restores as it always did.
    assert!(r.cache.has_pending_spill_io());
    r.drain();
    assert!(!r.cache.has_pending_spill_io());
    assert_eq!(r.cache.spilled_start_count(), 1);
    assert_eq!(r.restore(&toks), Some((BLOCK, fake_cs(7))));
    assert_eq!(r.cache.stats().starts_restored, 1);
    r.drain();
    r.finish();

    // The same eviction with the spill inline, as it was before the writer thread: the scheduler pays for
    // every one of the three writes.
    let mut r = rig("spill-inline-waits", 64 * MIB, 4);
    r.cache.set_spill_write_cost_for_test(WRITE_MS);
    let (_, tip) = r.retain(10_000, 1, 7);
    assert!(r.cache.evict_start(&mut r.pools, tip));
    let s = r.cache.stats();
    assert_eq!((s.starts_spilled, s.spill_starts_pending), (1, 0));
    assert_eq!((s.evict_us_total, s.evict_us_max), (3 * WRITE_MS * 1_000, 3 * WRITE_MS * 1_000));
    r.finish();
}

#[test]
fn a_full_spill_queue_drops_the_start_counted_and_frees_its_blocks_at_once() {
    let mut r = rig("spill-queue-full", 64 * MIB, 4);
    let one_start = start_file_bytes(1);
    r.cache.spill_by_hand_for_test(one_start + one_start / 2);
    let (_, tip_a) = r.retain(10_000, 1, 1);
    let (_, tip_b) = r.retain(20_000, 1, 2);
    let (entries_a, entries_b) = (r.entries(tip_a), r.entries(tip_b));

    assert!(r.cache.evict_start(&mut r.pools, tip_a));
    assert_eq!(r.cache.stats().spill_write_bytes_pending, one_start);
    assert!(r.cache.evict_start(&mut r.pools, tip_b));
    let s = r.cache.stats();
    assert_eq!((s.spill_writes_queued, s.spill_writes_dropped_queue_full), (3, 3), "B's three writes were refused");
    assert_eq!((s.spill_starts_pending, s.spill_starts_dropped, s.starts_spilled), (1, 1, 0));
    assert_eq!(r.refs(&entries_a), [1, 1], "A's blocks wait for the writer");
    assert_eq!(r.refs(&entries_b), [0, 0], "B was dropped unspilled: its blocks are free now");
    assert_eq!(s.spill_write_bytes_pending, one_start, "the queue never held more than its cap");

    r.drain();
    let s = r.cache.stats();
    // Every start evicted for spilling is spilled or counted as dropped; none is pending and none is lost.
    assert_eq!((s.evictions_pool_pressure, s.starts_spilled, s.spill_starts_dropped, s.spill_starts_pending), (2, 1, 1, 0));
    r.finish();
}

#[test]
fn a_writer_that_never_runs_cannot_stall_the_scheduler_and_its_spill_expires() {
    let mut r = rig("spill-hung-writer", 64 * MIB, 2);
    r.cache.spill_by_hand_for_test(u64::MAX);
    let (_, tip) = r.retain(10_000, 1, 1);
    let entries = r.entries(tip);

    // A lane needs both slots of each kind. One is free; the other is the start's.
    let mut tbl = BlockTable::new(16).unwrap();
    let exhausted = r.cache.ensure_span_blocks(&mut r.pools, &mut tbl, 0, 2 * BLOCK);
    assert!(matches!(exhausted, Err(CacheError::PoolExhausted(_))), "the start's blocks are with the writer");
    let s = r.cache.stats();
    assert_eq!((s.evictions_pool_pressure, s.spill_starts_pending, s.evict_us_max), (1, 1, 0));
    assert_eq!(r.refs(&entries), [1, 1]);
    // The lane is deferred, not failed: the scheduler asks this before it gives up on a lane.
    assert!(r.cache.spill_writes_hold_blocks());
    assert!(!r.cache.can_satisfy_span(&r.pools, &tbl, 0, 2 * BLOCK));

    // The disk never answers. The spill's deadline passes, and the scheduler takes its blocks back unread.
    r.cache.advance_test_clock_ms(DEFAULT_SPILL_WRITE_TIMEOUT.as_millis() as u64);
    assert_eq!(r.cache.poll_spill_writes(&mut r.pools), 0);
    let s = r.cache.stats();
    assert_eq!((s.spill_write_timeouts, s.spill_starts_dropped, s.spill_starts_pending, s.spill_writes_pending), (1, 1, 0, 0));
    assert_eq!(r.refs(&entries), [0, 0]);
    assert!(!r.cache.spill_writes_hold_blocks());
    r.cache.ensure_span_blocks(&mut r.pools, &mut tbl, 0, 2 * BLOCK).unwrap();
    assert_eq!(r.cache.run_spill_writer_for_test(usize::MAX), 0, "the cancelled writes left the queue");
    tbl.clear_entries(&mut r.pools).unwrap();
    r.finish();
}

#[test]
fn a_block_the_writer_has_taken_keeps_its_pin_when_its_spill_is_dropped() {
    let mut r = rig("spill-pin-outlives-drop", 64 * MIB, 4);
    r.cache.spill_by_hand_for_test(u64::MAX);
    let (_, tip) = r.retain(10_000, 1, 1);
    let entries = r.entries(tip);
    assert!(r.cache.evict_start(&mut r.pools, tip));
    let spill_id = *r.cache.pending_spills.keys().next().unwrap();

    // The writer takes and writes the first block. Its result is not collected yet, which is all the scheduler
    // can know of a block the writer holds.
    assert_eq!(r.cache.run_spill_writer_for_test(1), 1);
    r.cache.fail_pending_spill(&mut r.pools, spill_id);
    let mut refs = r.refs(&entries);
    refs.sort_unstable();
    assert_eq!(refs, [0, 1], "taken: still pinned. Still queued: cancelled, and unpinned at once");
    assert!(r.cache.spill_writes_hold_blocks(), "the taken block still holds its pool slot until collected");
    assert_eq!(r.cache.stats().spill_writes_pending, 1);
    let taken_key = *r.cache.pending_writes.keys().next().unwrap();
    let taken_file = r.cache.spill_store().unwrap().block_path(taken_key);
    assert_eq!(r.cache.run_spill_writer_for_test(usize::MAX), 0, "the two cancelled writes are never run");

    // Its result arrives: only now is the block free, and the file nobody wants is unlinked.
    assert_eq!(r.cache.poll_spill_writes(&mut r.pools), 1);
    assert_eq!(r.refs(&entries), [0, 0]);
    assert!(!r.cache.spill_writes_hold_blocks());
    assert!(taken_file.exists());
    r.drain();
    assert!(!taken_file.exists());
    let s = r.cache.stats();
    assert_eq!((s.starts_spilled, s.spill_starts_dropped, s.spill_writes_pending), (0, 1, 0));
    assert_eq!(r.cache.spill_store().unwrap().entry_count(), 0);
    r.finish();
}

#[test]
fn a_spill_too_big_for_the_disk_leaves_the_spilled_starts_it_would_have_displaced() {
    // 8 MiB of disk. Start A (one block of each kind, 6 MiB) fits; start B (two of each, 12 MiB) never can.
    for max_spilled_starts in [DEFAULT_MAX_SPILLED_STARTS, 1] {
        let mut r = rig("spill-too-big-keeps-old", 8 * MIB, 8);
        r.cache.max_spilled_starts = max_spilled_starts;
        let (toks_a, tip_a) = r.retain(10_000, 1, 1);
        assert!(r.cache.evict_start(&mut r.pools, tip_a));
        assert_eq!(r.cache.spilled_start_count(), 1);

        let (_, tip_b) = r.retain(20_000, 2, 2);
        assert!(r.cache.evict_start(&mut r.pools, tip_b));
        assert_eq!(r.cache.spilled_start_count(), 1, "A was not trimmed or collected for a spill that cannot land");
        assert_eq!(r.restore(&toks_a), Some((BLOCK, fake_cs(1))), "and A still restores");
        r.finish();
    }
}

#[test]
fn a_spill_whose_write_fails_leaves_the_spilled_start_it_would_have_trimmed() {
    let mut r = rig("spill-write-fails-keeps-old", 64 * MIB, 8);
    r.cache.max_spilled_starts = 1;
    let (toks_a, tip_a) = r.retain(10_000, 1, 1);
    assert!(r.cache.evict_start(&mut r.pools, tip_a));
    assert_eq!(r.cache.spilled_start_count(), 1);

    // B would take A's place at its commit. Its Window write fails: something already sits at that path.
    r.cache.spill_by_hand_for_test(u64::MAX);
    let (_, tip_b) = r.retain(20_000, 1, 2);
    let entries_b = r.entries(tip_b);
    assert!(r.cache.evict_start(&mut r.pools, tip_b));
    let window_key = key_of(&r.cache.pending_spills.values().next().unwrap().start, BlockKind::Window);
    let in_the_way = r.cache.spill_store().unwrap().block_path(window_key);
    std::fs::write(&in_the_way, b"not a spill block").unwrap();
    r.drain();

    let s = r.cache.stats();
    assert_eq!((s.starts_spilled, s.spill_starts_dropped, s.spill_io_errors, s.spill_starts_pending), (1, 1, 1, 0));
    assert_eq!(r.refs(&entries_b), [0, 0]);
    assert_eq!(r.cache.spilled_start_count(), 1, "A was not trimmed for a spill that did not land");
    assert_eq!(r.cache.spill_store().unwrap().entry_count(), 3, "B's landed blocks are gone, A's three remain");
    std::fs::remove_file(&in_the_way).unwrap();
    assert_eq!(r.restore(&toks_a), Some((BLOCK, fake_cs(1))));
    r.drain();
    r.finish();
}

#[test]
fn reusing_a_spilled_block_makes_it_as_recent_as_the_start_that_reuses_it() {
    // A is one block; B extends A by one block, so B's spill reuses A's two files. Room for A, B and C less
    // 50 bytes: when C lands, disk GC must collect one block, and the least recently used one must not be a
    // block B shares.
    let mut r = rig("spill-touch-on-reuse", 3 * start_file_bytes(1) - 50, 8);
    let (toks_a, tip_a) = r.retain(10_000, 1, 1);
    let mut toks_b = toks_a[..BLOCK].to_vec();
    toks_b.extend((0..=BLOCK as u32).map(|i| 20_000 + i));
    let tip_b = retain_test_prompt(&mut r.cache, &mut r.pools, &mut r.tbl, &mut r.st, &toks_b, 2);

    assert!(r.cache.evict_start(&mut r.pools, tip_a));
    let writes_a = r.cache.spill_store().unwrap().stats().writes_committed;
    assert!(r.cache.evict_start(&mut r.pools, tip_b));
    assert_eq!(r.cache.spill_store().unwrap().stats().writes_committed, writes_a + 3, "B reused A's two block files");
    assert_eq!(r.cache.spilled_start_count(), 2);

    let (_, tip_c) = r.retain(30_000, 1, 3);
    assert!(r.cache.evict_start(&mut r.pools, tip_c));
    assert_eq!(r.cache.spilled_start_count(), 2, "A, the oldest, gave way; B and C are spilled");
    assert_eq!(r.restore(&toks_b), Some((2 * BLOCK, fake_cs(2))), "B kept the blocks it shares with A");
    r.finish();
}

#[test]
fn the_spill_index_never_outgrows_what_a_load_will_read() {
    let start = |id: u64, tick: u64| {
        let sp = SpilledStart {
            namespace: 0,
            pos: BLOCK,
            reasons: PROMPT,
            cs_key: SpillKey::full(100 + id),
            entries: vec![(BlockKind::Full, BlockIndex::new(0), SpillKey::full(id))],
            toks: vec![id as u32; BLOCK],
            last_used_tick: tick,
        };
        (id, Arc::new(sp))
    };
    let snapshot = |records| SpillIndexSnapshot {
        kvb: 1,
        next_spill_id: 9,
        tick: 9,
        full_attn_budget: u64::MAX,
        model_fingerprint: 0,
        records,
    };
    let record_len = 46 + 4 * BLOCK + 4 + 14;
    let fixed_len = SPILL_INDEX_PREFIX_LEN + 8 + 32;
    let whole = snapshot(vec![start(1, 5), start(2, 7), start(3, 6)]).into_bytes(MAX_SPILL_INDEX_BYTES);
    assert_eq!(whole.len(), fixed_len + 3 * record_len);
    assert_eq!(u32::from_le_bytes(whole[32..36].try_into().unwrap()), 3);

    // Room for two records: the least recently used start (id 1, tick 5) is the one left out.
    let trimmed = snapshot(vec![start(1, 5), start(2, 7), start(3, 6)]).into_bytes(fixed_len + 2 * record_len + 10);
    assert_eq!(trimmed.len(), fixed_len + 2 * record_len);
    assert_eq!(u32::from_le_bytes(trimmed[32..36].try_into().unwrap()), 2);
    let ids: Vec<u64> = (0..2)
        .map(|i| u64::from_le_bytes(trimmed[fixed_len + i * record_len..][..8].try_into().unwrap()))
        .collect();
    assert_eq!(ids, [3, 2], "kept oldest first, as a load expects");
}

#[test]
fn a_trimmed_spill_index_reloads_its_newest_starts_instead_of_losing_them_all() {
    let mut r = rig("spill-index-trim-reload", 64 * MIB, 8);
    // An index image with room for one start's record, not two.
    let record_len = 46 + 4 * BLOCK + 4 + 14 * 2;
    r.cache.spill_index_max_bytes = SPILL_INDEX_PREFIX_LEN + 8 + 32 + record_len + 10;
    let (_, tip_a) = r.retain(10_000, 1, 1);
    let (toks_b, tip_b) = r.retain(20_000, 1, 2);
    assert!(r.cache.evict_start(&mut r.pools, tip_a));
    assert!(r.cache.evict_start(&mut r.pools, tip_b));
    assert_eq!(r.cache.spilled_start_count(), 2, "this run still has both");
    r.cache.shutdown(&mut r.pools);
    assert_zero_pool_leaks(&r.pools);
    drop(r.cache);

    // A restart reads the index: the newest start is there. Before the trim an oversized index was taken for a
    // corrupt one and every spill block was removed.
    let store = SpillStore::open_with_kvb(&r.dir.0, 64 * MIB, 1).unwrap();
    let mut cache = ServeBlockCache::with_spill(store);
    assert_eq!(cache.spilled_start_count(), 1);
    assert_eq!(cache.spill_store().unwrap().entry_count(), 3, "the unlisted start's blocks were swept");
    let mut pools = BlockPools::with_capacities(8, 8, 1).unwrap();
    let mut tbl = BlockTable::new(16).unwrap();
    let mut st = LaneBlockState::default();
    assert_eq!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &toks_b), Some((BLOCK, fake_cs(2))));
    cache.release_lane(&mut pools, &mut tbl, &mut st);
    cache.shutdown(&mut pools);
    assert_zero_pool_leaks(&pools);
}

#[test]
fn the_writer_thread_spills_or_counts_every_start_and_shutdown_leaves_no_pin() {
    let mut r = rig("spill-writer-thread", 64 * MIB, 8);
    r.cache.spill_in_background(u64::MAX);
    let tips: Vec<SealedId> = (0..3u32).map(|i| r.retain(10_000 * (i + 1), 1, i as u8).1).collect();
    for tip in tips {
        assert!(r.cache.evict_start(&mut r.pools, tip));
    }
    // However far the writer got, shutdown stops it: the block it holds is waited for, the rest are dropped
    // unread, and every one of the three starts is spilled or counted.
    r.cache.shutdown(&mut r.pools);
    assert_zero_pool_leaks(&r.pools);
    let s = r.cache.stats();
    assert_eq!(s.starts_spilled + s.spill_starts_dropped, 3);
    assert_eq!((s.spill_starts_pending, s.spill_writes_pending, s.spill_write_bytes_pending), (0, 0, 0));
    let spilled = r.cache.spilled_start_count();
    assert_eq!(spilled as u64, s.starts_spilled);
    drop(r.cache);

    // What it committed is what a restart finds.
    let store = SpillStore::open_with_kvb(&r.dir.0, 64 * MIB, 1).unwrap();
    let cache = ServeBlockCache::with_spill(store);
    assert_eq!(cache.spilled_start_count(), spilled);
    assert_eq!(cache.spill_store().unwrap().entry_count(), 3 * spilled);
}

#[test]
fn shutdown_finishes_owed_unlinks_and_leaves_unwritten_paths_alone() {
    let mut r = rig("spill-shutdown-owed-unlinks", 64 * MIB, 8);
    r.cache.max_spilled_starts = 1;
    r.cache.spill_by_hand_for_test(u64::MAX);

    let (_, tip_a) = r.retain(10_000, 1, 1);
    assert!(r.cache.evict_start(&mut r.pools, tip_a));
    r.drain();
    let a_sp = r.cache.spilled_starts.values().next().unwrap().clone();
    let a_paths: Vec<_> = std::iter::once(a_sp.cs_key)
        .chain(a_sp.entries.iter().map(|&(_, _, sk)| sk))
        .map(|sk| r.cache.spill_store().unwrap().block_path(sk))
        .collect();
    assert!(a_paths.iter().all(|p| p.exists()));

    // B commits and trims A, queueing three unlinks that have not run yet; C queues three block writes that
    // have not run yet, with an unrelated file sitting at C's Window path.
    let (toks_b, tip_b) = r.retain(20_000, 1, 2);
    assert!(r.cache.evict_start(&mut r.pools, tip_b));
    assert_eq!(r.cache.run_spill_writer_for_test(3), 3);
    assert_eq!(r.cache.poll_spill_writes(&mut r.pools), 3);
    assert!(a_paths.iter().all(|p| p.exists()), "A's unlinks are still queued on the writer");

    let (_, tip_c) = r.retain(30_000, 1, 3);
    assert!(r.cache.evict_start(&mut r.pools, tip_c));
    let c_win_key = key_of(&r.cache.pending_spills.values().next().unwrap().start, BlockKind::Window);
    let sentinel = r.cache.spill_store().unwrap().block_path(c_win_key);
    std::fs::write(&sentinel, b"unrelated file").unwrap();

    r.cache.shutdown(&mut r.pools);
    assert_zero_pool_leaks(&r.pools);
    assert!(a_paths.iter().all(|p| !p.exists()), "shutdown finished A's owed unlinks");
    assert_eq!(std::fs::read(&sentinel).unwrap(), b"unrelated file", "unread block write never unlinked sentinel");
    std::fs::remove_file(&sentinel).unwrap();
    drop(r.cache);

    let store = SpillStore::open_with_kvb(&r.dir.0, 64 * MIB, 1).unwrap();
    assert_eq!(store.stats().orphans_swept, 0);
    let mut cache = ServeBlockCache::with_spill(store);
    assert_eq!(cache.spilled_start_count(), 1);
    assert_eq!(cache.spill_store().unwrap().entry_count(), 3);
    let mut pools = BlockPools::with_capacities(8, 8, 1).unwrap();
    let mut tbl = BlockTable::new(16).unwrap();
    let mut st = LaneBlockState::default();
    assert_eq!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &toks_b), Some((BLOCK, fake_cs(2))));
    cache.release_lane(&mut pools, &mut tbl, &mut st);
    cache.shutdown(&mut pools);
    assert_zero_pool_leaks(&pools);
}

#[test]
fn late_worker_reads_and_unowned_writes_never_resurrect_removed_blocks() {
    // Tight two-start budget: a phantom charge from a late read or an unowned write would evict a live start.
    let mut r = rig("spill-no-resurrect", 2 * start_file_bytes(1), 8);
    r.cache.max_spilled_starts = 1;
    r.cache.spill_by_hand_for_test(u64::MAX);

    let (_, tip_a) = r.retain(10_000, 1, 1);
    assert!(r.cache.evict_start(&mut r.pools, tip_a));
    r.drain();
    let a_full = key_of(r.cache.spilled_starts.values().next().unwrap(), BlockKind::Full);
    let full_stride = BlockKind::Full.stride_bytes(1).unwrap() as usize;
    let raw_read = read_block_from_dir(&r.dir.0, 1, a_full, Some(full_stride));

    // B commits and trims A: A's keys leave the index at once (`forget_block_owing_unlink`), while A's files
    // wait in the writer's unlink queue.
    let (toks_b, tip_b) = r.retain(20_000, 1, 2);
    assert!(r.cache.evict_start(&mut r.pools, tip_b));
    assert_eq!(r.cache.run_spill_writer_for_test(3), 3);
    assert_eq!(r.cache.poll_spill_writes(&mut r.pools), 3);
    assert!(!r.cache.spill_store().unwrap().contains(a_full));

    // A cancelled restore's late read arrives now, and an untracked raw write lands for an unowned key.
    let _ = r.cache.spill_store.as_mut().unwrap().apply_raw_read(a_full, raw_read);
    let orphan_key = r.cache.alloc_spill_key(BlockKind::Full);
    let raw_write = write_block_to_dir(&r.dir.0, 1, orphan_key, 1, &vec![0u8; full_stride], None, true);
    r.cache.on_spill_block_written(&mut r.pools, orphan_key, raw_write);
    r.drain();

    let store = r.cache.spill_store().unwrap();
    assert!(!store.contains(a_full), "late read must not bring back a forgotten block");
    assert!(!store.contains(orphan_key), "unowned write must not stay indexed");
    assert!(!store.block_path(orphan_key).exists(), "unowned write file must be unlinked");
    assert_eq!(store.entry_count(), 3);
    assert_eq!(store.used_bytes(), start_file_bytes(1));

    // Room for a second live start remains intact: C lands alongside B without evicting B.
    r.cache.max_spilled_starts = 2;
    let (toks_c, tip_c) = r.retain(30_000, 1, 3);
    assert!(r.cache.evict_start(&mut r.pools, tip_c));
    r.drain();
    assert_eq!(r.cache.spilled_start_count(), 2);
    assert_eq!(r.restore(&toks_b), Some((BLOCK, fake_cs(2))));
    assert_eq!(r.restore(&toks_c), Some((BLOCK, fake_cs(3))));
    r.drain();
    r.finish();
}

#[test]
fn stale_entry_spill_key_after_corrupt_read_allocates_fresh_key_and_drops_pin_on_expiry() {
    let mut r = rig("spill-stale-ek-fresh", 64 * MIB, 8);
    let (toks_a, tip_a) = r.retain(10_000, 1, 1);
    let mut toks_b = toks_a[..BLOCK].to_vec();
    toks_b.extend((0..=BLOCK as u32).map(|i| 20_000 + i));
    let tip_b = retain_test_prompt(&mut r.cache, &mut r.pools, &mut r.tbl, &mut r.st, &toks_b, 2);
    // Keep a third resident start C sharing block 0 in RAM while A and B spill to disk.
    let mut toks_c = toks_a[..BLOCK].to_vec();
    toks_c.extend((0..=BLOCK as u32).map(|i| 30_000 + i));
    let tip_c = retain_test_prompt(&mut r.cache, &mut r.pools, &mut r.tbl, &mut r.st, &toks_c, 3);
    let entries_c = r.entries(tip_c);

    assert!(r.cache.evict_start(&mut r.pools, tip_a));
    assert!(r.cache.evict_start(&mut r.pools, tip_b));
    assert_eq!(r.cache.spilled_start_count(), 2);

    // Corrupt A's shared Full block on disk and attempt to restore A: `drop_corrupt` removes that file from
    // `SpillStore` and drops A, while B still lists the dead key in `spill_key_owners`.
    let dead_key = key_of(
        r.cache.spilled_starts.values().find(|sp| sp.pos == BLOCK).unwrap(),
        BlockKind::Full,
    );
    let dead_path = r.cache.spill_store().unwrap().block_path(dead_key);
    std::fs::write(&dead_path, b"corrupt").unwrap();
    assert_eq!(r.restore(&toks_a), None);
    assert!(!r.cache.spill_store().unwrap().contains(dead_key));
    assert_eq!(r.cache.spilled_start_count(), 1, "B still sits in spilled_starts with dead_key in spill_key_owners");

    // Evict C with the background queue stalled: C must allocate a fresh key (not reuse dead_key) and release
    // every write pin cleanly when its deadline expires.
    r.cache.spill_by_hand_for_test(u64::MAX);
    assert!(r.cache.evict_start(&mut r.pools, tip_c));
    let c_keys: Vec<_> = r.cache.pending_spills.values().next().unwrap().claimed_keys.clone();
    assert!(!c_keys.contains(&dead_key), "C allocated a fresh key instead of reusing the dead one");
    r.cache.advance_test_clock_ms(DEFAULT_SPILL_WRITE_TIMEOUT.as_millis() as u64);
    assert_eq!(r.cache.poll_spill_writes(&mut r.pools), 0);
    assert_eq!(r.refs(&entries_c), [0, 0, 0, 0], "every write pin on C's blocks was released on expiry");
    assert_eq!(r.cache.run_spill_writer_for_test(usize::MAX), 0);
    r.finish();
}

#[test]
fn a_start_with_a_stitch_guard_or_approx_flag_is_never_queued_for_spill() {
    let mut r = rig("spill-never-stitch-guard-or-approx", 64 * MIB, 8);
    r.cache.spill_by_hand_for_test(u64::MAX);

    // 1. A start whose Window entry is a zero-filled stitch guard must be refused by `queue_spill`.
    let (_, tip_guard) = r.retain(10_000, 1, 1);
    let win_entry = r
        .entries(tip_guard)
        .into_iter()
        .find(|&(k, _, _)| k == BlockKind::Window)
        .unwrap()
        .2;
    r.cache.stitch_guards.push((win_entry.slot(), win_entry.generation()));
    assert!(r.cache.evict_start(&mut r.pools, tip_guard));
    assert_eq!(r.cache.stats().spill_writes_queued, 0, "stitch guard slot must never be queued to SpillStore");
    assert_eq!(r.cache.stats().spill_starts_dropped, 1);

    // 2. An approximate start must never enter `queue_spill`.
    let (_, tip_approx) = r.retain(20_000, 1, 2);
    r.cache.starts.get_mut(&tip_approx).unwrap().approx = true;
    *r.cache.approx_per_scope.entry(0).or_insert(0) += 1;
    assert!(r.cache.evict_start(&mut r.pools, tip_approx));
    assert_eq!(r.cache.stats().spill_writes_queued, 0);
    assert_eq!(r.cache.spilled_start_count(), 0);
    r.finish();
}

#[test]
fn aborting_or_finishing_an_unowned_spill_never_unlinks_an_inflight_restore_block() {
    let mut r = rig("spill-preserve-inflight-restore-key", 64 * MIB, 8);
    r.cache.spill_by_hand_for_test(u64::MAX);

    let (toks_a, tip_a) = r.retain(10_000, 1, 1);
    // Keep a resident extension B sharing A's block 0 before A is evicted to disk.
    let mut toks_b = toks_a[..BLOCK].to_vec();
    toks_b.extend((0..=BLOCK as u32).map(|i| 20_000 + i));
    let tip_b = retain_test_prompt(&mut r.cache, &mut r.pools, &mut r.tbl, &mut r.st, &toks_b, 2);

    assert!(r.cache.evict_start(&mut r.pools, tip_a));
    r.drain();
    let a_id = *r.cache.spilled_starts.keys().next().unwrap();
    let a_full = key_of(&r.cache.spilled_starts[&a_id], BlockKind::Full);
    let a_full_path = r.cache.spill_store().unwrap().block_path(a_full);

    // Pin `a_full` as an in-flight restore key, queue B (which claims `a_full`), remove A (`a_full` stays on
    // disk for the restore and for B), then abort B: `abort_spill_claims` must not unlink `a_full` while pinned.
    r.cache.pin_inflight_restore_keys(a_id, &[a_full]);
    assert!(r.cache.evict_start(&mut r.pools, tip_b));
    let b_id = *r.cache.pending_spills.keys().next().unwrap();
    assert!(r.cache.remove_spilled_start_inner(a_id, true));
    r.cache.fail_pending_spill(&mut r.pools, b_id);
    r.drain();
    assert!(a_full_path.exists(), "abort_spill_claims must keep a_full on disk while a restore reads it");

    // Likewise an unowned write landing while pinned in `in_flight_restore_keys` must not be unlinked.
    let full_stride = BlockKind::Full.stride_bytes(1).unwrap() as usize;
    let extra_key = r.cache.alloc_spill_key(BlockKind::Full);
    let extra_path = r.cache.spill_store().unwrap().block_path(extra_key);
    r.cache.pin_inflight_restore_keys(999, &[extra_key]);
    let raw = write_block_to_dir(&r.dir.0, 1, extra_key, 1, &vec![0u8; full_stride], None, true);
    r.cache.on_spill_block_written(&mut r.pools, extra_key, raw);
    r.drain();
    assert!(extra_path.exists(), "on_spill_block_written must keep pinned restore key on disk");

    r.cache.unpin_inflight_restore_keys(a_id, &[a_full]);
    r.cache.unpin_inflight_restore_keys(999, &[extra_key]);
    r.finish();
}

#[test]
fn release_lane_invalid_aborts_pending_spills_sharing_suspect_blocks() {
    let mut r = rig("spill-invalid-logits-aborts-pending", 64 * MIB, 16);
    r.cache.spill_by_hand_for_test(u64::MAX);

    let (toks_b, tip_b) = r.retain(10_000, 1, 1);
    let (toks_c, tip_c) = r.retain(50_000, 1, 2);

    // Lane A binds B's block 0 in RAM before B and C are evicted into `pending_spills`.
    let mut toks_a = toks_b[..BLOCK].to_vec();
    toks_a.extend((0..=BLOCK as u32).map(|i| 90_000 + i));
    let mut tbl_a = BlockTable::new(16).unwrap();
    let mut st_a = LaneBlockState { prompt_len: toks_a.len(), ..Default::default() };
    assert_eq!(r.cache.match_and_bind(&mut r.pools, &mut tbl_a, &mut st_a, &toks_a).map(|(p, _)| p), Some(BLOCK));
    r.cache.ensure_span_blocks(&mut r.pools, &mut tbl_a, BLOCK, BLOCK).unwrap();
    r.cache.finish_prefill_span(&mut r.pools, &mut tbl_a, &mut st_a, &toks_a, BLOCK, BLOCK, || fake_cs(9));

    // Evict B and C so both sit in `pending_spills` (B shares block 0 with lane A; C shares nothing).
    assert!(r.cache.evict_start(&mut r.pools, tip_b));
    assert!(r.cache.evict_start(&mut r.pools, tip_c));
    assert_eq!(r.cache.stats().spill_starts_pending, 2);

    // Lane A fails on invalid logits: its own resident start is evicted without spilling AND B's pending spill
    // is aborted before it can commit suspect K/V to `--spill-dir`, while C's pending spill still commits.
    assert_eq!(r.cache.release_lane_invalid(&mut r.pools, &mut tbl_a, &mut st_a), 1);
    assert_eq!(r.cache.stats().spill_starts_pending, 1, "B's pending spill was aborted; C remains pending");
    assert_eq!(r.cache.stats().spill_starts_dropped, 1);

    r.drain();
    assert_eq!(r.cache.spilled_start_count(), 1);
    assert_eq!(r.restore(&toks_b), None, "suspect start B never reached --spill-dir");
    assert_eq!(r.restore(&toks_c), Some((BLOCK, fake_cs(2))), "unrelated start C committed cleanly");
    r.drain();
    r.finish();
}