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;
const WRITE_MS: u64 = 5_000;
struct Rig {
dir: ScratchDir,
cache: ServeBlockCache,
pools: BlockPools,
tbl: BlockTable,
st: LaneBlockState,
}
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 {
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
}
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());
}
}
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);
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");
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");
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();
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();
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);
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]);
assert!(r.cache.spill_writes_hold_blocks());
assert!(!r.cache.can_satisfy_span(&r.pools, &tbl, 0, 2 * BLOCK));
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();
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");
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() {
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);
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() {
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);
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);
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);
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));
}
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);
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()));
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() {
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));
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));
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));
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);
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);
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");
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);
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);
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);
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);
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");
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);
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));
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);
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();
}