diff --git a/crates/leleka-runtime/src/qwen_forward/kar_ple_cache.rs b/crates/leleka-runtime/src/qwen_forward/kar_ple_cache.rs index 4564caba..84da781b 100644 --- a/crates/leleka-runtime/src/qwen_forward/kar_ple_cache.rs +++ b/crates/leleka-runtime/src/qwen_forward/kar_ple_cache.rs @@ -5,7 +5,7 @@ use super::contract::{Error, Result}; use crate::model_binding::qwen4exp_input::{BindingIdentity, PLE_ROWS}; use crate::model_binding::qwen4exp_kar_ple::{KarPleBinding, KarRowPacket, KarRowReader}; use leleka_cuda_driver::{Context, DeviceBuffer}; -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; use std::hash::{BuildHasherDefault, Hasher}; use std::sync::Arc; use std::thread::JoinHandle; @@ -37,6 +37,110 @@ impl Hasher for RowHasher { } } type RowMap = HashMap>; +/// The rows the device cache holds, with a recency queue so the least recently used rows are found without scanning the map. +/// `order` holds `(age, row)` items in non-decreasing age (every age change pushes the new item at the back; ages only grow). +/// An item is live when the map still holds the row at exactly that age; an older item of a row that was touched since, or of an +/// evicted row, is stale and skipped (stale items at the front are dropped, the rest by `compact_if_loose`). A row has exactly one +/// live item. Finding the oldest `n` rows therefore reads the front of the queue, not the ~1M entries of a full cache. +#[derive(Default)] +struct Residents { + map: RowMap, + order: VecDeque<(u64, u64)>, + /// Items `oldest` examined, summed over calls (tests bound it). + #[cfg(test)] + examined: std::sync::atomic::AtomicUsize, +} +impl Residents { + fn len(&self) -> usize { + self.map.len() + } + fn get(&self, row: &u64) -> Option<&Entry> { + self.map.get(row) + } + fn contains_key(&self, row: &u64) -> bool { + self.map.contains_key(row) + } + fn try_reserve(&mut self, additional: usize) -> std::result::Result<(), std::collections::TryReserveError> { + self.map.try_reserve(additional)?; + self.order.try_reserve(additional) + } + /// Set the age of a held row (a no-op when it already has that age); returns its slot. + fn touch(&mut self, row: &u64, age: u64) -> Option { + let entry = self.map.get_mut(row)?; + let slot = entry.slot; + if entry.age != age { + entry.age = age; + self.order.push_back((age, *row)); + self.compact_if_loose(); + } + Some(slot) + } + fn insert(&mut self, row: u64, slot: u32, age: u64) { + self.map.insert(row, Entry { slot, age }); + self.order.push_back((age, row)); + self.compact_if_loose(); + } + fn remove(&mut self, row: &u64) { + self.map.remove(row); + while let Some(&(age, front)) = self.order.front() { + if self.map.get(&front).is_some_and(|e| e.age == age) { + break; + } + self.order.pop_front(); + } + } + fn compact_if_loose(&mut self) { + if self.order.len() > 2 * self.map.len() + 4096 { + let map = &self.map; + self.order.retain(|(age, row)| map.get(row).is_some_and(|e| e.age == *age)); + } + } + /// The `need` least recently used rows with age below `below` that `skip` does not name, oldest first, as `(row, slot)` + /// (rows of equal age in queue order); fewer when the cache holds fewer. Also returns how many items were examined: the cost, + /// which a test bounds. The queue answers; the full scan runs only when the queue gave fewer rows than asked. + fn oldest(&self, need: usize, below: u64, skip: impl Fn(u64) -> bool) -> Result<(Vec<(u64, u32)>, usize)> { + let mut out = Vec::<(u64, u32)>::new(); + out.try_reserve_exact(need.min(self.map.len())) + .map_err(|_| Error::InputAllocation)?; + let mut examined = 0usize; + for &(age, row) in &self.order { + if out.len() == need || age >= below { + break; + } + examined += 1; + if let Some(e) = self.map.get(&row) { + if e.age == age && !skip(row) { + out.push((row, e.slot)); + } + } + } + if out.len() < need { + let mut all: Vec<(u64, u64, u32)> = Vec::new(); + all.try_reserve_exact(self.map.len()) + .map_err(|_| Error::InputAllocation)?; + all.extend( + self.map + .iter() + .filter(|(r, e)| e.age < below && !skip(**r)) + .map(|(r, e)| (e.age, *r, e.slot)), + ); + examined += self.map.len(); + if all.len() > out.len() { + let take = need.min(all.len()); + if take < all.len() { + all.select_nth_unstable_by_key(take - 1, |c| (c.0, c.1)); + all.truncate(take); + } + all.sort_unstable_by_key(|c| (c.0, c.1)); + out.clear(); + out.extend(all.into_iter().map(|(_, r, s)| (r, s))); + } + } + #[cfg(test)] + self.examined.fetch_add(examined, std::sync::atomic::Ordering::Relaxed); + Ok((out, examined)) + } +} /// A chunk's PLE rows resolved to cache slots (`KarPleCache::stage_batch`): the update records the device must /// scatter and the slot of every row, plus the mapping changes `commit` publishes once the device has accepted them. pub(super) struct KarPleStaged { @@ -61,7 +165,7 @@ struct Lookup { miss_rows: Vec, pending: Vec<(u32, u32)>, } -fn lookup_rows(entries: &mut RowMap, rows: &[[u64; 16]], stamp: u64) -> Result { +fn lookup_rows(entries: &mut Residents, rows: &[[u64; 16]], stamp: u64) -> Result { let total = rows.len().checked_mul(16).ok_or(Error::Overflow)?; let mut slots = Vec::new(); slots @@ -71,9 +175,8 @@ fn lookup_rows(entries: &mut RowMap, rows: &[[u64; 16]], stamp: u64) -> R let mut miss_of = RowMap::::default(); let mut pending = Vec::<(u32, u32)>::new(); for (at, row) in rows.iter().flatten().enumerate() { - if let Some(entry) = entries.get_mut(row) { - entry.age = stamp; - slots.push(entry.slot); + if let Some(slot) = entries.touch(row, stamp) { + slots.push(slot); continue; } let miss = match miss_of.get(row) { @@ -98,7 +201,7 @@ fn lookup_rows(entries: &mut RowMap, rows: &[[u64; 16]], stamp: u64) -> R /// did not touch (age below `stamp`). Returns the slot and the evicted row (if any) per miss, and the new `next_slot`. #[allow(clippy::type_complexity)] fn assign_slots( - entries: &RowMap, + entries: &Residents, next_slot: u32, capacity: u32, stamp: u64, @@ -120,22 +223,85 @@ fn assign_slots( } let need = misses - from_free; if need > 0 { - let mut candidates: Vec<(u64, u64, u32)> = entries - .iter() - .filter(|(_, e)| e.age < stamp) - .map(|(r, e)| (e.age, *r, e.slot)) - .collect(); - if candidates.len() < need { + let (oldest, _) = entries.oldest(need, stamp, |_| false)?; + if oldest.len() < need { return Err(Error::InvalidDimension); } - candidates.select_nth_unstable_by_key(need - 1, |c| (c.0, c.1)); - for c in &candidates[..need] { - miss_slot.push(c.2); - victims.push(Some(c.1)); + for (row, slot) in oldest { + miss_slot.push(slot); + victims.push(Some(row)); } } Ok((miss_slot, victims, next_slot + from_free as u32)) } +/// One row of a gather the cache lacks: its position in the 16 rows, the slot it gets and the row evicted from that slot. +struct PlannedMiss { + at: usize, + row: u64, + slot: u32, + victim: Option, +} +struct GatherPlan { + misses: Vec, + selected: [u32; 16], + next_slot: u32, +} +/// The slot of each of the sixteen rows of one token: held rows keep theirs, each distinct missing row gets a free slot +/// (`next_slot..capacity`) or the slot of the least recently used row that is neither one of the sixteen nor already a victim. +/// Nothing is mutated. +fn plan_gather(entries: &Residents, mut next_slot: u32, capacity: u32, rows: &[u64; 16]) -> Result { + let mut misses = Vec::::new(); + misses.try_reserve_exact(16).map_err(|_| Error::InputAllocation)?; + let mut selected = [0u32; 16]; + for (i, row) in rows.iter().enumerate() { + if let Some(entry) = entries.get(row) { + selected[i] = entry.slot; + continue; + } + if let Some(miss) = misses.iter().find(|m| m.row == *row) { + selected[i] = miss.slot; + continue; + } + let (slot, victim) = if next_slot < capacity { + let slot = next_slot; + next_slot += 1; + (slot, None) + } else { + let (oldest, _) = entries.oldest(1, u64::MAX, |r| { + rows.contains(&r) || misses.iter().any(|m| m.victim == Some(r)) + })?; + let &(victim, slot) = oldest.first().ok_or(Error::InvalidDimension)?; + (slot, Some(victim)) + }; + selected[i] = slot; + misses.push(PlannedMiss { + at: i, + row: *row, + slot, + victim, + }); + } + Ok(GatherPlan { + misses, + selected, + next_slot, + }) +} +/// Publish a gather the device accepted: evict the victims, map the new rows, and age the sixteen rows `age_base + 1..=16` +/// in order (a row named twice keeps the later age), as the scan-based code did. +fn publish_gather(entries: &mut Residents, misses: &[PlannedMiss], rows: &[u64; 16], age_base: u64) { + for m in misses { + if let Some(victim) = m.victim { + entries.remove(&victim); + } + entries.insert(m.row, m.slot, age_base + 1); + } + for (i, row) in rows.iter().enumerate() { + entries + .touch(row, age_base + i as u64 + 1) + .expect("completed batch mapping"); + } +} struct Miss { row: u64, slot: u32, @@ -188,7 +354,7 @@ pub(crate) struct KarPleCache<'ctx> { binding: BindingIdentity, archive: [u8; 32], profile: [u8; 32], - entries: RowMap, + entries: Residents, next_slot: u32, age: u64, failed: bool, @@ -240,7 +406,7 @@ impl<'ctx> KarPleCache<'ctx> { binding: binding.identity(), archive: *binding.archive_digest(), profile: *binding.profile_digest(), - entries: RowMap::default(), + entries: Residents::default(), next_slot: 0, age: 0, failed: false, @@ -419,13 +585,7 @@ impl<'ctx> KarPleCache<'ctx> { } } for (row, slot, _) in staged.inserts { - self.entries.insert( - row, - Entry { - slot, - age: staged.stamp, - }, - ); + self.entries.insert(row, slot, staged.stamp); } self.next_slot = staged.next_slot; self.age = staged.stamp; @@ -459,42 +619,21 @@ impl<'ctx> KarPleCache<'ctx> { } else { None }; + let GatherPlan { + misses: planned, + selected, + next_slot, + } = plan_gather(&self.entries, self.next_slot, SLOTS, rows)?; let mut misses = Vec::::new(); misses - .try_reserve_exact(16) + .try_reserve_exact(planned.len()) .map_err(|_| Error::InputAllocation)?; - let mut selected = [0u32; 16]; - let mut next_slot = self.next_slot; - for (i, row) in rows.iter().enumerate() { - if let Some(entry) = self.entries.get(row) { - selected[i] = entry.slot; - continue; - } - if let Some(miss) = misses.iter().find(|m| m.row == *row) { - selected[i] = miss.slot; - continue; - } - let (slot, victim) = if next_slot < SLOTS { - let slot = next_slot; - next_slot += 1; - (slot, None) - } else { - let (victim, entry) = self - .entries - .iter() - .filter(|(r, _)| { - !rows.contains(r) && !misses.iter().any(|m| m.victim == Some(**r)) - }) - .min_by_key(|(_, e)| e.age) - .ok_or(Error::InvalidDimension)?; - (entry.slot, Some(*victim)) - }; - selected[i] = slot; - let packet = &packets.as_ref().expect("missing rows require packets")[i]; + for p in &planned { + let packet = &packets.as_ref().expect("missing rows require packets")[p.at]; misses.push(Miss { - row: *row, - slot, - victim, + row: p.row, + slot: p.slot, + victim: p.victim, payload: *packet.payload(), part: packet.partition(), }); @@ -564,24 +703,7 @@ impl<'ctx> KarPleCache<'ctx> { self.failed = true; return Err(error); } - for m in misses { - if let Some(victim) = m.victim { - self.entries.remove(&victim); - } - self.entries.insert( - m.row, - Entry { - slot: m.slot, - age: 0, - }, - ); - } - for (i, row) in rows.iter().enumerate() { - self.entries - .get_mut(row) - .expect("completed batch mapping") - .age = self.age + i as u64 + 1; - } + publish_gather(&mut self.entries, &planned, rows, self.age); self.next_slot = next_slot; self.age = final_age; Ok(values.into_boxed_slice()) @@ -703,7 +825,7 @@ mod slot_tests { /// What `KarPleCache::commit` does to the map, over the pure parts. fn apply( - entries: &mut RowMap, + entries: &mut Residents, lookup: &Lookup, miss_slot: &[u32], victims: &[Option], @@ -713,13 +835,7 @@ mod slot_tests { entries.remove(victim); } for (i, row) in lookup.miss_rows.iter().enumerate() { - entries.insert( - *row, - Entry { - slot: miss_slot[i], - age: stamp, - }, - ); + entries.insert(*row, miss_slot[i], stamp); } } fn chunk(rows: &[u64]) -> Vec<[u64; 16]> { @@ -728,16 +844,16 @@ mod slot_tests { .collect() } /// Every row maps to one slot and no slot serves two rows. - fn consistent(entries: &RowMap) { + fn consistent(entries: &Residents) { let mut seen = std::collections::HashSet::new(); - for entry in entries.values() { + for entry in entries.map.values() { assert!(seen.insert(entry.slot), "slot {} serves two rows", entry.slot); } } #[test] fn a_fresh_chunk_gets_distinct_free_slots_and_duplicates_share_one() { - let mut entries = RowMap::::default(); + let mut entries = Residents::default(); let rows = chunk(&[10, 20, 10, 30, 20, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140]); let lookup = lookup_rows(&mut entries, &rows, 1).unwrap(); assert_eq!(lookup.miss_rows.len(), 14); @@ -758,25 +874,25 @@ mod slot_tests { #[test] fn hits_keep_their_slots_and_refresh_their_age() { - let mut entries = RowMap::::default(); + let mut entries = Residents::default(); let first = chunk(&[1, 2, 3, 4]); let lookup = lookup_rows(&mut entries, &first, 1).unwrap(); let (slot, victims, _) = assign_slots(&entries, 0, 8, 1, lookup.miss_rows.len()).unwrap(); apply(&mut entries, &lookup, &slot, &victims, 1); - let before: Vec<(u64, u32)> = [1u64, 2, 3, 4].iter().map(|r| (*r, entries[r].slot)).collect(); + let before: Vec<(u64, u32)> = [1u64, 2, 3, 4].iter().map(|r| (*r, entries.map[r].slot)).collect(); let second = chunk(&[3, 4, 5, 6]); let lookup = lookup_rows(&mut entries, &second, 2).unwrap(); assert_eq!(lookup.miss_rows, vec![5, 6]); - assert_eq!(entries[&3].age, 2); - assert_eq!(entries[&1].age, 1); + assert_eq!(entries.map[&3].age, 2); + assert_eq!(entries.map[&1].age, 1); for (row, slot) in before { - assert_eq!(entries[&row].slot, slot); + assert_eq!(entries.map[&row].slot, slot); } } #[test] fn a_full_cache_evicts_the_oldest_rows_the_chunk_does_not_touch() { - let mut entries = RowMap::::default(); + let mut entries = Residents::default(); let capacity = 12u32; let mut next = 0u32; // chunk 1 fills 12 slots with rows 100..112 (stamp 1), chunk 2 refreshes 100..104 (stamp 2) @@ -800,7 +916,7 @@ mod slot_tests { assert_eq!(distinct.len(), 4); // the evicted rows' slots are the ones handed out for (i, v) in evicted.iter().enumerate() { - assert_eq!(entries[v].slot, slot[i]); + assert_eq!(entries.map[v].slot, slot[i]); } apply(&mut entries, &lookup, &slot, &victims, 3); consistent(&entries); @@ -814,12 +930,12 @@ mod slot_tests { /// id, so a reordered, shifted, repeated or partly new chunk finds each row in the slot it was given, and a hit never moves. #[test] fn rows_are_matched_by_row_id_never_by_position_in_the_chunk() { - let mut entries = RowMap::::default(); + let mut entries = Residents::default(); let first: Vec = (1..=32).map(|r| r * 1000).collect(); let lookup = lookup_rows(&mut entries, &chunk(&first), 1).unwrap(); let (slot, victims, _) = assign_slots(&entries, 0, 64, 1, lookup.miss_rows.len()).unwrap(); apply(&mut entries, &lookup, &slot, &victims, 1); - let given: std::collections::HashMap = entries.iter().map(|(r, e)| (*r, e.slot)).collect(); + let given: std::collections::HashMap = entries.map.iter().map(|(r, e)| (*r, e.slot)).collect(); let slot_of = |row: u64| given[&row]; let expect = |rows: &[u64]| -> Vec { rows.iter().map(|&r| slot_of(r)).collect() }; let flat = |lookup: &Lookup| lookup.slots.clone(); @@ -857,7 +973,7 @@ mod slot_tests { #[test] fn a_chunk_that_needs_more_slots_than_the_untouched_rows_hold_is_refused() { - let mut entries = RowMap::::default(); + let mut entries = Residents::default(); let lookup = lookup_rows(&mut entries, &chunk(&(0..8).collect::>()), 1).unwrap(); let (slot, victims, next) = assign_slots(&entries, 0, 8, 1, lookup.miss_rows.len()).unwrap(); apply(&mut entries, &lookup, &slot, &victims, 1); @@ -870,3 +986,316 @@ mod slot_tests { ); } } + +#[cfg(test)] +mod lru_tests { + use super::*; + use std::collections::HashMap; + + struct Rng(u64); + impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + /// Half the draws from a hot set, the rest from the whole universe. + fn row(&mut self, hot: u64, universe: u64) -> u64 { + if self.next() % 2 == 0 { + self.next() % hot + } else { + self.next() % universe + } + } + } + + /// The previous implementation, kept as the reference: a plain map scanned in full for every victim. + struct Scan { + map: HashMap, + next_slot: u32, + age: u64, + capacity: u32, + } + impl Scan { + fn new(capacity: u32) -> Self { + Self { + map: HashMap::new(), + next_slot: 0, + age: 0, + capacity, + } + } + /// (selected slots, misses as (row, slot, victim)) exactly as `KarPleCache::gather` chose them before the recency queue. + fn gather(&mut self, rows: &[u64; 16]) -> ([u32; 16], Vec<(u64, u32, Option)>) { + let mut misses = Vec::<(u64, u32, Option)>::new(); + let mut selected = [0u32; 16]; + let mut next_slot = self.next_slot; + for (i, row) in rows.iter().enumerate() { + if let Some(&(slot, _)) = self.map.get(row) { + selected[i] = slot; + continue; + } + if let Some(m) = misses.iter().find(|m| m.0 == *row) { + selected[i] = m.1; + continue; + } + let (slot, victim) = if next_slot < self.capacity { + next_slot += 1; + (next_slot - 1, None) + } else { + let (victim, (slot, _)) = self + .map + .iter() + .filter(|(r, _)| !rows.contains(r) && !misses.iter().any(|m| m.2 == Some(**r))) + .min_by_key(|(_, e)| e.1) + .unwrap(); + (*slot, Some(*victim)) + }; + selected[i] = slot; + misses.push((*row, slot, victim)); + } + for m in &misses { + if let Some(v) = m.2 { + self.map.remove(&v); + } + self.map.insert(m.0, (m.1, 0)); + } + for (i, row) in rows.iter().enumerate() { + self.map.get_mut(row).unwrap().1 = self.age + i as u64 + 1; + } + self.next_slot = next_slot; + self.age += 16; + (selected, misses) + } + } + + /// The device side: what a scatter writes into a slot is the row's own packet (here the row number), so a gathered row is right + /// exactly when its slot holds its own number. + struct Device(Vec); + + fn token(rng: &mut Rng, hot: u64, universe: u64) -> [u64; 16] { + std::array::from_fn(|_| rng.row(hot, universe)) + } + + /// Gathers (the decode path) on a cache much smaller than the row universe: the queue picks the same slots, the same victims + /// and ends in the same state as the full scan, and every gathered row is its own row. + #[test] + fn gather_equals_the_full_scan_on_random_sequences() { + for (capacity, hot, universe, seed) in [(64u32, 40u64, 500u64, 1u64), (257, 200, 3000, 2), (1000, 300, 1200, 3), (32, 20, 40, 4)] { + let mut rng = Rng(0x9e3779b97f4a7c15 ^ seed); + let mut old = Scan::new(capacity); + let mut new = Residents::default(); + let (mut next_slot, mut age) = (0u32, 0u64); + let mut device = Device(vec![u64::MAX; capacity as usize]); + let mut evictions = 0usize; + for step in 0..6000 { + let rows = token(&mut rng, hot, universe); + let (old_selected, old_misses) = old.gather(&rows); + let plan = plan_gather(&new, next_slot, capacity, &rows).unwrap(); + assert_eq!(plan.selected, old_selected, "step {step}"); + let planned: Vec<_> = plan.misses.iter().map(|m| (m.row, m.slot, m.victim)).collect(); + assert_eq!(planned, old_misses, "step {step}"); + evictions += planned.iter().filter(|m| m.2.is_some()).count(); + for m in &plan.misses { + device.0[m.slot as usize] = m.row; + } + publish_gather(&mut new, &plan.misses, &rows, age); + next_slot = plan.next_slot; + age += 16; + for (i, row) in rows.iter().enumerate() { + assert_eq!(device.0[plan.selected[i] as usize], *row, "step {step} position {i}: wrong row in the slot"); + } + } + assert!(evictions > 1000, "capacity {capacity}: the cache never filled ({evictions} evictions)"); + let mut a: Vec<_> = old.map.iter().map(|(r, (s, g))| (*r, *s, *g)).collect(); + let mut b: Vec<_> = new.map.iter().map(|(r, e)| (*r, e.slot, e.age)).collect(); + a.sort(); + b.sort(); + assert_eq!(a, b, "capacity {capacity}: final state"); + assert!(new.order.len() <= 2 * new.len() + 4096 + 16, "queue grew to {} for {} rows", new.order.len(), new.len()); + } + } + + /// Prompt chunks (`lookup_rows` + `assign_slots` + commit) mixed with decode gathers: every row always reads its own slot, no slot + /// serves two rows, and each victim is among the oldest untouched rows (no kept row is older than a victim). + #[test] + fn chunks_and_gathers_interleaved_keep_every_row_in_its_own_slot() { + let capacity = 300u32; + let mut rng = Rng(0x2545f4914f6cdd1d); + let mut entries = Residents::default(); + let (mut next_slot, mut age) = (0u32, 0u64); + let mut device = Device(vec![u64::MAX; capacity as usize]); + let mut chunk_evictions = 0usize; + for step in 0..1500 { + if step % 3 == 0 { + let n = 1 + (rng.next() % 6) as usize; + let rows: Vec<[u64; 16]> = (0..n).map(|_| token(&mut rng, 150, 2500)).collect(); + let stamp = age + 1; + let lookup = lookup_rows(&mut entries, &rows, stamp).unwrap(); + let (miss_slot, victims, next) = assign_slots(&entries, next_slot, capacity, stamp, lookup.miss_rows.len()).unwrap(); + // a victim is no younger than any row left in the cache that the chunk did not touch + let youngest_victim = victims.iter().flatten().map(|v| entries.map[v].age).max(); + if let Some(limit) = youngest_victim { + let victims_set: std::collections::HashSet = victims.iter().flatten().copied().collect(); + for (r, e) in &entries.map { + if e.age < stamp && !victims_set.contains(r) { + assert!(e.age >= limit, "step {step}: row {r} (age {}) outlived a victim of age {limit}", e.age); + } + } + } + chunk_evictions += victims.iter().flatten().count(); + let mut slots = lookup.slots.clone(); + for (at, miss) in &lookup.pending { + slots[*at as usize] = miss_slot[*miss as usize]; + } + for (i, row) in lookup.miss_rows.iter().enumerate() { + device.0[miss_slot[i] as usize] = *row; + } + for v in victims.iter().flatten() { + entries.remove(v); + } + for (i, row) in lookup.miss_rows.iter().enumerate() { + entries.insert(*row, miss_slot[i], stamp); + } + next_slot = next; + age = stamp; + for (at, row) in rows.iter().flatten().enumerate() { + assert_eq!(device.0[slots[at] as usize], *row, "step {step}: chunk position {at}"); + } + } else { + let rows = token(&mut rng, 150, 2500); + let plan = plan_gather(&entries, next_slot, capacity, &rows).unwrap(); + for m in &plan.misses { + device.0[m.slot as usize] = m.row; + } + publish_gather(&mut entries, &plan.misses, &rows, age); + next_slot = plan.next_slot; + age += 16; + for (i, row) in rows.iter().enumerate() { + assert_eq!(device.0[plan.selected[i] as usize], *row, "step {step}: gather position {i}"); + } + } + let mut seen = std::collections::HashSet::new(); + for e in entries.map.values() { + assert!(seen.insert(e.slot), "step {step}: slot {} serves two rows", e.slot); + } + assert!(entries.len() <= capacity as usize); + // one live queue item per row + let live = entries + .order + .iter() + .filter(|(a, r)| entries.map.get(r).is_some_and(|e| e.age == *a)) + .count(); + assert_eq!(live, entries.len(), "step {step}"); + } + assert!(chunk_evictions > 500, "the chunks never evicted ({chunk_evictions})"); + } + + /// A full cache of 200,000 rows: each missed row costs a handful of queue items, never the 200,000 entries the scan read. + #[test] + fn eviction_in_a_full_cache_examines_a_handful_of_items_not_the_cache() { + let capacity = 200_000u32; + let mut entries = Residents::default(); + let (mut next_slot, mut age) = (0u32, 0u64); + let mut row = 0u64; + let mut batches = 0; + let mut examined_after_full = 0usize; + let mut misses_after_full = 0usize; + while batches < capacity as usize / 16 + 2000 { + let rows: [u64; 16] = std::array::from_fn(|i| row + i as u64); + row += 16; + let before = entries.examined.load(std::sync::atomic::Ordering::Relaxed); + let plan = plan_gather(&entries, next_slot, capacity, &rows).unwrap(); + publish_gather(&mut entries, &plan.misses, &rows, age); + next_slot = plan.next_slot; + age += 16; + if next_slot == capacity { + examined_after_full += entries.examined.load(std::sync::atomic::Ordering::Relaxed) - before; + misses_after_full += plan.misses.len(); + } + batches += 1; + } + assert!(misses_after_full >= 16 * 1900, "{misses_after_full}"); + // each miss examines its victim plus the sixteen protected rows at most; the old scan examined `capacity` entries per miss + assert!( + examined_after_full <= misses_after_full * 40, + "{examined_after_full} items examined for {misses_after_full} misses (a scan would be {})", + misses_after_full * capacity as usize + ); + // and a hot row touched over and over leaves the queue bounded + for i in 0..50_000u64 { + entries.touch(&(row - 1 - (i % 4)), age + i + 1); + } + assert!(entries.order.len() <= 2 * entries.len() + 4096 + 1, "queue {}", entries.order.len()); + } + + /// A prompt chunk of 50,000 misses in a full cache reads the front of the queue, not the cache once per chunk. + #[test] + fn a_chunk_eviction_examines_about_as_many_items_as_it_needs() { + let capacity = 100_000u32; + let mut entries = Residents::default(); + for r in 0..capacity as u64 { + entries.insert(r, r as u32, 1 + r / 10); + } + let before = entries.examined.load(std::sync::atomic::Ordering::Relaxed); + let (victims, _) = entries.oldest(50_000, 1_000_000, |_| false).unwrap(); + assert_eq!(victims.len(), 50_000); + assert!(victims.iter().enumerate().all(|(i, (r, _))| *r == i as u64)); + let examined = entries.examined.load(std::sync::atomic::Ordering::Relaxed) - before; + assert_eq!(examined, 50_000); + } + + /// Fewer evictable rows than asked is refused by the caller; `oldest` itself returns what exists, found by the full scan. + #[test] + fn oldest_returns_what_exists_when_the_queue_runs_short() { + let mut entries = Residents::default(); + for r in 0..10u64 { + entries.insert(r, r as u32, r + 1); + } + let (victims, _) = entries.oldest(8, 6, |r| r == 2).unwrap(); + let rows: Vec = victims.iter().map(|v| v.0).collect(); + assert_eq!(rows, vec![0, 1, 3, 4]); + // a queue out of order (cannot happen by construction) is settled by the full scan, still oldest first + let mut entries = Residents::default(); + entries.insert(100, 0, 50); + entries.insert(101, 1, 10); + entries.insert(102, 2, 12); + let (victims, examined) = entries.oldest(2, 20, |_| false).unwrap(); + assert_eq!(victims, vec![(101, 1), (102, 2)]); + assert!(examined >= entries.len()); + } + + /// Cost of the old scan against the queue on a full cache of 1,048,576 rows (the production size): + /// `cargo test --release -p leleka-runtime scan_against_queue -- --ignored --nocapture`. + #[test] + #[ignore = "timing probe; prints the per-miss cost of the old scan and of the queue"] + fn scan_against_queue_on_a_full_cache() { + let capacity = SLOTS; + let mut entries = Residents::default(); + let mut old = Scan::new(capacity); + for r in 0..capacity as u64 { + entries.insert(r * 7 + 3, r as u32, 1 + r); + old.map.insert(r * 7 + 3, (r as u32, 1 + r)); + } + let rows: [u64; 16] = std::array::from_fn(|i| 1_000_000_007 + i as u64 * 2); + let t = std::time::Instant::now(); + let n = 20; + for _ in 0..n { + std::hint::black_box( + old.map + .iter() + .filter(|(r, _)| !rows.contains(r)) + .min_by_key(|(_, e)| e.1) + .map(|(r, _)| *r), + ); + } + let scan = t.elapsed() / n; + let t = std::time::Instant::now(); + for _ in 0..1000 { + std::hint::black_box(entries.oldest(1, u64::MAX, |r| rows.contains(&r)).unwrap()); + } + let queue = t.elapsed() / 1000; + println!("per missed row: old scan {scan:?}, recency queue {queue:?} (full cache of {capacity} rows)"); + } +}