use super::*;
fn fake_cs(tag: u8) -> Vec<u8> {
vec![tag; 16]
}
fn assert_zero_pool_leaks(pools: &BlockPools) {
for kind in KINDS {
let pool = pools.of(kind);
for i in 0..pool.len() {
let s = Slot::new((i + 1) as u32).unwrap();
assert_eq!(pool.record(s).unwrap().refs(), 0, "leaked ref in {kind:?} slot {}", s.get());
}
}
}
fn retain(
cache: &mut ServeBlockCache,
pools: &mut BlockPools,
tbl: &mut BlockTable,
state: &mut LaneBlockState,
tokens: &[u32],
tag: u8,
) -> SealedId {
let start = cache.match_and_bind(pools, tbl, state, tokens).map_or(0, |(p, _)| p);
let end = tokens.len() - 1;
cache.ensure_span_blocks(pools, tbl, start, end - start).unwrap();
cache.finish_prefill_span(pools, tbl, state, tokens, start, end - start, || fake_cs(tag));
let tip = *state.sealed.last().unwrap();
cache.release_lane(pools, tbl, state);
tip
}
fn bind_release(
cache: &mut ServeBlockCache,
pools: &mut BlockPools,
tbl: &mut BlockTable,
state: &mut LaneBlockState,
tokens: &[u32],
) -> usize {
let at = cache.match_and_bind(pools, tbl, state, tokens).map_or(0, |(p, _)| p);
cache.release_lane(pools, tbl, state);
at
}
fn saved(cache: &ServeBlockCache, sid: SealedId) -> u64 {
cache.starts[&sid].reuse.saved_tokens(cache.tick)
}
fn rank(cache: &ServeBlockCache, sid: SealedId) -> EvictionRank {
let leased = cache.leased_starts().contains(&sid);
cache.eviction_rank(sid, &cache.starts[&sid], leased)
}
fn victims(cache: &ServeBlockCache, pools: &BlockPools, need_win: usize, need_full: usize) -> Vec<SealedId> {
cache.select_eviction_victims(pools, need_win, need_full, None).unwrap().into_iter().map(|(sid, _)| sid).collect()
}
#[test]
fn reuse_credit_rotates_by_epoch_and_expires() {
let mut reuse = RecentReuse::default();
let epoch = REUSE_EPOCH_TICKS;
reuse.record(epoch - 1, 128);
assert_eq!(reuse.saved_tokens(epoch - 1), 128);
assert_eq!(reuse.saved_tokens(epoch), 64, "the previous epoch counts half");
reuse.record(epoch, 64);
assert_eq!(reuse.saved_tokens(epoch), 128);
assert_eq!(reuse.saved_tokens(2 * epoch), 32);
assert_eq!(reuse.saved_tokens(3 * epoch), 0, "credit two epochs old has expired");
reuse.record(3 * epoch, 64);
assert_eq!(reuse.saved_tokens(3 * epoch), 64, "a gap of two epochs drops the previous bucket");
}
#[test]
fn eviction_rank_orders_lease_then_live_then_recent_then_density() {
let sid = |i| SealedId::for_test(1, i);
let base = EvictionRank { leased: false, live: false, recent: true, saved_tokens: 0, bytes: 100, last_used_tick: 5, pos: 64, sid: sid(1) };
let lt = |a: &EvictionRank, b: &EvictionRank| a.compare(b, false) == std::cmp::Ordering::Less;
let leased = EvictionRank { leased: true, recent: false, last_used_tick: 0, sid: sid(2), ..base };
let hot = EvictionRank { saved_tokens: 1 << 40, live: true, sid: sid(3), ..base };
assert!(lt(&hot, &leased));
assert!(lt(&base, &EvictionRank { live: true, sid: sid(4), ..base }));
assert!(lt(&EvictionRank { recent: false, sid: sid(5), ..base }, &base));
let dense = EvictionRank { saved_tokens: 192, bytes: 2, sid: sid(6), ..base };
let raw = EvictionRank { saved_tokens: 256, bytes: 3, sid: sid(7), ..base };
assert!(lt(&raw, &dense));
let big = EvictionRank { saved_tokens: u64::MAX, bytes: u64::MAX - 1, sid: sid(8), ..base };
let bigger = EvictionRank { saved_tokens: u64::MAX, bytes: u64::MAX - 2, sid: sid(9), ..base };
assert!(lt(&big, &bigger));
assert!(lt(&EvictionRank { last_used_tick: 1, sid: sid(10), ..base }, &base));
assert!(lt(&EvictionRank { pos: 128, sid: sid(11), ..base }, &base));
assert!(raw.compare(&EvictionRank { last_used_tick: 9, ..dense }, true) == std::cmp::Ordering::Less);
assert!(hot.compare(&EvictionRank { last_used_tick: 9, ..base }, true) == std::cmp::Ordering::Less);
let older_hot = EvictionRank { last_used_tick: 1, saved_tokens: 512, sid: sid(12), ..base };
let newer_cold = EvictionRank { last_used_tick: 9, saved_tokens: 0, sid: sid(13), ..base };
assert_eq!(pick_ranked_victim(&[older_hot, newer_cold], false), Some((sid(13), true)));
assert_eq!(pick_ranked_victim(&[older_hot, newer_cold], true), Some((sid(12), false)));
assert_eq!(pick_ranked_victim(&[newer_cold], false), Some((sid(13), false)));
assert_eq!(pick_ranked_victim(&[], false), None);
}
#[test]
fn checkpoint_charges_each_referenced_slot_at_its_own_pool_stride() {
let mut pools = BlockPools::with_capacities(4, 4, 2).unwrap();
let mut cache = ServeBlockCache::new();
let mut tbl = BlockTable::new(4).unwrap();
cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 100).unwrap();
let mut entries = Vec::new();
let mut expected = 0;
for kind in [BlockKind::Full, BlockKind::Window] {
for b in 0..2 {
let bi = BlockIndex::new(b);
let entry = tbl.get(kind, bi).unwrap().unwrap();
entries.push((kind, bi, entry));
expected += pools.of(kind).slot_bytes(entry.slot()).unwrap().len() as u64;
}
}
assert_eq!(ServeBlockCache::checkpoint_slot_bytes(&pools, &entries), expected);
assert_ne!(
ServeBlockCache::checkpoint_slot_bytes(&pools, &entries[..2]),
ServeBlockCache::checkpoint_slot_bytes(&pools, &entries[2..]),
"equal entry counts from different pools are charged differently"
);
tbl.clear_entries(&mut pools).unwrap();
assert_zero_pool_leaks(&pools);
}
#[test]
fn pool_pressure_keeps_a_reused_prefix_over_a_newer_one_off_and_counts_the_ranked_eviction() {
let mut cache = ServeBlockCache::new();
let mut pools = BlockPools::with_capacities(4, 4, 1).unwrap();
let mut tbl = BlockTable::new(4).unwrap();
let mut lane = LaneBlockState::default();
let prompt: Vec<u32> = (0..=128).collect();
let long = retain(&mut cache, &mut pools, &mut tbl, &mut lane, &prompt, 1);
for _ in 0..6 {
assert_eq!(bind_release(&mut cache, &mut pools, &mut tbl, &mut lane, &prompt), 128);
}
lane.namespace = 7;
let short = retain(&mut cache, &mut pools, &mut tbl, &mut lane, &prompt[..=64], 2);
assert_eq!(saved(&cache, long), 6 * 128, "each bind credits the start with the tokens it skipped");
assert_eq!(saved(&cache, short), 0);
let picked = cache.select_eviction_victims(&pools, 0, 2, None).unwrap();
assert!(cache.starts[&long].last_used_tick < cache.starts[&short].last_used_tick);
assert_eq!(picked, [(short, true)], "LRU would have taken the older, hot `long`");
let mut hog_tbl = BlockTable::new(4).unwrap();
let mut hog = LaneBlockState { namespace: 9, ..Default::default() };
let other: Vec<u32> = (5000..=5128).collect();
let before = cache.stats().evictions_ranked_over_lru;
retain(&mut cache, &mut pools, &mut hog_tbl, &mut hog, &other, 3);
assert!(cache.starts.contains_key(&long), "the reused prefix stays resident");
assert!(!cache.starts.contains_key(&short));
assert_eq!(cache.stats().evictions_ranked_over_lru, before + 1, "the ranking decided this eviction");
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn retain_lru_restores_plain_lru_and_never_counts_a_ranked_eviction() {
for lru in [false, true] {
let mut cache = ServeBlockCache::new();
cache.set_retain_lru(lru);
let mut pools = BlockPools::with_capacities(4, 4, 1).unwrap();
let mut tbl = BlockTable::new(4).unwrap();
let mut lane = LaneBlockState::default();
let prompt: Vec<u32> = (0..=128).collect();
let long = retain(&mut cache, &mut pools, &mut tbl, &mut lane, &prompt, 1);
for _ in 0..3 {
bind_release(&mut cache, &mut pools, &mut tbl, &mut lane, &prompt);
}
lane.namespace = 7;
let short = retain(&mut cache, &mut pools, &mut tbl, &mut lane, &prompt[..=64], 2);
assert_eq!(victims(&cache, &pools, 0, 2), if lru { [long] } else { [short] }, "INK_RETAIN_LRU={lru}");
cache.set_max_retained_host_bytes(cache.retained_host_bytes() - 1);
let (victim, over_lru) = cache.host_trim_victim(None).unwrap();
assert_eq!(victim, if lru { long } else { short });
assert_eq!(over_lru, !lru);
cache.enforce_retained_host_budget(&mut pools, None);
assert_eq!(cache.stats().evictions_ranked_over_lru, u64::from(!lru));
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
}
#[test]
fn host_trim_ranks_by_host_bytes_while_pool_pressure_charges_slots() {
let mut cache = ServeBlockCache::new();
let mut pools = BlockPools::with_capacities(3, 3, 1).unwrap();
let mut tbl = BlockTable::new(3).unwrap();
let mut lane = LaneBlockState::default();
let short_prompt: Vec<u32> = (0..=64).collect();
let long_prompt: Vec<u32> = (1000..=1128).collect();
let [short, long] = [&short_prompt, &long_prompt].map(|prompt| {
lane.prompt_len = prompt.len();
let end = prompt.len() - 1;
cache.ensure_span_blocks(&mut pools, &mut tbl, 0, end).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut lane, prompt, 0, end, || vec![7; 4096]);
let tip = *lane.sealed.last().unwrap();
cache.release_lane(&mut pools, &mut tbl, &mut lane);
tip
});
for prompt in [&short_prompt, &short_prompt, &short_prompt, &long_prompt, &long_prompt] {
assert_eq!(bind_release(&mut cache, &mut pools, &mut tbl, &mut lane, prompt), prompt.len() - 1);
}
assert_eq!(saved(&cache, short), 192);
assert_eq!(saved(&cache, long), 256);
assert_eq!(victims(&cache, &pools, 0, 1), [long]);
cache.set_max_retained_host_bytes(cache.starts[&long].host_bytes());
cache.enforce_retained_host_budget(&mut pools, None);
assert!(!cache.starts.contains_key(&short));
assert!(cache.starts.contains_key(&long));
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn creation_grace_expires_and_a_second_save_never_renews_it() {
let mut cache = ServeBlockCache::new();
let mut pools = BlockPools::with_capacities(4, 4, 1).unwrap();
let mut tbl = BlockTable::new(2).unwrap();
let mut lane = LaneBlockState::default();
let tokens: Vec<u32> = (0..=64).collect();
let tip = retain(&mut cache, &mut pools, &mut tbl, &mut lane, &tokens, 1);
cache.tick += REUSE_EPOCH_TICKS - 2;
let young_tokens: Vec<u32> = (500..565).collect();
let young = retain(&mut cache, &mut pools, &mut tbl, &mut lane, &young_tokens, 2);
assert!(rank(&cache, tip).recent, "inside its creation grace");
lane.prompt_len = tokens.len();
cache.ensure_span_blocks(&mut pools, &mut tbl, 0, BLOCK).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut lane, &tokens, 0, BLOCK, || fake_cs(2));
cache.release_lane(&mut pools, &mut tbl, &mut lane);
assert_eq!(cache.starts[&tip].last_used_tick, cache.tick);
assert!(!rank(&cache, tip).recent, "a second save does not renew creation grace");
assert!(cache.starts[&young].last_used_tick < cache.starts[&tip].last_used_tick);
assert_eq!(cache.host_trim_victim(None).map(|v| v.0), Some(tip), "LRU alone would have taken the young start");
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn a_fresh_head_survives_pressure_over_expired_credit_and_binds_on_its_next_turn() {
let mut cache = ServeBlockCache::new();
let mut pools = BlockPools::with_capacities(3, 3, 1).unwrap();
let mut tbl = BlockTable::new(3).unwrap();
let mut lane = LaneBlockState::default();
let old: Vec<u32> = (0..=128).collect();
let stale = retain(&mut cache, &mut pools, &mut tbl, &mut lane, &old, 1);
for _ in 0..6 {
bind_release(&mut cache, &mut pools, &mut tbl, &mut lane, &old);
}
assert_eq!(saved(&cache, stale), 6 * 128);
cache.tick += 2 * REUSE_EPOCH_TICKS;
assert_eq!(saved(&cache, stale), 0, "two epochs idle: the credit has expired");
let head: Vec<u32> = (1000..=1064).collect();
let fresh = retain(&mut cache, &mut pools, &mut tbl, &mut lane, &head, 2);
let third: Vec<u32> = (2000..=2064).collect();
retain(&mut cache, &mut pools, &mut tbl, &mut lane, &third, 3);
assert!(!cache.starts.contains_key(&stale), "expired credit loses to a head inside its creation grace");
let mut next_turn = head;
next_turn.extend([71, 72]);
let (matched, cs) = cache.match_and_bind(&mut pools, &mut tbl, &mut lane, &next_turn).unwrap();
assert_eq!((matched, cs), (BLOCK, fake_cs(2)));
assert_eq!(saved(&cache, fresh), BLOCK as u64);
cache.release_lane(&mut pools, &mut tbl, &mut lane);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn a_deeper_rebind_credits_only_the_work_it_skipped() {
let mut cache = ServeBlockCache::new();
let mut pools = BlockPools::with_capacities(8, 8, 1).unwrap();
let mut tbl = BlockTable::new(8).unwrap();
let mut lane = LaneBlockState::default();
let mut producer_tbl = BlockTable::new(8).unwrap();
let mut producer = LaneBlockState::default();
let prompt: Vec<u32> = (0..=128).collect();
let short = retain(&mut cache, &mut pools, &mut tbl, &mut lane, &prompt[..=64], 1);
cache.match_and_bind(&mut pools, &mut tbl, &mut lane, &prompt).unwrap();
let long = retain(&mut cache, &mut pools, &mut producer_tbl, &mut producer, &prompt, 2);
let old_short_credit = saved(&cache, short);
assert_eq!(saved(&cache, long), 0);
cache.rebind_if_deeper_match(&mut pools, &mut tbl, &mut lane, &prompt, 64).unwrap();
assert_eq!(saved(&cache, short), old_short_credit, "an ancestor the lane had already computed earns nothing");
assert_eq!(saved(&cache, long), 64);
assert!(cache.rebind_if_deeper_match(&mut pools, &mut tbl, &mut lane, &prompt, 128).is_none());
assert_eq!(saved(&cache, long), 64, "a failed rebind earns nothing");
cache.release_lane(&mut pools, &mut tbl, &mut lane);
cache.starts.get_mut(&short).unwrap().reuse = RecentReuse { epoch: cache.tick / REUSE_EPOCH_TICKS, current: 64, previous: 0 };
cache.starts.get_mut(&short).unwrap().last_used_tick = 0;
assert_eq!(cache.host_trim_victim(None).map(|v| v.0), Some(long));
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn a_live_lanes_checkpoint_outranks_an_idle_hot_prefix_under_host_pressure() {
let mut cache = ServeBlockCache::new();
let mut pools = BlockPools::with_capacities(4, 4, 1).unwrap();
let mut tbl = BlockTable::new(4).unwrap();
let mut lane = LaneBlockState::default();
let prompt: Vec<u32> = (0..=128).collect();
let long = retain(&mut cache, &mut pools, &mut tbl, &mut lane, &prompt, 1);
for _ in 0..6 {
bind_release(&mut cache, &mut pools, &mut tbl, &mut lane, &prompt);
}
lane.namespace = 7;
let short = retain(&mut cache, &mut pools, &mut tbl, &mut lane, &prompt[..=64], 2);
cache.match_and_bind_in_namespace(&mut pools, &mut tbl, &mut lane, 7, &prompt).unwrap();
assert!(rank(&cache, short).live);
assert_eq!(cache.host_trim_victim(None).map(|v| v.0), Some(long), "a live card's start is taken last");
cache.release_lane(&mut pools, &mut tbl, &mut lane);
cache.set_max_retained_host_bytes(cache.starts[&long].host_bytes());
cache.enforce_retained_host_budget(&mut pools, None);
assert!(cache.starts.contains_key(&long), "once idle, the once-used branch loses to the six-use head");
assert!(!cache.starts.contains_key(&short));
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn the_card_lease_outranks_reuse_credit_until_it_expires() {
let mut pools = BlockPools::with_capacities(4, 4, 1).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_card_lease(Duration::from_secs(30));
cache.set_test_clock_ms(1_000);
let owner = approx_twin("lease-salt", 0, Some("card-a"));
let hot: Vec<u32> = (0..=64).collect();
let mut tbl = BlockTable::new(4).unwrap();
let mut anon = LaneBlockState::default();
let hot_tip = retain(&mut cache, &mut pools, &mut tbl, &mut anon, &hot, 1);
for _ in 0..6 {
assert_eq!(bind_release(&mut cache, &mut pools, &mut tbl, &mut anon, &hot), 64);
}
let card: Vec<u32> = (1000..=1064).collect();
let mut st_a = LaneBlockState { owner, ..Default::default() };
let card_tip = retain(&mut cache, &mut pools, &mut tbl, &mut st_a, &card, 2);
assert!(cache.leased_starts().contains(&card_tip));
assert_eq!(saved(&cache, card_tip), 0);
assert!(saved(&cache, hot_tip) > 0);
assert_eq!(victims(&cache, &pools, 0, 3), [hot_tip], "LRU and ranked orders agree: the unleased start goes");
assert_eq!(cache.host_trim_victim(None).map(|v| v.0), Some(hot_tip));
cache.advance_test_clock_ms(31_000);
assert!(!cache.leased_starts().contains(&card_tip));
assert_eq!(cache.host_trim_victim(None), Some((card_tip, true)));
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn a_disk_restore_earns_no_credit_until_a_resident_bind() {
let dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("target")
.join("block-cache-spill-tests")
.join(format!("retention-restore-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let store = SpillStore::open(&dir, 64 * 1024 * 1024).unwrap();
let mut cache = ServeBlockCache::with_spill(store);
let mut pools = BlockPools::with_capacities(8, 8, 1).unwrap();
let mut tbl = BlockTable::new(8).unwrap();
let mut lane = LaneBlockState::default();
let prompt: Vec<u32> = (0..=128).collect();
let tip = retain(&mut cache, &mut pools, &mut tbl, &mut lane, &prompt, 1);
assert!(cache.evict_start(&mut pools, tip));
assert_eq!(cache.spilled_start_count(), 1);
assert_eq!(cache.match_and_bind(&mut pools, &mut tbl, &mut lane, &prompt).map(|m| m.0), Some(128));
assert_eq!(cache.stats().starts_restored, 1);
let restored = *lane.sealed.last().unwrap();
assert_eq!(saved(&cache, restored), 0, "the restoring bind earns nothing");
assert!(!rank(&cache, restored).recent, "a restored start has no creation grace");
cache.release_lane(&mut pools, &mut tbl, &mut lane);
assert_eq!(bind_release(&mut cache, &mut pools, &mut tbl, &mut lane, &prompt), 128);
assert_eq!(saved(&cache, restored), 128, "a resident bind earns ordinary credit");
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
let _ = std::fs::remove_dir_all(&dir);
}