use crate::blockbook::PROMPT;
#[cfg(test)]
use crate::blockbook::EVERY;
use crate::blocks::{BlockEntry, BlockIndex, BlockKind, BlockPool, BlockPools, BlockTable, Slot, VerifyBlockFinalize, BLOCK, FULL_PASSES, NKV, WINDOW};
use crate::engine::EXT;
use crate::prefix::{BlockHandles, EntryTree, PrefixTree, SealedId};
use crate::spill::{
read_block_from_dir, unlink_block_in_dir, RawDiskRead, RawDiskWrite, ReadOutcome, Sha256, SpillBlockKind,
SpillBytes, SpillIo, SpillIoDone, SpillKey, SpillStore, SpillWriter,
};
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant};
#[cfg(standalone_blocks)]
#[path = "block_cache/trace.rs"]
pub(crate) mod trace;
pub const KINDS: [BlockKind; 2] = [BlockKind::Window, BlockKind::Full];
#[path = "checkpoint.rs"]
pub mod checkpoint;
pub use checkpoint::{
effective_pf_target, finish_parts, is_every_checkpoint, span_checkpoints, start_reasons, step_pf_target, StateAt,
EARLY_EVERY_LIMIT, EARLY_EVERY_TOKENS, LATE_EVERY_TOKENS,
};
pub const MAX_ADMIT_DECODE_RESERVE: usize = 4096;
#[cfg(test)]
thread_local! {
pub(crate) static TEST_ADMIT_DECODE_RESERVE: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
}
fn admit_decode_reserve() -> usize {
#[cfg(test)]
if let Some(reserve) = TEST_ADMIT_DECODE_RESERVE.with(|r| r.get()) {
return reserve;
}
MAX_ADMIT_DECODE_RESERVE
}
pub const DEFAULT_MAX_SPILLED_STARTS: usize = 512;
pub const MAX_INFLIGHT_RESTORE_STAGING_BYTES: usize = 512 * 1024 * 1024;
const SPILL_INDEX_MAGIC: [u8; 8] = *b"INKYSPID";
const SPILL_INDEX_VERSION: u32 = 3;
const SPILL_INDEX_HEADER_LEN: usize = 84;
const SPILL_INDEX_PREFIX_LEN: usize = 52;
const MAX_SPILL_INDEX_BYTES: usize = 64 * 1024 * 1024;
pub const DEFAULT_MAX_RETAINED_HOST_BYTES: u64 = 512 << 20;
pub const DEFAULT_MAX_APPROX_STARTS_PER_SCOPE: usize = 2048;
pub const DEFAULT_SPILL_WRITE_TIMEOUT: Duration = Duration::from_secs(30);
pub const DEFAULT_SPILL_WRITE_QUEUE_BYTES: u64 = 2 << 30;
pub const LEFT_HEAL_TOKENS: usize = 16 * BLOCK;
pub const MIN_HEAL_TOKENS: usize = 24 * BLOCK;
pub const MIN_STITCH_TOKENS: usize = LEFT_HEAL_TOKENS + MIN_HEAL_TOKENS + 2 * BLOCK;
const STITCH_ROLL_BASE: u64 = 0x9e37_79b9_7f4a_7c15;
const STITCH_ROLL_BASE_POW_63: u64 = {
let mut p = 1u64;
let mut i = 0;
while i < BLOCK - 1 {
p = p.wrapping_mul(STITCH_ROLL_BASE);
i += 1;
}
p
};
const MAX_STITCH_BUCKET_LEN: usize = 16;
#[inline]
fn mix_stitch_token(t: u32) -> u64 {
let mut z = (t as u64).wrapping_add(0x9e37_79b9_7f4a_7c15);
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
z ^ (z >> 31)
}
#[inline]
pub fn stitch_hash_64(chunk: &[u32]) -> u64 {
debug_assert_eq!(chunk.len(), BLOCK);
let mut h = 0u64;
for &t in chunk {
h = h.wrapping_mul(STITCH_ROLL_BASE).wrapping_add(mix_stitch_token(t));
}
h
}
#[inline]
pub fn slide_stitch_hash_64(h: u64, leaving: u32, entering: u32) -> u64 {
let without_first = h.wrapping_sub(mix_stitch_token(leaving).wrapping_mul(STITCH_ROLL_BASE_POW_63));
without_first.wrapping_mul(STITCH_ROLL_BASE).wrapping_add(mix_stitch_token(entering))
}
fn copy_full_slot_rows(
src_slot: &[u8],
src_ib: usize,
dst_slot: &mut [u8],
dst_ib: usize,
count: usize,
kvb: u32,
) {
if count == 0 {
return;
}
let mode = crate::blocks::KvMode::from_kvb_tag(kvb).unwrap_or_else(|_| panic!("invalid kvb {kvb}"));
assert!(src_ib + count <= BLOCK && dst_ib + count <= BLOCK, "in-block slice out of range");
let row = mode.row_bytes() as usize;
let head_bytes = BLOCK * row;
let total_heads = FULL_PASSES * 2 * NKV;
assert_eq!(src_slot.len(), total_heads * head_bytes);
assert_eq!(dst_slot.len(), total_heads * head_bytes);
if src_ib == 0 && dst_ib == 0 && count == BLOCK {
dst_slot.copy_from_slice(src_slot);
return;
}
let copy_len = count * row;
let src_in_head = src_ib * row;
let dst_in_head = dst_ib * row;
for h in 0..total_heads {
let base = h * head_bytes;
dst_slot[base + dst_in_head..base + dst_in_head + copy_len]
.copy_from_slice(&src_slot[base + src_in_head..base + src_in_head + copy_len]);
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StitchSource {
Retained { sid: SealedId, src_start: usize },
Ikv { cart_idx: usize, src_start: usize },
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct StitchSpanPlan {
pub span_start: usize,
pub stitch_start: usize,
pub heal_start: usize,
pub span_end: usize,
pub source: StitchSource,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StitchApplyOutcome {
Applied { stitched_tokens: usize, zero_copy_blocks: usize },
SourceGone,
PoolBusy,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StitchStartOutcome {
Applied { stitched_tokens: usize, zero_copy_blocks: usize },
Staging,
SourceGone,
PoolBusy,
}
#[derive(Debug)]
pub struct CompletedIkvStage {
pub lane: usize,
pub stitched_tokens: Option<usize>,
pub heal_start: usize,
pub elapsed: Duration,
pub corrupt_fallback: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CacheError {
PoolExhausted(BlockKind),
}
impl std::fmt::Display for CacheError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CacheError::PoolExhausted(kind) => write!(f, "KV block pool exhausted ({kind:?})"),
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CacheStats {
pub slots_taken: u64,
pub slots_reused: u64,
pub blocks_sealed: u64,
pub shared_dedups: u64,
pub start_points_saved: u64,
pub start_points_evicted: u64,
pub start_matches: u64,
pub cached_tokens_total: u64,
pub window_pruned: u64,
pub admit_deferred_pool_pressure: u64,
pub step_deferred_pool_pressure: u64,
pub singleflight_rebinds: u64,
pub singleflight_saved_tokens: u64,
pub starts_spilled: u64,
pub starts_restored: u64,
pub corrupt_fallbacks: u64,
pub last_restore_us: u64,
pub restore_us_total: u64,
pub lanes_released: u64,
pub spill_maint_passes: u64,
pub spill_maint_evictions: u64,
pub spill_write_timeouts: u64,
pub ikv_cartridges_loaded: u64,
pub ikv_quarantined: u64,
pub stitch_hits: u64,
pub stitched_tokens_total: u64,
pub approx_starts_saved: u64,
pub approx_start_matches: u64,
pub approx_cached_tokens_total: u64,
pub evictions_pool_pressure: u64,
pub evictions_host_budget: u64,
pub evictions_approx_scope_cap: u64,
pub evictions_stale_invalid: u64,
pub evictions_shutdown: u64,
pub evictions_superseded: u64,
pub evictions_ranked_over_lru: u64,
pub activity_ticks: u64,
pub turn_end_starts_saved: u64,
pub turn_end_starts_not_saved: [u64; TurnEndMiss::ALL.len()],
pub restores_failed: u64,
pub spill_reads_hit: u64,
pub spill_reads_miss: u64,
pub spill_bytes_read: u64,
pub spill_read_us_total: u64,
pub spill_writes_queued: u64,
pub spill_writes_dropped_queue_full: u64,
pub spill_writes_pending: u64,
pub spill_write_bytes_pending: u64,
pub spill_starts_dropped: u64,
pub spill_starts_pending: u64,
pub spill_io_errors: u64,
pub evict_us_total: u64,
pub evict_us_max: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EvictCause {
PoolPressure,
HostBudget,
ApproxScopeCap,
StaleInvalid,
Shutdown,
Superseded,
}
pub const MAX_OWNER_PRIOR_ENTRIES: usize = 8_192;
#[derive(Clone, Debug)]
struct OwnerPriorTurn {
seq: u64,
prompt_saved_pos: usize,
prompt_len: usize,
reply_saved_pos: usize,
total_len: usize,
prompt_tip_id: Option<SealedId>,
reply_tip_id: Option<SealedId>,
tip_id: Option<SealedId>,
spilled_tip_id: Option<SealedId>,
spilled_prompt_tip_id: Option<SealedId>,
tail_toks: Vec<u32>,
truncated_tail: bool,
evicted: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ObservedPrior {
pub has_prior: bool,
pub prompt_saved_pos: usize,
pub prompt_len: usize,
pub reply_saved_pos: usize,
pub total_len: usize,
pub prompt_tip_id: Option<SealedId>,
pub reply_tip_id: Option<SealedId>,
pub proven_common_len: usize,
pub evicted: bool,
pub any_saved_start_missing: bool,
pub first_divergent_pos: Option<usize>,
}
#[cfg(test)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CacheMemorySnapshot {
pub window_slots_used: usize,
pub window_slots_capacity: usize,
pub window_slots_bytes_used: u64,
pub window_slots_bytes_capacity: u64,
pub full_slots_used: usize,
pub full_slots_capacity: usize,
pub full_slots_bytes_used: u64,
pub full_slots_bytes_capacity: u64,
pub retained_host_bytes: u64,
pub retained_host_budget_bytes: u64,
pub retained_starts: usize,
pub approx_retained_starts: usize,
pub spilled_starts: usize,
pub evictions_pool_pressure: u64,
pub evictions_host_budget: u64,
pub evictions_approx_scope_cap: u64,
pub evictions_stale_invalid: u64,
pub evictions_shutdown: u64,
pub evictions_superseded: u64,
pub starts_spilled: u64,
pub spill_writes_committed: u64,
pub spill_bytes_written: u64,
pub spill_write_us_total: u64,
pub spill_write_timeouts: u64,
pub spill_disk_used_bytes: u64,
pub spill_disk_max_bytes: u64,
pub spill_disk_gc_evictions: u64,
pub spill_reads_hit: u64,
pub spill_reads_miss: u64,
pub spill_bytes_read: u64,
pub spill_read_us_total: u64,
pub starts_restored: u64,
pub restores_failed: u64,
pub restore_us_total: u64,
}
#[cfg(test)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CacheMemoryInterval {
pub window_slots_used: usize,
pub window_slots_capacity: usize,
pub window_slots_bytes_used: u64,
pub window_slots_bytes_capacity: u64,
pub full_slots_used: usize,
pub full_slots_capacity: usize,
pub full_slots_bytes_used: u64,
pub full_slots_bytes_capacity: u64,
pub retained_host_bytes: u64,
pub retained_host_budget_bytes: u64,
pub retained_starts: usize,
pub approx_retained_starts: usize,
pub spilled_starts: usize,
pub evictions_pool_pressure: u64,
pub evictions_host_budget: u64,
pub evictions_approx_scope_cap: u64,
pub evictions_stale_invalid: u64,
pub evictions_shutdown: u64,
pub evictions_superseded: u64,
pub starts_spilled: u64,
pub spill_writes_committed: u64,
pub spill_bytes_written: u64,
pub spill_write_us_total: u64,
pub spill_write_timeouts: u64,
pub spill_disk_used_bytes: u64,
pub spill_disk_max_bytes: u64,
pub spill_disk_gc_evictions: u64,
pub spill_reads_hit: u64,
pub spill_reads_miss: u64,
pub spill_bytes_read: u64,
pub spill_read_us_total: u64,
pub starts_restored: u64,
pub restores_failed: u64,
pub restore_us_total: u64,
}
#[cfg(test)]
impl CacheMemorySnapshot {
pub fn delta_since(&self, prev: &Self) -> CacheMemoryInterval {
CacheMemoryInterval {
window_slots_used: self.window_slots_used,
window_slots_capacity: self.window_slots_capacity,
window_slots_bytes_used: self.window_slots_bytes_used,
window_slots_bytes_capacity: self.window_slots_bytes_capacity,
full_slots_used: self.full_slots_used,
full_slots_capacity: self.full_slots_capacity,
full_slots_bytes_used: self.full_slots_bytes_used,
full_slots_bytes_capacity: self.full_slots_bytes_capacity,
retained_host_bytes: self.retained_host_bytes,
retained_host_budget_bytes: self.retained_host_budget_bytes,
retained_starts: self.retained_starts,
approx_retained_starts: self.approx_retained_starts,
spilled_starts: self.spilled_starts,
evictions_pool_pressure: self.evictions_pool_pressure.saturating_sub(prev.evictions_pool_pressure),
evictions_host_budget: self.evictions_host_budget.saturating_sub(prev.evictions_host_budget),
evictions_approx_scope_cap: self.evictions_approx_scope_cap.saturating_sub(prev.evictions_approx_scope_cap),
evictions_stale_invalid: self.evictions_stale_invalid.saturating_sub(prev.evictions_stale_invalid),
evictions_shutdown: self.evictions_shutdown.saturating_sub(prev.evictions_shutdown),
evictions_superseded: self.evictions_superseded.saturating_sub(prev.evictions_superseded),
starts_spilled: self.starts_spilled.saturating_sub(prev.starts_spilled),
spill_writes_committed: self.spill_writes_committed.saturating_sub(prev.spill_writes_committed),
spill_bytes_written: self.spill_bytes_written.saturating_sub(prev.spill_bytes_written),
spill_write_us_total: self.spill_write_us_total.saturating_sub(prev.spill_write_us_total),
spill_write_timeouts: self.spill_write_timeouts.saturating_sub(prev.spill_write_timeouts),
spill_disk_used_bytes: self.spill_disk_used_bytes,
spill_disk_max_bytes: self.spill_disk_max_bytes,
spill_disk_gc_evictions: self.spill_disk_gc_evictions.saturating_sub(prev.spill_disk_gc_evictions),
spill_reads_hit: self.spill_reads_hit.saturating_sub(prev.spill_reads_hit),
spill_reads_miss: self.spill_reads_miss.saturating_sub(prev.spill_reads_miss),
spill_bytes_read: self.spill_bytes_read.saturating_sub(prev.spill_bytes_read),
spill_read_us_total: self.spill_read_us_total.saturating_sub(prev.spill_read_us_total),
starts_restored: self.starts_restored.saturating_sub(prev.starts_restored),
restores_failed: self.restores_failed.saturating_sub(prev.restores_failed),
restore_us_total: self.restore_us_total.saturating_sub(prev.restore_us_total),
}
}
#[cfg(not(standalone_blocks))]
pub fn to_json(self) -> serde_json::Value {
serde_json::json!({
"window_slots_used": self.window_slots_used,
"window_slots_capacity": self.window_slots_capacity,
"window_slots_bytes_used": self.window_slots_bytes_used,
"window_slots_bytes_capacity": self.window_slots_bytes_capacity,
"full_slots_used": self.full_slots_used,
"full_slots_capacity": self.full_slots_capacity,
"full_slots_bytes_used": self.full_slots_bytes_used,
"full_slots_bytes_capacity": self.full_slots_bytes_capacity,
"retained_host_bytes": self.retained_host_bytes,
"retained_host_budget_bytes": self.retained_host_budget_bytes,
"retained_starts": self.retained_starts,
"approx_retained_starts": self.approx_retained_starts,
"spilled_starts": self.spilled_starts,
"evictions_pool_pressure": self.evictions_pool_pressure,
"evictions_host_budget": self.evictions_host_budget,
"evictions_approx_scope_cap": self.evictions_approx_scope_cap,
"evictions_stale_invalid": self.evictions_stale_invalid,
"evictions_shutdown": self.evictions_shutdown,
"evictions_superseded": self.evictions_superseded,
"starts_spilled": self.starts_spilled,
"spill_writes_committed": self.spill_writes_committed,
"spill_bytes_written": self.spill_bytes_written,
"spill_write_us_total": self.spill_write_us_total,
"spill_write_timeouts": self.spill_write_timeouts,
"spill_disk_used_bytes": self.spill_disk_used_bytes,
"spill_disk_max_bytes": self.spill_disk_max_bytes,
"spill_disk_gc_evictions": self.spill_disk_gc_evictions,
"spill_reads_hit": self.spill_reads_hit,
"spill_reads_miss": self.spill_reads_miss,
"spill_bytes_read": self.spill_bytes_read,
"spill_read_us_total": self.spill_read_us_total,
"starts_restored": self.starts_restored,
"restores_failed": self.restores_failed,
"restore_us_total": self.restore_us_total,
})
}
}
#[cfg(test)]
impl CacheMemoryInterval {
#[cfg(not(standalone_blocks))]
pub fn to_json(self) -> serde_json::Value {
serde_json::json!({
"window_slots_used": self.window_slots_used,
"window_slots_capacity": self.window_slots_capacity,
"window_slots_bytes_used": self.window_slots_bytes_used,
"window_slots_bytes_capacity": self.window_slots_bytes_capacity,
"full_slots_used": self.full_slots_used,
"full_slots_capacity": self.full_slots_capacity,
"full_slots_bytes_used": self.full_slots_bytes_used,
"full_slots_bytes_capacity": self.full_slots_bytes_capacity,
"retained_host_bytes": self.retained_host_bytes,
"retained_host_budget_bytes": self.retained_host_budget_bytes,
"retained_starts": self.retained_starts,
"approx_retained_starts": self.approx_retained_starts,
"spilled_starts": self.spilled_starts,
"evictions_pool_pressure": self.evictions_pool_pressure,
"evictions_host_budget": self.evictions_host_budget,
"evictions_approx_scope_cap": self.evictions_approx_scope_cap,
"evictions_stale_invalid": self.evictions_stale_invalid,
"evictions_shutdown": self.evictions_shutdown,
"evictions_superseded": self.evictions_superseded,
"starts_spilled": self.starts_spilled,
"spill_writes_committed": self.spill_writes_committed,
"spill_bytes_written": self.spill_bytes_written,
"spill_write_us_total": self.spill_write_us_total,
"spill_write_timeouts": self.spill_write_timeouts,
"spill_disk_used_bytes": self.spill_disk_used_bytes,
"spill_disk_max_bytes": self.spill_disk_max_bytes,
"spill_disk_gc_evictions": self.spill_disk_gc_evictions,
"spill_reads_hit": self.spill_reads_hit,
"spill_reads_miss": self.spill_reads_miss,
"spill_bytes_read": self.spill_bytes_read,
"spill_read_us_total": self.spill_read_us_total,
"starts_restored": self.starts_restored,
"restores_failed": self.restores_failed,
"restore_us_total": self.restore_us_total,
})
}
}
#[derive(Default, Debug)]
pub struct LaneBlockState {
pub namespace: u64,
pub sealed: Vec<SealedId>,
pub prompt_len: usize,
pub written: usize,
pub(crate) stitched_approx: bool,
pub(crate) approx_path: bool,
pub owner: u64,
pub(crate) side_call: bool,
pub(crate) save_owner_turn: u64,
pub(crate) turn_ckpt: Option<TurnCheckpoint>,
pub(crate) turn_ckpt_miss: Option<TurnEndMiss>,
pub(crate) bound_lane: Option<usize>,
pub(crate) prompt_saved_pos: usize,
pub(crate) prompt_saved_id: Option<SealedId>,
pub(crate) bound_start_id: Option<SealedId>,
pub(crate) lease_holds: Vec<SealedId>,
pub(crate) reply_saved_pos: usize,
pub(crate) reply_saved_id: Option<SealedId>,
pub(crate) tail_toks: Vec<u32>,
pub(crate) observed_prior: ObservedPrior,
pub internal_resume: bool,
pub resume_reply_tokens: usize,
}
impl LaneBlockState {
#[inline]
fn effective_prompt_len(&self, toks_len: usize) -> usize {
toks_len.saturating_sub(self.resume_reply_tokens)
}
}
#[derive(Debug)]
pub(crate) struct TurnCheckpoint {
end: usize,
cs: Vec<u8>,
window: Vec<(BlockIndex, BlockEntry)>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TurnEndStart {
#[default]
NotDue,
Saved,
NotSaved(TurnEndMiss),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TurnEndMiss {
NoCheckpoint,
Behind,
OffPath,
BlockMissing,
BlockNotLive,
}
impl TurnEndMiss {
pub const ALL: [TurnEndMiss; 5] = [
TurnEndMiss::NoCheckpoint,
TurnEndMiss::Behind,
TurnEndMiss::OffPath,
TurnEndMiss::BlockMissing,
TurnEndMiss::BlockNotLive,
];
#[cfg(test)]
pub fn name(self) -> &'static str {
match self {
TurnEndMiss::NoCheckpoint => "no_checkpoint",
TurnEndMiss::Behind => "behind",
TurnEndMiss::OffPath => "off_path",
TurnEndMiss::BlockMissing => "block_missing",
TurnEndMiss::BlockNotLive => "block_not_live",
}
}
}
impl TurnEndStart {
pub fn record_tag(self) -> &'static str {
match self {
TurnEndStart::NotDue => "not_due",
TurnEndStart::Saved => "saved",
TurnEndStart::NotSaved(TurnEndMiss::NoCheckpoint) => "not_saved:no_checkpoint",
TurnEndStart::NotSaved(TurnEndMiss::Behind) => "not_saved:behind",
TurnEndStart::NotSaved(TurnEndMiss::OffPath) => "not_saved:off_path",
TurnEndStart::NotSaved(TurnEndMiss::BlockMissing) => "not_saved:block_missing",
TurnEndStart::NotSaved(TurnEndMiss::BlockNotLive) => "not_saved:block_not_live",
}
}
}
pub(crate) fn approx_namespace(ns: u64, owner: u64) -> u64 {
debug_assert_ne!(owner, ns, "a twin namespace never equals its exact namespace");
owner
}
pub fn approx_twin(salt: &str, ns: u64, card_id: Option<&str>) -> u64 {
let Some(id) = card_id.filter(|s| !s.is_empty()) else { return 0 };
let mut hasher = crate::spill::Sha256::new();
hasher.update(b"inky-approx-twin-v1\0");
hasher.update(&(salt.len() as u64).to_le_bytes());
hasher.update(salt.as_bytes());
hasher.update(b"\0approx\0");
hasher.update(&ns.to_le_bytes());
hasher.update(&(id.len() as u64).to_le_bytes());
hasher.update(id.as_bytes());
let digest = hasher.finalize();
let mut twin = u64::from_le_bytes(digest[..8].try_into().unwrap()).max(1);
if twin == ns {
twin ^= 1;
}
twin.max(1)
}
const REUSE_EPOCH_TICKS: u64 = 64;
#[derive(Default, Clone, Copy, Debug)]
struct RecentReuse {
epoch: u64,
current: u64,
previous: u64,
}
impl RecentReuse {
fn record(&mut self, tick: u64, skipped: usize) {
let epoch = tick / REUSE_EPOCH_TICKS;
if epoch != self.epoch {
self.previous = if epoch - self.epoch == 1 { self.current } else { 0 };
self.current = 0;
self.epoch = epoch;
}
self.current = self.current.saturating_add(skipped as u64);
}
fn saved_tokens(&self, tick: u64) -> u64 {
match (tick / REUSE_EPOCH_TICKS).saturating_sub(self.epoch) {
0 => self.current.saturating_add(self.previous / 2),
1 => self.current / 2,
_ => 0,
}
}
}
#[derive(Clone, Copy, Debug)]
struct EvictionRank {
leased: bool,
live: bool,
recent: bool,
saved_tokens: u64,
bytes: u64,
last_used_tick: u64,
pos: usize,
sid: SealedId,
}
impl EvictionRank {
fn compare(&self, other: &Self, lru: bool) -> std::cmp::Ordering {
if lru {
return self.lru_cmp(other);
}
self.leased
.cmp(&other.leased)
.then_with(|| self.live.cmp(&other.live))
.then_with(|| self.recent.cmp(&other.recent))
.then_with(|| {
(u128::from(self.saved_tokens) * u128::from(other.bytes))
.cmp(&(u128::from(other.saved_tokens) * u128::from(self.bytes)))
})
.then_with(|| self.last_used_tick.cmp(&other.last_used_tick))
.then_with(|| other.pos.cmp(&self.pos))
.then_with(|| self.sid.cmp(&other.sid))
}
fn lru_cmp(&self, other: &Self) -> std::cmp::Ordering {
self.leased
.cmp(&other.leased)
.then_with(|| self.last_used_tick.cmp(&other.last_used_tick))
.then_with(|| other.pos.cmp(&self.pos))
.then_with(|| self.sid.cmp(&other.sid))
}
}
fn pick_ranked_victim(cands: &[EvictionRank], lru: bool) -> Option<(SealedId, bool)> {
let chosen = cands.iter().min_by(|a, b| a.compare(b, lru))?;
let over_lru = !lru && cands.iter().min_by(|a, b| a.lru_cmp(b)).is_some_and(|first| first.sid != chosen.sid);
Some((chosen.sid, over_lru))
}
struct RetainedStart {
namespace: u64,
approx: bool,
scope: u64,
pos: usize,
cs: Vec<u8>,
reasons: u8,
slot_bytes: u64,
entries: Vec<(BlockKind, BlockIndex, BlockEntry)>,
toks: Vec<u32>,
reuse: RecentReuse,
created_tick: Option<u64>,
last_used_tick: u64,
last_owner: u64,
owner_turn: u64,
last_used_ms: u64,
}
impl RetainedStart {
fn host_bytes(&self) -> u64 {
(self.cs.len() as u64).saturating_add((self.toks.len() as u64).saturating_mul(4)).saturating_add(
(self.entries.len() as u64)
.saturating_mul(std::mem::size_of::<(BlockKind, BlockIndex, BlockEntry)>() as u64),
)
}
}
struct SpilledStart {
namespace: u64,
pos: usize,
reasons: u8,
cs_key: SpillKey,
entries: Vec<(BlockKind, BlockIndex, SpillKey)>,
toks: Vec<u32>,
last_used_tick: u64,
}
struct SpillIndexSnapshot {
kvb: u32,
next_spill_id: u64,
tick: u64,
full_attn_budget: u64,
model_fingerprint: u64,
records: Vec<(u64, Arc<SpilledStart>)>,
}
impl SpillIndexSnapshot {
fn into_bytes(mut self, max_len: usize) -> Vec<u8> {
self.records.retain(|(_, sp)| sp.toks.len() == sp.pos && sp.pos > 0 && sp.pos.is_multiple_of(BLOCK));
self.records.sort_by_key(|(id, sp)| (sp.last_used_tick, *id));
let mut room = max_len.saturating_sub(SPILL_INDEX_PREFIX_LEN + 8 + 32);
let mut first_kept = self.records.len();
while first_kept > 0 {
let sp = &self.records[first_kept - 1].1;
let record_len = 46 + 4 * sp.toks.len() + 4 + 14 * sp.entries.len();
if record_len > room {
break;
}
room -= record_len;
first_kept -= 1;
}
self.records.drain(..first_kept);
let mut payload = Vec::new();
for (id, sp) in &self.records {
payload.extend_from_slice(&id.to_le_bytes());
payload.extend_from_slice(&sp.namespace.to_le_bytes());
payload.extend_from_slice(&(sp.pos as u64).to_le_bytes());
payload.push(sp.reasons);
payload.extend_from_slice(&sp.last_used_tick.to_le_bytes());
payload.push(sp.cs_key.kind as u8);
payload.extend_from_slice(&sp.cs_key.id.to_le_bytes());
payload.extend_from_slice(&(sp.toks.len() as u32).to_le_bytes());
for &t in &sp.toks {
payload.extend_from_slice(&t.to_le_bytes());
}
payload.extend_from_slice(&(sp.entries.len() as u32).to_le_bytes());
for &(kind, bi, sk) in &sp.entries {
payload.push(kind_idx(kind) as u8);
payload.extend_from_slice(&bi.get().to_le_bytes());
payload.push(sk.kind as u8);
payload.extend_from_slice(&sk.id.to_le_bytes());
}
}
let valid_count = self.records.len() as u32;
let mut header = [0u8; SPILL_INDEX_HEADER_LEN];
header[0..8].copy_from_slice(&SPILL_INDEX_MAGIC);
header[8..12].copy_from_slice(&SPILL_INDEX_VERSION.to_le_bytes());
header[12..16].copy_from_slice(&self.kvb.to_le_bytes());
header[16..24].copy_from_slice(&self.next_spill_id.to_le_bytes());
header[24..32].copy_from_slice(&self.tick.to_le_bytes());
header[32..36].copy_from_slice(&valid_count.to_le_bytes());
header[36..44].copy_from_slice(&self.full_attn_budget.to_le_bytes());
header[44..52].copy_from_slice(&self.model_fingerprint.to_le_bytes());
let payload_len = payload.len() as u64;
let mut hasher = Sha256::new();
hasher.update(&header[0..SPILL_INDEX_PREFIX_LEN]);
hasher.update(&payload_len.to_le_bytes());
hasher.update(&payload);
let digest = hasher.finalize();
let mut full = Vec::with_capacity(SPILL_INDEX_HEADER_LEN + 8 + payload.len());
full.extend_from_slice(&header[0..SPILL_INDEX_PREFIX_LEN]);
full.extend_from_slice(&payload_len.to_le_bytes());
full.extend_from_slice(&digest);
full.extend_from_slice(&payload);
full
}
}
struct PriorFixup {
owner: u64,
seq: u64,
tip: bool,
prompt_tip: bool,
}
struct PendingSpill {
start: SpilledStart,
prior_fixups: Vec<PriorFixup>,
claimed_keys: Vec<SpillKey>,
shield: Option<(u64, Vec<SpillKey>)>,
waiting: usize,
deadline_ms: u64,
}
struct PendingWrite {
job: u64,
bytes: u64,
pin: Option<(BlockKind, Slot)>,
waiters: Vec<u64>,
}
struct RestoreSource {
spill_id: u64,
keys: HashSet<SpillKey>,
resident_start: Option<SealedId>,
}
#[derive(Debug)]
pub enum AdmitBindOutcome {
Immediate(Option<(usize, Vec<u8>)>),
Restoring { target_pos: usize },
}
#[derive(Debug)]
pub struct CompletedRestore {
pub lane: usize,
pub matched: Option<(usize, Vec<u8>)>,
pub elapsed: Duration,
pub corrupt_fallback: bool,
}
struct RestoreJob {
lane: usize,
restore_seq: u64,
dir: PathBuf,
kvb: u32,
cs_key: SpillKey,
blocks: Vec<(usize, SpillKey, usize)>,
cancel_flag: Arc<AtomicBool>,
began: Instant,
}
enum RestoreMsgPayload {
RecurrentState { key: SpillKey, raw: RawDiskRead },
Block { idx: usize, key: SpillKey, raw: RawDiskRead },
Done { elapsed: Duration },
Aborted { key: SpillKey, raw: RawDiskRead },
}
struct RestoreMsg {
lane: usize,
restore_seq: u64,
budget_bytes: usize,
payload: RestoreMsgPayload,
}
struct StagingBudget {
inner: Mutex<usize>,
cvar: Condvar,
}
impl StagingBudget {
fn new() -> Self {
Self { inner: Mutex::new(0), cvar: Condvar::new() }
}
fn acquire(&self, bytes: usize, cancel: &AtomicBool) -> bool {
if bytes == 0 {
return !cancel.load(Ordering::Acquire);
}
let capped = bytes.min(MAX_INFLIGHT_RESTORE_STAGING_BYTES);
let mut used = self.inner.lock().unwrap_or_else(|e| e.into_inner());
loop {
if cancel.load(Ordering::Acquire) {
return false;
}
if *used == 0 || used.saturating_add(capped) <= MAX_INFLIGHT_RESTORE_STAGING_BYTES {
*used = used.saturating_add(capped);
return true;
}
let (next, _) = self.cvar.wait_timeout(used, Duration::from_millis(5)).unwrap_or_else(|e| e.into_inner());
used = next;
}
}
fn release(&self, bytes: usize) {
if bytes == 0 {
return;
}
let capped = bytes.min(MAX_INFLIGHT_RESTORE_STAGING_BYTES);
let mut used = self.inner.lock().unwrap_or_else(|e| e.into_inner());
*used = used.saturating_sub(capped);
self.cvar.notify_all();
}
}
struct RestoreWake {
seq: Mutex<u64>,
cvar: Condvar,
}
impl RestoreWake {
fn new() -> Self {
Self { seq: Mutex::new(0), cvar: Condvar::new() }
}
fn notify(&self) {
let mut g = self.seq.lock().unwrap_or_else(|e| e.into_inner());
*g = g.wrapping_add(1);
self.cvar.notify_all();
}
fn wait_timeout(&self, last_seen: &mut u64, timeout: Duration) {
let g = self.seq.lock().unwrap_or_else(|e| e.into_inner());
if *g != *last_seen {
*last_seen = *g;
return;
}
let (g2, _) = self.cvar.wait_timeout(g, timeout).unwrap_or_else(|e| e.into_inner());
*last_seen = *g2;
}
}
struct RestoreWorker {
job_tx: Option<Sender<RestoreJob>>,
msg_rx: Receiver<RestoreMsg>,
budget: Arc<StagingBudget>,
join: Option<std::thread::JoinHandle<()>>,
}
impl RestoreWorker {
fn spawn(wake_bg: Arc<RestoreWake>) -> Self {
let (job_tx, job_rx) = channel::<RestoreJob>();
let (msg_tx, msg_rx) = channel::<RestoreMsg>();
let budget = Arc::new(StagingBudget::new());
let budget_bg = budget.clone();
let join = std::thread::Builder::new()
.name("inky-spill-restore".into())
.spawn(move || {
while let Ok(job) = job_rx.recv() {
if job.cancel_flag.load(Ordering::Acquire) {
continue;
}
let cs_est = crate::spill::MAX_RECURRENT_STATE_BYTES.min(4 * 1024 * 1024);
if !budget_bg.acquire(cs_est, &job.cancel_flag) {
continue;
}
let cs_raw = read_block_from_dir(&job.dir, job.kvb, job.cs_key, Some(0));
if job.cancel_flag.load(Ordering::Acquire) {
budget_bg.release(cs_est);
continue;
}
let cs_ok = matches!(
&cs_raw.outcome,
ReadOutcome::Hit(blk) if blk.recurrent_state.as_ref().is_some_and(|s| !s.is_empty())
);
if !cs_ok {
if msg_tx
.send(RestoreMsg {
lane: job.lane,
restore_seq: job.restore_seq,
budget_bytes: cs_est,
payload: RestoreMsgPayload::Aborted { key: job.cs_key, raw: cs_raw },
})
.is_err()
{
budget_bg.release(cs_est);
break;
}
wake_bg.notify();
continue;
}
if msg_tx
.send(RestoreMsg {
lane: job.lane,
restore_seq: job.restore_seq,
budget_bytes: cs_est,
payload: RestoreMsgPayload::RecurrentState { key: job.cs_key, raw: cs_raw },
})
.is_err()
{
budget_bg.release(cs_est);
break;
}
wake_bg.notify();
let mut aborted = false;
for (idx, key, expected_len) in job.blocks {
if !budget_bg.acquire(expected_len, &job.cancel_flag) {
aborted = true;
break;
}
let raw = read_block_from_dir(&job.dir, job.kvb, key, Some(expected_len));
if job.cancel_flag.load(Ordering::Acquire) {
budget_bg.release(expected_len);
aborted = true;
break;
}
let hit = matches!(&raw.outcome, ReadOutcome::Hit(_));
let payload = if hit {
RestoreMsgPayload::Block { idx, key, raw }
} else {
RestoreMsgPayload::Aborted { key, raw }
};
if msg_tx
.send(RestoreMsg {
lane: job.lane,
restore_seq: job.restore_seq,
budget_bytes: expected_len,
payload,
})
.is_err()
{
budget_bg.release(expected_len);
return;
}
wake_bg.notify();
if !hit {
aborted = true;
break;
}
}
if !aborted && !job.cancel_flag.load(Ordering::Acquire) {
if msg_tx
.send(RestoreMsg {
lane: job.lane,
restore_seq: job.restore_seq,
budget_bytes: 0,
payload: RestoreMsgPayload::Done { elapsed: job.began.elapsed() },
})
.is_err()
{
return;
}
wake_bg.notify();
}
}
})
.expect("spawn inky-spill-restore worker");
Self { job_tx: Some(job_tx), msg_rx, budget, join: Some(join) }
}
}
impl Drop for RestoreWorker {
fn drop(&mut self) {
self.job_tx.take();
while let Ok(msg) = self.msg_rx.try_recv() {
self.budget.release(msg.budget_bytes);
}
if let Some(j) = self.join.take() {
let _ = j.join();
}
}
}
struct IkvStageJob {
lane: usize,
stage_seq: u64,
lane_namespace: u64,
expected_namespace: u64,
catalog: Arc<crate::ikv::IkvCatalog>,
cart_idx: usize,
src_start: usize,
n_stitch_blks: usize,
cancel_flag: Arc<AtomicBool>,
began: Instant,
}
enum IkvStagePayload {
Block { idx: usize, bytes: Vec<u8> },
Done { elapsed: Duration },
Aborted { elapsed: Duration },
}
struct IkvStageMsg {
lane: usize,
stage_seq: u64,
budget_bytes: usize,
payload: IkvStagePayload,
}
struct IkvStageWorker {
job_tx: Option<Sender<IkvStageJob>>,
msg_rx: Receiver<IkvStageMsg>,
budget: Arc<StagingBudget>,
join: Option<std::thread::JoinHandle<()>>,
}
impl IkvStageWorker {
fn spawn(wake_bg: Arc<RestoreWake>) -> Self {
let (job_tx, job_rx) = channel::<IkvStageJob>();
let (msg_tx, msg_rx) = channel::<IkvStageMsg>();
let budget = Arc::new(StagingBudget::new());
let budget_bg = budget.clone();
let join = std::thread::Builder::new()
.name("inky-ikv-stage".into())
.spawn(move || {
while let Ok(job) = job_rx.recv() {
if job.cancel_flag.load(Ordering::Acquire) {
continue;
}
let Some(cart) = job.catalog.get(job.cart_idx) else {
let _ = msg_tx.send(IkvStageMsg {
lane: job.lane,
stage_seq: job.stage_seq,
budget_bytes: 0,
payload: IkvStagePayload::Aborted { elapsed: job.began.elapsed() },
});
wake_bg.notify();
continue;
};
let mut chan_closed = false;
let res = cart.stream_full_span_blocks(
job.lane_namespace,
job.expected_namespace,
job.src_start,
job.n_stitch_blks,
&job.cancel_flag,
|idx, bytes| {
let len = bytes.len();
if !budget_bg.acquire(len, &job.cancel_flag) {
return Ok(());
}
if job.cancel_flag.load(Ordering::Acquire) {
budget_bg.release(len);
return Ok(());
}
if msg_tx
.send(IkvStageMsg {
lane: job.lane,
stage_seq: job.stage_seq,
budget_bytes: len,
payload: IkvStagePayload::Block { idx, bytes },
})
.is_err()
{
budget_bg.release(len);
chan_closed = true;
return Err(crate::ikv::IkvError::Quarantined);
}
wake_bg.notify();
Ok(())
},
);
if chan_closed {
return;
}
if job.cancel_flag.load(Ordering::Acquire) {
continue;
}
let payload = match res {
Ok(()) => IkvStagePayload::Done { elapsed: job.began.elapsed() },
Err(_) => IkvStagePayload::Aborted { elapsed: job.began.elapsed() },
};
if msg_tx
.send(IkvStageMsg {
lane: job.lane,
stage_seq: job.stage_seq,
budget_bytes: 0,
payload,
})
.is_err()
{
return;
}
wake_bg.notify();
}
})
.expect("spawn inky-ikv-stage worker");
Self { job_tx: Some(job_tx), msg_rx, budget, join: Some(join) }
}
}
impl Drop for IkvStageWorker {
fn drop(&mut self) {
self.job_tx.take();
while let Ok(msg) = self.msg_rx.try_recv() {
self.budget.release(msg.budget_bytes);
}
if let Some(j) = self.join.take() {
let _ = j.join();
}
}
}
struct PendingIkvStage {
stage_seq: u64,
plan: StitchSpanPlan,
toks: Vec<u32>,
reserved_slots: Vec<(Slot, u32)>,
loaded_blocks: usize,
cancel_flag: Arc<AtomicBool>,
}
struct PendingRestore {
restore_seq: u64,
spill_id: u64,
namespace: u64,
pos: usize,
reasons: u8,
full_toks: Vec<u32>,
protected_keys: Vec<SpillKey>,
held_reused: Vec<(BlockKind, BlockIndex, BlockEntry)>,
reserved_slots: Vec<(BlockKind, BlockIndex, BlockEntry)>,
loaded_cs: Option<Vec<u8>>,
loaded_blocks: usize,
cancel_flag: Arc<AtomicBool>,
}
fn newly_expired_window_blocks(start: usize, end: usize) -> std::ops::Range<usize> {
let first_needed = |pos: usize| crate::blocks::first_live_window_block_at(pos, EXT, BLOCK);
first_needed(start)..first_needed(end)
}
fn to_spill_kind(kind: BlockKind) -> SpillBlockKind {
match kind {
BlockKind::Full => SpillBlockKind::Full,
BlockKind::Window => SpillBlockKind::Window,
}
}
fn kind_idx(kind: BlockKind) -> usize {
match kind {
BlockKind::Window => 0,
BlockKind::Full => 1,
}
}
fn max_every_checkpoint_le(n: usize) -> usize {
if n < EARLY_EVERY_TOKENS {
0
} else if n <= EARLY_EVERY_LIMIT {
(n / EARLY_EVERY_TOKENS) * EARLY_EVERY_TOKENS
} else {
(n / LATE_EVERY_TOKENS) * LATE_EVERY_TOKENS
}
}
fn count_every_checkpoints_le(limit: usize) -> usize {
if limit < EARLY_EVERY_TOKENS {
0
} else if limit <= EARLY_EVERY_LIMIT {
limit / EARLY_EVERY_TOKENS
} else {
EARLY_EVERY_LIMIT / EARLY_EVERY_TOKENS + (limit - EARLY_EVERY_LIMIT) / LATE_EVERY_TOKENS
}
}
fn every_checkpoint_at(idx: usize) -> usize {
let early_cnt = EARLY_EVERY_LIMIT / EARLY_EVERY_TOKENS;
if idx < early_cnt {
(idx + 1) * EARLY_EVERY_TOKENS
} else {
EARLY_EVERY_LIMIT + (idx + 1 - early_cnt) * LATE_EVERY_TOKENS
}
}
pub fn compute_block_hashes(toks: &[u32]) -> Vec<u64> {
let n_blocks = toks.len() / BLOCK;
let mut out = Vec::with_capacity(n_blocks);
let mut h = 0x9e37_79b9_7f4a_7c15u64;
for b in 0..n_blocks {
let blk = &toks[b * BLOCK..(b + 1) * BLOCK];
let mut i = 0usize;
while i + 2 <= BLOCK {
let pair = u64::from(blk[i]) | (u64::from(blk[i + 1]) << 32);
h ^= pair.wrapping_add(0x517c_c1b7_2722_0a95);
h = h.rotate_left(29).wrapping_mul(0x94d0_49bb_1331_11eb);
i += 2;
}
h ^= h >> 32;
out.push(h);
}
out
}
#[derive(Clone, Copy, Debug)]
pub struct InflightPrefillLane<'a> {
pub lane: usize,
pub namespace: u64,
pub toks: &'a [u32],
pub block_hashes: Option<&'a [u64]>,
pub n_past: usize,
pub pf_end: usize,
pub runnable: bool,
pub eligible_follower: bool,
}
fn can_lead_meta(me: &InflightPrefillLane<'_>, producer: &InflightPrefillLane<'_>, next: usize) -> bool {
if me.namespace != producer.namespace
|| !me.runnable
|| !me.eligible_follower
|| next <= me.n_past
|| next >= me.pf_end
|| !producer.runnable
|| producer.n_past >= next
|| next >= producer.pf_end
{
return false;
}
let ahead = producer.n_past > me.n_past || (producer.n_past == me.n_past && producer.lane < me.lane);
let prompt_checkpoint = (producer.pf_end - 1) / BLOCK * BLOCK;
ahead && (is_every_checkpoint(next) || next == prompt_checkpoint)
}
fn can_lead(me: &InflightPrefillLane<'_>, producer: &InflightPrefillLane<'_>, next: usize) -> bool {
if !can_lead_meta(me, producer, next) {
return false;
}
let next_bi = next / BLOCK - 1;
if let (Some(mh), Some(ph)) =
(me.block_hashes.and_then(|h| h.get(next_bi)), producer.block_hashes.and_then(|h| h.get(next_bi)))
{
if mh != ph {
return false;
}
}
std::ptr::eq(me.toks.as_ptr(), producer.toks.as_ptr()) || producer.toks[..next] == me.toks[..next]
}
#[cfg(any(test, standalone_blocks))]
pub fn find_prefill_leader(lanes: &[InflightPrefillLane<'_>], idx: usize) -> Option<usize> {
let me = lanes.get(idx)?;
let next = effective_pf_target(me.n_past, me.pf_end);
lanes.iter().find(|producer| can_lead(me, producer, next)).map(|producer| producer.lane)
}
pub fn find_prefill_leaders(lanes: &[InflightPrefillLane<'_>]) -> Vec<Option<usize>> {
let mut out = vec![None; lanes.len()];
if lanes.len() <= 1 {
return out;
}
let owned: Vec<Vec<u64>> = lanes
.iter()
.map(|l| if l.block_hashes.is_some() { Vec::new() } else { compute_block_hashes(l.toks) })
.collect();
let hashes_of = |i: usize| -> &[u64] { lanes[i].block_hashes.unwrap_or(&owned[i]) };
for (idx, me) in lanes.iter().enumerate() {
let next = effective_pf_target(me.n_past, me.pf_end);
if !me.runnable || !me.eligible_follower || next <= me.n_past || next >= me.pf_end {
continue;
}
let next_bi = next / BLOCK - 1;
let Some(&mh) = hashes_of(idx).get(next_bi) else {
continue;
};
for (p_idx, producer) in lanes.iter().enumerate() {
if !can_lead_meta(me, producer, next) {
continue;
}
if hashes_of(p_idx).get(next_bi) != Some(&mh) {
continue;
}
if std::ptr::eq(me.toks.as_ptr(), producer.toks.as_ptr()) || producer.toks[..next] == me.toks[..next] {
out[idx] = Some(producer.lane);
break;
}
}
}
out
}
fn pair_shared_checkpoint_exact(
me: &InflightPrefillLane<'_>,
producer: &InflightPrefillLane<'_>,
next: usize,
final_checkpoint: usize,
) -> usize {
if !can_lead(me, producer, next) {
return 0;
}
let limit = me.pf_end.min(producer.pf_end) - 1;
let common_final = final_checkpoint == (producer.pf_end - 1) / BLOCK * BLOCK;
if common_final
&& (std::ptr::eq(me.toks.as_ptr(), producer.toks.as_ptr())
|| me.toks[next..final_checkpoint] == producer.toks[next..final_checkpoint])
{
return final_checkpoint;
}
let last_periodic = max_every_checkpoint_le(limit);
if last_periodic >= next {
if std::ptr::eq(me.toks.as_ptr(), producer.toks.as_ptr())
|| me.toks[next..last_periodic] == producer.toks[next..last_periodic]
{
return last_periodic;
}
let before = &me.toks[next..last_periodic];
let after = &producer.toks[next..last_periodic];
let common = next + before.iter().zip(after).take_while(|(a, b)| a == b).count();
return max_every_checkpoint_le(common);
}
0
}
fn pair_hash_candidate_checkpoint(
me: &InflightPrefillLane<'_>,
me_hashes: &[u64],
producer: &InflightPrefillLane<'_>,
prod_hashes: &[u64],
next: usize,
final_checkpoint: usize,
) -> usize {
if !can_lead_meta(me, producer, next) {
return 0;
}
let next_bi = next / BLOCK - 1;
if me_hashes.get(next_bi) != prod_hashes.get(next_bi) || me_hashes.get(next_bi).is_none() {
return 0;
}
let prod_final = (producer.pf_end - 1) / BLOCK * BLOCK;
if final_checkpoint == prod_final && final_checkpoint >= next {
let f_bi = final_checkpoint / BLOCK - 1;
if me_hashes.get(f_bi).is_some() && me_hashes.get(f_bi) == prod_hashes.get(f_bi) {
return final_checkpoint;
}
}
let limit = me.pf_end.min(producer.pf_end) - 1;
let cnt = count_every_checkpoints_le(limit);
if cnt == 0 {
return 0;
}
let mut lo_start = 0usize;
while lo_start < cnt && every_checkpoint_at(lo_start) < next {
lo_start += 1;
}
if lo_start >= cnt {
return 0;
}
let first_bi = every_checkpoint_at(lo_start) / BLOCK - 1;
if me_hashes.get(first_bi).is_none() || me_hashes.get(first_bi) != prod_hashes.get(first_bi) {
return 0;
}
let mut lo = lo_start;
let mut hi = cnt - 1;
while lo < hi {
let mid = lo + (hi - lo).div_ceil(2);
let bi = every_checkpoint_at(mid) / BLOCK - 1;
if me_hashes.get(bi).is_some() && me_hashes.get(bi) == prod_hashes.get(bi) {
lo = mid;
} else {
hi = mid - 1;
}
}
every_checkpoint_at(lo)
}
fn shared_checkpoint_against_hashed<'a>(
me: &InflightPrefillLane<'_>,
me_hashes: &[u64],
producers: impl Iterator<Item = (&'a InflightPrefillLane<'a>, &'a [u64])> + Clone,
) -> usize {
let next = effective_pf_target(me.n_past, me.pf_end);
if !me.runnable || !me.eligible_follower || next <= me.n_past || next >= me.pf_end {
return 0;
}
let final_checkpoint = me.pf_end.saturating_sub(1) / BLOCK * BLOCK;
let mut best_ckpt = 0usize;
let mut best_prod: Option<&InflightPrefillLane<'_>> = None;
for (prod, ph) in producers.clone() {
let cand = pair_hash_candidate_checkpoint(me, me_hashes, prod, ph, next, final_checkpoint);
if cand > best_ckpt {
best_ckpt = cand;
best_prod = Some(prod);
if best_ckpt == final_checkpoint {
break;
}
}
}
let Some(winner) = best_prod else {
return 0;
};
if std::ptr::eq(me.toks.as_ptr(), winner.toks.as_ptr()) || me.toks[..best_ckpt] == winner.toks[..best_ckpt] {
return best_ckpt;
}
let mut exact_best = 0usize;
for (prod, _) in producers {
exact_best = exact_best.max(pair_shared_checkpoint_exact(me, prod, next, final_checkpoint));
if exact_best == final_checkpoint {
break;
}
}
exact_best
}
#[cfg(any(test, standalone_blocks))]
fn inflight_shared_checkpoint(me: &InflightPrefillLane<'_>, lanes: &[InflightPrefillLane<'_>]) -> usize {
let me_owned;
let me_hashes: &[u64] = match me.block_hashes {
Some(h) => h,
None => {
me_owned = compute_block_hashes(me.toks);
&me_owned
}
};
let owned: Vec<Vec<u64>> = lanes
.iter()
.map(|l| if l.block_hashes.is_some() { Vec::new() } else { compute_block_hashes(l.toks) })
.collect();
let iter = lanes.iter().enumerate().map(|(i, l)| (l, l.block_hashes.unwrap_or(&owned[i])));
shared_checkpoint_against_hashed(me, me_hashes, iter)
}
#[derive(Clone, Copy, Debug)]
pub struct InflightLaneReserve<'a> {
pub lane: usize,
pub namespace: u64,
pub toks: &'a [u32],
pub block_hashes: Option<&'a [u64]>,
pub n_past: usize,
pub pf_end: usize,
pub cached: usize,
pub written: usize,
pub gen: usize,
pub max_gen: usize,
pub runnable: bool,
}
impl<'a> InflightLaneReserve<'a> {
fn reserved_end(&self) -> usize {
let prompt_end = self.n_past.max(self.pf_end);
prompt_end + self.max_gen.saturating_sub(self.gen.max(1)).min(admit_decode_reserve())
}
fn as_prefill_lane(&self) -> Option<InflightPrefillLane<'a>> {
(self.gen == 0 && self.n_past < self.pf_end).then_some(InflightPrefillLane {
lane: self.lane,
namespace: self.namespace,
toks: self.toks,
block_hashes: self.block_hashes,
n_past: self.n_past,
pf_end: self.pf_end,
runnable: self.runnable,
eligible_follower: self.n_past == self.cached && self.written == self.n_past,
})
}
}
struct PreparedPrefillEntry<'a> {
pf: InflightPrefillLane<'a>,
owned_hashes: Vec<u64>,
written: usize,
reserved_end_blocks: usize,
credited: usize,
}
impl<'a> PreparedPrefillEntry<'a> {
fn hashes(&self) -> &[u64] {
self.pf.block_hashes.unwrap_or(&self.owned_hashes)
}
fn demanded_blocks(&self, credited: usize) -> usize {
self.reserved_end_blocks - self.written.max(credited).div_ceil(BLOCK)
}
}
type LastEvalCredited = (usize, u64, usize, usize, usize, usize);
pub struct PreparedInflightCohort<'a> {
len: usize,
prefills: Vec<PreparedPrefillEntry<'a>>,
base_reserved_full: usize,
base_window_growth: usize,
base_steady_window: usize,
cached_headroom: std::cell::Cell<Option<(usize, usize, usize)>>,
last_eval_credited: std::cell::Cell<Option<LastEvalCredited>>,
}
impl<'a> PreparedInflightCohort<'a> {
pub fn empty() -> Self {
Self {
len: 0,
prefills: Vec::new(),
base_reserved_full: 0,
base_window_growth: 0,
base_steady_window: 0,
cached_headroom: std::cell::Cell::new(None),
last_eval_credited: std::cell::Cell::new(None),
}
}
pub fn invalidate_headroom(&self) {
self.cached_headroom.set(None);
}
#[cfg(any(test, standalone_blocks))]
pub fn new(active: &[InflightLaneReserve<'a>]) -> Self {
let mut cohort = Self::empty();
for &lane in active {
cohort.push_admitted(lane);
}
cohort
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
#[cfg(any(test, standalone_blocks))]
pub fn reserved_full_slots(&self) -> usize {
self.base_reserved_full
}
fn eval_with_candidate(&self, cand: &InflightLaneReserve<'_>, cand_hashes: &[u64]) -> (usize, usize, usize) {
let cand_end = (cand.pf_end + cand.max_gen.saturating_sub(1)).div_ceil(BLOCK);
let win_growth = self.base_window_growth + (cand_end - cand.written.div_ceil(BLOCK));
let steady_win = self.base_steady_window + cand_end.min(WINDOW / BLOCK + 1);
let cand_res_blocks = cand.reserved_end().div_ceil(BLOCK);
let Some(cand_pf) = cand.as_prefill_lane() else {
let full = self.base_reserved_full + (cand_res_blocks - cand.written.div_ceil(BLOCK));
return (full, win_growth, steady_win);
};
let cand_credited = if cand_pf.eligible_follower {
let iter = self.prefills.iter().map(|e| (&e.pf, e.hashes()));
shared_checkpoint_against_hashed(&cand_pf, cand_hashes, iter)
} else {
0
};
self.last_eval_credited.set(Some((
cand.toks.as_ptr() as usize,
cand.namespace,
cand.pf_end,
cand.n_past,
cand.lane,
cand_credited,
)));
let mut full = self.base_reserved_full + (cand_res_blocks - cand.written.max(cand_credited).div_ceil(BLOCK));
if cand_pf.runnable {
for existing in &self.prefills {
if !existing.pf.runnable || !existing.pf.eligible_follower {
continue;
}
let ahead = cand_pf.n_past > existing.pf.n_past
|| (cand_pf.n_past == existing.pf.n_past && cand_pf.lane < existing.pf.lane);
if !ahead {
continue;
}
let ex_next = effective_pf_target(existing.pf.n_past, existing.pf.pf_end);
let ex_final = existing.pf.pf_end.saturating_sub(1) / BLOCK * BLOCK;
let cand_for_ex = pair_hash_candidate_checkpoint(
&existing.pf,
existing.hashes(),
&cand_pf,
cand_hashes,
ex_next,
ex_final,
);
if cand_for_ex > existing.credited {
let verified = if std::ptr::eq(existing.pf.toks.as_ptr(), cand_pf.toks.as_ptr())
|| existing.pf.toks[..cand_for_ex] == cand_pf.toks[..cand_for_ex]
{
cand_for_ex
} else {
pair_shared_checkpoint_exact(&existing.pf, &cand_pf, ex_next, ex_final)
};
let new_cred = existing.credited.max(verified);
if new_cred > existing.credited {
full = full + existing.demanded_blocks(new_cred) - existing.demanded_blocks(existing.credited);
}
}
}
}
(full, win_growth, steady_win)
}
pub fn push_admitted(&mut self, lane: InflightLaneReserve<'a>) {
self.len += 1;
let end = (lane.pf_end + lane.max_gen.saturating_sub(1)).div_ceil(BLOCK);
self.base_window_growth += end - lane.written.div_ceil(BLOCK);
self.base_steady_window += end.min(WINDOW / BLOCK + 1);
let res_blocks = lane.reserved_end().div_ceil(BLOCK);
let Some(pf) = lane.as_prefill_lane() else {
self.base_reserved_full += res_blocks - lane.written.div_ceil(BLOCK);
return;
};
let owned_hashes = if pf.block_hashes.is_some() { Vec::new() } else { compute_block_hashes(pf.toks) };
let new_hashes: &[u64] = pf.block_hashes.unwrap_or(&owned_hashes);
let credited = if pf.eligible_follower {
if let Some((ptr, ns, len, np, ln, memo_cred)) = self.last_eval_credited.take() {
if ptr == pf.toks.as_ptr() as usize
&& ns == pf.namespace
&& len == pf.pf_end
&& np == pf.n_past
&& ln == pf.lane
{
memo_cred
} else {
let iter = self.prefills.iter().map(|e| (&e.pf, e.hashes()));
shared_checkpoint_against_hashed(&pf, new_hashes, iter)
}
} else {
let iter = self.prefills.iter().map(|e| (&e.pf, e.hashes()));
shared_checkpoint_against_hashed(&pf, new_hashes, iter)
}
} else {
self.last_eval_credited.set(None);
0
};
if pf.runnable {
for existing in &mut self.prefills {
if !existing.pf.runnable || !existing.pf.eligible_follower {
continue;
}
let ahead =
pf.n_past > existing.pf.n_past || (pf.n_past == existing.pf.n_past && pf.lane < existing.pf.lane);
if !ahead {
continue;
}
let ex_next = effective_pf_target(existing.pf.n_past, existing.pf.pf_end);
let ex_final = existing.pf.pf_end.saturating_sub(1) / BLOCK * BLOCK;
let ex_h = existing.pf.block_hashes.unwrap_or(&existing.owned_hashes);
let cand_for_ex =
pair_hash_candidate_checkpoint(&existing.pf, ex_h, &pf, new_hashes, ex_next, ex_final);
if cand_for_ex > existing.credited {
let verified = if std::ptr::eq(existing.pf.toks.as_ptr(), pf.toks.as_ptr())
|| existing.pf.toks[..cand_for_ex] == pf.toks[..cand_for_ex]
{
cand_for_ex
} else {
pair_shared_checkpoint_exact(&existing.pf, &pf, ex_next, ex_final)
};
if verified > existing.credited {
let old_blocks = existing.demanded_blocks(existing.credited);
existing.credited = verified;
let new_blocks = existing.demanded_blocks(existing.credited);
self.base_reserved_full = self.base_reserved_full + new_blocks - old_blocks;
}
}
}
}
let entry =
PreparedPrefillEntry { pf, owned_hashes, written: lane.written, reserved_end_blocks: res_blocks, credited };
self.base_reserved_full += entry.demanded_blocks(credited);
self.prefills.push(entry);
}
}
#[cfg(any(test, standalone_blocks))]
pub fn reserved_inflight_full_slots(lanes: &[InflightLaneReserve<'_>]) -> usize {
let _ = inflight_shared_checkpoint as fn(&InflightPrefillLane<'_>, &[InflightPrefillLane<'_>]) -> usize;
PreparedInflightCohort::new(lanes).reserved_full_slots()
}
fn entry_is_live_sealed(pools: &BlockPools, kind: BlockKind, e: BlockEntry) -> bool {
pools.of(kind).record(e.slot()).ok().is_some_and(|r| r.generation() == e.generation() && r.sealed() && r.refs() > 0)
}
pub struct ServeBlockCache {
tree: EntryTree,
starts: HashMap<SealedId, RetainedStart>,
start_slot_refs: [Vec<u32>; 2],
tick: u64,
stats: CacheStats,
spill_store: Option<SpillStore>,
spill_writer: Option<SpillWriter>,
spill_inline: bool,
pending_spills: HashMap<u64, PendingSpill>,
pending_writes: HashMap<SpillKey, PendingWrite>,
spill_queue_bytes: u64,
max_spill_queue_bytes: u64,
spill_index_dirty: bool,
spill_index_in_flight: bool,
spill_index_max_bytes: usize,
spilled_tree: PrefixTree<u64>,
spilled_starts: HashMap<u64, Arc<SpilledStart>>,
spilled_tips: HashMap<u64, SealedId>,
spill_key_owners: HashMap<SpillKey, Vec<u64>>,
entry_spill_keys: HashMap<(u8, u32, u32), SpillKey>,
spill_key_to_entry: HashMap<SpillKey, (u8, u32, u32)>,
next_spill_id: u64,
max_spilled_starts: usize,
restore_worker: Option<RestoreWorker>,
pending_restores: HashMap<usize, PendingRestore>,
in_flight_restore_keys: HashMap<SpillKey, u32>,
in_flight_restore_spills: HashSet<u64>,
next_restore_seq: u64,
shared_wake: Arc<RestoreWake>,
last_wake_seq: u64,
retained_host_bytes: u64,
max_retained_host_bytes: u64,
card_lease: Duration,
clock_origin: Instant,
next_owner_turn: u64,
latest_owner_turn: HashMap<u64, u64>,
held_starts: HashMap<SealedId, u32>,
#[cfg(any(test, standalone_blocks))]
test_clock_ms: Option<Arc<std::sync::atomic::AtomicU64>>,
spill_write_timeout: Duration,
spill_full_attn_budget: u64,
spill_model_fingerprint: u64,
kv_stitch: bool,
approx_retain: bool,
prefill_through: bool,
approx_per_scope: HashMap<u64, usize>,
max_approx_starts_per_scope: usize,
release_superseded_starts: bool,
retain_lru: bool,
stitch_index: HashMap<(u64, u64), Vec<(SealedId, u32)>>,
stitch_guards: Vec<(Slot, u32)>,
ikv_namespace: u64,
ikv_catalog: Option<Arc<crate::ikv::IkvCatalog>>,
ikv_stage_worker: Option<IkvStageWorker>,
pending_ikv_stages: HashMap<usize, PendingIkvStage>,
next_ikv_stage_seq: u64,
owner_prior: HashMap<u64, OwnerPriorTurn>,
prior_checkpoint_owners: HashMap<SealedId, Vec<u64>>,
next_owner_prior_seq: u64,
}
impl Default for ServeBlockCache {
fn default() -> Self {
Self::new()
}
}
impl ServeBlockCache {
pub fn new() -> Self {
Self {
tree: EntryTree::new(),
starts: HashMap::new(),
start_slot_refs: [Vec::new(), Vec::new()],
tick: 0,
stats: CacheStats::default(),
spill_store: None,
spill_writer: None,
spill_inline: true,
pending_spills: HashMap::new(),
pending_writes: HashMap::new(),
spill_queue_bytes: 0,
max_spill_queue_bytes: u64::MAX,
spill_index_dirty: false,
spill_index_in_flight: false,
spill_index_max_bytes: MAX_SPILL_INDEX_BYTES,
spilled_tree: PrefixTree::new(),
spilled_starts: HashMap::new(),
spilled_tips: HashMap::new(),
spill_key_owners: HashMap::new(),
entry_spill_keys: HashMap::new(),
spill_key_to_entry: HashMap::new(),
next_spill_id: 1,
max_spilled_starts: DEFAULT_MAX_SPILLED_STARTS,
restore_worker: None,
pending_restores: HashMap::new(),
in_flight_restore_keys: HashMap::new(),
in_flight_restore_spills: HashSet::new(),
next_restore_seq: 1,
shared_wake: Arc::new(RestoreWake::new()),
last_wake_seq: 0,
retained_host_bytes: 0,
max_retained_host_bytes: DEFAULT_MAX_RETAINED_HOST_BYTES,
card_lease: Duration::ZERO,
clock_origin: Instant::now(),
next_owner_turn: 0,
latest_owner_turn: HashMap::new(),
held_starts: HashMap::new(),
#[cfg(any(test, standalone_blocks))]
test_clock_ms: None,
spill_write_timeout: DEFAULT_SPILL_WRITE_TIMEOUT,
spill_full_attn_budget: u64::MAX,
spill_model_fingerprint: 0,
kv_stitch: false,
approx_retain: false,
prefill_through: true,
approx_per_scope: HashMap::new(),
max_approx_starts_per_scope: DEFAULT_MAX_APPROX_STARTS_PER_SCOPE,
release_superseded_starts: false,
retain_lru: false,
stitch_index: HashMap::new(),
stitch_guards: Vec::new(),
ikv_namespace: 0,
ikv_catalog: None,
ikv_stage_worker: None,
pending_ikv_stages: HashMap::new(),
next_ikv_stage_seq: 1,
owner_prior: HashMap::new(),
prior_checkpoint_owners: HashMap::new(),
next_owner_prior_seq: 1,
}
}
pub fn set_kv_stitch(&mut self, enabled: bool) {
self.kv_stitch = enabled;
if !enabled {
self.stitch_index.clear();
}
}
pub fn kv_stitch_enabled(&self) -> bool {
self.kv_stitch
}
pub fn set_approx_retain(&mut self, enabled: bool) {
self.approx_retain = enabled;
}
pub fn set_prefill_through(&mut self, enabled: bool) {
self.prefill_through = enabled;
}
pub fn prefill_through(&self) -> bool {
self.prefill_through
}
pub fn approx_retain_enabled(&self) -> bool {
self.approx_retain
}
pub fn ingress_common_prefix(&self, namespace: u64, owner: u64, toks: &[u32]) -> usize {
let exact = self.tree.common_prefix_in_namespace(namespace, toks);
if self.approx_retain && owner != 0 {
exact.max(self.tree.common_prefix_in_namespace(approx_namespace(namespace, owner), toks))
} else {
exact
}
}
pub fn max_retained_host_bytes(&self) -> u64 {
self.max_retained_host_bytes
}
pub fn set_card_lease(&mut self, lease: Duration) {
self.card_lease = lease;
}
pub fn card_lease(&self) -> Duration {
self.card_lease
}
fn now_ms(&self) -> u64 {
#[cfg(any(test, standalone_blocks))]
if let Some(clk) = &self.test_clock_ms {
return clk.load(Ordering::Relaxed);
}
self.clock_origin.elapsed().as_millis().min(u64::MAX as u128) as u64
}
fn now_us(&self) -> u64 {
#[cfg(any(test, standalone_blocks))]
if let Some(clk) = &self.test_clock_ms {
return clk.load(Ordering::Relaxed).saturating_mul(1000);
}
self.clock_origin.elapsed().as_micros().min(u64::MAX as u128) as u64
}
fn alloc_owner_turn(&mut self) -> u64 {
self.next_owner_turn = self.next_owner_turn.saturating_add(1);
self.next_owner_turn
}
fn record_owner_turn(&mut self, owner: u64, turn: u64) {
if owner == 0 || turn == 0 {
return;
}
if self.latest_owner_turn.len() > self.starts.len().saturating_mul(2).saturating_add(64) {
let live_owners: HashSet<u64> =
self.starts.values().filter(|st| st.last_owner != 0).map(|st| st.last_owner).collect();
self.latest_owner_turn.retain(|o, _| live_owners.contains(o));
}
let entry = self.latest_owner_turn.entry(owner).or_insert(0);
if turn > *entry {
*entry = turn;
}
}
fn ensure_save_owner_turn(&mut self, state: &mut LaneBlockState) -> u64 {
if self.card_lease.is_zero() || state.owner == 0 {
state.save_owner_turn = 0;
0
} else {
if state.save_owner_turn == 0 {
let turn = self.alloc_owner_turn();
state.save_owner_turn = turn;
self.record_owner_turn(state.owner, turn);
}
state.save_owner_turn
}
}
fn is_start_leased_at(&self, sid: SealedId, st: &RetainedStart, now_ms: u64, lease_ms: u64) -> bool {
lease_ms > 0
&& (st.reasons & PROMPT) != 0
&& st.last_owner != 0
&& st.owner_turn != 0
&& self.latest_owner_turn.get(&st.last_owner) == Some(&st.owner_turn)
&& (now_ms < st.last_used_ms.saturating_add(lease_ms) || self.held_starts.contains_key(&sid))
}
fn hold_start(&mut self, state: &mut LaneBlockState, sid: SealedId) {
if self.card_lease.is_zero() || state.owner == 0 || state.lease_holds.contains(&sid) {
return;
}
state.lease_holds.push(sid);
*self.held_starts.entry(sid).or_insert(0) += 1;
}
fn drop_lease_holds(&mut self, state: &mut LaneBlockState) {
for sid in state.lease_holds.drain(..) {
if let Some(n) = self.held_starts.get_mut(&sid) {
*n -= 1;
if *n == 0 {
self.held_starts.remove(&sid);
}
}
}
}
fn settle_lease_at_release(&mut self, state: &mut LaneBlockState, cancelled: bool) {
self.drop_lease_holds(state);
if self.card_lease.is_zero() || state.owner == 0 {
return;
}
if cancelled {
self.latest_owner_turn.remove(&state.owner);
return;
}
let now_ms = self.now_ms();
let latest = self.latest_owner_turn.get(&state.owner).copied();
for sid in [state.reply_saved_id, state.prompt_saved_id, state.bound_start_id].into_iter().flatten() {
if let Some(st) = self.starts.get_mut(&sid) {
if st.last_owner == state.owner && st.owner_turn != 0 && latest == Some(st.owner_turn) {
st.last_used_ms = now_ms;
}
}
}
}
fn leased_starts(&self) -> HashSet<SealedId> {
let lease_ms = self.card_lease.as_millis().min(u64::MAX as u128) as u64;
if lease_ms == 0 || self.starts.is_empty() {
return HashSet::new();
}
let now_ms = self.now_ms();
self.starts
.iter()
.filter(|(&sid, st)| self.is_start_leased_at(sid, st, now_ms, lease_ms))
.map(|(&sid, _)| sid)
.collect()
}
fn note_bound_chain_owner(
&mut self,
ids: &[SealedId],
sid: SealedId,
state: &mut LaneBlockState,
prompt_len: usize,
matched_at: usize,
) {
self.note_bound_start_owner(sid, state, prompt_len, matched_at);
if matched_at > prompt_len {
if state.prompt_saved_pos == 0 {
let prompt_ckpt = ((prompt_len.saturating_sub(1)) / BLOCK) * BLOCK;
for cand_pos in [prompt_len, prompt_ckpt] {
if cand_pos > 0 && cand_pos.is_multiple_of(BLOCK) {
if let Some(&anc_id) = ids.get(cand_pos / BLOCK - 1) {
if self.starts.contains_key(&anc_id) {
state.prompt_saved_pos = cand_pos;
state.prompt_saved_id = Some(anc_id);
break;
}
}
}
}
}
if matched_at.is_multiple_of(BLOCK) && matched_at > state.reply_saved_pos && self.starts.contains_key(&sid) {
state.reply_saved_pos = matched_at;
state.reply_saved_id = Some(sid);
}
}
}
fn note_bound_start_owner(&mut self, sid: SealedId, state: &mut LaneBlockState, prompt_len: usize, matched_at: usize) {
let prompt_ckpt = ((prompt_len.saturating_sub(1)) / BLOCK) * BLOCK;
if matched_at > 0
&& (matched_at == prompt_ckpt || matched_at == prompt_len)
&& matched_at >= state.prompt_saved_pos
&& self.starts.contains_key(&sid)
{
state.prompt_saved_pos = matched_at;
state.prompt_saved_id = Some(sid);
}
if self.card_lease.is_zero() || state.owner == 0 {
return;
}
if self.starts.contains_key(&sid) {
state.bound_start_id = Some(sid);
self.hold_start(state, sid);
}
let refresh = self.starts.get(&sid).is_some_and(|st| {
st.last_owner == state.owner
&& (st.reasons & PROMPT) != 0
&& st.owner_turn != 0
&& self.latest_owner_turn.get(&state.owner) == Some(&st.owner_turn)
});
if refresh {
let now_ms = self.now_ms();
if let Some(st) = self.starts.get_mut(&sid) {
st.last_used_ms = now_ms;
}
}
}
#[cfg(any(test, standalone_blocks))]
pub fn set_test_clock_ms(&mut self, now_ms: u64) {
self.test_clock_ms = Some(Arc::new(std::sync::atomic::AtomicU64::new(now_ms)));
}
#[cfg(any(test, standalone_blocks))]
pub fn advance_test_clock_ms(&mut self, delta_ms: u64) {
match &self.test_clock_ms {
Some(clk) => {
let _ = clk.fetch_add(delta_ms, Ordering::Relaxed);
}
None => {
self.test_clock_ms = Some(Arc::new(std::sync::atomic::AtomicU64::new(delta_ms)));
}
}
}
#[cfg(any(test, standalone_blocks))]
pub fn retained_host_bytes_now(&self) -> u64 {
self.retained_host_bytes
}
fn is_stitch_guard(&self, e: BlockEntry) -> bool {
e.kind() == BlockKind::Window && self.stitch_guards.contains(&(e.slot(), e.generation()))
}
fn entry_is_valid_kv(&self, pools: &BlockPools, kind: BlockKind, e: BlockEntry) -> bool {
!self.is_stitch_guard(e) && entry_is_live_sealed(pools, kind, e)
}
fn insert_and_pin_approx_block(
&mut self,
pools: &BlockPools,
tbl: &BlockTable,
ns: u64,
parent: Option<SealedId>,
b: usize,
toks: &[u32],
) -> Option<SealedId> {
let bi = BlockIndex::new(b as u32);
let fe = tbl.get(BlockKind::Full, bi).ok().flatten()?;
if !self.entry_is_valid_kv(pools, BlockKind::Full, fe) {
return None;
}
let we = tbl
.get(BlockKind::Window, bi)
.ok()
.flatten()
.filter(|&w| self.entry_is_valid_kv(pools, BlockKind::Window, w));
let blk_toks = &toks[b * BLOCK..(b + 1) * BLOCK];
let id = self.tree.insert_in_namespace(ns, parent, b * BLOCK, blk_toks, BlockHandles::new(fe, we)).ok()?;
if let Some(canon) = self.tree.handle(id) {
let full_stale = !self.entry_is_valid_kv(pools, BlockKind::Full, canon.full());
let win_stale = canon
.window()
.is_some_and(|cw| !self.entry_is_valid_kv(pools, BlockKind::Window, cw));
if full_stale || win_stale || (canon.window().is_none() && we.is_some()) {
let best_f = if full_stale { fe } else { canon.full() };
let best_w = if win_stale || canon.window().is_none() { we } else { canon.window() };
let _ = self.tree.set_handle(id, BlockHandles::new(best_f, best_w));
}
}
if self.tree.pin(id).is_err() {
self.tree.prune_unreferenced(id);
return None;
}
Some(id)
}
pub fn enter_approx_path(
&mut self,
pools: &BlockPools,
tbl: &BlockTable,
state: &mut LaneBlockState,
toks: &[u32],
) {
if !self.approx_retain || state.owner == 0 || !state.stitched_approx {
return;
}
let ns = approx_namespace(state.namespace, state.owner);
debug_assert_ne!(ns, state.namespace, "a twin never equals its exact namespace");
let n = (state.written / BLOCK).min(toks.len() / BLOCK);
if state.approx_path {
let start_blk = state.sealed.len();
if start_blk == n {
return;
}
if start_blk < n {
let mut parent = state.sealed.last().copied();
let mut added: Vec<SealedId> = Vec::with_capacity(n - start_blk);
for b in start_blk..n {
let Some(id) = self.insert_and_pin_approx_block(pools, tbl, ns, parent, b, toks) else {
break;
};
added.push(id);
parent = Some(id);
}
if added.len() != n - start_blk {
for id in added.into_iter().rev() {
self.tree.unpin(id);
self.tree.prune_unreferenced(id);
}
let old_tip = state.sealed.last().copied();
for id in state.sealed.drain(..) {
self.tree.unpin(id);
}
if let Some(old_tip) = old_tip {
self.tree.prune_unreferenced(old_tip);
}
state.approx_path = false;
return;
}
state.sealed.extend(added);
state.stitched_approx = true;
state.approx_path = true;
return;
}
let old_tip = state.sealed.last().copied();
for id in state.sealed.drain(..) {
self.tree.unpin(id);
}
if let Some(old_tip) = old_tip {
self.tree.prune_unreferenced(old_tip);
}
state.approx_path = false;
}
let mut ids: Vec<SealedId> = Vec::with_capacity(n);
let mut parent: Option<SealedId> = None;
for b in 0..n {
let Some(id) = self.insert_and_pin_approx_block(pools, tbl, ns, parent, b, toks) else {
break;
};
ids.push(id);
parent = Some(id);
}
if ids.len() != n {
for id in ids.into_iter().rev() {
self.tree.unpin(id);
self.tree.prune_unreferenced(id);
}
return;
}
let old_tip = state.sealed.last().copied();
for id in state.sealed.drain(..) {
self.tree.unpin(id);
}
if let Some(old_tip) = old_tip {
self.tree.prune_unreferenced(old_tip);
}
state.sealed = ids;
state.stitched_approx = true;
state.approx_path = true;
}
fn bind_deeper_approx_start(
&mut self,
pools: &mut BlockPools,
tbl: &mut BlockTable,
state: &mut LaneBlockState,
toks: &[u32],
exact_at: usize,
) -> Option<(usize, Vec<u8>)> {
if !self.approx_retain || state.owner == 0 || toks.len() <= 1 {
return None;
}
let ns = approx_namespace(state.namespace, state.owner);
let search = &toks[..toks.len() - 1];
loop {
let matched = self.tree.deepest_start_in_namespace(ns, search);
if matched.at <= exact_at {
return None;
}
let sid = matched.start?;
let live = match self.starts.get(&sid) {
Some(st) => {
st.approx
&& st.namespace == ns
&& st.pos == matched.at
&& st.entries.iter().all(|&(kind, _, e)| self.entry_is_valid_kv(pools, kind, e))
}
None => false,
};
if !live {
if !self.evict_start_inner(pools, sid, false, None, EvictCause::StaleInvalid) {
return None;
}
continue;
}
self.record_prefix_reuse(&matched.ids, 0);
let prompt_len = state.effective_prompt_len(toks.len());
self.note_bound_chain_owner(&matched.ids, sid, state, prompt_len, matched.at);
let (cs, entries) = {
let st = self.starts.get(&sid).expect("checked approximate start exists");
(st.cs.clone(), st.entries.clone())
};
for &(kind, bi, e) in &entries {
tbl.fill(pools.of_mut(kind), bi, e.slot(), e.generation()).expect("install approximate start block");
}
for &id in &matched.ids {
self.tree.pin(id).expect("pin matched approximate prefix block");
}
state.prompt_len = prompt_len;
state.sealed = matched.ids;
state.written = matched.at;
state.stitched_approx = true;
state.approx_path = true;
if !state.internal_resume {
self.stats.approx_start_matches += 1;
self.stats.approx_cached_tokens_total += matched.at as u64;
}
return Some((matched.at, cs));
}
}
#[cfg(any(test, standalone_blocks))]
pub fn set_ikv_catalog(&mut self, catalog: Arc<crate::ikv::IkvCatalog>) {
self.set_ikv_catalog_for_namespace(catalog, 0);
}
pub fn set_ikv_catalog_for_namespace(&mut self, catalog: Arc<crate::ikv::IkvCatalog>, namespace: u64) {
self.stats.ikv_cartridges_loaded = catalog.len() as u64;
self.stats.ikv_quarantined = catalog.quarantined_count();
self.ikv_namespace = namespace;
self.ikv_catalog = Some(catalog);
}
#[inline]
fn sync_ikv_quarantined_stat(&mut self) {
if let Some(cat) = &self.ikv_catalog {
self.stats.ikv_quarantined = cat.quarantined_count();
}
}
fn index_retained_start_for_stitch(&mut self, sid: SealedId) {
if !self.kv_stitch {
return;
}
let Some(st) = self.starts.get(&sid) else {
return;
};
if st.toks.len() < BLOCK {
return;
}
let ns = st.namespace;
let n_blocks = st.toks.len() / BLOCK;
for b in 0..n_blocks {
let h = stitch_hash_64(&st.toks[b * BLOCK..(b + 1) * BLOCK]);
let bucket = self.stitch_index.entry((ns, h)).or_default();
if !bucket.contains(&(sid, b as u32)) {
if bucket.len() >= MAX_STITCH_BUCKET_LEN {
bucket.remove(0);
}
bucket.push((sid, b as u32));
}
}
}
fn unindex_retained_start_for_stitch(&mut self, sid: SealedId, namespace: u64, toks: &[u32]) {
if toks.len() < BLOCK || self.stitch_index.is_empty() {
return;
}
let n_blocks = toks.len() / BLOCK;
for b in 0..n_blocks {
let h = stitch_hash_64(&toks[b * BLOCK..(b + 1) * BLOCK]);
let remove_bucket = if let Some(bucket) = self.stitch_index.get_mut(&(namespace, h)) {
bucket.retain(|&(id, _)| id != sid);
bucket.is_empty()
} else {
false
};
if remove_bucket {
self.stitch_index.remove(&(namespace, h));
}
}
}
pub fn recommended_host_budget_bytes(available_kv_budget_bytes: u64) -> u64 {
if available_kv_budget_bytes == 0 {
return 0;
}
(available_kv_budget_bytes / 32).clamp(16 << 20, DEFAULT_MAX_RETAINED_HOST_BYTES)
}
pub fn set_max_retained_host_bytes(&mut self, max_bytes: u64) {
self.max_retained_host_bytes = max_bytes;
}
pub fn retained_host_bytes(&self) -> u64 {
self.retained_host_bytes
}
#[cfg(any(test, standalone_blocks))]
pub fn set_spill_write_timeout(&mut self, timeout: Duration) {
self.spill_write_timeout = timeout;
}
#[cfg(any(test, standalone_blocks))]
pub fn with_spill(store: SpillStore) -> Self {
Self::with_spill_compat(store, None, 0)
}
#[cfg(any(test, standalone_blocks))]
pub fn with_spill_compat(store: SpillStore, full_attn_budget: Option<usize>, model_fingerprint: u64) -> Self {
Self::with_spill_compat_sparse(store, full_attn_budget, None, 0, model_fingerprint)
}
pub fn with_spill_compat_sparse(
store: SpillStore,
full_attn_budget: Option<usize>,
sparse_topk: Option<usize>,
sparse_anchors: usize,
model_fingerprint: u64,
) -> Self {
let mut cache = Self::new();
cache.spill_full_attn_budget = match sparse_topk {
Some(topk) => (1u64 << 63) | (((sparse_anchors as u64) & 0x7fff_ffff) << 32) | ((topk as u64) & 0xffff_ffff),
None => full_attn_budget.map_or(u64::MAX, |b| b as u64),
};
cache.spill_model_fingerprint = model_fingerprint;
cache.spill_store = Some(store);
cache.load_spill_index_on_open();
cache
}
pub fn spill_store(&self) -> Option<&SpillStore> {
self.spill_store.as_ref()
}
pub fn spill_in_background(&mut self, max_queue_bytes: u64) {
let Some(store) = self.spill_store.as_ref() else {
return;
};
let wake = self.shared_wake.clone();
let writer = self.spill_writer.get_or_insert_with(|| SpillWriter::new(store.dir(), store.kvb()));
writer.start_thread(Arc::new(move || wake.notify()));
self.spill_inline = false;
self.max_spill_queue_bytes = max_queue_bytes;
}
#[cfg(test)]
pub(crate) fn spill_by_hand_for_test(&mut self, max_queue_bytes: u64) {
self.spill_inline = false;
self.max_spill_queue_bytes = max_queue_bytes;
}
#[cfg(test)]
pub(crate) fn run_spill_writer_for_test(&mut self, max: usize) -> usize {
self.spill_writer.as_ref().map_or(0, |w| w.run_queued(max))
}
#[cfg(test)]
pub(crate) fn set_spill_write_cost_for_test(&mut self, ms_per_write: u64) {
let clock = self.test_clock_ms.clone().expect("set_test_clock_ms first");
let store = self.spill_store.as_ref().expect("a spill store");
let writer = self.spill_writer.get_or_insert_with(|| SpillWriter::new(store.dir(), store.kvb()));
writer.set_block_hook(Some(Arc::new(move |_| {
clock.fetch_add(ms_per_write, Ordering::Relaxed);
})));
}
pub fn spill_writes_hold_blocks(&self) -> bool {
self.pending_writes.values().any(|w| w.pin.is_some())
}
pub fn has_pending_spill_io(&self) -> bool {
!self.pending_writes.is_empty() || self.spill_index_in_flight || self.spill_index_dirty
}
fn push_spill_io(&mut self, job: SpillIo, urgent: bool) -> u64 {
let store = self.spill_store.as_ref().expect("spill I/O requires an open store");
let writer = self.spill_writer.get_or_insert_with(|| SpillWriter::new(store.dir(), store.kvb()));
writer.push(job, urgent)
}
fn drop_spill_block(&mut self, key: SpillKey) {
let Some(store) = self.spill_store.as_mut() else {
return;
};
if self.spill_inline {
store.remove_block(key);
return;
}
store.forget_block_owing_unlink(key);
self.push_spill_io(SpillIo::Unlink { key }, true);
}
fn unlink_owed_spill_blocks(&mut self, keys: Vec<SpillKey>) {
for key in keys {
if self.spill_inline {
if let Some(store) = self.spill_store.as_ref() {
let _ = unlink_block_in_dir(store.dir(), key);
}
} else {
self.push_spill_io(SpillIo::Unlink { key }, true);
}
}
}
fn pin_inflight_restore_keys(&mut self, spill_id: u64, keys: &[SpillKey]) {
self.in_flight_restore_spills.insert(spill_id);
for &k in keys {
*self.in_flight_restore_keys.entry(k).or_insert(0) += 1;
}
}
fn unpin_inflight_restore_keys(&mut self, spill_id: u64, keys: &[SpillKey]) {
for &k in keys {
if let Some(cnt) = self.in_flight_restore_keys.get_mut(&k) {
*cnt = cnt.saturating_sub(1);
if *cnt == 0 {
self.in_flight_restore_keys.remove(&k);
}
}
}
let still_active = self.pending_restores.values().any(|pr| pr.spill_id == spill_id);
if !still_active {
self.in_flight_restore_spills.remove(&spill_id);
}
}
fn protected_spill_keys(&self, extra: Option<&RestoreSource>) -> HashSet<SpillKey> {
let mut out: HashSet<SpillKey> = self.in_flight_restore_keys.keys().copied().collect();
if let Some(source) = extra {
out.extend(source.keys.iter().copied());
}
for pending in self.pending_spills.values() {
out.extend(pending.claimed_keys.iter().copied());
}
out
}
fn spill_index_snapshot(&self) -> Option<SpillIndexSnapshot> {
let store = self.spill_store.as_ref()?;
Some(SpillIndexSnapshot {
kvb: store.kvb(),
next_spill_id: self.next_spill_id,
tick: self.tick,
full_attn_budget: self.spill_full_attn_budget,
model_fingerprint: self.spill_model_fingerprint,
records: self.spilled_starts.iter().map(|(&id, sp)| (id, sp.clone())).collect(),
})
}
fn persist_spill_index(&mut self) {
if !self.spill_inline {
self.spill_index_dirty = self.spill_store.is_some();
return;
}
let Some(snapshot) = self.spill_index_snapshot() else {
return;
};
let image = snapshot.into_bytes(self.spill_index_max_bytes);
if self.spill_store.as_ref().is_some_and(|store| store.write_index_bytes(&image).is_err()) {
self.stats.spill_io_errors += 1;
}
}
fn flush_spill_index(&mut self) {
if !self.spill_index_dirty || self.spill_index_in_flight {
return;
}
let Some(snapshot) = self.spill_index_snapshot() else {
return;
};
self.spill_index_dirty = false;
self.spill_index_in_flight = true;
let max_len = self.spill_index_max_bytes;
self.push_spill_io(SpillIo::Index { build: Box::new(move || snapshot.into_bytes(max_len)) }, true);
}
fn load_spill_index_on_open(&mut self) {
let Some(raw) = self.spill_store.as_mut().and_then(|s| s.read_index_bytes(MAX_SPILL_INDEX_BYTES)) else {
if let Some(store) = self.spill_store.as_mut() {
store.retain_keys(&HashSet::new());
}
return;
};
let store_kvb = self.spill_store.as_ref().unwrap().kvb();
let reject = |this: &mut Self| {
if let Some(store) = this.spill_store.as_mut() {
store.remove_index(true);
store.retain_keys(&HashSet::new());
}
};
if raw.len() < SPILL_INDEX_PREFIX_LEN + 8 + 32 {
reject(self);
return;
}
if raw[0..8] != SPILL_INDEX_MAGIC {
reject(self);
return;
}
let version = u32::from_le_bytes(raw[8..12].try_into().unwrap());
let file_kvb = u32::from_le_bytes(raw[12..16].try_into().unwrap());
let saved_next_spill_id = u64::from_le_bytes(raw[16..24].try_into().unwrap());
let saved_tick = u64::from_le_bytes(raw[24..32].try_into().unwrap());
let count = u32::from_le_bytes(raw[32..36].try_into().unwrap()) as usize;
let file_budget = u64::from_le_bytes(raw[36..44].try_into().unwrap());
let file_model_fp = u64::from_le_bytes(raw[44..52].try_into().unwrap());
if version != SPILL_INDEX_VERSION
|| file_kvb != store_kvb
|| file_budget != self.spill_full_attn_budget
|| file_model_fp != self.spill_model_fingerprint
{
reject(self);
return;
}
let payload_len = u64::from_le_bytes(raw[52..60].try_into().unwrap());
let stored_digest: [u8; 32] = raw[60..92].try_into().unwrap();
let payload = &raw[92..];
if payload.len() as u64 != payload_len {
reject(self);
return;
}
let mut hasher = Sha256::new();
hasher.update(&raw[0..60]);
hasher.update(payload);
if hasher.finalize() != stored_digest {
reject(self);
return;
}
let parse_records = || -> Option<Vec<(u64, SpilledStart)>> {
let mut cur = 0usize;
let mut out = Vec::with_capacity(count.min(self.max_spilled_starts + 16));
for _ in 0..count {
if cur + 46 > payload.len() {
return None;
}
let id = u64::from_le_bytes(payload[cur..cur + 8].try_into().ok()?);
let namespace = u64::from_le_bytes(payload[cur + 8..cur + 16].try_into().ok()?);
let pos = usize::try_from(u64::from_le_bytes(payload[cur + 16..cur + 24].try_into().ok()?)).ok()?;
let reasons = payload[cur + 24];
let last_used_tick = u64::from_le_bytes(payload[cur + 25..cur + 33].try_into().ok()?);
let cs_kind = SpillBlockKind::from_u32(u32::from(payload[cur + 33]))?;
let cs_id = u64::from_le_bytes(payload[cur + 34..cur + 42].try_into().ok()?);
let toks_len = u32::from_le_bytes(payload[cur + 42..cur + 46].try_into().ok()?) as usize;
cur += 46;
if pos == 0 || !pos.is_multiple_of(BLOCK) || toks_len != pos {
return None;
}
let toks_bytes = toks_len.checked_mul(4)?;
if cur + toks_bytes + 4 > payload.len() {
return None;
}
let mut toks = Vec::with_capacity(toks_len);
for i in 0..toks_len {
let off = cur + i * 4;
toks.push(u32::from_le_bytes(payload[off..off + 4].try_into().ok()?));
}
cur += toks_bytes;
let entries_len = u32::from_le_bytes(payload[cur..cur + 4].try_into().ok()?) as usize;
cur += 4;
let entries_bytes = entries_len.checked_mul(14)?;
if cur + entries_bytes > payload.len() {
return None;
}
let mut entries = Vec::with_capacity(entries_len);
for i in 0..entries_len {
let off = cur + i * 14;
let bk = match payload[off] {
0 => BlockKind::Window,
1 => BlockKind::Full,
_ => return None,
};
let bi = BlockIndex::new(u32::from_le_bytes(payload[off + 1..off + 5].try_into().ok()?));
let sk_kind = SpillBlockKind::from_u32(u32::from(payload[off + 5]))?;
let sk_id = u64::from_le_bytes(payload[off + 6..off + 14].try_into().ok()?);
entries.push((bk, bi, SpillKey::new(sk_kind, sk_id)));
}
cur += entries_bytes;
out.push((
id,
SpilledStart {
namespace,
pos,
reasons,
cs_key: SpillKey::new(cs_kind, cs_id),
entries,
toks,
last_used_tick,
},
));
}
(cur == payload.len()).then_some(out)
};
let Some(mut decoded) = parse_records() else {
reject(self);
return;
};
decoded.sort_by_key(|&(id, ref sp)| (sp.last_used_tick, id));
if decoded.len() > self.max_spilled_starts {
let drop_n = decoded.len() - self.max_spilled_starts;
decoded.drain(0..drop_n);
}
let mut max_id = saved_next_spill_id.max(1);
let mut max_tick = saved_tick;
let mut kept_keys = HashSet::new();
let mut skipped_any = false;
for (spill_id, sp) in decoded {
let store = self.spill_store.as_ref().unwrap();
let all_present = store.contains(sp.cs_key) && sp.entries.iter().all(|&(_, _, sk)| store.contains(sk));
if !all_present {
skipped_any = true;
continue;
}
max_id = max_id.max(spill_id.saturating_add(1));
max_tick = max_tick.max(sp.last_used_tick);
let n_blocks = sp.pos / BLOCK;
let mut parent = None;
for b in 0..n_blocks {
let id = self
.spilled_tree
.insert_in_namespace(
sp.namespace,
parent,
b * BLOCK,
&sp.toks[b * BLOCK..(b + 1) * BLOCK],
spill_id,
)
.expect("insert loaded spilled block into spilled_tree");
parent = Some(id);
}
let tip = parent.expect("non-empty loaded spilled blocks");
if self.spilled_tree.start_holders(tip) > 0 {
if let Some(old_id) = self.spilled_tree.handle(tip) {
self.remove_spilled_start_inner(old_id, false);
}
let mut p = None;
for b in 0..n_blocks {
let id = self
.spilled_tree
.insert_in_namespace(sp.namespace, p, b * BLOCK, &sp.toks[b * BLOCK..(b + 1) * BLOCK], spill_id)
.expect("re-insert loaded spilled block into spilled_tree");
p = Some(id);
}
let new_tip = p.expect("non-empty loaded spilled blocks");
let _ = self.spilled_tree.set_handle(new_tip, spill_id);
self.spilled_tree.retain_start(new_tip).expect("retain loaded spilled start");
self.spilled_tips.insert(spill_id, new_tip);
} else {
let _ = self.spilled_tree.set_handle(tip, spill_id);
self.spilled_tree.retain_start(tip).expect("retain loaded spilled start");
self.spilled_tips.insert(spill_id, tip);
}
kept_keys.insert(sp.cs_key);
self.spill_key_owners.entry(sp.cs_key).or_default().push(spill_id);
for &(_, _, sk) in &sp.entries {
kept_keys.insert(sk);
self.spill_key_owners.entry(sk).or_default().push(spill_id);
}
self.spilled_starts.insert(spill_id, Arc::new(sp));
}
self.next_spill_id = max_id;
self.tick = self.tick.max(max_tick);
let swept = self.spill_store.as_mut().map_or(0, |s| s.retain_keys(&kept_keys));
if skipped_any || swept > 0 {
self.persist_spill_index();
}
}
pub fn maintain_spill_during_gpu(&mut self) -> usize {
if self.spill_store.is_none() {
return 0;
}
let mut evicted = 0usize;
let mut index_dirty = false;
while self.spilled_starts.len() > self.max_spilled_starts {
let oldest = self
.spilled_starts
.iter()
.filter(|(id, _)| !self.in_flight_restore_spills.contains(id))
.min_by_key(|(_, sp)| (sp.last_used_tick, std::cmp::Reverse(sp.pos)))
.map(|(&id, _)| id);
let Some(oid) = oldest else { break };
if self.remove_spilled_start_inner(oid, true) {
index_dirty = true;
}
evicted += 1;
}
let protected = self.protected_spill_keys(None);
let (gc_evicted, starts_dropped) = self.settle_spill_budget(0, &protected);
evicted += gc_evicted;
if index_dirty || starts_dropped {
self.persist_spill_index();
}
self.stats.spill_maint_passes += 1;
self.stats.spill_maint_evictions += evicted as u64;
evicted
}
fn in_flight_spill_bytes(&self, except: u64) -> u64 {
let Some(store) = self.spill_store.as_ref() else {
return 0;
};
let mut seen: HashSet<SpillKey> = HashSet::new();
let mut total = 0u64;
for (&id, pending) in &self.pending_spills {
if id == except {
continue;
}
for &sk in &pending.claimed_keys {
let in_flight_only = self
.spill_key_owners
.get(&sk)
.is_some_and(|owners| owners.iter().all(|o| *o != except && self.pending_spills.contains_key(o)));
if in_flight_only && seen.insert(sk) {
total = total.saturating_add(store.entry_bytes(sk).unwrap_or(0));
}
}
}
total
}
fn settle_spill_budget(&mut self, except: u64, protected: &HashSet<SpillKey>) -> (usize, bool) {
let in_flight = self.in_flight_spill_bytes(except);
let inline = self.spill_inline;
let Some(store) = self.spill_store.as_mut() else {
return (0, false);
};
if store.used_bytes() <= store.max_bytes().saturating_add(in_flight) {
return (0, false);
}
let mut owed_unlinks = Vec::new();
let gc_evicted = store.settle_budget(in_flight, protected, (!inline).then_some(&mut owed_unlinks));
self.unlink_owed_spill_blocks(owed_unlinks);
let starts_dropped = self.drop_starts_of_gc_evicted(&gc_evicted);
(gc_evicted.len(), starts_dropped)
}
pub fn spilled_start_count(&self) -> usize {
self.spilled_starts.len()
}
pub fn record_step_deferred_pool_pressure(&mut self) {
self.stats.step_deferred_pool_pressure += 1;
}
pub fn stats(&self) -> CacheStats {
let mut s = self.stats;
s.activity_ticks = self.tick;
if let Some(st) = &self.spill_store {
let ds = st.stats();
s.spill_reads_hit = ds.reads_hit;
s.spill_reads_miss = ds.reads_miss;
s.spill_bytes_read = ds.bytes_read;
s.spill_read_us_total = ds.read_us_total;
}
s.spill_writes_pending = self.pending_writes.len() as u64;
s.spill_write_bytes_pending = self.spill_queue_bytes;
s.spill_starts_pending = self.pending_spills.len() as u64;
s
}
#[cfg(test)]
pub fn memory_snapshot(&self, pools: &BlockPools) -> CacheMemorySnapshot {
let (win_used, win_cap) = self.pool_occupancy(pools, BlockKind::Window);
let (full_used, full_cap) = self.pool_occupancy(pools, BlockKind::Full);
let win_stride = pools.window.stride_bytes();
let full_stride = pools.full.stride_bytes();
let approx_retained_starts: usize = self.approx_per_scope.values().copied().sum();
let cs = self.stats();
let (
spill_writes_committed,
spill_bytes_written,
spill_write_us_total,
spill_disk_used_bytes,
spill_disk_max_bytes,
spill_disk_gc_evictions,
) = match &self.spill_store {
Some(store) => {
let ds = store.stats();
(
ds.writes_committed,
ds.bytes_written,
ds.write_us_total,
store.used_bytes(),
store.max_bytes(),
ds.disk_gc_evictions,
)
}
None => (0, 0, 0, 0, 0, 0),
};
CacheMemorySnapshot {
window_slots_used: win_used,
window_slots_capacity: win_cap,
window_slots_bytes_used: (win_used as u64).saturating_mul(win_stride),
window_slots_bytes_capacity: (win_cap as u64).saturating_mul(win_stride),
full_slots_used: full_used,
full_slots_capacity: full_cap,
full_slots_bytes_used: (full_used as u64).saturating_mul(full_stride),
full_slots_bytes_capacity: (full_cap as u64).saturating_mul(full_stride),
retained_host_bytes: self.retained_host_bytes,
retained_host_budget_bytes: self.max_retained_host_bytes,
retained_starts: self.starts.len(),
approx_retained_starts,
spilled_starts: self.spilled_starts.len(),
evictions_pool_pressure: cs.evictions_pool_pressure,
evictions_host_budget: cs.evictions_host_budget,
evictions_approx_scope_cap: cs.evictions_approx_scope_cap,
evictions_stale_invalid: cs.evictions_stale_invalid,
evictions_shutdown: cs.evictions_shutdown,
evictions_superseded: cs.evictions_superseded,
starts_spilled: cs.starts_spilled,
spill_writes_committed,
spill_bytes_written,
spill_write_us_total,
spill_write_timeouts: cs.spill_write_timeouts,
spill_disk_used_bytes,
spill_disk_max_bytes,
spill_disk_gc_evictions,
spill_reads_hit: cs.spill_reads_hit,
spill_reads_miss: cs.spill_reads_miss,
spill_bytes_read: cs.spill_bytes_read,
spill_read_us_total: cs.spill_read_us_total,
starts_restored: cs.starts_restored,
restores_failed: cs.restores_failed,
restore_us_total: cs.restore_us_total,
}
}
fn register_prior_checkpoint_ids(&mut self, owner: u64, prior: &OwnerPriorTurn) {
let mut registered: [Option<SealedId>; 3] = [None; 3];
let mut n = 0usize;
for id in [prior.prompt_tip_id, prior.reply_tip_id, prior.tip_id].into_iter().flatten() {
if registered[..n].contains(&Some(id)) {
continue;
}
registered[n] = Some(id);
n += 1;
let owners = self.prior_checkpoint_owners.entry(id).or_default();
if !owners.contains(&owner) {
owners.push(owner);
}
}
}
fn unregister_prior_checkpoint_ids(&mut self, owner: u64, prior: &OwnerPriorTurn) {
for id in [prior.prompt_tip_id, prior.reply_tip_id, prior.tip_id].into_iter().flatten() {
let empty = if let Some(owners) = self.prior_checkpoint_owners.get_mut(&id) {
owners.retain(|&o| o != owner);
owners.is_empty()
} else {
false
};
if empty {
self.prior_checkpoint_owners.remove(&id);
}
}
}
pub fn observe_prior(&self, owner: u64, toks: &[u32]) -> ObservedPrior {
if owner == 0 {
return ObservedPrior::default();
}
let Some(p) = self.owner_prior.get(&owner) else {
return ObservedPrior::default();
};
let prompt_missing =
p.prompt_saved_pos > 0 && p.prompt_tip_id.is_none_or(|id| !self.starts.contains_key(&id));
let reply_missing =
p.reply_saved_pos > 0 && p.reply_tip_id.is_none_or(|id| !self.starts.contains_key(&id));
let any_saved_start_missing = p.evicted || prompt_missing || reply_missing;
let _ = p.truncated_tail;
let check_tail = |chain_len: usize| -> (Option<usize>, usize) {
for (i, &expected) in p.tail_toks.iter().enumerate() {
let idx = chain_len + i;
if toks.get(idx).copied() != Some(expected) {
return (Some(idx), idx);
}
}
(None, chain_len + p.tail_toks.len())
};
let (first_divergent_pos, proven_common_len) = match p.tip_id {
Some(tip) => match self
.tree
.first_divergence_along_chain(tip, toks)
.or_else(|| p.spilled_tip_id.and_then(|stip| self.spilled_tree.first_divergence_along_chain(stip, toks)))
{
Some(Err(diff_idx)) => (Some(diff_idx), diff_idx),
Some(Ok(chain_len)) => check_tail(chain_len),
None => match p
.prompt_tip_id
.and_then(|ptip| self.tree.first_divergence_along_chain(ptip, toks))
.or_else(|| {
p.spilled_prompt_tip_id
.and_then(|sptip| self.spilled_tree.first_divergence_along_chain(sptip, toks))
}) {
Some(Err(diff_idx)) => (Some(diff_idx), diff_idx),
Some(Ok(chain_len)) => (None, chain_len),
None => (None, 0),
},
},
None => {
if !p.evicted && !p.tail_toks.is_empty() {
check_tail(0)
} else {
(None, 0)
}
}
};
ObservedPrior {
has_prior: true,
prompt_saved_pos: p.prompt_saved_pos,
prompt_len: p.prompt_len,
reply_saved_pos: p.reply_saved_pos,
total_len: p.total_len,
prompt_tip_id: p.prompt_tip_id,
reply_tip_id: p.reply_tip_id,
proven_common_len,
evicted: p.evicted,
any_saved_start_missing,
first_divergent_pos,
}
}
pub fn classify_observed_reuse(
owner: u64,
restore_at: usize,
restore_failed: bool,
obs: ObservedPrior,
sealed: &[SealedId],
) -> (&'static str, Option<usize>) {
let _ = (obs.total_len, obs.evicted);
if restore_at > 0 {
if owner != 0 && obs.has_prior {
let matched_prompt_ckpt = obs.prompt_saved_pos >= BLOCK
&& obs.prompt_saved_pos <= restore_at
&& obs
.prompt_tip_id
.is_some_and(|id| sealed.get(obs.prompt_saved_pos / BLOCK - 1) == Some(&id));
let matched_reply_ckpt = obs.reply_saved_pos >= BLOCK
&& obs.reply_saved_pos <= restore_at
&& obs
.reply_tip_id
.is_some_and(|id| sealed.get(obs.reply_saved_pos / BLOCK - 1) == Some(&id));
let reply_continuous = obs.reply_saved_pos > 0
&& restore_at >= obs.reply_saved_pos
&& (matched_reply_ckpt || obs.proven_common_len >= obs.reply_saved_pos)
&& obs.first_divergent_pos.is_none_or(|d| d >= restore_at);
let prompt_continuous = obs.prompt_saved_pos > 0
&& (matched_prompt_ckpt || obs.proven_common_len >= obs.prompt_saved_pos);
if reply_continuous {
("hit_reply_end", obs.first_divergent_pos)
} else if prompt_continuous
&& restore_at == obs.prompt_saved_pos
&& obs.first_divergent_pos.is_some_and(|d| d >= obs.prompt_len)
{
("hit_prompt_end_diverged", obs.first_divergent_pos)
} else if obs.first_divergent_pos.is_some() {
("hit_prefix_diverged", obs.first_divergent_pos)
} else if prompt_continuous
&& restore_at >= obs.prompt_saved_pos
&& obs.first_divergent_pos.is_none()
{
("hit_prompt_end", None)
} else {
("hit_shared_prefix", None)
}
} else {
("hit_shared_prefix", None)
}
} else if restore_failed {
("miss_restore_failed", obs.first_divergent_pos)
} else if owner == 0 || !obs.has_prior {
("miss_no_prior_turn", None)
} else if obs.first_divergent_pos.is_some() {
("miss_diverged", obs.first_divergent_pos)
} else if obs.any_saved_start_missing {
("miss_evicted", None)
} else {
("miss_prior_unsealed", None)
}
}
pub fn retained_start_count(&self) -> usize {
self.starts.len()
}
fn inc_start_slot_ref(&mut self, kind: BlockKind, slot: Slot) {
let idx = slot.pool_index().get() as usize;
let v = &mut self.start_slot_refs[kind_idx(kind)];
if v.len() <= idx {
v.resize(idx + 1, 0);
}
v[idx] = v[idx].checked_add(1).expect("start_slot_refs overflow");
}
fn dec_start_slot_ref(&mut self, kind: BlockKind, slot: Slot) {
let idx = slot.pool_index().get() as usize;
let v = &mut self.start_slot_refs[kind_idx(kind)];
debug_assert!(idx < v.len() && v[idx] > 0, "start_slot_refs underflow");
if idx < v.len() && v[idx] > 0 {
v[idx] -= 1;
}
}
pub fn pool_occupancy(&self, pools: &BlockPools, kind: BlockKind) -> (usize, usize) {
let pool = pools.of(kind);
let (_, free) = pool.count_usable_and_avail(&[]);
(pool.len().saturating_sub(free), pool.len())
}
pub fn free_plus_evictable_slots(&self, pools: &BlockPools, kind: BlockKind) -> usize {
self.pool_headroom(pools, kind).1
}
fn pool_headroom(&self, pools: &BlockPools, kind: BlockKind) -> (usize, usize) {
pools.of(kind).count_usable_and_avail(&self.start_slot_refs[kind_idx(kind)])
}
fn resident_start(&self, pools: &BlockPools, namespace: u64, toks: &[u32]) -> Option<&RetainedStart> {
if self.starts.is_empty() {
return None;
}
let prefix = toks.get(..toks.len().checked_sub(1)?)?;
let matched = self.tree.deepest_start_in_namespace(namespace, prefix);
let st = self.starts.get(&matched.start?)?;
(!st.approx && st.namespace == namespace && st.entries.iter().all(|&(kind, _, e)| self.entry_is_valid_kv(pools, kind, e)))
.then_some(st)
}
#[cfg(any(test, standalone_blocks))]
pub fn peek_match_len(&self, pools: &BlockPools, toks: &[u32]) -> usize {
self.peek_match_len_in_namespace(pools, 0, toks)
}
#[cfg(any(test, standalone_blocks))]
pub fn peek_match_len_in_namespace(&self, pools: &BlockPools, namespace: u64, toks: &[u32]) -> usize {
self.resident_start(pools, namespace, toks).map_or(0, |st| st.pos)
}
#[allow(clippy::too_many_arguments)]
pub fn can_admit_with_cohort_in_namespace(
&mut self,
pools: &BlockPools,
cohort: &PreparedInflightCohort<'_>,
lane: usize,
namespace: u64,
toks: &[u32],
cand_block_hashes: Option<&[u64]>,
max_gen: usize,
chunk: usize,
) -> bool {
if cohort.is_empty() {
return true;
}
let owned_hashes;
let cand_hashes: &[u64] = match cand_block_hashes {
Some(h) => h,
None => {
owned_hashes = compute_block_hashes(toks);
&owned_hashes
}
};
let (usable_window, available_window, available_full) = match cohort.cached_headroom.get() {
Some(h) => h,
None => {
let (uw, aw) = self.pool_headroom(pools, BlockKind::Window);
let af = self.free_plus_evictable_slots(pools, BlockKind::Full);
cohort.cached_headroom.set(Some((uw, aw, af)));
(uw, aw, af)
}
};
let mut pins = [0; 2];
let mut cached = 0;
if let Some(st) = self.resident_start(pools, namespace, toks) {
cached = st.pos;
for &(kind, _, entry) in &st.entries {
let i = kind_idx(kind);
let slot = entry.slot();
let refs = self.start_slot_refs[i][slot.pool_index().get() as usize];
if pools.of(kind).record(slot).unwrap().refs() == refs {
pins[i] += 1;
}
}
}
let fits = |start: usize, newly_pinned: [usize; 2]| {
let cand = InflightLaneReserve {
lane,
namespace,
toks,
block_hashes: Some(cand_hashes),
n_past: start,
pf_end: toks.len(),
cached: start,
written: start,
gen: 0,
max_gen,
runnable: true,
};
let (base_full, base_win_growth, steady_window) = cohort.eval_with_candidate(&cand, cand_hashes);
let full = base_full + newly_pinned[kind_idx(BlockKind::Full)];
let window_growth = base_win_growth + newly_pinned[kind_idx(BlockKind::Window)];
let peak_window = steady_window + chunk.div_ceil(BLOCK) + (cohort.len + 1);
let window_ok = window_growth <= available_window || peak_window <= usable_window;
full <= available_full && window_ok
};
let mut ok = fits(cached, pins);
if ok && !toks.is_empty() && !self.spilled_starts.is_empty() {
let disk = self.spilled_tree.deepest_start_in_namespace(namespace, &toks[..toks.len() - 1]).at;
if disk > cached {
let blocks = disk / BLOCK;
let already_pinned_full = cached / BLOCK - pins[kind_idx(BlockKind::Full)];
ok = fits(disk, [blocks.min(WINDOW / BLOCK), blocks - already_pinned_full]);
}
}
if !ok {
self.stats.admit_deferred_pool_pressure += 1;
}
ok
}
#[cfg(any(test, standalone_blocks))]
#[allow(clippy::too_many_arguments)]
pub fn can_admit_with_cohort(
&mut self,
pools: &BlockPools,
cohort: &PreparedInflightCohort<'_>,
lane: usize,
toks: &[u32],
cand_block_hashes: Option<&[u64]>,
max_gen: usize,
chunk: usize,
) -> bool {
self.can_admit_with_cohort_in_namespace(pools, cohort, lane, 0, toks, cand_block_hashes, max_gen, chunk)
}
#[cfg(any(test, standalone_blocks))]
#[allow(clippy::too_many_arguments)]
pub fn can_admit_in_namespace(
&mut self,
pools: &BlockPools,
active: &[InflightLaneReserve<'_>],
lane: usize,
namespace: u64,
toks: &[u32],
max_gen: usize,
chunk: usize,
) -> bool {
if active.is_empty() {
return true;
}
let cohort = PreparedInflightCohort::new(active);
self.can_admit_with_cohort_in_namespace(pools, &cohort, lane, namespace, toks, None, max_gen, chunk)
}
#[cfg(any(test, standalone_blocks))]
pub fn can_admit(
&mut self,
pools: &BlockPools,
active: &[InflightLaneReserve<'_>],
lane: usize,
toks: &[u32],
max_gen: usize,
chunk: usize,
) -> bool {
self.can_admit_in_namespace(pools, active, lane, 0, toks, max_gen, chunk)
}
pub fn rebind_if_deeper_match(
&mut self,
pools: &mut BlockPools,
tbl: &mut BlockTable,
state: &mut LaneBlockState,
toks: &[u32],
n_past: usize,
) -> Option<(usize, Vec<u8>)> {
if state.stitched_approx
|| state.written != n_past
|| state.written != state.sealed.len() * BLOCK
|| toks.len() <= 1
{
return None;
}
let namespace = state.namespace;
let search = &toks[..toks.len() - 1];
let mut matched = self.tree.deepest_start_in_namespace(namespace, search);
loop {
if matched.at <= n_past {
return None;
}
let sid = matched.start?;
let all_live = match self.starts.get(&sid) {
Some(st) => {
debug_assert_eq!(st.pos, matched.at);
!st.approx && st.namespace == namespace
&& st.entries.iter().all(|&(kind, _, e)| self.entry_is_valid_kv(pools, kind, e))
}
None => false,
};
if all_live {
break;
}
self.evict_start_inner(pools, sid, false, None, EvictCause::StaleInvalid);
matched = self.tree.deepest_start_in_namespace(namespace, search);
}
let sid = matched.start.expect("validated live start id");
let (cs, entries) = {
let st = self.starts.get(&sid).expect("validated live start exists");
(st.cs.clone(), st.entries.clone())
};
let Ok(mut staged) = BlockTable::new(tbl.blocks_per_kind()) else {
return None;
};
for &(kind, bi, e) in &entries {
if staged.fill(pools.of_mut(kind), bi, e.slot(), e.generation()).is_err() {
let _ = staged.clear_entries(pools);
return None;
}
}
let mut pinned_ids: Vec<SealedId> = Vec::with_capacity(matched.ids.len());
for &id in &matched.ids {
if self.tree.pin(id).is_err() {
for pid in pinned_ids {
self.tree.unpin(pid);
}
let _ = staged.clear_entries(pools);
return None;
}
pinned_ids.push(id);
}
staged.mark_full_sync();
tbl.clear_entries(pools).expect("clear lane block table for rebind");
let old_tip = state.sealed.last().copied();
for id in state.sealed.drain(..) {
self.tree.unpin(id);
}
if let Some(old_tip) = old_tip {
if !pinned_ids.contains(&old_tip) {
self.tree.prune_unreferenced(old_tip);
}
}
self.record_prefix_reuse(&pinned_ids, n_past);
let prompt_len = state.effective_prompt_len(toks.len());
self.note_bound_chain_owner(&pinned_ids, sid, state, prompt_len, matched.at);
Self::drop_turn_checkpoint(pools, state);
state.turn_ckpt_miss = None;
*tbl = staged;
state.prompt_len = prompt_len;
state.sealed = pinned_ids;
state.written = matched.at;
state.stitched_approx = false;
state.approx_path = false;
if !state.internal_resume {
self.stats.start_matches += 1;
self.stats.cached_tokens_total += matched.at as u64;
self.stats.singleflight_rebinds += 1;
self.stats.singleflight_saved_tokens += (matched.at - n_past) as u64;
}
Some((matched.at, cs))
}
#[cfg(any(test, standalone_blocks))]
pub fn match_and_bind_in_namespace(
&mut self,
pools: &mut BlockPools,
tbl: &mut BlockTable,
state: &mut LaneBlockState,
namespace: u64,
toks: &[u32],
) -> Option<(usize, Vec<u8>)> {
state.namespace = namespace; self.match_and_bind(pools, tbl, state, toks)
}
pub fn match_and_bind(
&mut self,
pools: &mut BlockPools,
tbl: &mut BlockTable,
state: &mut LaneBlockState,
toks: &[u32],
) -> Option<(usize, Vec<u8>)> {
debug_assert!(state.sealed.is_empty(), "lane must be released before match_and_bind");
let namespace = state.namespace;
state.prompt_len = state.effective_prompt_len(toks.len());
state.written = 0;
state.stitched_approx = false;
state.approx_path = false;
state.save_owner_turn = 0;
state.prompt_saved_pos = 0;
state.prompt_saved_id = None;
state.bound_start_id = None;
Self::drop_turn_checkpoint(pools, state);
state.turn_ckpt_miss = None;
self.drop_lease_holds(state);
state.reply_saved_pos = 0;
state.reply_saved_id = None;
state.tail_toks.clear();
if toks.len() <= 1 {
return None;
}
let search = &toks[..toks.len() - 1];
let mut in_ram = self.tree.deepest_start_in_namespace(namespace, search); if in_ram.at > 0 {
if let Some(sid) = in_ram.start {
let all_live = match self.starts.get(&sid) {
Some(st) => {
debug_assert_eq!(st.pos, in_ram.at);
!st.approx && st.namespace == namespace
&& st.entries.iter().all(|&(kind, _, e)| self.entry_is_valid_kv(pools, kind, e))
}
None => false,
};
if !all_live {
self.evict_start_inner(pools, sid, false, None, EvictCause::StaleInvalid);
in_ram = self.tree.deepest_start_in_namespace(namespace, search);
}
} else {
in_ram.at = 0;
}
}
let mut restored_tip = None;
if self.spill_store.is_some() && !self.spilled_starts.is_empty() {
let on_disk = self.spilled_tree.deepest_start_in_namespace(namespace, search);
if on_disk.at > in_ram.at {
if let Some(&spill_id) = on_disk.blocks.last() {
restored_tip = self.try_restore_spilled_start(pools, namespace, toks, spill_id, &in_ram);
}
}
}
let restored = restored_tip.and_then(|(tip, published)| published.then_some(tip));
let matched =
if restored_tip.is_some() { self.tree.deepest_start_in_namespace(namespace, search) } else { in_ram };
if let Some(bound) = self.bind_deeper_approx_start(pools, tbl, state, toks, matched.at) {
return Some(bound);
}
self.bind_matched_resident_start(pools, tbl, state, toks.len(), matched, restored)
}
fn bind_resident_start(
&mut self,
pools: &mut BlockPools,
tbl: &mut BlockTable,
state: &mut LaneBlockState,
toks: &[u32],
restored: Option<SealedId>,
) -> Option<(usize, Vec<u8>)> {
state.prompt_len = toks.len();
state.written = 0;
if toks.len() <= 1 {
return None;
}
let matched = self.tree.deepest_start_in_namespace(state.namespace, &toks[..toks.len() - 1]);
let prompt_len = state.effective_prompt_len(toks.len());
self.bind_matched_resident_start(pools, tbl, state, prompt_len, matched, restored)
}
fn bind_matched_resident_start(
&mut self,
pools: &mut BlockPools,
tbl: &mut BlockTable,
state: &mut LaneBlockState,
prompt_len: usize,
matched: crate::prefix::StartMatch<BlockHandles>,
restored: Option<SealedId>,
) -> Option<(usize, Vec<u8>)> {
let namespace = state.namespace;
state.prompt_len = prompt_len;
if matched.at == 0 {
return None;
}
let sid = matched.start?;
let st = self.starts.get(&sid)?;
debug_assert_eq!(st.pos, matched.at);
let all_live =
!st.approx && st.namespace == namespace && st.entries.iter().all(|&(kind, _, e)| self.entry_is_valid_kv(pools, kind, e));
if !all_live {
self.evict_start_inner(pools, sid, false, None, EvictCause::StaleInvalid);
return None;
}
if Some(sid) == restored {
self.tick += 1;
let now = self.tick;
for &anc in &matched.ids {
if let Some(st) = self.starts.get_mut(&anc) {
st.last_used_tick = now;
}
}
} else {
self.record_prefix_reuse(&matched.ids, 0);
}
self.note_bound_chain_owner(&matched.ids, sid, state, prompt_len, matched.at);
let (cs, entries) = {
let st = self.starts.get(&sid).expect("checked start exists");
(st.cs.clone(), st.entries.clone())
};
for &(kind, bi, e) in &entries {
tbl.fill(pools.of_mut(kind), bi, e.slot(), e.generation()).expect("install start-point block");
}
for &id in &matched.ids {
self.tree.pin(id).expect("pin matched prefix block");
}
state.sealed = matched.ids;
state.written = matched.at;
state.stitched_approx = false;
state.approx_path = false;
if !state.internal_resume {
self.stats.start_matches += 1;
self.stats.cached_tokens_total += matched.at as u64;
}
Some((matched.at, cs))
}
fn record_prefix_reuse(&mut self, ids: &[SealedId], n_past: usize) {
self.tick += 1;
let now = self.tick;
for id in ids {
if let Some(st) = self.starts.get_mut(id) {
st.last_used_tick = now;
st.reuse.record(now, st.pos.saturating_sub(n_past));
}
}
}
fn alloc_spill_key(&mut self, kind: BlockKind) -> SpillKey {
self.spill_store.as_mut().expect("spill keys require an open store").fresh_key(to_spill_kind(kind))
}
fn remove_spilled_start(&mut self, spill_id: u64, delete_from_disk: bool) {
if self.remove_spilled_start_inner(spill_id, delete_from_disk) {
self.persist_spill_index();
}
}
fn remove_spilled_start_inner(&mut self, spill_id: u64, delete_from_disk: bool) -> bool {
let Some(sp) = self.spilled_starts.remove(&spill_id) else {
return false;
};
if let Some(tip) = self.spilled_tips.remove(&spill_id) {
let _ = self.spilled_tree.release_start(tip);
self.spilled_tree.prune_unreferenced(tip);
}
for sk in std::iter::once(sp.cs_key).chain(sp.entries.iter().map(|&(_, _, k)| k)) {
let remove_key = if let Some(owners) = self.spill_key_owners.get_mut(&sk) {
owners.retain(|&id| id != spill_id);
owners.is_empty()
} else {
false
};
if remove_key {
self.spill_key_owners.remove(&sk);
if let Some(entry_key) = self.spill_key_to_entry.remove(&sk) {
self.entry_spill_keys.remove(&entry_key);
}
if delete_from_disk && !self.in_flight_restore_keys.contains_key(&sk) {
self.drop_spill_block(sk);
}
}
}
true
}
fn drop_starts_of_gc_evicted(&mut self, evicted: &[SpillKey]) -> bool {
let mut dirty = false;
for &gk in evicted {
if let Some(entry_key) = self.spill_key_to_entry.remove(&gk) {
self.entry_spill_keys.remove(&entry_key);
}
if let Some(owners) = self.spill_key_owners.remove(&gk) {
for oid in owners {
debug_assert!(!self.pending_spills.contains_key(&oid), "disk GC evicted a pending spill's block");
if self.remove_spilled_start_inner(oid, true) {
dirty = true;
}
}
}
}
dirty
}
fn claim_spill_key(&mut self, spill_id: u64, sk: SpillKey, claimed: &mut Vec<SpillKey>) {
let owners = self.spill_key_owners.entry(sk).or_default();
if !owners.contains(&spill_id) {
owners.push(spill_id);
claimed.push(sk);
}
}
fn forget_spill_key_mapping(&mut self, sk: SpillKey) {
if let Some(entry_key) = self.spill_key_to_entry.remove(&sk) {
self.entry_spill_keys.remove(&entry_key);
}
}
fn release_pending_write(&mut self, pools: &mut BlockPools, sk: SpillKey) {
let Some(write) = self.pending_writes.remove(&sk) else {
return;
};
self.spill_queue_bytes = self.spill_queue_bytes.saturating_sub(write.bytes);
if let Some((kind, slot)) = write.pin {
pools.of_mut(kind).record_mut(slot).unwrap().drop_ref().expect("drop a cancelled spill write pin");
}
if let Some(store) = self.spill_store.as_mut() {
store.release_write_reservation(sk);
}
}
fn abort_spill_claims(&mut self, pools: &mut BlockPools, spill_id: u64, claimed: &[SpillKey]) {
for &sk in claimed {
let mut cancel_job = None;
if let Some(write) = self.pending_writes.get_mut(&sk) {
write.waiters.retain(|&id| id != spill_id);
if write.waiters.is_empty() {
cancel_job = Some(write.job);
}
}
let unowned = if let Some(owners) = self.spill_key_owners.get_mut(&sk) {
owners.retain(|&id| id != spill_id);
owners.is_empty()
} else {
false
};
if unowned {
self.spill_key_owners.remove(&sk);
}
if let Some(job) = cancel_job {
if self.spill_writer.as_ref().is_some_and(|writer| writer.cancel(job)) {
self.release_pending_write(pools, sk);
if unowned {
self.forget_spill_key_mapping(sk);
}
}
continue;
}
if unowned && !self.pending_writes.contains_key(&sk) {
self.forget_spill_key_mapping(sk);
if !self.in_flight_restore_keys.contains_key(&sk) {
self.drop_spill_block(sk);
}
}
}
}
fn oldest_trimmable_spilled_start(&self, shield: Option<u64>) -> Option<u64> {
self.spilled_starts
.iter()
.filter(|(id, _)| Some(**id) != shield && !self.in_flight_restore_spills.contains(id))
.min_by_key(|(_, sp)| (sp.last_used_tick, std::cmp::Reverse(sp.pos)))
.map(|(&id, _)| id)
}
fn spilled_start_slot_available(&self, shield: Option<u64>) -> bool {
let over = (self.spilled_starts.len() + 1).saturating_sub(self.max_spilled_starts);
over == 0
|| self
.spilled_starts
.keys()
.filter(|id| Some(**id) != shield && !self.in_flight_restore_spills.contains(id))
.count()
>= over
}
fn queue_spill(
&mut self,
pools: &mut BlockPools,
st: &mut RetainedStart,
restore: Option<&RestoreSource>,
) -> Option<u64> {
if self.spill_store.is_none()
|| st.approx
|| self.max_spilled_starts == 0
|| st.pos == 0
|| !st.pos.is_multiple_of(BLOCK)
|| st.toks.len() != st.pos
|| st.entries.is_empty()
{
return None;
}
if self.spill_write_timeout.is_zero() {
self.stats.spill_write_timeouts += 1;
return None;
}
for &(kind, _, e) in &st.entries {
if !self.entry_is_valid_kv(pools, kind, e) || pools.of(kind).slot_raw_region(e.slot()).is_none() {
return None;
}
}
let shield_spill = restore.map(|source| source.spill_id);
if !self.spilled_start_slot_available(shield_spill) {
return None;
}
let spill_id = self.next_spill_id;
self.next_spill_id = self.next_spill_id.wrapping_add(1).max(1);
let mut protected = self.protected_spill_keys(restore);
let mut claimed_keys: Vec<SpillKey> = Vec::with_capacity(st.entries.len() + 1);
let mut have: HashSet<SpillKey> = HashSet::new();
for &(kind, _, e) in &st.entries {
let ek = (kind_idx(kind) as u8, e.slot().get(), e.generation());
if let Some(&sk) = self.entry_spill_keys.get(&ek) {
let on_disk = self.spill_store.as_ref().is_some_and(|store| store.contains(sk));
if on_disk || self.pending_writes.contains_key(&sk) {
protected.insert(sk);
have.insert(sk);
self.claim_spill_key(spill_id, sk, &mut claimed_keys);
}
}
}
struct NewWrite {
kind: BlockKind,
slot: Slot,
generation: u32,
entry_key: (u8, u32, u32),
key: SpillKey,
bytes: u64,
}
let mut new_writes: Vec<NewWrite> = Vec::new();
let mut spilled_entries: Vec<(BlockKind, BlockIndex, SpillKey)> = Vec::with_capacity(st.entries.len());
let mut total_bytes = SpillStore::block_file_bytes(0, st.cs.len()).ok();
for &(kind, bi, e) in &st.entries {
let entry_key = (kind_idx(kind) as u8, e.slot().get(), e.generation());
if let Some(&key) = self.entry_spill_keys.get(&entry_key).filter(|k| have.contains(k)) {
spilled_entries.push((kind, bi, key));
continue;
}
let key = self.alloc_spill_key(kind);
spilled_entries.push((kind, bi, key));
let bytes = SpillStore::block_file_bytes(pools.of(kind).stride_bytes() as usize, 0).ok();
total_bytes = total_bytes.zip(bytes).map(|(total, bytes)| total.saturating_add(bytes));
new_writes.push(NewWrite {
kind,
slot: e.slot(),
generation: e.generation(),
entry_key,
key,
bytes: bytes.unwrap_or(0),
});
}
let Some(total_bytes) = total_bytes else {
self.abort_spill_claims(pools, spill_id, &claimed_keys);
return None;
};
if self.spill_queue_bytes.saturating_add(total_bytes) > self.max_spill_queue_bytes {
self.stats.spill_writes_dropped_queue_full += new_writes.len() as u64 + 1;
self.abort_spill_claims(pools, spill_id, &claimed_keys);
return None;
}
let fits = self.spill_store.as_ref().is_some_and(|store| {
let after = store.bytes_after_full_gc(&protected).saturating_add(store.reserved_bytes());
after.saturating_add(total_bytes) <= store.max_bytes()
});
if !fits {
if let Some(store) = self.spill_store.as_mut() {
store.note_over_budget_drop();
}
self.abort_spill_claims(pools, spill_id, &claimed_keys);
return None;
}
let timeout_ms = self.spill_write_timeout.as_millis().min(u128::from(u64::MAX)) as u64;
let deadline_ms = self.now_ms().saturating_add(timeout_ms);
let mut waiting = 0usize;
for sk in &claimed_keys {
if let Some(write) = self.pending_writes.get_mut(sk) {
write.waiters.push(spill_id);
waiting += 1;
}
}
for w in new_writes {
let pool = pools.of_mut(w.kind);
let (ptr, len) = pool.slot_raw_region(w.slot).expect("a spilled block has bytes");
let urgent = pool.record(w.slot).is_ok_and(|rec| rec.refs() == 1);
pool.record_mut(w.slot).unwrap().add_ref().expect("pin a block for its spill write");
if let Some(old_key) = self.entry_spill_keys.insert(w.entry_key, w.key) {
self.spill_key_to_entry.remove(&old_key);
}
self.spill_key_to_entry.insert(w.key, w.entry_key);
self.claim_spill_key(spill_id, w.key, &mut claimed_keys);
if let Some(store) = self.spill_store.as_mut() {
store.reserve_write(w.key, w.bytes);
}
let job = self.push_spill_io(
SpillIo::Block {
key: w.key,
generation: u64::from(w.generation),
kv: SpillBytes::Pinned { ptr: ptr as *const u8, len },
state: None,
refuse_existing: true,
},
urgent,
);
self.pending_writes
.insert(w.key, PendingWrite { job, bytes: w.bytes, pin: Some((w.kind, w.slot)), waiters: vec![spill_id] });
self.spill_queue_bytes = self.spill_queue_bytes.saturating_add(w.bytes);
self.stats.spill_writes_queued += 1;
waiting += 1;
}
let cs_key = self.alloc_spill_key(BlockKind::Full);
let cs = std::mem::take(&mut st.cs);
let cs_bytes = SpillStore::block_file_bytes(0, cs.len()).unwrap_or(0);
self.claim_spill_key(spill_id, cs_key, &mut claimed_keys);
if let Some(store) = self.spill_store.as_mut() {
store.reserve_write(cs_key, cs_bytes);
}
let job = self.push_spill_io(
SpillIo::Block {
key: cs_key,
generation: 1,
kv: SpillBytes::Owned(Vec::new()),
state: Some(cs),
refuse_existing: true,
},
true,
);
self.pending_writes.insert(cs_key, PendingWrite { job, bytes: cs_bytes, pin: None, waiters: vec![spill_id] });
self.spill_queue_bytes = self.spill_queue_bytes.saturating_add(cs_bytes);
self.stats.spill_writes_queued += 1;
waiting += 1;
self.pending_spills.insert(
spill_id,
PendingSpill {
start: SpilledStart {
namespace: st.namespace,
pos: st.pos,
reasons: st.reasons,
cs_key,
entries: spilled_entries,
toks: std::mem::take(&mut st.toks),
last_used_tick: st.last_used_tick,
},
prior_fixups: Vec::new(),
claimed_keys,
shield: restore.map(|source| (source.spill_id, source.keys.iter().copied().collect())),
waiting,
deadline_ms,
},
);
Some(spill_id)
}
fn on_spill_block_written(&mut self, pools: &mut BlockPools, key: SpillKey, raw: RawDiskWrite) {
let Some(write) = self.pending_writes.remove(&key) else {
let landed = self.spill_store.as_mut().is_some_and(|store| store.apply_raw_write(key, raw).is_ok());
if !landed {
self.stats.spill_io_errors += 1;
} else if !self.spill_key_owners.contains_key(&key) {
self.forget_spill_key_mapping(key);
if !self.in_flight_restore_keys.contains_key(&key) {
self.drop_spill_block(key);
}
}
return;
};
self.spill_queue_bytes = self.spill_queue_bytes.saturating_sub(write.bytes);
if let Some((kind, slot)) = write.pin {
pools.of_mut(kind).record_mut(slot).unwrap().drop_ref().expect("drop a landed spill write pin");
}
let landed = self.spill_store.as_mut().is_some_and(|store| store.apply_raw_write(key, raw).is_ok());
if !landed {
self.stats.spill_io_errors += 1;
self.spill_key_owners.remove(&key);
self.forget_spill_key_mapping(key);
for spill_id in write.waiters {
self.fail_pending_spill(pools, spill_id);
}
return;
}
if !self.spill_key_owners.contains_key(&key) {
self.forget_spill_key_mapping(key);
if !self.in_flight_restore_keys.contains_key(&key) {
self.drop_spill_block(key);
}
return;
}
for spill_id in write.waiters {
let last = self.pending_spills.get_mut(&spill_id).is_some_and(|pending| {
pending.waiting = pending.waiting.saturating_sub(1);
pending.waiting == 0
});
if last {
self.commit_pending_spill(pools, spill_id);
}
}
}
fn commit_pending_spill(&mut self, pools: &mut BlockPools, spill_id: u64) {
let Some(pending) = self.pending_spills.get(&spill_id) else {
return;
};
let shield_spill = pending.shield.as_ref().map(|(id, _)| *id);
let mut protected = self.protected_spill_keys(None);
if let Some((_, keys)) = &pending.shield {
protected.extend(keys.iter().copied());
}
let in_flight = self.in_flight_spill_bytes(spill_id);
let (all_present, fits) = self.spill_store.as_ref().map_or((false, false), |store| {
let start = &pending.start;
let all_present = store.contains(start.cs_key) && start.entries.iter().all(|&(_, _, sk)| store.contains(sk));
(all_present, store.bytes_after_full_gc(&protected) <= store.max_bytes().saturating_add(in_flight))
});
if !all_present || !fits || !self.spilled_start_slot_available(shield_spill) {
if all_present && !fits {
if let Some(store) = self.spill_store.as_mut() {
store.note_over_budget_drop();
}
}
self.fail_pending_spill(pools, spill_id);
return;
}
let pending = self.pending_spills.remove(&spill_id).expect("checked above");
let st = pending.start;
if let Some(store) = self.spill_store.as_mut() {
for &(_, _, sk) in &st.entries {
store.touch(sk);
}
store.touch(st.cs_key);
}
while self.spilled_starts.len() >= self.max_spilled_starts {
let Some(oldest) = self.oldest_trimmable_spilled_start(shield_spill) else {
break;
};
self.remove_spilled_start_inner(oldest, true);
}
self.settle_spill_budget(spill_id, &protected);
let n_blocks = st.pos / BLOCK;
let mut parent = None;
for b in 0..n_blocks {
let id = self
.spilled_tree
.insert_in_namespace(st.namespace, parent, b * BLOCK, &st.toks[b * BLOCK..(b + 1) * BLOCK], spill_id)
.expect("insert spilled block into spilled_tree");
parent = Some(id);
}
let tip = parent.expect("non-empty spilled blocks");
let spilled_tip = if self.spilled_tree.start_holders(tip) > 0 {
if let Some(old_id) = self.spilled_tree.handle(tip) {
let _ = self.remove_spilled_start_inner(old_id, true);
}
let mut p = None;
for b in 0..n_blocks {
let id = self
.spilled_tree
.insert_in_namespace(st.namespace, p, b * BLOCK, &st.toks[b * BLOCK..(b + 1) * BLOCK], spill_id)
.expect("re-insert spilled block into spilled_tree");
p = Some(id);
}
p.expect("non-empty spilled blocks")
} else {
tip
};
let _ = self.spilled_tree.set_handle(spilled_tip, spill_id);
self.spilled_tree.retain_start(spilled_tip).expect("retain spilled start");
self.spilled_tips.insert(spill_id, spilled_tip);
self.spilled_starts.insert(spill_id, Arc::new(st));
self.stats.starts_spilled += 1;
for fixup in pending.prior_fixups {
if let Some(prior) = self.owner_prior.get_mut(&fixup.owner) {
if prior.seq == fixup.seq {
if fixup.tip {
prior.spilled_tip_id = Some(spilled_tip);
}
if fixup.prompt_tip {
prior.spilled_prompt_tip_id = Some(spilled_tip);
}
}
}
}
self.persist_spill_index();
}
fn fail_pending_spill(&mut self, pools: &mut BlockPools, spill_id: u64) {
let Some(pending) = self.pending_spills.remove(&spill_id) else {
return;
};
self.abort_spill_claims(pools, spill_id, &pending.claimed_keys);
self.stats.spill_starts_dropped += 1;
for fixup in pending.prior_fixups {
if let Some(prior) = self.owner_prior.get_mut(&fixup.owner) {
if prior.seq == fixup.seq
&& prior.tip_id.is_some_and(|id| !self.tree.contains_node(id))
&& prior.spilled_tip_id.is_none_or(|stip| !self.spilled_tree.contains_node(stip))
{
prior.tail_toks.clear();
}
}
}
}
fn collect_spill_results(&mut self, pools: &mut BlockPools) -> usize {
let mut collected = 0usize;
while let Some(done) = self.spill_writer.as_ref().and_then(|writer| writer.try_recv()) {
collected += 1;
match done {
SpillIoDone::Block { key, raw } => self.on_spill_block_written(pools, key, raw),
SpillIoDone::Unlink { result, .. } => {
if result.is_err() {
self.stats.spill_io_errors += 1;
}
}
SpillIoDone::Index { result } => {
self.spill_index_in_flight = false;
if result.is_err() {
self.stats.spill_io_errors += 1;
}
}
}
}
collected
}
pub fn poll_spill_writes(&mut self, pools: &mut BlockPools) -> usize {
if self.spill_writer.is_none() {
return 0;
}
let collected = self.collect_spill_results(pools);
if !self.pending_spills.is_empty() {
let now_ms = self.now_ms();
let mut expired: Vec<u64> =
self.pending_spills.iter().filter(|(_, p)| now_ms >= p.deadline_ms).map(|(&id, _)| id).collect();
expired.sort_unstable();
for spill_id in expired {
self.stats.spill_write_timeouts += 1;
self.fail_pending_spill(pools, spill_id);
}
}
self.flush_spill_index();
collected
}
fn finish_spill_io_inline(&mut self, pools: &mut BlockPools) {
if !self.spill_inline {
return;
}
while self.spill_writer.as_ref().is_some_and(|writer| writer.run_queued(usize::MAX) > 0) {
self.collect_spill_results(pools);
}
}
fn stop_spill_writer(&mut self, pools: &mut BlockPools) {
let Some(writer) = self.spill_writer.as_mut() else {
return;
};
let dropped = writer.stop();
self.spill_inline = true;
self.collect_spill_results(pools);
self.spill_writer = None;
for job in dropped {
match job {
SpillIo::Block { key, .. } => {
self.spill_key_owners.remove(&key);
self.forget_spill_key_mapping(key);
self.release_pending_write(pools, key);
}
SpillIo::Unlink { key } => {
if let Some(store) = self.spill_store.as_ref() {
if unlink_block_in_dir(store.dir(), key).is_err() {
self.stats.spill_io_errors += 1;
}
}
}
SpillIo::Index { .. } => {
self.spill_index_in_flight = false;
self.spill_index_dirty = self.spill_store.is_some();
}
}
}
let unread: Vec<SpillKey> = self.pending_writes.keys().copied().collect();
for sk in unread {
self.spill_key_owners.remove(&sk);
self.forget_spill_key_mapping(sk);
self.release_pending_write(pools, sk);
}
let mut pending: Vec<u64> = self.pending_spills.keys().copied().collect();
pending.sort_unstable();
for spill_id in pending {
self.fail_pending_spill(pools, spill_id);
}
if self.spill_index_dirty || self.spill_index_in_flight {
self.spill_index_dirty = false;
self.spill_index_in_flight = false;
self.persist_spill_index();
}
}
fn try_restore_spilled_start(
&mut self,
pools: &mut BlockPools,
namespace: u64,
toks: &[u32],
spill_id: u64,
in_ram: &crate::prefix::StartMatch<BlockHandles>,
) -> Option<(SealedId, bool)> {
let (sp_ns, pos, reasons, cs_key, entries) = {
let sp = self.spilled_starts.get(&spill_id)?;
(sp.namespace, sp.pos, sp.reasons, sp.cs_key, sp.entries.clone())
};
if sp_ns != namespace || pos == 0 || !pos.is_multiple_of(BLOCK) || pos >= toks.len() {
if pos == 0 || !pos.is_multiple_of(BLOCK) {
self.remove_spilled_start(spill_id, true);
}
return None;
}
let mut reused_full: Vec<(BlockIndex, BlockEntry)> = Vec::new();
let mut disk_entries: Vec<(BlockKind, BlockIndex, SpillKey)> = Vec::new();
for &(kind, bi, sk) in &entries {
if kind == BlockKind::Full {
let b_idx = bi.get() as usize;
if b_idx < in_ram.blocks.len() {
let fe = in_ram.blocks[b_idx].full();
if entry_is_live_sealed(pools, BlockKind::Full, fe) {
reused_full.push((bi, fe));
continue;
}
}
}
disk_entries.push((kind, bi, sk));
}
let need_full = disk_entries.iter().filter(|&&(k, _, _)| k == BlockKind::Full).count();
let need_win = disk_entries.iter().filter(|&&(k, _, _)| k == BlockKind::Window).count();
if (need_full > 0 && pools.full.slab_count() == 0) || (need_win > 0 && pools.window.slab_count() == 0) {
return None;
}
let full_srefs = &self.start_slot_refs[kind_idx(BlockKind::Full)];
let reused_evictable = reused_full
.iter()
.filter(|&&(_, fe)| {
let idx = fe.slot().pool_index().get() as usize;
let sref = full_srefs.get(idx).copied().unwrap_or(0);
pools.full.record(fe.slot()).ok().is_some_and(|r| r.refs() <= sref)
})
.count();
let avail_full = self.free_plus_evictable_slots(pools, BlockKind::Full).saturating_sub(reused_evictable);
let avail_win = self.free_plus_evictable_slots(pools, BlockKind::Window);
if need_full > avail_full || need_win > avail_win {
return None;
}
let restore_began = Instant::now();
let cs = match self.spill_store.as_mut()?.read_block(cs_key, Some(0)) {
ReadOutcome::Hit(blk) => match blk.recurrent_state {
Some(cs) if !cs.is_empty() => cs,
_ => {
self.stats.corrupt_fallbacks += 1;
self.stats.restores_failed += 1;
self.remove_spilled_start(spill_id, true);
return None;
}
},
ReadOutcome::Miss(_) => {
self.stats.corrupt_fallbacks += 1;
self.stats.restores_failed += 1;
self.remove_spilled_start(spill_id, true);
return None;
}
};
let source = RestoreSource {
spill_id,
keys: entries.iter().map(|&(_, _, key)| key).chain(std::iter::once(cs_key)).collect(),
resident_start: in_ram.start,
};
let mut held = Vec::with_capacity(entries.len());
for (bi, fe) in reused_full {
pools.full.record_mut(fe.slot()).unwrap().add_ref().expect("pin reused full block");
held.push((BlockKind::Full, bi, fe));
}
if self.stage_restore_blocks(pools, &source, &disk_entries, &mut held).is_none() {
Self::release_restore_refs(pools, held);
self.stats.restores_failed += 1;
return None;
}
let elapsed_us = restore_began.elapsed().as_micros().min(u128::from(u64::MAX)) as u64;
Some(self.publish_restored_checkpoint(
pools,
spill_id,
namespace,
pos,
reasons,
cs,
&toks[..pos],
held,
elapsed_us,
))
}
#[allow(clippy::too_many_arguments)]
fn publish_restored_checkpoint(
&mut self,
pools: &mut BlockPools,
spill_id: u64,
namespace: u64,
pos: usize,
reasons: u8,
cs: Vec<u8>,
prefix_toks: &[u32],
held: Vec<(BlockKind, BlockIndex, BlockEntry)>,
elapsed_us: u64,
) -> (SealedId, bool) {
let mut full_by_bi: HashMap<u32, BlockEntry> = HashMap::with_capacity(pos / BLOCK);
let mut win_by_bi: HashMap<u32, BlockEntry> = HashMap::with_capacity(WINDOW / BLOCK);
for &(kind, bi, e) in &held {
match kind {
BlockKind::Full => {
full_by_bi.insert(bi.get(), e);
}
BlockKind::Window => {
win_by_bi.insert(bi.get(), e);
}
}
}
let n_blocks = pos / BLOCK;
let win_lo = pos.saturating_sub(WINDOW) / BLOCK;
let mut parent = None;
let mut final_entries = Vec::with_capacity(n_blocks + WINDOW / BLOCK);
for b in 0..n_blocks {
let bi = BlockIndex::new(b as u32);
let full_e = *full_by_bi.get(&(b as u32)).expect("restored full entry");
let win_e_opt = win_by_bi.get(&(b as u32)).copied();
let handles = BlockHandles::new(full_e, win_e_opt);
let id = self
.tree
.insert_in_namespace(namespace, parent, b * BLOCK, &prefix_toks[b * BLOCK..(b + 1) * BLOCK], handles)
.expect("insert restored block into EntryTree");
let canon = self.tree.handle(id).expect("inserted handle");
let canon_f = canon.full();
let best_f = if canon_f != full_e && entry_is_live_sealed(pools, BlockKind::Full, canon_f) {
canon_f
} else {
full_e
};
let best_w = match (win_e_opt, canon.window()) {
(Some(we), Some(cw)) if cw != we && self.entry_is_valid_kv(pools, BlockKind::Window, cw) => Some(cw),
(Some(we), _) => Some(we),
(None, Some(cw)) if self.entry_is_valid_kv(pools, BlockKind::Window, cw) => Some(cw),
(None, _) => None,
};
if best_f != canon_f || best_w != canon.window() {
let _ = self.tree.set_handle(id, BlockHandles::new(best_f, best_w));
}
final_entries.push((BlockKind::Full, bi, best_f));
if b >= win_lo {
if let Some(we) = best_w {
final_entries.push((BlockKind::Window, bi, we));
}
}
parent = Some(id);
}
let tip = parent.expect("non-empty restored start");
self.tick += 1;
let now = self.tick;
let published = !self.starts.contains_key(&tip);
if let Some(existing) = self.starts.get_mut(&tip) {
existing.reasons |= reasons;
existing.last_used_tick = now;
} else {
for &(kind, _, e) in &final_entries {
pools.of_mut(kind).record_mut(e.slot()).unwrap().add_ref().expect("retain restored start point ref");
self.inc_start_slot_ref(kind, e.slot());
}
self.tree.retain_start(tip).expect("retain restored start in EntryTree");
let st = RetainedStart {
namespace,
approx: false,
scope: namespace,
pos,
cs,
reasons,
slot_bytes: Self::checkpoint_slot_bytes(pools, &final_entries),
entries: final_entries,
toks: prefix_toks.to_vec(),
reuse: RecentReuse::default(),
created_tick: None,
last_used_tick: now,
last_owner: 0,
owner_turn: 0,
last_used_ms: 0,
};
self.retained_host_bytes = self.retained_host_bytes.saturating_add(st.host_bytes());
self.starts.insert(tip, st);
self.index_retained_start_for_stitch(tip);
self.enforce_retained_host_budget(pools, Some(tip));
}
Self::release_restore_refs(pools, held); self.remove_spilled_start(spill_id, true);
self.stats.starts_restored += 1;
self.stats.last_restore_us = elapsed_us;
self.stats.restore_us_total = self.stats.restore_us_total.saturating_add(elapsed_us);
(tip, published)
}
pub fn begin_admit_bind_in_namespace(
&mut self,
pools: &mut BlockPools,
lane: usize,
tbl: &mut BlockTable,
state: &mut LaneBlockState,
namespace: u64,
toks: &[u32],
) -> AdmitBindOutcome {
state.namespace = namespace;
self.begin_admit_bind(pools, lane, tbl, state, toks)
}
pub fn begin_admit_bind(
&mut self,
pools: &mut BlockPools,
lane: usize,
tbl: &mut BlockTable,
state: &mut LaneBlockState,
toks: &[u32],
) -> AdmitBindOutcome {
debug_assert!(state.sealed.is_empty(), "lane must be released before begin_admit_bind");
debug_assert!(!self.pending_restores.contains_key(&lane), "lane already restoring");
debug_assert!(!self.pending_ikv_stages.contains_key(&lane), "lane already staging ikv");
let namespace = state.namespace;
state.prompt_len = state.effective_prompt_len(toks.len());
state.written = 0;
state.stitched_approx = false;
state.approx_path = false;
state.bound_lane = Some(lane);
state.save_owner_turn = 0;
state.prompt_saved_pos = 0;
state.prompt_saved_id = None;
state.bound_start_id = None;
Self::drop_turn_checkpoint(pools, state);
state.turn_ckpt_miss = None;
self.drop_lease_holds(state);
state.reply_saved_pos = 0;
state.reply_saved_id = None;
state.tail_toks.clear();
if toks.len() <= 1 {
return AdmitBindOutcome::Immediate(None);
}
let search = &toks[..toks.len() - 1];
let mut in_ram = self.tree.deepest_start_in_namespace(namespace, search);
if in_ram.at > 0 {
if let Some(sid) = in_ram.start {
let all_live = match self.starts.get(&sid) {
Some(st) => {
debug_assert_eq!(st.pos, in_ram.at);
!st.approx && st.namespace == namespace
&& st.entries.iter().all(|&(kind, _, e)| self.entry_is_valid_kv(pools, kind, e))
}
None => false,
};
if !all_live {
self.evict_start_inner(pools, sid, false, None, EvictCause::StaleInvalid);
in_ram = self.tree.deepest_start_in_namespace(namespace, search);
}
} else {
in_ram.at = 0;
}
}
let spilled_at = if self.spill_store.is_some() && !self.spilled_starts.is_empty() {
self.spilled_tree.deepest_start_in_namespace(namespace, search).at
} else {
0
};
if let Some(bound) = self.bind_deeper_approx_start(pools, tbl, state, toks, in_ram.at.max(spilled_at)) {
return AdmitBindOutcome::Immediate(Some(bound));
}
if self.spill_store.is_none() || self.spilled_starts.is_empty() {
return AdmitBindOutcome::Immediate(self.bind_resident_start(pools, tbl, state, toks, None));
}
let on_disk = self.spilled_tree.deepest_start_in_namespace(namespace, search);
if on_disk.at <= in_ram.at {
return AdmitBindOutcome::Immediate(self.bind_resident_start(pools, tbl, state, toks, None));
}
let Some(&spill_id) = on_disk.blocks.last() else {
return AdmitBindOutcome::Immediate(self.bind_resident_start(pools, tbl, state, toks, None));
};
if self.in_flight_restore_spills.contains(&spill_id) {
return AdmitBindOutcome::Immediate(self.bind_resident_start(pools, tbl, state, toks, None));
}
let Some((sp_ns, pos, reasons, cs_key, entries)) = self
.spilled_starts
.get(&spill_id)
.map(|sp| (sp.namespace, sp.pos, sp.reasons, sp.cs_key, sp.entries.clone()))
else {
return AdmitBindOutcome::Immediate(self.bind_resident_start(pools, tbl, state, toks, None));
};
if sp_ns != namespace || pos == 0 || !pos.is_multiple_of(BLOCK) || pos >= toks.len() {
if pos == 0 || !pos.is_multiple_of(BLOCK) {
self.remove_spilled_start(spill_id, true);
}
return AdmitBindOutcome::Immediate(self.bind_resident_start(pools, tbl, state, toks, None));
}
let mut reused_full: Vec<(BlockIndex, BlockEntry)> = Vec::new();
let mut disk_entries: Vec<(BlockKind, BlockIndex, SpillKey)> = Vec::new();
for &(kind, bi, sk) in &entries {
if kind == BlockKind::Full {
let b_idx = bi.get() as usize;
if b_idx < in_ram.blocks.len() {
let fe = in_ram.blocks[b_idx].full();
if entry_is_live_sealed(pools, BlockKind::Full, fe) {
reused_full.push((bi, fe));
continue;
}
}
}
disk_entries.push((kind, bi, sk));
}
let need_full = disk_entries.iter().filter(|&&(k, _, _)| k == BlockKind::Full).count();
let need_win = disk_entries.iter().filter(|&&(k, _, _)| k == BlockKind::Window).count();
if (need_full > 0 && pools.full.slab_count() == 0) || (need_win > 0 && pools.window.slab_count() == 0) {
return AdmitBindOutcome::Immediate(self.bind_resident_start(pools, tbl, state, toks, None));
}
let mut held_reused = Vec::with_capacity(reused_full.len());
for (bi, fe) in reused_full {
pools.full.record_mut(fe.slot()).unwrap().add_ref().expect("pin reused full block for async restore");
held_reused.push((BlockKind::Full, bi, fe));
}
let victims = match self.select_eviction_victims(pools, need_win, need_full, in_ram.start) {
Ok(v) => v,
Err(_) => {
Self::release_restore_refs(pools, held_reused);
self.stats.restores_failed += 1;
return AdmitBindOutcome::Immediate(self.bind_resident_start(pools, tbl, state, toks, None));
}
};
let protected_vec: Vec<SpillKey> = entries.iter().map(|&(_, _, k)| k).chain(std::iter::once(cs_key)).collect();
let source =
RestoreSource { spill_id, keys: protected_vec.iter().copied().collect(), resident_start: in_ram.start };
self.pin_inflight_restore_keys(spill_id, &protected_vec);
for victim in victims {
self.evict_ranked_victim(pools, victim, Some(&source), EvictCause::PoolPressure);
}
if self.evict_past_pending_spills(pools, need_win, need_full, in_ram.start, Some(&source)).is_err() {
Self::release_restore_refs(pools, held_reused);
self.unpin_inflight_restore_keys(spill_id, &protected_vec);
self.stats.restores_failed += 1;
return AdmitBindOutcome::Immediate(self.bind_resident_start(pools, tbl, state, toks, None));
}
let mut reserved_slots = Vec::with_capacity(disk_entries.len());
let mut blocks_for_worker = Vec::with_capacity(disk_entries.len());
for (idx, &(kind, bi, sk)) in disk_entries.iter().enumerate() {
let Ok((slot, generation)) = self.take_zeroed_slot_inner(pools, kind, Some(&source)) else {
Self::release_restore_refs(pools, reserved_slots);
Self::release_restore_refs(pools, held_reused);
self.unpin_inflight_restore_keys(spill_id, &protected_vec);
self.stats.restores_failed += 1;
return AdmitBindOutcome::Immediate(self.bind_resident_start(pools, tbl, state, toks, None));
};
let pool = pools.of_mut(kind);
let expected_len = pool.stride_bytes() as usize;
pool.clear_gpu_zero_pending(slot);
let rec = pool.record_mut(slot).unwrap();
rec.set_length(BLOCK as u32).expect("set reserved restore block length");
rec.seal();
rec.add_ref().expect("pin reserved restore slot");
let offset = pool.offset(slot).expect("reserved restore slot offset");
reserved_slots.push((kind, bi, BlockEntry::new(slot, generation, offset, kind, pool.kvb())));
blocks_for_worker.push((idx, sk, expected_len));
}
let (dir, kvb) = {
let store = self.spill_store.as_ref().expect("checked spill_store");
(store.dir().to_path_buf(), store.kvb())
};
let restore_seq = self.next_restore_seq;
self.next_restore_seq = self.next_restore_seq.wrapping_add(1).max(1);
let cancel_flag = Arc::new(AtomicBool::new(false));
let began = Instant::now();
self.pending_restores.insert(
lane,
PendingRestore {
restore_seq,
spill_id,
namespace,
pos,
reasons,
full_toks: toks.to_vec(),
protected_keys: protected_vec.clone(),
held_reused,
reserved_slots,
loaded_cs: None,
loaded_blocks: 0,
cancel_flag: cancel_flag.clone(),
},
);
let wake = self.shared_wake.clone();
let worker = self.restore_worker.get_or_insert_with(|| RestoreWorker::spawn(wake));
if worker
.job_tx
.as_ref()
.and_then(|tx| {
tx.send(RestoreJob {
lane,
restore_seq,
dir,
kvb,
cs_key,
blocks: blocks_for_worker,
cancel_flag,
began,
})
.ok()
})
.is_none()
{
self.cancel_restore(pools, lane);
return AdmitBindOutcome::Immediate(self.bind_resident_start(pools, tbl, state, toks, None));
}
AdmitBindOutcome::Restoring { target_pos: pos }
}
pub fn has_inflight_restores(&self) -> bool {
!self.pending_restores.is_empty() || !self.pending_ikv_stages.is_empty()
}
pub fn has_pending_ikv_stage(&self, lane: usize) -> bool {
self.pending_ikv_stages.contains_key(&lane)
}
pub fn wait_restore_activity(&mut self, timeout: Duration) {
let wake = self.shared_wake.clone();
wake.wait_timeout(&mut self.last_wake_seq, timeout);
}
pub fn cancel_ikv_stage(&mut self, pools: &mut BlockPools, lane: usize) -> bool {
let Some(ps) = self.pending_ikv_stages.remove(&lane) else {
return false;
};
ps.cancel_flag.store(true, Ordering::Release);
for (slot, _) in ps.reserved_slots {
pools.full.record_mut(slot).unwrap().drop_ref().expect("drop cancelled ikv stage slot ref");
}
true
}
pub fn cancel_restore(&mut self, pools: &mut BlockPools, lane: usize) -> bool {
let mut any = self.cancel_ikv_stage(pools, lane);
if let Some(pr) = self.pending_restores.remove(&lane) {
pr.cancel_flag.store(true, Ordering::Release);
Self::release_restore_refs(pools, pr.reserved_slots);
Self::release_restore_refs(pools, pr.held_reused);
self.unpin_inflight_restore_keys(pr.spill_id, &pr.protected_keys);
any = true;
}
any
}
pub fn cancel_all_restores(&mut self, pools: &mut BlockPools) {
let r_lanes: Vec<usize> = self.pending_restores.keys().copied().collect();
for l in r_lanes {
self.cancel_restore(pools, l);
}
let s_lanes: Vec<usize> = self.pending_ikv_stages.keys().copied().collect();
for l in s_lanes {
self.cancel_ikv_stage(pools, l);
}
}
pub fn poll_restores<F>(&mut self, pools: &mut BlockPools, mut lane_tables: F) -> Vec<CompletedRestore>
where
F: FnMut(usize) -> Option<(&'static (), *mut BlockTable, *mut LaneBlockState)>,
{
let mut ready_msgs = Vec::new();
if let Some(worker) = self.restore_worker.as_ref() {
while let Ok(msg) = worker.msg_rx.try_recv() {
worker.budget.release(msg.budget_bytes);
ready_msgs.push(msg);
}
}
let mut completed = Vec::new();
for msg in ready_msgs {
let is_current = self.pending_restores.get(&msg.lane).is_some_and(|pr| pr.restore_seq == msg.restore_seq);
if !is_current {
match msg.payload {
RestoreMsgPayload::RecurrentState { key, raw }
| RestoreMsgPayload::Block { key, raw, .. }
| RestoreMsgPayload::Aborted { key, raw } => {
if let Some(store) = self.spill_store.as_mut() {
let _ = store.apply_raw_read(key, raw);
}
}
RestoreMsgPayload::Done { .. } => {}
}
continue;
}
match msg.payload {
RestoreMsgPayload::RecurrentState { key, raw } => {
let outcome = self.spill_store.as_mut().map(|s| s.apply_raw_read(key, raw));
if let Some(ReadOutcome::Hit(blk)) = outcome {
if let Some(pr) = self.pending_restores.get_mut(&msg.lane) {
pr.loaded_cs = blk.recurrent_state;
}
}
}
RestoreMsgPayload::Block { idx, key, raw } => {
let outcome = self.spill_store.as_mut().map(|s| s.apply_raw_read(key, raw));
if let Some(ReadOutcome::Hit(blk)) = outcome {
if let Some(pr) = self.pending_restores.get_mut(&msg.lane) {
let (kind, _, entry) = pr.reserved_slots[idx];
let pool = pools.of_mut(kind);
pool.slot_bytes_mut(entry.slot())
.expect("reserved restore slot bytes")
.copy_from_slice(&blk.kv_bytes);
pool.on_slot_restored_from_spill(entry.slot());
pr.loaded_blocks += 1;
}
}
}
RestoreMsgPayload::Done { elapsed } => {
let pr = self.pending_restores.remove(&msg.lane).unwrap();
self.unpin_inflight_restore_keys(pr.spill_id, &pr.protected_keys);
let ok_complete = pr.loaded_cs.as_ref().is_some_and(|c| !c.is_empty())
&& pr.loaded_blocks == pr.reserved_slots.len();
if ok_complete {
let mut held = pr.held_reused;
held.extend(pr.reserved_slots);
let elapsed_us = elapsed.as_micros().min(u128::from(u64::MAX)) as u64;
let cs = pr.loaded_cs.unwrap();
let (tip, published) = self.publish_restored_checkpoint(
pools,
pr.spill_id,
pr.namespace,
pr.pos,
pr.reasons,
cs,
&pr.full_toks[..pr.pos],
held,
elapsed_us,
);
let matched = if let Some((_, tbl_ptr, st_ptr)) = lane_tables(msg.lane) {
let (tbl, st) = unsafe { (&mut *tbl_ptr, &mut *st_ptr) };
st.namespace = pr.namespace;
self.bind_resident_start(pools, tbl, st, &pr.full_toks, published.then_some(tip))
} else {
None
};
completed.push(CompletedRestore { lane: msg.lane, matched, elapsed, corrupt_fallback: false });
} else {
Self::release_restore_refs(pools, pr.reserved_slots);
Self::release_restore_refs(pools, pr.held_reused);
self.stats.corrupt_fallbacks += 1;
self.stats.restores_failed += 1;
self.remove_spilled_start(pr.spill_id, true);
let matched = if let Some((_, tbl_ptr, st_ptr)) = lane_tables(msg.lane) {
let (tbl, st) = unsafe { (&mut *tbl_ptr, &mut *st_ptr) };
st.namespace = pr.namespace;
self.bind_resident_start(pools, tbl, st, &pr.full_toks, None)
} else {
None
};
completed.push(CompletedRestore { lane: msg.lane, matched, elapsed, corrupt_fallback: true });
}
}
RestoreMsgPayload::Aborted { key, raw } => {
if let Some(store) = self.spill_store.as_mut() {
let _ = store.apply_raw_read(key, raw);
}
let pr = self.pending_restores.remove(&msg.lane).unwrap();
pr.cancel_flag.store(true, Ordering::Release);
self.unpin_inflight_restore_keys(pr.spill_id, &pr.protected_keys);
Self::release_restore_refs(pools, pr.reserved_slots);
Self::release_restore_refs(pools, pr.held_reused);
self.stats.corrupt_fallbacks += 1;
self.stats.restores_failed += 1;
self.remove_spilled_start(pr.spill_id, true);
let matched = if let Some((_, tbl_ptr, st_ptr)) = lane_tables(msg.lane) {
let (tbl, st) = unsafe { (&mut *tbl_ptr, &mut *st_ptr) };
st.namespace = pr.namespace;
self.bind_resident_start(pools, tbl, st, &pr.full_toks, None)
} else {
None
};
completed.push(CompletedRestore {
lane: msg.lane,
matched,
elapsed: Duration::ZERO,
corrupt_fallback: true,
});
}
}
}
completed
}
fn stage_restore_blocks(
&mut self,
pools: &mut BlockPools,
source: &RestoreSource,
disk_entries: &[(BlockKind, BlockIndex, SpillKey)],
held: &mut Vec<(BlockKind, BlockIndex, BlockEntry)>,
) -> Option<()> {
let mut verified_before_eviction = false;
for (i, &(kind, bi, key)) in disk_entries.iter().enumerate() {
if !verified_before_eviction && pools.of(kind).lowest_free().is_none() {
for &(remaining_kind, _, remaining_key) in &disk_entries[i..] {
let len = pools.of(remaining_kind).stride_bytes() as usize;
self.read_restore_kv(source.spill_id, remaining_key, len)?;
}
verified_before_eviction = true;
}
let len = pools.of(kind).stride_bytes() as usize;
let bytes = self.read_restore_kv(source.spill_id, key, len)?;
let (slot, generation) = self.take_zeroed_slot_inner(pools, kind, Some(source)).ok()?;
let pool = pools.of_mut(kind);
pool.slot_bytes_mut(slot).ok()?.copy_from_slice(&bytes);
pool.clear_gpu_zero_pending(slot);
let rec = pool.record_mut(slot).unwrap();
rec.set_length(BLOCK as u32).expect("set restored block length");
rec.seal();
rec.add_ref().expect("pin restored block");
pool.on_slot_restored_from_spill(slot);
let offset = pool.offset(slot).expect("restored slot offset");
held.push((kind, bi, BlockEntry::new(slot, generation, offset, kind, pool.kvb())));
}
Some(())
}
fn read_restore_kv(&mut self, spill_id: u64, key: SpillKey, expected_len: usize) -> Option<Vec<u8>> {
match self.spill_store.as_mut()?.read_block(key, Some(expected_len)) {
ReadOutcome::Hit(block) => Some(block.kv_bytes),
ReadOutcome::Miss(_) => {
self.stats.corrupt_fallbacks += 1;
self.remove_spilled_start(spill_id, true);
None
}
}
}
fn release_restore_refs(pools: &mut BlockPools, held: Vec<(BlockKind, BlockIndex, BlockEntry)>) {
for (kind, _, entry) in held {
pools.of_mut(kind).record_mut(entry.slot()).unwrap().drop_ref().expect("drop restore ref");
}
}
fn reclaimable_slots(&self, pools: &BlockPools, kind: BlockKind, protected_start: Option<SealedId>) -> usize {
let Some(psid) = protected_start else {
return self.free_plus_evictable_slots(pools, kind);
};
let Some(pst) = self.starts.get(&psid) else {
return self.free_plus_evictable_slots(pools, kind);
};
let mut protected_refs: HashMap<u32, u32> = HashMap::new();
for &(ekind, _, e) in &pst.entries {
if ekind == kind {
*protected_refs.entry(e.slot().pool_index().get()).or_insert(0) += 1;
}
}
let pool = pools.of(kind);
let srefs = &self.start_slot_refs[kind_idx(kind)];
let mut avail = 0usize;
for i in 0..pool.len() {
let slot = Slot::new((i + 1) as u32).expect("valid pool slot");
let rec = pool.record(slot).expect("pool record");
if rec.generation() < u32::MAX {
let held_by_starts = srefs.get(i).copied().unwrap_or(0);
let held_by_prot = protected_refs.get(&(i as u32)).copied().unwrap_or(0);
if rec.refs() <= held_by_starts.saturating_sub(held_by_prot) {
avail += 1;
}
}
}
avail
}
fn checkpoint_slot_bytes(pools: &BlockPools, entries: &[(BlockKind, BlockIndex, BlockEntry)]) -> u64 {
entries.iter().map(|(kind, _, _)| pools.of(*kind).stride_bytes()).fold(0u64, u64::saturating_add)
}
fn eviction_rank(&self, sid: SealedId, st: &RetainedStart, leased: bool) -> EvictionRank {
let mut rank = self.host_eviction_rank(sid, st, leased);
rank.bytes = rank.bytes.saturating_add(st.slot_bytes);
rank
}
fn host_eviction_rank(&self, sid: SealedId, st: &RetainedStart, leased: bool) -> EvictionRank {
let saved_tokens = st.reuse.saved_tokens(self.tick);
EvictionRank {
leased,
live: self.tree.pin_count(sid) != 0,
recent: saved_tokens != 0
|| st.created_tick.is_some_and(|created| self.tick.saturating_sub(created) < REUSE_EPOCH_TICKS),
saved_tokens,
bytes: st.host_bytes().max(1),
last_used_tick: st.last_used_tick,
pos: st.pos,
sid,
}
}
fn evict_ranked_victim(
&mut self,
pools: &mut BlockPools,
(sid, over_lru): (SealedId, bool),
restore: Option<&RestoreSource>,
cause: EvictCause,
) -> bool {
let evicted = self.evict_start_inner(pools, sid, cause != EvictCause::ApproxScopeCap, restore, cause);
if evicted && over_lru {
self.stats.evictions_ranked_over_lru += 1;
}
evicted
}
fn select_eviction_victims(
&self,
pools: &BlockPools,
need_win: usize,
need_full: usize,
protected_start: Option<SealedId>,
) -> Result<Vec<(SealedId, bool)>, CacheError> {
let mut sim_free = [pools.window.count_free_up_to(need_win), pools.full.count_free_up_to(need_full)];
if sim_free[0] >= need_win && sim_free[1] >= need_full {
return Ok(Vec::new());
}
if sim_free[0] < need_win && need_win > self.reclaimable_slots(pools, BlockKind::Window, protected_start) {
return Err(CacheError::PoolExhausted(BlockKind::Window));
}
if sim_free[1] < need_full && need_full > self.reclaimable_slots(pools, BlockKind::Full, protected_start) {
return Err(CacheError::PoolExhausted(BlockKind::Full));
}
let mut protected_slot_refs: [HashMap<u32, u32>; 2] = [HashMap::new(), HashMap::new()];
if let Some(psid) = protected_start {
if let Some(pst) = self.starts.get(&psid) {
for &(k, _, e) in &pst.entries {
*protected_slot_refs[kind_idx(k)].entry(e.slot().pool_index().get()).or_insert(0) += 1;
}
}
}
let leased = self.leased_starts();
let lru = self.retain_lru;
let mut cands: Vec<EvictionRank> = self
.starts
.iter()
.filter(|(&sid, _)| Some(sid) != protected_start)
.map(|(&sid, st)| self.eviction_rank(sid, st, leased.contains(&sid)))
.collect();
cands.sort_unstable_by(|a, b| a.compare(b, lru));
let can_free_any = |sid: SealedId| {
self.starts[&sid].entries.iter().any(|&(kind, _, e)| {
let ki = kind_idx(kind);
let idx = e.slot().pool_index().get();
let Ok(rec) = pools.of(kind).record(e.slot()) else {
return false;
};
if rec.generation() != e.generation() || rec.generation() == u32::MAX || rec.refs() == 0 {
return false;
}
let sref = self.start_slot_refs[ki].get(idx as usize).copied().unwrap_or(0);
let pref = protected_slot_refs[ki].get(&idx).copied().unwrap_or(0);
rec.refs() <= sref.saturating_sub(pref)
})
};
let mut dropped: [HashMap<u32, u32>; 2] = [HashMap::new(), HashMap::new()];
let mut victims = Vec::new();
for cand in &cands {
let sid = cand.sid;
let st = &self.starts[&sid];
if !can_free_any(sid) {
continue;
}
victims.push(sid);
for &(kind, _, e) in &st.entries {
let ki = kind_idx(kind);
let idx = e.slot().pool_index().get();
if let Ok(rec) = pools.of(kind).record(e.slot()) {
if rec.generation() == e.generation() && rec.generation() < u32::MAX && rec.refs() > 0 {
let d = dropped[ki].entry(idx).or_insert(0);
*d += 1;
if *d == rec.refs() {
sim_free[ki] += 1;
}
}
}
}
if sim_free[0] >= need_win && sim_free[1] >= need_full {
break;
}
}
if sim_free[0] < need_win {
return Err(CacheError::PoolExhausted(BlockKind::Window));
}
if sim_free[1] < need_full {
return Err(CacheError::PoolExhausted(BlockKind::Full));
}
if lru {
return Ok(victims.into_iter().map(|sid| (sid, false)).collect());
}
cands.sort_unstable_by(EvictionRank::lru_cmp);
let lru_first: HashSet<SealedId> =
cands.iter().map(|c| c.sid).filter(|&sid| can_free_any(sid)).take(victims.len()).collect();
Ok(victims.into_iter().map(|sid| (sid, !lru_first.contains(&sid))).collect())
}
pub fn can_satisfy_span(&self, pools: &BlockPools, tbl: &BlockTable, p0: usize, t: usize) -> bool {
self.span_shortfall(pools, tbl, p0, t) == Some([0, 0])
}
pub fn span_shortfall(&self, pools: &BlockPools, tbl: &BlockTable, p0: usize, t: usize) -> Option<[usize; 2]> {
if t == 0 {
return Some([0, 0]);
}
let lo_blk = p0 / BLOCK;
let hi_blk = (p0 + t - 1) / BLOCK;
let mut need = [0usize; 2];
for b in lo_blk..=hi_blk {
let bi = BlockIndex::new(b as u32);
for kind in KINDS {
if tbl.get(kind, bi).ok()?.is_none() {
need[kind_idx(kind)] += 1;
}
}
}
for kind in KINDS {
let n = &mut need[kind_idx(kind)];
if *n > 0 {
*n = n.saturating_sub(self.reclaimable_slots(pools, kind, None));
}
}
Some(need)
}
pub fn lane_exclusive_slots(&self, pools: &BlockPools, tbl: &BlockTable) -> [usize; 2] {
let mut exclusive = [0usize; 2];
for (_, e) in tbl.entries() {
let ki = kind_idx(e.kind());
let Ok(rec) = pools.of(e.kind()).record(e.slot()) else { continue };
let held_by_starts = self.start_slot_refs[ki].get(e.slot().pool_index().get() as usize).copied().unwrap_or(0);
if rec.generation() == e.generation() && rec.refs() == held_by_starts + 1 {
exclusive[ki] += 1;
}
}
exclusive
}
pub fn kind_slot(kind: BlockKind) -> usize {
kind_idx(kind)
}
#[allow(dead_code)]
fn evict_start(&mut self, pools: &mut BlockPools, sid: SealedId) -> bool {
self.evict_start_inner(pools, sid, true, None, EvictCause::PoolPressure)
}
#[cfg(test)]
pub(crate) fn evict_all_starts_for_test(&mut self, pools: &mut BlockPools) -> usize {
let sids: Vec<SealedId> = self.starts.keys().copied().collect();
let mut n = 0usize;
for sid in sids {
if self.evict_start(pools, sid) {
n += 1;
}
}
n
}
fn evict_start_inner(
&mut self,
pools: &mut BlockPools,
sid: SealedId,
allow_spill: bool,
restore: Option<&RestoreSource>,
cause: EvictCause,
) -> bool {
let began_us = self.now_us();
let Some(mut st) = self.starts.remove(&sid) else {
return false;
};
self.unindex_retained_start_for_stitch(sid, st.namespace, &st.toks);
if st.approx {
if let Some(n) = self.approx_per_scope.get_mut(&st.scope) {
*n = n.saturating_sub(1);
if *n == 0 {
self.approx_per_scope.remove(&st.scope);
}
}
}
self.retained_host_bytes = self.retained_host_bytes.saturating_sub(st.host_bytes());
let queued_spill = if allow_spill && self.spill_store.is_some() && !st.approx {
let queued = self.queue_spill(pools, &mut st, restore);
if queued.is_none() {
self.stats.spill_starts_dropped += 1;
}
queued
} else {
None
};
let _ = self.tree.release_start(sid);
for (kind, _, e) in st.entries {
self.dec_start_slot_ref(kind, e.slot());
let pool = pools.of_mut(kind);
if let Ok(rec) = pool.record(e.slot()) {
if rec.generation() == e.generation() && rec.refs() > 0 {
pool.record_mut(e.slot()).unwrap().drop_ref().unwrap();
}
}
}
self.tree.prune_unreferenced(sid);
let mut prior_fixups: Vec<PriorFixup> = Vec::new();
if let Some(owners) = self.prior_checkpoint_owners.get(&sid).cloned() {
for owner in owners {
if let Some(p) = self.owner_prior.get_mut(&owner) {
let (tip, prompt_tip) = (p.tip_id == Some(sid), p.prompt_tip_id == Some(sid));
if queued_spill.is_some() && (tip || prompt_tip) {
prior_fixups.push(PriorFixup { owner, seq: p.seq, tip, prompt_tip });
}
if p.prompt_tip_id == Some(sid) || p.reply_tip_id == Some(sid) {
p.evicted = true;
}
if !(queued_spill.is_some() && tip)
&& p.tip_id.is_some_and(|id| !self.tree.contains_node(id))
&& p.spilled_tip_id.is_none_or(|stip| !self.spilled_tree.contains_node(stip))
{
p.tail_toks.clear();
}
}
}
if !self.tree.contains_node(sid) {
self.prior_checkpoint_owners.remove(&sid);
}
}
if let Some(pending) = queued_spill.and_then(|spill_id| self.pending_spills.get_mut(&spill_id)) {
pending.prior_fixups = prior_fixups;
}
self.stats.start_points_evicted += 1;
match cause {
EvictCause::PoolPressure => self.stats.evictions_pool_pressure += 1,
EvictCause::HostBudget => self.stats.evictions_host_budget += 1,
EvictCause::ApproxScopeCap => self.stats.evictions_approx_scope_cap += 1,
EvictCause::StaleInvalid => self.stats.evictions_stale_invalid += 1,
EvictCause::Shutdown => self.stats.evictions_shutdown += 1,
EvictCause::Superseded => self.stats.evictions_superseded += 1,
}
self.finish_spill_io_inline(pools);
let took_us = self.now_us().saturating_sub(began_us);
self.stats.evict_us_total = self.stats.evict_us_total.saturating_add(took_us);
self.stats.evict_us_max = self.stats.evict_us_max.max(took_us);
true
}
fn evict_past_pending_spills(
&mut self,
pools: &mut BlockPools,
need_win: usize,
need_full: usize,
protected_start: Option<SealedId>,
restore: Option<&RestoreSource>,
) -> Result<(), CacheError> {
while !self.pending_writes.is_empty() {
let victims = self.select_eviction_victims(pools, need_win, need_full, protected_start)?;
if victims.is_empty() {
break;
}
for victim in victims {
self.evict_ranked_victim(pools, victim, restore, EvictCause::PoolPressure);
}
}
Ok(())
}
fn evict_for_slots(
&mut self,
pools: &mut BlockPools,
need_win: usize,
need_full: usize,
protected_start: Option<SealedId>,
) -> Result<(), CacheError> {
let victims = self.select_eviction_victims(pools, need_win, need_full, protected_start)?;
for victim in victims {
self.evict_ranked_victim(pools, victim, None, EvictCause::PoolPressure);
}
self.evict_past_pending_spills(pools, need_win, need_full, protected_start, None)
}
fn enforce_approx_scope_cap(&mut self, pools: &mut BlockPools, scope: u64, protect: Option<SealedId>) {
while self.approx_per_scope.get(&scope).copied().unwrap_or(0) > self.max_approx_starts_per_scope {
let leased = self.leased_starts();
let cands: Vec<EvictionRank> = self
.starts
.iter()
.filter(|(sid, st)| st.approx && st.scope == scope && Some(**sid) != protect)
.map(|(&sid, st)| self.eviction_rank(sid, st, leased.contains(&sid)))
.collect();
let Some(victim) = pick_ranked_victim(&cands, self.retain_lru) else { break };
if !self.evict_ranked_victim(pools, victim, None, EvictCause::ApproxScopeCap) {
break;
}
}
}
#[cfg(any(test, standalone_blocks))]
pub fn set_max_approx_starts_per_scope(&mut self, cap: usize) {
self.max_approx_starts_per_scope = cap.max(1);
}
fn enforce_retained_host_budget(&mut self, pools: &mut BlockPools, protect_sid: Option<SealedId>) {
while self.retained_host_bytes > self.max_retained_host_bytes {
let Some(victim) = self.host_trim_victim(protect_sid) else {
break;
};
self.evict_ranked_victim(pools, victim, None, EvictCause::HostBudget);
}
}
fn host_trim_victim(&self, protect_sid: Option<SealedId>) -> Option<(SealedId, bool)> {
let leased = self.leased_starts();
let cands: Vec<EvictionRank> = self
.starts
.iter()
.filter(|(&sid, _)| !(protect_sid == Some(sid) && self.max_retained_host_bytes > 0))
.map(|(&sid, st)| self.host_eviction_rank(sid, st, leased.contains(&sid)))
.collect();
pick_ranked_victim(&cands, self.retain_lru)
}
#[cfg(test)]
fn evict_one_lru_start_inner(
&mut self,
pools: &mut BlockPools,
allow_spill: bool,
restore: Option<&RestoreSource>,
) -> bool {
self.evict_one_lru_start_with_cause(pools, allow_spill, restore, EvictCause::PoolPressure)
}
fn evict_one_lru_start_with_cause(
&mut self,
pools: &mut BlockPools,
allow_spill: bool,
restore: Option<&RestoreSource>,
cause: EvictCause,
) -> bool {
let leased = self.leased_starts();
let victim = self
.starts
.iter()
.filter(|(&sid, _)| !restore.is_some_and(|source| source.resident_start == Some(sid)))
.min_by_key(|(sid, st)| (leased.contains(sid), st.last_used_tick, std::cmp::Reverse(st.pos)))
.map(|(&sid, _)| sid);
let Some(sid) = victim else {
return false;
};
self.evict_start_inner(pools, sid, allow_spill, restore, cause)
}
#[cfg(any(test, standalone_blocks))]
pub fn take_zeroed_slot(&mut self, pools: &mut BlockPools, kind: BlockKind) -> Result<(Slot, u32), CacheError> {
self.take_zeroed_slot_inner(pools, kind, None)
}
fn take_zeroed_slot_inner(
&mut self,
pools: &mut BlockPools,
kind: BlockKind,
restore: Option<&RestoreSource>,
) -> Result<(Slot, u32), CacheError> {
if let Some(slot) = pools.of(kind).lowest_free() {
let pool = pools.of_mut(kind);
let _ = pool.take_unzeroed(slot).expect("take slot");
let gen = pool.record(slot).unwrap().generation();
self.stats.slots_taken += 1;
if gen > 1 {
self.stats.slots_reused += 1;
}
return Ok((slot, gen));
}
let need_win = usize::from(kind == BlockKind::Window);
let need_full = usize::from(kind == BlockKind::Full);
let protected_start = restore.and_then(|r| r.resident_start);
let victims = self.select_eviction_victims(pools, need_win, need_full, protected_start)?;
for victim in victims {
self.evict_ranked_victim(pools, victim, restore, EvictCause::PoolPressure);
}
self.evict_past_pending_spills(pools, need_win, need_full, protected_start, restore)?;
let Some(slot) = pools.of(kind).lowest_free() else {
return Err(CacheError::PoolExhausted(kind));
};
let pool = pools.of_mut(kind);
let _ = pool.take_unzeroed(slot).expect("take slot");
let gen = pool.record(slot).unwrap().generation();
self.stats.slots_taken += 1;
if gen > 1 {
self.stats.slots_reused += 1;
}
Ok((slot, gen))
}
pub fn ensure_span_blocks(
&mut self,
pools: &mut BlockPools,
tbl: &mut BlockTable,
p0: usize,
t: usize,
) -> Result<(), CacheError> {
self.try_ensure_span_blocks_with(pools, tbl, p0, t, |_, _| Ok(())).map(|_| ())
}
pub fn ensure_span_blocks_tracking(
&mut self,
pools: &mut BlockPools,
tbl: &mut BlockTable,
p0: usize,
t: usize,
) -> Result<Vec<(BlockKind, BlockIndex)>, CacheError> {
self.try_ensure_span_blocks_with(pools, tbl, p0, t, |_, _| Ok(()))
}
pub(crate) fn try_ensure_span_blocks_with<F>(
&mut self,
pools: &mut BlockPools,
tbl: &mut BlockTable,
p0: usize,
t: usize,
mut pre_step: F,
) -> Result<Vec<(BlockKind, BlockIndex)>, CacheError>
where
F: FnMut(usize, BlockKind) -> Result<(), CacheError>,
{
debug_assert!(t >= 1);
let lo_blk = p0 / BLOCK;
let hi_blk = (p0 + t - 1) / BLOCK;
let mut missing: Vec<(BlockKind, BlockIndex)> = Vec::new();
let mut need_win = 0usize;
let mut need_full = 0usize;
for b in lo_blk..=hi_blk {
let bi = BlockIndex::new(b as u32);
for kind in KINDS {
let existing = tbl.get(kind, bi).expect("block in table range");
if let Some(entry) = existing {
let rec = pools.of(kind).record(entry.slot()).expect("existing slot record");
assert_eq!(rec.generation(), entry.generation(), "stale entry in active lane table");
assert!(!rec.sealed(), "attempt to write into sealed {kind:?} block {b}");
} else {
missing.push((kind, bi));
match kind {
BlockKind::Window => need_win += 1,
BlockKind::Full => need_full += 1,
}
}
}
}
if missing.is_empty() {
return Ok(Vec::new());
}
let victims = self.select_eviction_victims(pools, need_win, need_full, None)?;
let mut newly_allocated: Vec<(BlockKind, BlockIndex)> = Vec::with_capacity(missing.len());
let mut deferred_after_eviction: Vec<(BlockKind, BlockIndex)> = Vec::new();
for (kind, bi) in missing {
if let Err(err) = pre_step(bi.get() as usize, kind) {
for (rk, rbi) in newly_allocated.into_iter().rev() {
tbl.clear_kind_entry(pools.of_mut(rk), rbi) .expect("rollback newly allocated block entry");
}
return Err(err);
}
if let Some(slot) = pools.of(kind).lowest_free() {
let pool = pools.of_mut(kind);
let _ = pool.take_unzeroed(slot).expect("take slot");
let gen = pool.record(slot).unwrap().generation();
self.stats.slots_taken += 1;
if gen > 1 {
self.stats.slots_reused += 1;
}
tbl.fill(pool, bi, slot, gen).expect("fill newly taken free slot");
newly_allocated.push((kind, bi));
} else {
deferred_after_eviction.push((kind, bi));
}
}
if !deferred_after_eviction.is_empty() {
for victim in victims {
self.evict_ranked_victim(pools, victim, None, EvictCause::PoolPressure);
}
let still_win = deferred_after_eviction.iter().filter(|(kind, _)| *kind == BlockKind::Window).count();
let still_full = deferred_after_eviction.len() - still_win;
if let Err(err) = self.evict_past_pending_spills(pools, still_win, still_full, None, None) {
for (rk, rbi) in newly_allocated.into_iter().rev() {
tbl.clear_kind_entry(pools.of_mut(rk), rbi).expect("rollback newly allocated block entry");
}
return Err(err);
}
for (kind, bi) in deferred_after_eviction {
let Some(slot) = pools.of(kind).lowest_free() else {
for (rk, rbi) in newly_allocated.into_iter().rev() {
tbl.clear_kind_entry(pools.of_mut(rk), rbi).expect("rollback newly allocated block entry");
}
return Err(CacheError::PoolExhausted(kind));
};
let pool = pools.of_mut(kind);
let _ = pool.take_unzeroed(slot).expect("take slot");
let gen = pool.record(slot).unwrap().generation();
self.stats.slots_taken += 1;
if gen > 1 {
self.stats.slots_reused += 1;
}
tbl.fill(pool, bi, slot, gen).expect("fill newly evicted slot");
newly_allocated.push((kind, bi));
}
}
Ok(newly_allocated)
}
fn prune_expired_window(&mut self, pools: &mut BlockPools, tbl: &mut BlockTable, start: usize, end: usize) {
for b in newly_expired_window_blocks(start, end) {
let bi = BlockIndex::new(b as u32);
if tbl.get(BlockKind::Window, bi).expect("window block in range").is_some() {
tbl.clear_kind_entry(&mut pools.window, bi).expect("prune expired window block");
self.stats.window_pruned += 1;
}
}
}
pub fn finish_prefill_span<F>(
&mut self,
pools: &mut BlockPools,
tbl: &mut BlockTable,
state: &mut LaneBlockState,
toks: &[u32],
p0: usize,
t: usize,
read_cs: F,
) where
F: FnOnce() -> Vec<u8>,
{
let end = p0 + t;
state.written = end;
let sealing = !state.stitched_approx || state.approx_path;
let seal_ns = if state.approx_path { approx_namespace(state.namespace, state.owner) } else { state.namespace };
let lo_blk = p0 / BLOCK;
let hi_blk = (end - 1) / BLOCK;
for b in lo_blk..=hi_blk {
let bi = BlockIndex::new(b as u32);
let block_len = (end - b * BLOCK).min(BLOCK) as u32;
let full_e = tbl.get(BlockKind::Full, bi).unwrap().expect("full entry");
let win_e = tbl.get(BlockKind::Window, bi).unwrap().expect("window entry");
for (kind, e) in [(BlockKind::Full, full_e), (BlockKind::Window, win_e)] {
let rec = pools.of_mut(kind).record_mut(e.slot()).unwrap();
rec.set_length(block_len).expect("set block length");
if block_len == BLOCK as u32 {
rec.seal();
}
}
if block_len == BLOCK as u32 {
self.stats.blocks_sealed += 1;
if sealing && (b == 0 || state.sealed.len() == b) {
let parent = if b == 0 { None } else { state.sealed.get(b - 1).copied() };
let blk_toks = &toks[b * BLOCK..(b + 1) * BLOCK];
let handles = BlockHandles::new(full_e, Some(win_e));
let id = self
.tree
.insert_in_namespace(seal_ns, parent, b * BLOCK, blk_toks, handles)
.expect("insert sealed block into EntryTree");
let canon = self.tree.handle(id).expect("inserted handle");
let canon_f = canon.full();
let canon_w = canon.window();
let mut best_f = full_e;
let mut best_w = win_e;
if canon_f != full_e && entry_is_live_sealed(pools, BlockKind::Full, canon_f) {
tbl.fill(&mut pools.full, bi, canon_f.slot(), canon_f.generation())
.expect("share canonical full block");
best_f = canon_f;
self.stats.shared_dedups += 1;
}
if let Some(canon_w) =
canon_w.filter(|&w| w != win_e && self.entry_is_valid_kv(pools, BlockKind::Window, w))
{
tbl.fill(&mut pools.window, bi, canon_w.slot(), canon_w.generation())
.expect("share canonical window block");
best_w = canon_w;
}
if best_f != canon_f || Some(best_w) != canon_w {
let _ = self.tree.set_handle(id, BlockHandles::new(best_f, Some(best_w)));
}
self.tree.pin(id).expect("pin newly sealed block");
if state.sealed.len() == b {
state.sealed.push(id);
} else {
let old = state.sealed[b];
if old != id {
self.tree.unpin(old);
}
state.sealed[b] = id;
}
}
}
}
if sealing && end > 0 && end.is_multiple_of(BLOCK) && state.sealed.len() == end / BLOCK {
let reasons = start_reasons(end, state.prompt_len, state.approx_path);
if reasons != 0 {
let tip = *state.sealed.last().unwrap();
self.tick += 1;
let now = self.tick;
let lease_ms = self.card_lease.as_millis().min(u64::MAX as u128) as u64;
let (save_turn, now_ms) = if lease_ms > 0 && state.owner != 0 && (reasons & PROMPT) != 0 {
(self.ensure_save_owner_turn(state), self.now_ms())
} else {
(0, 0)
};
let can_claim_existing = save_turn != 0
&& self
.starts
.get(&tip)
.is_some_and(|st| {
st.last_owner == state.owner || !self.is_start_leased_at(tip, st, now_ms, lease_ms)
});
let keep_toks = (self.spill_store.is_some() || self.kv_stitch) && !state.approx_path;
let mut check_host_budget = false;
if let Some(existing) = self.starts.get_mut(&tip) {
existing.reasons |= reasons;
existing.last_used_tick = now;
if can_claim_existing {
existing.last_owner = state.owner;
existing.owner_turn = save_turn;
existing.last_used_ms = now_ms;
}
if keep_toks && existing.toks.is_empty() {
let added = (end as u64).saturating_mul(4);
existing.toks = toks[..end].to_vec();
self.retained_host_bytes = self.retained_host_bytes.saturating_add(added);
if !existing.approx {
self.index_retained_start_for_stitch(tip);
}
check_host_budget = true;
}
} else {
let mut entries = Vec::with_capacity(end / BLOCK + WINDOW / BLOCK);
for b in 0..(end / BLOCK) {
let bi = BlockIndex::new(b as u32);
let fe = tbl.get(BlockKind::Full, bi).unwrap().expect("start point full block");
entries.push((BlockKind::Full, bi, fe));
}
let win_lo = end.saturating_sub(WINDOW) / BLOCK;
for b in win_lo..(end / BLOCK) {
let bi = BlockIndex::new(b as u32);
let we = tbl.get(BlockKind::Window, bi).unwrap().expect("start point window block");
entries.push((BlockKind::Window, bi, we));
}
if entries.iter().all(|&(kind, _, e)| self.entry_is_valid_kv(pools, kind, e)) {
let cs = read_cs();
for &(kind, _, e) in &entries {
pools.of_mut(kind).record_mut(e.slot()).unwrap().add_ref().expect("retain start point ref");
self.inc_start_slot_ref(kind, e.slot()); }
self.tree.retain_start(tip).expect("retain start in EntryTree");
let st = RetainedStart {
namespace: seal_ns,
approx: state.approx_path,
scope: state.namespace,
pos: end,
cs,
reasons,
slot_bytes: Self::checkpoint_slot_bytes(pools, &entries),
entries,
toks: if keep_toks { toks[..end].to_vec() } else { Vec::new() },
reuse: RecentReuse::default(),
created_tick: Some(now),
last_used_tick: now,
last_owner: if save_turn != 0 { state.owner } else { 0 },
owner_turn: save_turn,
last_used_ms: now_ms,
};
self.retained_host_bytes = self.retained_host_bytes.saturating_add(st.host_bytes());
self.starts.insert(tip, st);
if state.approx_path {
self.stats.approx_starts_saved += 1;
*self.approx_per_scope.entry(state.namespace).or_insert(0) += 1;
self.enforce_approx_scope_cap(pools, state.namespace, Some(tip));
} else {
self.index_retained_start_for_stitch(tip);
self.stats.start_points_saved += 1;
}
check_host_budget = true;
}
}
if (reasons & PROMPT) != 0 && end >= state.prompt_saved_pos && self.starts.contains_key(&tip) {
state.prompt_saved_pos = end;
state.prompt_saved_id = Some(tip);
self.hold_start(state, tip);
}
if check_host_budget {
self.enforce_retained_host_budget(pools, Some(tip));
}
}
}
if state.owner != 0 && end <= toks.len() {
let sealed_end = state.sealed.len() * BLOCK;
state.tail_toks.clear();
if end >= sealed_end && end - sealed_end < BLOCK {
state.tail_toks.extend_from_slice(&toks[sealed_end..end]);
}
}
self.prune_expired_window(pools, tbl, p0, end);
}
#[allow(clippy::too_many_arguments)]
pub fn finish_prefill_span_through<F, G>(
&mut self,
pools: &mut BlockPools,
tbl: &mut BlockTable,
state: &mut LaneBlockState,
toks: &[u32],
p0: usize,
t: usize,
ckpts: &[usize],
read_kept: G,
read_cs: F,
) where
F: FnOnce() -> Vec<u8>,
G: Fn(usize) -> Vec<u8>,
{
let mut read_cs = Some(read_cs);
for (lo, hi, at) in finish_parts(p0, t, ckpts) {
match at {
StateAt::Kept(m) => self.finish_prefill_span(pools, tbl, state, toks, lo, hi - lo, || read_kept(m)),
StateAt::End => self.finish_prefill_span(pools, tbl, state, toks, lo, hi - lo, read_cs.take().unwrap()),
}
}
}
pub fn finish_decode_span(
&mut self,
pools: &mut BlockPools,
tbl: &mut BlockTable,
state: &mut LaneBlockState,
pos: usize,
) {
let end = pos + 1;
state.written = end;
let b = pos / BLOCK;
let bi = BlockIndex::new(b as u32);
let block_len = (end - b * BLOCK).min(BLOCK) as u32;
for kind in KINDS {
let e = tbl.get(kind, bi).unwrap().expect("decode block entry");
pools.of_mut(kind).record_mut(e.slot()).unwrap().set_length(block_len).expect("set decode length");
}
self.prune_expired_window(pools, tbl, pos, end);
}
pub fn seal_decode_block<F>(
&mut self,
pools: &mut BlockPools,
tbl: &BlockTable,
state: &mut LaneBlockState,
toks: &[u32],
pos: usize,
read_cs: F,
) where
F: FnOnce() -> Vec<u8>,
{
self.seal_verify_step(pools, tbl, state, toks, pos, None, read_cs);
}
pub fn keeps_turn_end_start(&self, state: &LaneBlockState) -> bool {
self.approx_retain && state.owner != 0
}
#[allow(clippy::too_many_arguments)]
pub fn seal_verify_step<F>(
&mut self,
pools: &mut BlockPools,
tbl: &BlockTable,
state: &mut LaneBlockState,
toks: &[u32],
pos: usize,
crossed: Option<(usize, Vec<u8>)>,
read_cs: F,
) where
F: FnOnce() -> Vec<u8>,
{
let end = pos + 1;
if !self.keeps_turn_end_start(state) || toks.len() < end {
return;
}
debug_assert_ne!(approx_namespace(state.namespace, state.owner), state.namespace);
let mut done = state.sealed.len();
let mut entries: Vec<(BlockEntry, BlockEntry)> = Vec::new();
while (done + 1) * BLOCK <= end {
let bi = BlockIndex::new(done as u32);
let (Some(fe), Some(we)) =
(tbl.get(BlockKind::Full, bi).ok().flatten(), tbl.get(BlockKind::Window, bi).ok().flatten())
else {
break;
};
let full = [(BlockKind::Full, fe), (BlockKind::Window, we)]
.iter()
.all(|&(kind, e)| pools.of(kind).record(e.slot()).is_ok_and(|r| r.length() == BLOCK as u32));
if !full {
break;
}
for (kind, e) in [(BlockKind::Full, fe), (BlockKind::Window, we)] {
pools.of_mut(kind).record_mut(e.slot()).unwrap().seal();
}
entries.push((fe, we));
done += 1;
}
if !state.approx_path {
if entries.is_empty() {
return;
}
state.stitched_approx = true;
self.enter_approx_path(pools, tbl, state, toks);
if !state.approx_path {
return;
}
} else {
let ns = approx_namespace(state.namespace, state.owner);
for (fe, we) in entries {
let b = state.sealed.len();
let parent = if b == 0 { None } else { state.sealed.get(b - 1).copied() };
let we_opt = self.entry_is_valid_kv(pools, BlockKind::Window, we).then_some(we);
let Ok(id) = self.tree.insert_in_namespace(
ns,
parent,
b * BLOCK,
&toks[b * BLOCK..(b + 1) * BLOCK],
BlockHandles::new(fe, we_opt),
) else {
return;
};
if let Some(canon) = self.tree.handle(id) {
let full_stale = !self.entry_is_valid_kv(pools, BlockKind::Full, canon.full());
let win_stale = canon
.window()
.is_some_and(|cw| !self.entry_is_valid_kv(pools, BlockKind::Window, cw));
if full_stale || win_stale || (canon.window().is_none() && we_opt.is_some()) {
let best_f = if full_stale { fe } else { canon.full() };
let best_w = if win_stale || canon.window().is_none() { we_opt } else { canon.window() };
let _ = self.tree.set_handle(id, BlockHandles::new(best_f, best_w));
}
}
if self.tree.pin(id).is_err() {
self.tree.prune_unreferenced(id);
return;
}
state.sealed.push(id);
}
}
if state.owner != 0 && end <= toks.len() {
let sealed_end = state.sealed.len() * BLOCK;
state.tail_toks.clear();
if end >= sealed_end && end - sealed_end < BLOCK {
state.tail_toks.extend_from_slice(&toks[sealed_end..end]);
}
}
let boundary = if end >= BLOCK && end.is_multiple_of(BLOCK) {
Some((end, None))
} else {
crossed
.filter(|&(at, _)| at >= BLOCK && at.is_multiple_of(BLOCK) && at < end && end - at < BLOCK)
.map(|(at, cs)| (at, Some(cs)))
};
if let Some((at, kept_cs)) = boundary {
if state.sealed.len() * BLOCK >= at {
let cs = kept_cs.unwrap_or_else(read_cs);
self.take_turn_checkpoint(pools, tbl, state, at, cs);
}
}
}
fn take_turn_checkpoint(
&mut self,
pools: &mut BlockPools,
tbl: &BlockTable,
state: &mut LaneBlockState,
end: usize,
cs: Vec<u8>,
) {
let mut window = Vec::with_capacity(WINDOW / BLOCK);
let mut miss = None;
for b in end.saturating_sub(WINDOW) / BLOCK..end / BLOCK {
let bi = BlockIndex::new(b as u32);
match tbl.get(BlockKind::Window, bi).ok().flatten() {
Some(we) if self.entry_is_valid_kv(pools, BlockKind::Window, we) => window.push((bi, we)),
Some(_) => miss = Some(TurnEndMiss::BlockNotLive),
None => miss = Some(TurnEndMiss::BlockMissing),
}
}
if miss.is_none() {
for &(_, we) in &window {
pools.window.record_mut(we.slot()).unwrap().add_ref().expect("hold turn checkpoint window block");
}
Self::drop_turn_checkpoint(pools, state);
state.turn_ckpt_miss = None;
state.turn_ckpt = Some(TurnCheckpoint { end, cs, window });
} else {
state.turn_ckpt_miss = miss;
}
}
fn drop_turn_checkpoint(pools: &mut BlockPools, state: &mut LaneBlockState) {
let Some(ckpt) = state.turn_ckpt.take() else { return };
Self::release_turn_checkpoint_holds(pools, &ckpt.window);
}
fn release_turn_checkpoint_holds(pools: &mut BlockPools, window: &[(BlockIndex, BlockEntry)]) {
for &(_, we) in window {
let rec = pools.window.record_mut(we.slot()).expect("held window slot record");
debug_assert_eq!(rec.generation(), we.generation(), "a held window slot is never retaken");
if rec.generation() == we.generation() {
rec.drop_ref().expect("drop turn checkpoint window hold");
}
}
}
fn retain_turn_end_start(
&mut self,
pools: &mut BlockPools,
tbl: &BlockTable,
state: &mut LaneBlockState,
) -> TurnEndStart {
let ckpt = state.turn_ckpt.take();
let miss = state.turn_ckpt_miss.take();
let last_boundary = state.written / BLOCK * BLOCK;
let due = self.keeps_turn_end_start(state) && last_boundary > state.prompt_len;
let outcome = match ckpt {
None if due => TurnEndStart::NotSaved(miss.unwrap_or(TurnEndMiss::NoCheckpoint)),
None => TurnEndStart::NotDue,
Some(TurnCheckpoint { end, cs, window }) => {
let saved = self.save_turn_end_start(pools, tbl, state, end, cs, &window);
Self::release_turn_checkpoint_holds(pools, &window);
match saved {
Err(miss) => TurnEndStart::NotSaved(miss),
Ok(()) if end < last_boundary => TurnEndStart::NotSaved(TurnEndMiss::Behind),
Ok(()) => TurnEndStart::Saved,
}
}
};
match outcome {
TurnEndStart::NotDue => {}
TurnEndStart::Saved => self.stats.turn_end_starts_saved += 1,
TurnEndStart::NotSaved(miss) => self.stats.turn_end_starts_not_saved[miss as usize] += 1,
}
outcome
}
fn save_turn_end_start(
&mut self,
pools: &mut BlockPools,
tbl: &BlockTable,
state: &mut LaneBlockState,
end: usize,
cs: Vec<u8>,
window: &[(BlockIndex, BlockEntry)],
) -> Result<(), TurnEndMiss> {
if !self.approx_retain
|| !state.approx_path
|| state.owner == 0
|| end < BLOCK
|| !end.is_multiple_of(BLOCK)
|| state.sealed.len() * BLOCK < end
{
return Err(TurnEndMiss::OffPath);
}
let tip = state.sealed[end / BLOCK - 1];
self.tick += 1;
let now = self.tick;
if self.starts.contains_key(&tip) {
let (save_turn, now_ms) = if !self.card_lease.is_zero() && state.owner != 0 {
(self.ensure_save_owner_turn(state), self.now_ms())
} else {
(0, 0)
};
if let Some(existing) = self.starts.get_mut(&tip) {
existing.reasons |= PROMPT;
existing.last_used_tick = now;
if save_turn != 0 {
existing.last_owner = state.owner;
existing.owner_turn = save_turn;
existing.last_used_ms = now_ms;
}
state.reply_saved_pos = end;
state.reply_saved_id = Some(tip);
}
return Ok(());
}
let mut entries = Vec::with_capacity(end / BLOCK + WINDOW / BLOCK);
for b in 0..(end / BLOCK) {
let bi = BlockIndex::new(b as u32);
let Some(fe) = tbl.get(BlockKind::Full, bi).ok().flatten() else { return Err(TurnEndMiss::BlockMissing) };
entries.push((BlockKind::Full, bi, fe));
}
entries.extend(window.iter().map(|&(bi, we)| (BlockKind::Window, bi, we)));
if !entries.iter().all(|&(kind, _, e)| self.entry_is_valid_kv(pools, kind, e)) {
return Err(TurnEndMiss::BlockNotLive);
}
for &(kind, _, e) in &entries {
pools.of_mut(kind).record_mut(e.slot()).unwrap().add_ref().expect("retain turn-end start ref");
self.inc_start_slot_ref(kind, e.slot());
}
self.tree.retain_start(tip).expect("retain turn-end start in EntryTree");
let (save_turn, now_ms) = if !self.card_lease.is_zero() && state.owner != 0 {
(self.ensure_save_owner_turn(state), self.now_ms())
} else {
(0, 0)
};
let st = RetainedStart {
namespace: approx_namespace(state.namespace, state.owner),
approx: true,
scope: state.namespace,
pos: end,
cs,
reasons: PROMPT,
slot_bytes: Self::checkpoint_slot_bytes(pools, &entries),
entries,
toks: Vec::new(),
reuse: RecentReuse::default(),
created_tick: Some(now),
last_used_tick: now,
last_owner: if save_turn != 0 { state.owner } else { 0 },
owner_turn: save_turn,
last_used_ms: now_ms,
};
self.retained_host_bytes = self.retained_host_bytes.saturating_add(st.host_bytes());
self.starts.insert(tip, st);
state.reply_saved_pos = end;
state.reply_saved_id = Some(tip);
self.stats.approx_starts_saved += 1;
*self.approx_per_scope.entry(state.namespace).or_insert(0) += 1;
self.enforce_approx_scope_cap(pools, state.namespace, Some(tip));
self.enforce_retained_host_budget(pools, Some(tip));
Ok(())
}
fn release_superseded_turn_starts(&mut self, pools: &mut BlockPools, state: &LaneBlockState, cancelled: bool) {
if !self.release_superseded_starts
|| cancelled
|| !state.approx_path
|| state.owner == 0
|| state.written < state.prompt_len
{
return;
}
let ns = approx_namespace(state.namespace, state.owner);
let keep = [state.prompt_saved_id, state.reply_saved_id];
let Some(kept_blocks) = keep
.iter()
.flatten()
.filter_map(|sid| {
let st = self.starts.get(sid)?;
let blocks = st.pos / BLOCK;
(st.approx && st.namespace == ns && blocks > 0 && state.sealed.get(blocks - 1) == Some(sid))
.then_some(blocks)
})
.max()
else {
return;
};
let superseded: Vec<SealedId> = state.sealed[..kept_blocks - 1]
.iter()
.copied()
.filter(|sid| {
!keep.contains(&Some(*sid)) && self.starts.get(sid).is_some_and(|st| st.approx && st.namespace == ns)
})
.collect();
for sid in superseded {
self.evict_start_inner(pools, sid, false, None, EvictCause::Superseded);
}
}
pub fn set_release_superseded_starts(&mut self, enabled: bool) {
self.release_superseded_starts = enabled;
}
#[cfg(test)]
pub fn release_superseded_starts_enabled(&self) -> bool {
self.release_superseded_starts
}
pub fn set_retain_lru(&mut self, lru: bool) {
self.retain_lru = lru;
}
#[cfg(test)]
pub fn retain_lru_enabled(&self) -> bool {
self.retain_lru
}
#[cfg(test)]
fn finish_verify_span(
&mut self,
pools: &mut BlockPools,
tbl: &mut BlockTable,
state: &mut LaneBlockState,
allocated: &[(BlockKind, BlockIndex)],
p0: usize,
n_keep: usize,
) {
if n_keep == 0 {
for &(kind, bi) in allocated.iter().rev() {
tbl.clear_kind_entry(pools.of_mut(kind), bi).expect("release aborted verify draft block");
}
return;
}
let accepted_end = p0 + n_keep;
for &(kind, bi) in allocated.iter().rev() {
let blk_start = (bi.get() as usize) * BLOCK;
if blk_start >= accepted_end {
tbl.clear_kind_entry(pools.of_mut(kind), bi).expect("release rejected verify draft block");
}
}
let lo_blk = p0 / BLOCK;
let hi_blk = (accepted_end - 1) / BLOCK;
for b in lo_blk..=hi_blk {
let bi = BlockIndex::new(b as u32);
let block_len = (accepted_end - b * BLOCK).min(BLOCK) as u32;
for kind in KINDS {
let e = tbl.get(kind, bi).unwrap().expect("retained verify block entry");
let rec = pools.of_mut(kind).record_mut(e.slot()).unwrap();
assert!(!rec.sealed(), "verify must never seal {kind:?} block {b}");
rec.set_length(block_len).expect("set verify block length");
}
}
state.written = accepted_end;
self.prune_expired_window(pools, tbl, p0, accepted_end);
}
#[allow(clippy::too_many_arguments)]
pub fn finish_verify_span_and_sync<D>(
&mut self,
pools: &mut BlockPools,
tbl: &mut BlockTable,
state: &mut LaneBlockState,
allocated: &[(BlockKind, BlockIndex)],
p0: usize,
n_keep: usize,
sync_dirty: D,
) -> Result<VerifyBlockFinalize, String>
where
D: FnMut(BlockKind, &BlockPool, &mut BlockTable) -> Result<usize, String>,
{
let committed_len = p0 + n_keep;
let fin = crate::blocks::finalize_verify_blocks_at(
pools,
tbl,
allocated,
p0,
committed_len,
EXT,
BLOCK,
|_, _, _| {},
sync_dirty,
)?;
if n_keep > 0 {
state.written = fin.committed_len;
}
self.stats.window_pruned += fin.window_pruned;
Ok(fin)
}
#[cfg(test)]
#[allow(clippy::too_many_arguments)]
pub(crate) fn finish_verify_span_to_slices(
&mut self,
pools: &mut BlockPools,
tbl: &mut BlockTable,
state: &mut LaneBlockState,
allocated: &[(BlockKind, BlockIndex)],
p0: usize,
n_keep: usize,
full_dst: &mut [u64],
win_dst: &mut [u64],
) -> Result<VerifyBlockFinalize, String> {
self.finish_verify_span_and_sync(pools, tbl, state, allocated, p0, n_keep, |kind, pool, tbl| match kind {
BlockKind::Full => tbl.sync_dirty_to_slice(kind, pool, full_dst).map_err(|e| format!("{e}")),
BlockKind::Window => tbl.sync_dirty_to_slice(kind, pool, win_dst).map_err(|e| format!("{e}")),
})
}
pub fn plan_stitches(
&self,
pools: &BlockPools,
namespace: u64,
toks: &[u32],
matched_pos: usize,
) -> Vec<StitchSpanPlan> {
if !self.kv_stitch || toks.len() < matched_pos.saturating_add(MIN_STITCH_TOKENS) || toks.len() < BLOCK {
return Vec::new();
}
let has_ikv = namespace == self.ikv_namespace && pools.full.slab_count() > 0
&& self.ikv_catalog.as_ref().is_some_and(|c| !c.is_empty());
if !has_ikv && self.stitch_index.is_empty() {
return Vec::new();
}
let mut plans = Vec::new();
let mut min_start = matched_pos;
let last_anchor_pos = toks.len() - BLOCK;
if min_start > last_anchor_pos {
return plans;
}
let mut covered_ret_diags: HashMap<(SealedId, usize), usize> = HashMap::new();
let mut covered_ikv_diags: HashMap<(usize, usize), usize> = HashMap::new();
let mut i = min_start;
let mut h = stitch_hash_64(&toks[i..i + BLOCK]);
loop {
let mut best: Option<(usize, bool, usize, StitchSpanPlan)> = None;
if has_ikv {
if let Some(cat) = &self.ikv_catalog {
if let Some(cands) = cat.lookup_anchor(h) {
for &(cart_idx, page_idx) in cands {
let src_anchor = (page_idx as usize) * BLOCK;
let diag = i.wrapping_sub(src_anchor);
if covered_ikv_diags.get(&(cart_idx, diag)).is_some_and(|&cov_end| i < cov_end) {
continue;
}
let Some(cart) = cat.get(cart_idx) else {
continue;
};
if cart.is_quarantined() {
continue;
}
let ctoks = cart.tokens();
if src_anchor + BLOCK > ctoks.len()
|| ctoks[src_anchor..src_anchor + BLOCK] != toks[i..i + BLOCK]
{
continue;
}
let mut s_start = i;
let mut c_start = src_anchor;
while s_start > min_start && c_start > 0 && toks[s_start - 1] == ctoks[c_start - 1] {
s_start -= 1;
c_start -= 1;
}
let mut s_end = i + BLOCK;
let mut c_end = src_anchor + BLOCK;
while s_end < toks.len() && c_end < ctoks.len() && toks[s_end] == ctoks[c_end] {
s_end += 1;
c_end += 1;
}
let cov = covered_ikv_diags.entry((cart_idx, diag)).or_insert(0);
*cov = (*cov).max(s_end);
if s_end - s_start >= MIN_STITCH_TOKENS {
let stitch_start = (s_start + LEFT_HEAL_TOKENS).div_ceil(BLOCK) * BLOCK;
let heal_start = (s_end.saturating_sub(MIN_HEAL_TOKENS) / BLOCK) * BLOCK;
if heal_start >= stitch_start + BLOCK {
let src_start = c_start + (stitch_start - s_start);
let stitched = heal_start - stitch_start;
let cand = StitchSpanPlan {
span_start: s_start,
stitch_start,
heal_start,
span_end: s_end,
source: StitchSource::Ikv { cart_idx, src_start },
};
if best.is_none_or(|(bs, bzc, _, _)| (stitched, false) > (bs, bzc)) {
best = Some((stitched, false, s_end, cand));
}
}
}
}
}
}
}
if let Some(cands) = self.stitch_index.get(&(namespace, h)) {
for &(sid, blk_idx) in cands {
let src_anchor = (blk_idx as usize) * BLOCK;
let diag = i.wrapping_sub(src_anchor);
if covered_ret_diags.get(&(sid, diag)).is_some_and(|&cov_end| i < cov_end) {
continue;
}
let Some(st) = self.starts.get(&sid) else {
continue;
};
if st.approx || st.namespace != namespace || src_anchor + BLOCK > st.toks.len() {
continue;
}
if st.toks[src_anchor..src_anchor + BLOCK] != toks[i..i + BLOCK] {
continue;
}
let full_cnt = st.pos / BLOCK;
if st.entries.len() < full_cnt {
continue;
}
let mut s_start = i;
let mut a_start = src_anchor;
while s_start > min_start && a_start > 0 && toks[s_start - 1] == st.toks[a_start - 1] {
s_start -= 1;
a_start -= 1;
}
let mut s_end = i + BLOCK;
let mut a_end = src_anchor + BLOCK;
while s_end < toks.len() && a_end < st.toks.len() && toks[s_end] == st.toks[a_end] {
s_end += 1;
a_end += 1;
}
let cov = covered_ret_diags.entry((sid, diag)).or_insert(0);
*cov = (*cov).max(s_end);
if s_end - s_start >= MIN_STITCH_TOKENS {
let stitch_start = (s_start + LEFT_HEAL_TOKENS).div_ceil(BLOCK) * BLOCK; let heal_start = (s_end.saturating_sub(MIN_HEAL_TOKENS) / BLOCK) * BLOCK; if heal_start >= stitch_start + BLOCK {
let src_start = a_start + (stitch_start - s_start);
let src_end = src_start + (heal_start - stitch_start);
let lo_sb = src_start / BLOCK;
let hi_sb = (src_end - 1) / BLOCK;
let is_zc = src_start.is_multiple_of(BLOCK);
if !is_zc && pools.full.slab_count() == 0 {
continue;
}
let all_live = hi_sb < full_cnt
&& st.entries[lo_sb..=hi_sb].iter().enumerate().all(|(off, &(k, bi, fe))| {
k == BlockKind::Full
&& bi.get() as usize == lo_sb + off
&& entry_is_live_sealed(pools, BlockKind::Full, fe)
});
if all_live {
let stitched = heal_start - stitch_start;
let cand = StitchSpanPlan {
span_start: s_start,
stitch_start,
heal_start,
span_end: s_end,
source: StitchSource::Retained { sid, src_start },
};
if best.is_none_or(|(bs, bzc, _, _)| (stitched, is_zc) > (bs, bzc)) {
best = Some((stitched, is_zc, s_end, cand));
}
}
}
}
}
}
if let Some((_, _, s_end, plan)) = best {
plans.push(plan);
min_start = s_end;
covered_ret_diags.clear();
covered_ikv_diags.clear();
if min_start > last_anchor_pos {
break;
}
i = min_start;
h = stitch_hash_64(&toks[i..i + BLOCK]);
continue;
}
if i >= last_anchor_pos {
break;
}
h = slide_stitch_hash_64(h, toks[i], toks[i + BLOCK]);
i += 1;
}
plans
}
fn finish_binding_stitched_lane(
&mut self,
pools: &mut BlockPools,
tbl: &mut BlockTable,
state: &mut LaneBlockState,
plan: &StitchSpanPlan,
missing_win_blks: Vec<BlockIndex>,
) -> usize {
self.prune_expired_window(pools, tbl, plan.stitch_start, plan.heal_start);
if !missing_win_blks.is_empty() {
let w_slot = pools.window.lowest_free().expect("verified free window slot for stitch healing");
let _ = pools.window.take(w_slot).expect("take zero-filled window slot for stitch healing");
let w_gen = pools.window.record(w_slot).unwrap().generation();
self.stats.slots_taken += 1;
if w_gen > 1 {
self.stats.slots_reused += 1;
}
{
let w_rec = pools.window.record_mut(w_slot).unwrap();
w_rec.set_length(BLOCK as u32).expect("set zeroed window length");
w_rec.seal();
}
let window = &pools.window;
self.stitch_guards.retain(|&(s, g)| window.record(s).is_ok_and(|r| r.generation() == g && r.refs() > 0));
self.stitch_guards.push((w_slot, w_gen));
for bi in missing_win_blks {
tbl.fill(&mut pools.window, bi, w_slot, w_gen).expect("bind zeroed window slot for stitch healing");
}
}
state.stitched_approx = true; state.written = plan.heal_start;
let stitched_tokens = plan.heal_start - plan.stitch_start;
self.stats.stitch_hits += 1;
self.stats.stitched_tokens_total += stitched_tokens as u64;
stitched_tokens
}
pub fn start_stitch_plan(
&mut self,
pools: &mut BlockPools,
lane: usize,
tbl: &mut BlockTable,
state: &mut LaneBlockState,
toks: &[u32],
plan: &StitchSpanPlan,
) -> StitchStartOutcome {
if self.pending_ikv_stages.contains_key(&lane) {
return StitchStartOutcome::Staging;
}
let StitchSource::Ikv { cart_idx, src_start } = plan.source else {
return match self.apply_stitch_plan(pools, tbl, state, toks, plan) {
StitchApplyOutcome::Applied { stitched_tokens, zero_copy_blocks } => {
StitchStartOutcome::Applied { stitched_tokens, zero_copy_blocks }
}
StitchApplyOutcome::SourceGone => StitchStartOutcome::SourceGone,
StitchApplyOutcome::PoolBusy => StitchStartOutcome::PoolBusy,
};
};
if !self.kv_stitch
|| plan.stitch_start >= plan.heal_start
|| !plan.stitch_start.is_multiple_of(BLOCK)
|| !plan.heal_start.is_multiple_of(BLOCK)
|| state.written != plan.stitch_start
|| plan.heal_start >= toks.len()
|| state.namespace != self.ikv_namespace
|| pools.full.slab_count() == 0
{
return StitchStartOutcome::SourceGone;
}
let lo_blk = plan.stitch_start / BLOCK;
let hi_blk = plan.heal_start / BLOCK;
let n_stitch_blks = hi_blk - lo_blk;
for b in lo_blk..hi_blk {
match tbl.get(BlockKind::Full, BlockIndex::new(b as u32)) {
Ok(None) => {}
_ => return StitchStartOutcome::SourceGone,
}
}
let lo_win_blk = hi_blk.saturating_sub(WINDOW / BLOCK);
let mut need_win = 0usize;
for b in lo_blk.max(lo_win_blk)..hi_blk {
match tbl.get(BlockKind::Window, BlockIndex::new(b as u32)) {
Ok(None) => need_win = 1,
Ok(Some(_)) => {}
Err(_) => return StitchStartOutcome::SourceGone,
}
}
if need_win > 0 && pools.window.slab_count() == 0 {
return StitchStartOutcome::SourceGone;
}
let (usable_win, _) = self.pool_headroom(pools, BlockKind::Window);
let (usable_full, _) = self.pool_headroom(pools, BlockKind::Full);
if need_win > usable_win || n_stitch_blks > usable_full {
return StitchStartOutcome::SourceGone;
}
let Some(cat) = self.ikv_catalog.clone() else {
return StitchStartOutcome::SourceGone;
};
let Some(cart) = cat.get(cart_idx) else {
return StitchStartOutcome::SourceGone;
};
let src_end = src_start + n_stitch_blks * BLOCK;
if cart.is_quarantined()
|| cart.header().kvb != pools.full.kvb()
|| src_end > cart.n_tokens()
|| cart.tokens()[src_start..src_end] != toks[plan.stitch_start..plan.heal_start]
{
return StitchStartOutcome::SourceGone;
}
if self.evict_for_slots(pools, need_win, n_stitch_blks, None).is_err() {
return StitchStartOutcome::PoolBusy;
}
let mut reserved_slots: Vec<(Slot, u32)> = Vec::with_capacity(n_stitch_blks);
for _ in 0..n_stitch_blks {
let Some(slot) = pools.full.lowest_free() else {
for (s, _) in reserved_slots {
let _ = pools.full.record_mut(s).unwrap().drop_ref();
}
return StitchStartOutcome::PoolBusy;
};
let _ = pools.full.take_unzeroed(slot).expect("take slot for async ikv stage");
let gen = pools.full.record(slot).unwrap().generation();
pools.full.record_mut(slot).unwrap().add_ref().expect("reserve slot for async ikv stage");
self.stats.slots_taken += 1;
if gen > 1 {
self.stats.slots_reused += 1;
}
reserved_slots.push((slot, gen));
}
state.bound_lane = Some(lane);
let stage_seq = self.next_ikv_stage_seq;
self.next_ikv_stage_seq = self.next_ikv_stage_seq.wrapping_add(1).max(1);
let cancel_flag = Arc::new(AtomicBool::new(false));
let began = Instant::now();
self.pending_ikv_stages.insert(
lane,
PendingIkvStage {
stage_seq,
plan: *plan,
toks: toks.to_vec(),
reserved_slots,
loaded_blocks: 0,
cancel_flag: cancel_flag.clone(),
},
);
let wake = self.shared_wake.clone();
let worker = self.ikv_stage_worker.get_or_insert_with(|| IkvStageWorker::spawn(wake));
if worker
.job_tx
.as_ref()
.and_then(|tx| {
tx.send(IkvStageJob {
lane,
stage_seq,
lane_namespace: state.namespace,
expected_namespace: self.ikv_namespace,
catalog: cat,
cart_idx,
src_start,
n_stitch_blks,
cancel_flag,
began,
})
.ok()
})
.is_none()
{
self.cancel_ikv_stage(pools, lane);
return StitchStartOutcome::SourceGone;
}
StitchStartOutcome::Staging
}
pub fn poll_ikv_stages<F>(&mut self, pools: &mut BlockPools, mut lane_tables: F) -> Vec<CompletedIkvStage>
where
F: FnMut(usize) -> Option<(&'static (), *mut BlockTable, *mut LaneBlockState)>,
{
let mut ready_msgs = Vec::new();
if let Some(worker) = self.ikv_stage_worker.as_ref() {
while let Ok(msg) = worker.msg_rx.try_recv() {
worker.budget.release(msg.budget_bytes);
ready_msgs.push(msg);
}
}
let mut completed = Vec::new();
for msg in ready_msgs {
let is_current = self.pending_ikv_stages.get(&msg.lane).is_some_and(|ps| ps.stage_seq == msg.stage_seq);
if !is_current {
continue;
}
match msg.payload {
IkvStagePayload::Block { idx, bytes } => {
if let Some(ps) = self.pending_ikv_stages.get_mut(&msg.lane) {
if let Some(&(slot, _)) = ps.reserved_slots.get(idx) {
pools
.full
.slot_bytes_mut(slot)
.expect("reserved ikv stage slot bytes")
.copy_from_slice(&bytes);
ps.loaded_blocks += 1;
}
}
}
IkvStagePayload::Done { elapsed } => {
let ps = self.pending_ikv_stages.remove(&msg.lane).unwrap();
let plan = ps.plan;
let lo_blk = plan.stitch_start / BLOCK;
let hi_blk = plan.heal_start / BLOCK;
let all_loaded = ps.loaded_blocks == ps.reserved_slots.len();
if !all_loaded {
for (s, _) in ps.reserved_slots {
let _ = pools.full.record_mut(s).unwrap().drop_ref();
}
self.stats.corrupt_fallbacks += 1;
self.sync_ikv_quarantined_stat();
completed.push(CompletedIkvStage {
lane: msg.lane,
stitched_tokens: None,
heal_start: plan.heal_start,
elapsed,
corrupt_fallback: true,
});
continue;
}
let Some((_, tbl_ptr, st_ptr)) = lane_tables(msg.lane) else {
for (s, _) in ps.reserved_slots {
let _ = pools.full.record_mut(s).unwrap().drop_ref();
}
continue;
};
let (tbl, state) = unsafe { (&mut *tbl_ptr, &mut *st_ptr) };
let lo_win_blk = hi_blk.saturating_sub(WINDOW / BLOCK);
let mut missing_win_blks = Vec::new();
let mut valid_tbl = state.written == plan.stitch_start;
for b in lo_blk.max(lo_win_blk)..hi_blk {
let bi = BlockIndex::new(b as u32);
match tbl.get(BlockKind::Window, bi) {
Ok(None) => missing_win_blks.push(bi),
Ok(Some(_)) => {}
Err(_) => valid_tbl = false,
}
}
let need_win = usize::from(!missing_win_blks.is_empty());
if valid_tbl
&& need_win > 0
&& pools.window.lowest_free().is_none()
&& self.evict_for_slots(pools, need_win, 0, None).is_err()
{
valid_tbl = false;
}
if !valid_tbl || (need_win > 0 && pools.window.lowest_free().is_none()) {
for (s, _) in ps.reserved_slots {
let _ = pools.full.record_mut(s).unwrap().drop_ref();
}
completed.push(CompletedIkvStage {
lane: msg.lane,
stitched_tokens: None,
heal_start: plan.heal_start,
elapsed,
corrupt_fallback: false,
});
continue;
}
for (k, (slot, gen)) in ps.reserved_slots.into_iter().enumerate() {
pools.full.clear_gpu_zero_pending(slot);
{
let rec = pools.full.record_mut(slot).unwrap();
rec.set_length(BLOCK as u32).expect("set ikv staged block length");
rec.seal();
}
pools.full.on_slot_restored_from_spill(slot);
let bi = BlockIndex::new((lo_blk + k) as u32);
tbl.fill(&mut pools.full, bi, slot, gen).expect("bind staged ikv full block");
pools.full.record_mut(slot).unwrap().drop_ref().expect("drop provisional ikv stage ref");
}
let stitched_tokens = self.finish_binding_stitched_lane(pools, tbl, state, &plan, missing_win_blks);
self.enter_approx_path(pools, tbl, state, &ps.toks);
completed.push(CompletedIkvStage {
lane: msg.lane,
stitched_tokens: Some(stitched_tokens),
heal_start: plan.heal_start,
elapsed,
corrupt_fallback: false,
});
}
IkvStagePayload::Aborted { elapsed } => {
let ps = self.pending_ikv_stages.remove(&msg.lane).unwrap();
ps.cancel_flag.store(true, Ordering::Release);
for (s, _) in ps.reserved_slots {
let _ = pools.full.record_mut(s).unwrap().drop_ref();
}
self.stats.corrupt_fallbacks += 1;
self.sync_ikv_quarantined_stat();
completed.push(CompletedIkvStage {
lane: msg.lane,
stitched_tokens: None,
heal_start: ps.plan.heal_start,
elapsed,
corrupt_fallback: true,
});
}
}
}
completed
}
pub fn apply_stitch_plan(
&mut self,
pools: &mut BlockPools,
tbl: &mut BlockTable,
state: &mut LaneBlockState,
toks: &[u32],
plan: &StitchSpanPlan,
) -> StitchApplyOutcome {
if !self.kv_stitch
|| plan.stitch_start >= plan.heal_start
|| !plan.stitch_start.is_multiple_of(BLOCK)
|| !plan.heal_start.is_multiple_of(BLOCK)
|| state.written != plan.stitch_start
|| plan.heal_start >= toks.len()
{
return StitchApplyOutcome::SourceGone;
}
let lo_blk = plan.stitch_start / BLOCK;
let hi_blk = plan.heal_start / BLOCK;
let n_stitch_blks = hi_blk - lo_blk;
for b in lo_blk..hi_blk {
match tbl.get(BlockKind::Full, BlockIndex::new(b as u32)) {
Ok(None) => {}
_ => return StitchApplyOutcome::SourceGone,
}
}
let lo_win_blk = hi_blk.saturating_sub(WINDOW / BLOCK);
let mut missing_win_blks = Vec::new();
for b in lo_blk.max(lo_win_blk)..hi_blk {
let bi = BlockIndex::new(b as u32);
match tbl.get(BlockKind::Window, bi) {
Ok(None) => missing_win_blks.push(bi),
Ok(Some(_)) => {}
Err(_) => return StitchApplyOutcome::SourceGone,
}
}
let need_win = usize::from(!missing_win_blks.is_empty());
if need_win > 0 && pools.window.slab_count() == 0 {
return StitchApplyOutcome::SourceGone;
}
let (usable_win, _) = self.pool_headroom(pools, BlockKind::Window);
let (usable_full, _) = self.pool_headroom(pools, BlockKind::Full);
if need_win > usable_win {
return StitchApplyOutcome::SourceGone;
}
let mut zero_copy_blocks = 0usize;
match plan.source {
StitchSource::Retained { sid, src_start } if src_start.is_multiple_of(BLOCK) => {
let src_entries: Vec<BlockEntry> = {
let Some(st) = self.starts.get(&sid) else {
return StitchApplyOutcome::SourceGone;
};
let src_end = src_start + n_stitch_blks * BLOCK;
let full_cnt = st.pos / BLOCK;
if st.namespace != state.namespace || st.approx
|| src_end > st.toks.len()
|| st.entries.len() < full_cnt
|| st.toks[src_start..src_end] != toks[plan.stitch_start..plan.heal_start]
{
return StitchApplyOutcome::SourceGone;
}
let lo_sb = src_start / BLOCK;
let mut out = Vec::with_capacity(n_stitch_blks);
for k in 0..n_stitch_blks {
let (kind, bi, fe) = st.entries[lo_sb + k];
if kind != BlockKind::Full
|| bi.get() as usize != lo_sb + k
|| !entry_is_live_sealed(pools, BlockKind::Full, fe)
{
return StitchApplyOutcome::SourceGone;
}
out.push(fe);
}
out
};
if need_win > 0 && self.evict_for_slots(pools, need_win, 0, Some(sid)).is_err() {
return StitchApplyOutcome::PoolBusy;
}
self.tick += 1;
if let Some(st) = self.starts.get_mut(&sid) {
st.last_used_tick = self.tick;
}
for (k, fe) in src_entries.into_iter().enumerate() {
if !pools.full.has_gpu_storage()
&& pools.full.has_sketches()
&& pools.full.slot_sketch_valid_len(fe.slot()).unwrap_or(BLOCK as u8) < BLOCK as u8
{
pools.full.on_slot_restored_from_spill(fe.slot());
}
let bi = BlockIndex::new((lo_blk + k) as u32);
tbl.fill(&mut pools.full, bi, fe.slot(), fe.generation()) .expect("bind zero-copy stitched full block");
}
zero_copy_blocks = n_stitch_blks;
}
StitchSource::Retained { sid, src_start } => {
if pools.full.slab_count() == 0 || n_stitch_blks > usable_full {
return StitchApplyOutcome::SourceGone;
}
let src_entries: Vec<BlockEntry> = {
let Some(st) = self.starts.get(&sid) else {
return StitchApplyOutcome::SourceGone;
};
let src_end = src_start + n_stitch_blks * BLOCK;
let full_cnt = st.pos / BLOCK;
if st.namespace != state.namespace
|| st.approx
|| src_end > st.toks.len()
|| st.entries.len() < full_cnt
|| st.toks[src_start..src_end] != toks[plan.stitch_start..plan.heal_start]
{
return StitchApplyOutcome::SourceGone;
}
let lo_sb = src_start / BLOCK;
let hi_sb = (src_end - 1) / BLOCK;
let mut out = Vec::with_capacity(hi_sb - lo_sb + 1);
for sb in lo_sb..=hi_sb {
let (kind, bi, fe) = st.entries[sb];
if kind != BlockKind::Full
|| bi.get() as usize != sb
|| !entry_is_live_sealed(pools, BlockKind::Full, fe)
{
return StitchApplyOutcome::SourceGone;
}
out.push(fe);
}
out
};
if self.evict_for_slots(pools, need_win, n_stitch_blks, Some(sid)).is_err() {
return StitchApplyOutcome::PoolBusy;
}
self.tick += 1;
if let Some(st) = self.starts.get_mut(&sid) {
st.last_used_tick = self.tick;
}
let kvb = pools.full.kvb();
let stride = pools.full.stride_bytes() as usize;
let rem = src_start % BLOCK;
let first_part = BLOCK - rem;
let mut assembled = vec![0u8; stride];
for k in 0..n_stitch_blks {
{
let s0 = pools.full.slot_bytes(src_entries[k].slot()).expect("src slot 0 bytes");
copy_full_slot_rows(s0, rem, &mut assembled, 0, first_part, kvb);
let s1 = pools.full.slot_bytes(src_entries[k + 1].slot()).expect("src slot 1 bytes");
copy_full_slot_rows(s1, 0, &mut assembled, first_part, rem, kvb);
}
let slot = pools.full.lowest_free().expect("verified free full slot for unaligned stitch");
let _ = pools.full.take_unzeroed(slot).expect("take unzeroed full slot for stitch");
let gen = pools.full.record(slot).unwrap().generation();
self.stats.slots_taken += 1;
if gen > 1 {
self.stats.slots_reused += 1;
}
pools.full.slot_bytes_mut(slot).expect("dst stitch slot bytes").copy_from_slice(&assembled);
pools.full.clear_gpu_zero_pending(slot);
{
let rec = pools.full.record_mut(slot).unwrap();
rec.set_length(BLOCK as u32).expect("set stitched full length");
rec.seal();
}
pools.full.on_slot_restored_from_spill(slot);
let bi = BlockIndex::new((lo_blk + k) as u32);
tbl.fill(&mut pools.full, bi, slot, gen).expect("bind unaligned stitched full block");
}
}
StitchSource::Ikv { cart_idx, src_start } => {
if state.namespace != self.ikv_namespace || pools.full.slab_count() == 0 || n_stitch_blks > usable_full
{
return StitchApplyOutcome::SourceGone;
}
let Some(cat) = self.ikv_catalog.clone() else {
return StitchApplyOutcome::SourceGone;
};
let Some(cart) = cat.get(cart_idx) else {
return StitchApplyOutcome::SourceGone;
};
let src_end = src_start + n_stitch_blks * BLOCK;
if cart.is_quarantined()
|| cart.header().kvb != pools.full.kvb()
|| src_end > cart.n_tokens()
|| cart.tokens()[src_start..src_end] != toks[plan.stitch_start..plan.heal_start]
{
return StitchApplyOutcome::SourceGone;
}
if self.evict_for_slots(pools, need_win, n_stitch_blks, None).is_err() {
return StitchApplyOutcome::PoolBusy;
}
let mut staged_slots: Vec<(Slot, u32)> = Vec::with_capacity(n_stitch_blks);
for _ in 0..n_stitch_blks {
let Some(slot) = pools.full.lowest_free() else {
for (s, _) in staged_slots {
let _ = pools.full.record_mut(s).unwrap().drop_ref();
}
return StitchApplyOutcome::PoolBusy;
};
let _ = pools.full.take_unzeroed(slot).expect("take slot for ikv stitch");
let gen = pools.full.record(slot).unwrap().generation();
pools.full.record_mut(slot).unwrap().add_ref().expect("provisional ikv stitch ref");
self.stats.slots_taken += 1;
if gen > 1 {
self.stats.slots_reused += 1;
}
staged_slots.push((slot, gen));
}
let read_res = cart.read_full_span_into_blocks(
state.namespace,
self.ikv_namespace,
src_start,
n_stitch_blks,
|k, blk_bytes| {
let (slot, _) = staged_slots[k];
pools
.full
.slot_bytes_mut(slot)
.expect("staged ikv slot bytes")
.copy_from_slice(blk_bytes);
Ok(())
},
);
if read_res.is_err() {
for (s, _) in staged_slots {
let _ = pools.full.record_mut(s).unwrap().drop_ref();
}
self.stats.corrupt_fallbacks += 1;
self.sync_ikv_quarantined_stat();
return StitchApplyOutcome::SourceGone;
}
for (k, (slot, gen)) in staged_slots.into_iter().enumerate() {
pools.full.clear_gpu_zero_pending(slot);
{
let rec = pools.full.record_mut(slot).unwrap();
rec.set_length(BLOCK as u32).expect("set ikv stitched block length");
rec.seal();
}
pools.full.on_slot_restored_from_spill(slot);
let bi = BlockIndex::new((lo_blk + k) as u32);
tbl.fill(&mut pools.full, bi, slot, gen).expect("bind ikv stitched full block");
pools.full.record_mut(slot).unwrap().drop_ref().expect("drop provisional ikv stitch ref");
}
}
}
let stitched_tokens = self.finish_binding_stitched_lane(pools, tbl, state, plan, missing_win_blks);
self.enter_approx_path(pools, tbl, state, toks);
StitchApplyOutcome::Applied { stitched_tokens, zero_copy_blocks }
}
pub fn release_lane(&mut self, pools: &mut BlockPools, tbl: &mut BlockTable, state: &mut LaneBlockState) {
self.release_lane_with_toks(pools, tbl, state, None, false);
}
pub fn release_lane_preempted(
&mut self,
pools: &mut BlockPools,
tbl: &mut BlockTable,
state: &mut LaneBlockState,
) -> TurnEndStart {
self.release_lane_inner(pools, tbl, state, None, false, true)
}
pub fn release_lane_with_toks(
&mut self,
pools: &mut BlockPools,
tbl: &mut BlockTable,
state: &mut LaneBlockState,
committed_toks: Option<&[u32]>,
cancelled: bool,
) -> TurnEndStart {
self.release_lane_inner(pools, tbl, state, committed_toks, cancelled, false)
}
fn release_lane_inner(
&mut self,
pools: &mut BlockPools,
tbl: &mut BlockTable,
state: &mut LaneBlockState,
committed_toks: Option<&[u32]>,
cancelled: bool,
preempted: bool,
) -> TurnEndStart {
if let Some(lane_idx) = state.bound_lane.take() {
self.cancel_ikv_stage(pools, lane_idx);
}
let turn_end = self.retain_turn_end_start(pools, tbl, state);
self.release_superseded_turn_starts(pools, state, cancelled || preempted);
self.settle_lease_at_release(state, cancelled);
tbl.clear_entries(pools).expect("clear lane block table");
let sealed_snapshot = std::mem::take(&mut state.sealed);
let tip = sealed_snapshot.last().copied();
for &id in &sealed_snapshot {
self.tree.unpin(id);
}
if let Some(tip) = tip {
self.tree.prune_unreferenced(tip);
}
if !preempted
&& state.owner != 0
&& state.written > 0
&& (state.written >= state.prompt_len || !self.owner_prior.contains_key(&state.owner))
{
let live_pos_and_tip = sealed_snapshot
.iter()
.enumerate()
.rev()
.find(|&(_, &id)| self.tree.contains_node(id))
.map(|(idx, &id)| ((idx + 1) * BLOCK, id));
let (live_chain_len, live_tip) = match live_pos_and_tip {
Some((len, id)) => (len, Some(id)),
None => (0, None),
};
let prompt_tip_id = state.prompt_saved_id.filter(|&id| self.tree.contains_node(id));
let reply_tip_id = state.reply_saved_id.filter(|&id| self.tree.contains_node(id));
let prompt_saved_pos = if prompt_tip_id.is_some() { state.prompt_saved_pos } else { 0 };
let reply_saved_pos = if reply_tip_id.is_some() { state.reply_saved_pos } else { 0 };
let (tail_toks, total_len, truncated_tail) = match committed_toks {
Some(toks) if toks.len() >= live_chain_len => {
let rem = toks.len() - live_chain_len;
let take_n = rem.min(BLOCK - 1);
(
toks[live_chain_len..live_chain_len + take_n].to_vec(),
toks.len(),
rem >= BLOCK,
)
}
_ => {
if live_chain_len == sealed_snapshot.len() * BLOCK && state.tail_toks.len() < BLOCK {
let tail = std::mem::take(&mut state.tail_toks);
let tlen = live_chain_len + tail.len();
(tail, state.written.max(tlen), state.written > tlen)
} else {
(Vec::new(), state.written.max(live_chain_len), state.written > live_chain_len)
}
}
};
if !self.owner_prior.contains_key(&state.owner) && self.owner_prior.len() >= MAX_OWNER_PRIOR_ENTRIES {
if let Some((&oldest_owner, _)) = self.owner_prior.iter().min_by_key(|(_, v)| v.seq) {
if let Some(evicted_prior) = self.owner_prior.remove(&oldest_owner) {
self.unregister_prior_checkpoint_ids(oldest_owner, &evicted_prior);
}
}
}
let seq = self.next_owner_prior_seq;
self.next_owner_prior_seq = self.next_owner_prior_seq.saturating_add(1);
let new_prior = OwnerPriorTurn {
seq,
prompt_saved_pos,
prompt_len: state.prompt_len,
reply_saved_pos,
total_len,
prompt_tip_id,
reply_tip_id,
tip_id: live_tip,
spilled_tip_id: None,
spilled_prompt_tip_id: None,
tail_toks,
truncated_tail,
evicted: state.prompt_saved_pos > prompt_saved_pos || state.reply_saved_pos > reply_saved_pos,
};
if let Some(old_prior) = self.owner_prior.insert(state.owner, new_prior) {
self.unregister_prior_checkpoint_ids(state.owner, &old_prior);
}
if let Some(cur_prior) = self.owner_prior.get(&state.owner).cloned() {
self.register_prior_checkpoint_ids(state.owner, &cur_prior);
}
}
state.namespace = 0;
state.prompt_len = 0;
state.written = 0;
state.stitched_approx = false;
state.approx_path = false;
state.owner = 0;
state.side_call = false;
state.save_owner_turn = 0;
state.prompt_saved_pos = 0;
state.prompt_saved_id = None;
state.bound_start_id = None;
state.reply_saved_pos = 0;
state.reply_saved_id = None;
state.tail_toks.clear();
state.observed_prior = ObservedPrior::default();
state.internal_resume = false;
state.resume_reply_tokens = 0;
self.stats.lanes_released += 1;
turn_end
}
pub fn release_lane_invalid(
&mut self,
pools: &mut BlockPools,
tbl: &mut BlockTable,
state: &mut LaneBlockState,
) -> usize {
let key = |kind: BlockKind, e: BlockEntry| (kind_idx(kind) as u8, e.slot().get(), e.generation());
let mut suspect: HashSet<(u8, u32, u32)> = tbl.entries().map(|(_, e)| key(e.kind(), e)).collect();
if let Some(ckpt) = &state.turn_ckpt {
suspect.extend(ckpt.window.iter().map(|&(_, we)| key(BlockKind::Window, we)));
}
Self::drop_turn_checkpoint(pools, state);
state.turn_ckpt_miss = Some(TurnEndMiss::OffPath);
self.release_lane_with_toks(pools, tbl, state, None, true);
let mut victims: Vec<(std::cmp::Reverse<usize>, u64, SealedId)> = self
.starts
.iter()
.filter(|(_, st)| st.entries.iter().any(|&(kind, _, e)| suspect.contains(&key(kind, e))))
.map(|(&sid, st)| (std::cmp::Reverse(st.pos), st.last_used_tick, sid))
.collect();
victims.sort_by_key(|&(pos, tick, _)| (pos, tick));
let mut evicted = 0;
for (_, _, sid) in victims {
if self.evict_start_inner(pools, sid, false, None, EvictCause::StaleInvalid) {
evicted += 1;
}
}
let mut pending_victims: Vec<u64> = self
.pending_spills
.iter()
.filter(|(_, pending)| {
pending
.claimed_keys
.iter()
.any(|sk| self.spill_key_to_entry.get(sk).is_some_and(|ek| suspect.contains(ek)))
})
.map(|(&spill_id, _)| spill_id)
.collect();
pending_victims.sort_unstable();
for spill_id in pending_victims {
self.fail_pending_spill(pools, spill_id);
}
evicted
}
pub fn shutdown(&mut self, pools: &mut BlockPools) {
self.cancel_all_restores(pools);
self.stop_spill_writer(pools);
while self.evict_one_lru_start_with_cause(pools, false, None, EvictCause::Shutdown) {}
let window = &pools.window;
self.stitch_guards.retain(|&(s, g)| window.record(s).is_ok_and(|r| r.generation() == g && r.refs() > 0));
self.latest_owner_turn.clear();
self.owner_prior.clear();
self.prior_checkpoint_owners.clear();
}
}
#[cfg(standalone_blocks)]
#[derive(Clone, Debug)]
pub struct OwnershipSnapshot {
pub num_full: usize,
pub num_win: usize,
pub full_refs: Vec<u32>,
pub win_refs: Vec<u32>,
pub full_gen: Vec<u32>,
pub win_gen: Vec<u32>,
pub start_full_refs: Vec<u32>,
pub start_win_refs: Vec<u32>,
pub actual_start_full_refs: Vec<u32>,
pub actual_start_win_refs: Vec<u32>,
pub table_full_refs: Vec<u32>,
pub table_win_refs: Vec<u32>,
pub free_plus_evict_full: usize,
pub free_plus_evict_win: usize,
pub lane_full_blocks: Vec<Vec<u32>>,
pub lane_win_blocks: Vec<Vec<u32>>,
pub lane_win_count: Vec<usize>,
pub all_lane_entries_live: bool,
pub all_start_entries_live_sealed: bool,
pub tree_start_holders_match: bool,
pub tree_pins_match_lanes: bool,
pub expired_win_present: bool,
pub spill_owners_consistent: bool,
pub spilled_tips_consistent: bool,
pub retained_starts: usize,
pub spilled_starts: usize,
pub tree_nodes: usize,
pub stitch_index_buckets: usize,
}
#[cfg(standalone_blocks)]
impl ServeBlockCache {
pub fn ownership_snapshot(
&self,
pools: &BlockPools,
lanes: &[(&BlockTable, &LaneBlockState)],
) -> OwnershipSnapshot {
let num_full = pools.full.len();
let num_win = pools.window.len();
let mut full_refs = Vec::with_capacity(num_full);
let mut full_gen = Vec::with_capacity(num_full);
for i in 0..num_full {
let slot = Slot::new((i + 1) as u32).unwrap();
let r = pools.full.record(slot).unwrap();
full_refs.push(r.refs());
full_gen.push(r.generation());
}
let mut win_refs = Vec::with_capacity(num_win);
let mut win_gen = Vec::with_capacity(num_win);
for i in 0..num_win {
let slot = Slot::new((i + 1) as u32).unwrap();
let r = pools.window.record(slot).unwrap();
win_refs.push(r.refs());
win_gen.push(r.generation());
}
let mut start_full_refs = vec![0u32; num_full];
for (i, &c) in self.start_slot_refs[kind_idx(BlockKind::Full)].iter().enumerate() {
if i < num_full {
start_full_refs[i] = c;
}
}
let mut start_win_refs = vec![0u32; num_win];
for (i, &c) in self.start_slot_refs[kind_idx(BlockKind::Window)].iter().enumerate() {
if i < num_win {
start_win_refs[i] = c;
}
}
let mut actual_start_full_refs = vec![0u32; num_full];
let mut actual_start_win_refs = vec![0u32; num_win];
let mut all_start_entries_live_sealed = true;
for st in self.starts.values() {
if st.reasons == 0 {
all_start_entries_live_sealed = false;
}
for &(kind, _, e) in &st.entries {
if !self.entry_is_valid_kv(pools, kind, e) {
all_start_entries_live_sealed = false;
}
let idx = e.slot().pool_index().get() as usize;
match kind {
BlockKind::Full => actual_start_full_refs[idx] += 1,
BlockKind::Window => actual_start_win_refs[idx] += 1,
}
}
}
let mut table_full_refs = vec![0u32; num_full];
let mut table_win_refs = vec![0u32; num_win];
let mut lane_full_blocks = Vec::with_capacity(lanes.len());
let mut lane_win_blocks = Vec::with_capacity(lanes.len());
let mut lane_win_count = Vec::with_capacity(lanes.len());
let mut all_lane_entries_live = true;
let mut expired_win_present = false;
let mut expected_pins: HashMap<SealedId, u32> = HashMap::new();
for &(tbl, st) in lanes {
let mut f_blks = Vec::new();
let mut w_blks = Vec::new();
let min_live_win_blk = if st.written > 0 { st.written.saturating_sub(EXT - 1) / BLOCK } else { 0 };
for (bi, e) in tbl.entries() {
let pool = pools.of(e.kind());
match pool.record(e.slot()) {
Ok(rec) if rec.generation() == e.generation() && rec.refs() > 0 => {}
_ => all_lane_entries_live = false,
}
let idx = e.slot().pool_index().get() as usize;
match e.kind() {
BlockKind::Full => {
table_full_refs[idx] += 1;
f_blks.push(bi.get());
}
BlockKind::Window => {
table_win_refs[idx] += 1;
w_blks.push(bi.get());
if st.written > 0 && (bi.get() as usize) < min_live_win_blk {
expired_win_present = true;
}
}
}
}
if let Some(ckpt) = &st.turn_ckpt {
for &(_, we) in &ckpt.window {
if self.is_stitch_guard(we) || !entry_is_live_sealed(pools, BlockKind::Window, we) {
all_lane_entries_live = false;
}
table_win_refs[we.slot().pool_index().get() as usize] += 1;
}
}
lane_win_count.push(w_blks.len());
lane_full_blocks.push(f_blks);
lane_win_blocks.push(w_blks);
for &sid in &st.sealed {
*expected_pins.entry(sid).or_insert(0) += 1;
}
}
let mut tree_start_holders_match = true;
let mut tree_pins_match_lanes = true;
let tree_entries = self.tree.entries();
let tree_ids: HashSet<SealedId> = tree_entries.iter().map(|&(id, _)| id).collect();
for &sid in self.starts.keys() {
if !tree_ids.contains(&sid) || self.tree.start_holders(sid) == 0 {
tree_start_holders_match = false;
}
}
for (&sid, &want) in &expected_pins {
if !tree_ids.contains(&sid) || self.tree.pin_count(sid) != want {
tree_pins_match_lanes = false;
}
}
for (sid, _) in tree_entries {
let want_start = u32::from(self.starts.contains_key(&sid));
if self.tree.start_holders(sid) != want_start {
tree_start_holders_match = false;
}
let want_pin = expected_pins.get(&sid).copied().unwrap_or(0);
if self.tree.pin_count(sid) != want_pin {
tree_pins_match_lanes = false;
}
}
let mut expected_owners: HashMap<SpillKey, Vec<u64>> = HashMap::new();
let mut spilled_tips_consistent = self.spilled_tips.len() == self.spilled_starts.len();
for (&spill_id, sp) in &self.spilled_starts {
if sp.reasons == 0 {
spilled_tips_consistent = false;
}
match self.spilled_tips.get(&spill_id) {
Some(&tip) => {
if self.spilled_tree.start_holders(tip) == 0 || self.spilled_tree.handle(tip) != Some(spill_id) {
spilled_tips_consistent = false;
}
}
None => spilled_tips_consistent = false,
}
for sk in std::iter::once(sp.cs_key).chain(sp.entries.iter().map(|&(_, _, k)| k)) {
expected_owners.entry(sk).or_default().push(spill_id);
}
}
let mut spill_owners_consistent = expected_owners.len() == self.spill_key_owners.len();
if spill_owners_consistent {
for (sk, mut want) in expected_owners {
want.sort_unstable();
match self.spill_key_owners.get(&sk) {
Some(got_raw) => {
let mut got = got_raw.clone();
got.sort_unstable();
if got != want {
spill_owners_consistent = false;
break;
}
if let Some(store) = &self.spill_store {
if !store.contains(sk) {
spill_owners_consistent = false;
break;
}
}
}
None => {
spill_owners_consistent = false;
break;
}
}
}
}
OwnershipSnapshot {
num_full,
num_win,
full_refs,
win_refs,
full_gen,
win_gen,
start_full_refs,
start_win_refs,
actual_start_full_refs,
actual_start_win_refs,
table_full_refs,
table_win_refs,
free_plus_evict_full: self.free_plus_evictable_slots(pools, BlockKind::Full),
free_plus_evict_win: self.free_plus_evictable_slots(pools, BlockKind::Window),
lane_full_blocks,
lane_win_blocks,
lane_win_count,
all_lane_entries_live,
all_start_entries_live_sealed,
tree_start_holders_match,
tree_pins_match_lanes,
expired_win_present,
spill_owners_consistent,
spilled_tips_consistent,
retained_starts: self.starts.len(),
spilled_starts: self.spilled_starts.len(),
tree_nodes: self.tree.entries().len(),
stitch_index_buckets: self.stitch_index.len(),
}
}
pub fn expected_deepest_live_at(&self, pools: &BlockPools, namespace: u64, toks: &[u32]) -> usize {
if toks.len() <= 1 {
return 0;
}
let prefix = &toks[..toks.len() - 1];
let mut best = 0usize;
for st in self.starts.values() {
if st.namespace == namespace
&& st.pos <= prefix.len()
&& !st.toks.is_empty()
&& prefix.starts_with(&st.toks)
&& st.entries.iter().all(|&(k, _, e)| entry_is_live_sealed(pools, k, e))
{
best = best.max(st.pos);
}
}
let ram = self.peek_match_len_in_namespace(pools, namespace, toks);
best = best.max(ram);
for (&sid, st) in &self.starts {
if st.namespace == namespace && st.pos > best && st.pos <= prefix.len() {
let _ = sid;
}
}
if self.spill_store.is_some() {
let disk = self.spilled_tree.deepest_start_in_namespace(namespace, prefix).at;
best = best.max(disk);
}
best
}
}
#[cfg(test)]
mod tests {
use super::*;
mod spill_model;
mod spill_writer;
#[cfg(not(standalone_blocks))]
mod file_reuse;
mod turn_end_start;
fn fake_cs(tag: u8) -> Vec<u8> {
vec![tag; 16]
}
#[test]
fn window_pruning_visits_each_expired_block_once() {
assert_eq!(newly_expired_window_blocks(0, 2048), 0..16);
assert_eq!(newly_expired_window_blocks(2048, 4096), 16..48);
let pos = 131072;
let first_live = (pos - EXT) / BLOCK;
let visited: Vec<_> = (pos..pos + BLOCK).flat_map(|p| newly_expired_window_blocks(p, p + 1)).collect();
assert_eq!(visited, vec![first_live]);
assert_eq!(newly_expired_window_blocks(pos, pos + BLOCK - 2), first_live..first_live);
assert_eq!(newly_expired_window_blocks(pos + BLOCK - 2, pos + BLOCK - 1), first_live..first_live + 1);
}
#[test]
fn effective_pf_target_stops_at_every_and_prompt_boundaries() {
assert_eq!(effective_pf_target(0, 18), 18);
assert_eq!(effective_pf_target(0, 64), 64);
let mut p = 0;
let mut stops = Vec::new();
while p < 8266 {
let next = effective_pf_target(p, 8266);
assert!(next > p && next <= 8266);
stops.push(next);
p = next;
}
assert_eq!(stops, vec![2048, 4096, 6144, 8192, 8256, 8266]);
assert_eq!(effective_pf_target(6144, 8256), 8192);
assert_eq!(effective_pf_target(8192, 8256), 8256);
assert_eq!(effective_pf_target(16384, 25000), 20480);
assert_eq!(effective_pf_target(20480, 25000), 24576);
assert_eq!(effective_pf_target(24576, 25000), 24960);
assert_eq!(effective_pf_target(24960, 25000), 25000);
}
#[test]
fn multiturn_reuse_and_cross_card_sharing_with_zero_leaks() {
let mut pools = BlockPools::with_capacities(512, 256, 2).unwrap();
let mut cache = ServeBlockCache::new();
let mut tbl = BlockTable::new(512).unwrap();
let mut st = LaneBlockState::default();
let turn1: Vec<u32> = (0..8266u32).map(|i| (i * 17 + 3) % 50000).collect();
assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &turn1).is_none());
let mut p = 0;
while p < turn1.len() {
let next = effective_pf_target(p, turn1.len());
cache.ensure_span_blocks(&mut pools, &mut tbl, p, next - p).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &turn1, p, next - p, || {
fake_cs((next / BLOCK) as u8)
});
p = next;
}
for d in 0..100 {
let pos = turn1.len() + d;
cache.ensure_span_blocks(&mut pools, &mut tbl, pos, 1).unwrap();
cache.finish_decode_span(&mut pools, &mut tbl, &mut st, pos);
}
cache.release_lane(&mut pools, &mut tbl, &mut st);
assert_eq!(cache.retained_start_count(), 5);
let mut turn2 = turn1.clone();
turn2.extend((0..140u32).map(|i| 60000 + i));
let (matched, cs) = cache
.match_and_bind(&mut pools, &mut tbl, &mut st, &turn2)
.expect("Turn 2 must match Turn 1 prompt checkpoint");
assert_eq!(matched, 8256);
assert_eq!(cs, fake_cs((8256 / BLOCK) as u8));
let oldest = BlockIndex::new(((matched - EXT) / BLOCK) as u32);
let near_boundary = matched + BLOCK - 2;
for (start, end) in [(matched, near_boundary), (near_boundary, near_boundary + 1)] {
cache.ensure_span_blocks(&mut pools, &mut tbl, start, end - start).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &turn2, start, end - start, || fake_cs(0));
assert_eq!(tbl.get(BlockKind::Window, oldest).unwrap().is_some(), end == near_boundary);
assert!(tbl.get(BlockKind::Full, oldest).unwrap().is_some());
}
cache.release_lane(&mut pools, &mut tbl, &mut st);
let mut card2 = turn1[..6500].to_vec();
card2.extend((0..1000u32).map(|i| 70000 + i));
let (matched_c2, cs_c2) = cache
.match_and_bind(&mut pools, &mut tbl, &mut st, &card2)
.expect("Card 2 must match shared EVERY checkpoint");
assert_eq!(matched_c2, 6144);
assert_eq!(cs_c2, fake_cs((6144 / BLOCK) as u8));
cache.release_lane(&mut pools, &mut tbl, &mut st);
cache.shutdown(&mut pools);
assert_eq!(cache.retained_start_count(), 0);
assert_eq!(cache.free_plus_evictable_slots(&pools, BlockKind::Full), 512);
assert_eq!(cache.free_plus_evictable_slots(&pools, BlockKind::Window), 256);
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());
}
}
}
#[test]
fn lru_eviction_and_pool_pressure_guard_never_panic() {
let mut pools = BlockPools::with_capacities(80, 48, 2).unwrap();
let mut cache = ServeBlockCache::new();
let mut tbl = BlockTable::new(128).unwrap();
let mut st = LaneBlockState::default();
for req in 0..4u32 {
let toks: Vec<u32> = (0..1030u32).map(|i| req * 10000 + i).collect();
let _ = cache.match_and_bind(&mut pools, &mut tbl, &mut st, &toks);
let mut p = 0;
while p < toks.len() {
let next = effective_pf_target(p, toks.len());
cache.ensure_span_blocks(&mut pools, &mut tbl, p, next - p).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &toks, p, next - p, || fake_cs(req as u8));
p = next;
}
cache.release_lane(&mut pools, &mut tbl, &mut st);
}
assert!(cache.stats().start_points_evicted > 0, "tight pool must trigger LRU eviction");
let req3_ext: Vec<u32> = (0..1050u32).map(|i| 3 * 10000 + i).collect();
assert_eq!(cache.peek_match_len(&pools, &req3_ext), 1024);
let big: Vec<u32> = (0..4000u32).map(|i| 90000 + i).collect();
assert!(cache.can_admit(&pools, &[], 0, &big, 1024, 2048));
assert_eq!(
cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 3840),
Err(CacheError::PoolExhausted(BlockKind::Window))
);
cache.release_lane(&mut pools, &mut tbl, &mut st);
let active_toks: Vec<u32> = (0..3840u32).map(|i| 50000 + i).collect();
let mut ap = 0;
while ap < active_toks.len() {
let chunk_t = 1024.min(active_toks.len() - ap);
cache.ensure_span_blocks(&mut pools, &mut tbl, ap, chunk_t).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &active_toks, ap, chunk_t, || fake_cs(9));
ap += chunk_t;
}
assert!(
!cache.can_admit(
&pools,
&[InflightLaneReserve {
lane: 0,
namespace: 0,
toks: &active_toks,
block_hashes: None,
n_past: ap,
pf_end: ap,
cached: 0,
written: ap,
gen: 0,
max_gen: 1,
runnable: true
}],
1,
&big,
1024,
2048
),
"should defer when active lane consumes pool"
);
cache.release_lane(&mut pools, &mut tbl, &mut st);
cache.shutdown(&mut pools);
}
#[test]
fn concurrent_same_prefix_dedups_and_refreshes_expired_window() {
let mut pools = BlockPools::with_capacities(256, 128, 2).unwrap();
let mut cache = ServeBlockCache::new();
let mut tbl0 = BlockTable::new(256).unwrap();
let mut tbl1 = BlockTable::new(256).unwrap();
let mut st0 = LaneBlockState::default();
let mut st1 = LaneBlockState::default();
let prompt0: Vec<u32> = (0..2100u32).collect();
let mut p = 0;
while p < prompt0.len() {
let next = effective_pf_target(p, prompt0.len());
cache.ensure_span_blocks(&mut pools, &mut tbl0, p, next - p).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl0, &mut st0, &prompt0, p, next - p, || fake_cs(1));
p = next;
}
cache.release_lane(&mut pools, &mut tbl0, &mut st0);
let mut prompt1 = prompt0[..640].to_vec();
prompt1.extend((0..200u32).map(|i| 80000 + i));
assert!(cache.match_and_bind(&mut pools, &mut tbl1, &mut st1, &prompt1).is_none());
let mut p1 = 0;
while p1 < prompt1.len() {
let next = effective_pf_target(p1, prompt1.len());
cache.ensure_span_blocks(&mut pools, &mut tbl1, p1, next - p1).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl1, &mut st1, &prompt1, p1, next - p1, || fake_cs(2));
p1 = next;
}
cache.release_lane(&mut pools, &mut tbl1, &mut st1);
assert!(cache.stats().shared_dedups >= 10, "blocks 0..10 full slots should dedup");
let mut prompt0_ext = prompt0.clone();
prompt0_ext.push(99999);
assert_eq!(cache.peek_match_len(&pools, &prompt0_ext), 2048);
cache.shutdown(&mut pools);
}
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());
}
}
}
#[test]
fn singleflight_22_lanes_rebind_and_prefill_only_distinct_tails() {
use crate::scheduler::{ServeLaneInput, ServeStepPlan, ServeStepPlanner};
let mut pools = BlockPools::with_capacities(512, 512, 2).unwrap();
let mut cache = ServeBlockCache::new();
let prefix: Vec<u32> = (0..8500u32).map(|i| (i * 31 + 7) % 50000).collect();
struct SimLane {
toks: Vec<u32>,
tbl: BlockTable,
blocks: LaneBlockState,
n_past: usize,
cached: usize,
prefilled: usize,
cs: Vec<u8>,
active: bool,
}
let nlanes = 22usize;
let chunk = 4096usize;
let mut lanes: Vec<SimLane> = (0..nlanes)
.map(|i| {
let mut toks = prefix.clone();
toks.extend((0..300u32).map(|j| 60000 + (i as u32) * 1000 + j));
SimLane {
toks,
tbl: BlockTable::new(512).unwrap(),
blocks: LaneBlockState::default(),
n_past: 0,
cached: 0,
prefilled: 0,
cs: Vec::new(),
active: false,
}
})
.collect();
let mut planner = ServeStepPlanner::new(nlanes, 16);
for i in 0..nlanes {
let reserves: Vec<InflightLaneReserve<'_>> = lanes
.iter()
.enumerate()
.filter(|(_, l)| l.active)
.map(|(idx, l)| InflightLaneReserve {
lane: idx,
namespace: 0,
toks: &l.toks,
block_hashes: None,
n_past: l.n_past,
pf_end: l.toks.len(),
cached: l.cached,
written: l.blocks.written,
gen: 0,
max_gen: 128,
runnable: true,
})
.collect();
assert!(
cache.can_admit(&pools, &reserves, i, &lanes[i].toks, 128, chunk),
"lane {i} should admit under singleflight shared prefix accounting"
);
let l = &mut lanes[i];
assert!(cache.match_and_bind(&mut pools, &mut l.tbl, &mut l.blocks, &l.toks).is_none());
l.active = true;
planner.on_admit(i);
}
let mut checkpoints_sealed = false;
let mut leader_only_steps = 0usize;
loop {
if checkpoints_sealed {
checkpoints_sealed = false;
for l in &mut lanes {
if l.active && l.n_past == l.cached && l.blocks.written == l.n_past {
if let Some((matched_at, cs)) =
cache.rebind_if_deeper_match(&mut pools, &mut l.tbl, &mut l.blocks, &l.toks, l.n_past)
{
l.cs = cs;
l.n_past = matched_at;
l.cached = matched_at;
}
}
}
}
let cands: Vec<InflightPrefillLane<'_>> = lanes
.iter()
.enumerate()
.filter(|(_, l)| l.active && l.n_past < l.toks.len())
.map(|(i, l)| InflightPrefillLane {
lane: i,
namespace: 0,
toks: &l.toks,
block_hashes: None,
n_past: l.n_past,
pf_end: l.toks.len(),
runnable: true,
eligible_follower: l.n_past == l.cached && l.blocks.written == l.n_past,
})
.collect();
if cands.is_empty() {
break;
}
let mut deferred = vec![false; nlanes];
for (idx, c) in cands.iter().enumerate() {
if find_prefill_leader(&cands, idx).is_some() {
deferred[c.lane] = true;
}
}
let inputs: Vec<ServeLaneInput> = lanes
.iter()
.enumerate()
.map(|(i, l)| ServeLaneInput {
runnable: l.active && l.n_past < l.toks.len() && !deferred[i],
n_past: l.n_past,
pf_end: effective_pf_target(l.n_past, l.toks.len()),
has_pending_decode: false,
})
.collect();
let Some(ServeStepPlan::Prefill(spans)) = planner.plan_and_begin_step(&inputs, chunk, BLOCK) else {
panic!("expected prefill plan while lanes remain unfinished");
};
if lanes[0].n_past < 8192 {
assert_eq!(spans.len(), 1);
assert_eq!(spans[0].0, 0);
for f in 1..nlanes {
assert_eq!(planner.wait_ticks(f), 0);
}
leader_only_steps += 1;
}
let before_starts = cache.stats().start_points_saved;
for (i, p0, t) in spans {
let l = &mut lanes[i];
cache.ensure_span_blocks(&mut pools, &mut l.tbl, p0, t).unwrap();
cache.finish_prefill_span(&mut pools, &mut l.tbl, &mut l.blocks, &l.toks, p0, t, || {
fake_cs(((p0 + t) / BLOCK) as u8)
});
l.n_past = p0 + t;
l.prefilled += t;
}
if cache.stats().start_points_saved > before_starts {
checkpoints_sealed = true;
}
assert!(planner.complete_step().is_empty());
}
assert_eq!(leader_only_steps, 4, "lane 0 should run 4 leader chunks at 2048/4096/6144/8192");
assert_eq!(lanes[0].cached, 0);
assert_eq!(lanes[0].prefilled, 8800);
for (i, lane) in lanes.iter().enumerate().take(nlanes).skip(1) {
assert_eq!(lane.cached, 8192, "follower {i} should cache up to 8192");
assert_eq!(lane.prefilled, 608, "follower {i} should prefill only [8192..8800)");
assert_eq!(lane.cs, fake_cs((8192 / BLOCK) as u8));
}
assert!(cache.stats().singleflight_rebinds >= 21);
assert_eq!(cache.stats().singleflight_saved_tokens, 21 * 8192);
for l in &mut lanes {
cache.release_lane(&mut pools, &mut l.tbl, &mut l.blocks);
}
assert_eq!(cache.free_plus_evictable_slots(&pools, BlockKind::Full), 512);
assert_eq!(cache.free_plus_evictable_slots(&pools, BlockKind::Window), 512);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn singleflight_leader_cancellation_promotes_next_follower_without_leaks() {
use crate::scheduler::{ServeLaneInput, ServeStepPlan, ServeStepPlanner};
let mut pools = BlockPools::with_capacities(512, 256, 2).unwrap();
let mut cache = ServeBlockCache::new();
let prefix: Vec<u32> = (0..8500u32).map(|i| (i * 19 + 5) % 50000).collect();
let nlanes = 4usize;
let mut toks_list = Vec::with_capacity(nlanes);
let mut tbls = Vec::with_capacity(nlanes);
let mut blocks = Vec::with_capacity(nlanes);
let mut n_past = vec![0usize; nlanes];
let mut cached = vec![0usize; nlanes];
let mut active = vec![true; nlanes];
let mut planner = ServeStepPlanner::new(nlanes, 16);
for i in 0..nlanes {
let mut toks = prefix.clone();
toks.extend((0..300u32).map(|j| 70000 + (i as u32) * 1000 + j));
let mut tbl = BlockTable::new(512).unwrap();
let mut st = LaneBlockState::default();
assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &toks).is_none());
toks_list.push(toks);
tbls.push(tbl);
blocks.push(st);
planner.on_admit(i);
}
let inputs: Vec<ServeLaneInput> = (0..nlanes)
.map(|i| ServeLaneInput {
runnable: i == 0,
n_past: 0,
pf_end: effective_pf_target(0, toks_list[i].len()),
has_pending_decode: false,
})
.collect();
let Some(ServeStepPlan::Prefill(spans)) = planner.plan_and_begin_step(&inputs, 4096, BLOCK) else {
panic!("expected step 1 prefill");
};
assert_eq!(spans, vec![(0, 0, 2048)]);
cache.ensure_span_blocks(&mut pools, &mut tbls[0], 0, 2048).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbls[0], &mut blocks[0], &toks_list[0], 0, 2048, || fake_cs(32));
n_past[0] = 2048;
assert!(planner.complete_step().is_empty());
for i in 1..nlanes {
let (m, _) = cache
.rebind_if_deeper_match(&mut pools, &mut tbls[i], &mut blocks[i], &toks_list[i], n_past[i])
.expect("follower must rebind to 2048");
assert_eq!(m, 2048);
n_past[i] = m;
cached[i] = m;
}
assert!(planner.request_cancel(0));
cache.release_lane(&mut pools, &mut tbls[0], &mut blocks[0]);
active[0] = false;
let mut checkpoints_sealed = false;
loop {
if checkpoints_sealed {
checkpoints_sealed = false;
for i in 0..nlanes {
if active[i] && n_past[i] == cached[i] && blocks[i].written == n_past[i] {
if let Some((m, _)) = cache.rebind_if_deeper_match(
&mut pools,
&mut tbls[i],
&mut blocks[i],
&toks_list[i],
n_past[i],
) {
n_past[i] = m;
cached[i] = m;
}
}
}
}
let cands: Vec<InflightPrefillLane<'_>> = (0..nlanes)
.filter(|&i| active[i] && n_past[i] < toks_list[i].len())
.map(|i| InflightPrefillLane {
lane: i,
namespace: 0,
toks: &toks_list[i],
block_hashes: None,
n_past: n_past[i],
pf_end: toks_list[i].len(),
runnable: true,
eligible_follower: n_past[i] == cached[i] && blocks[i].written == n_past[i],
})
.collect();
if cands.is_empty() {
break;
}
let mut deferred = vec![false; nlanes];
for (idx, c) in cands.iter().enumerate() {
let leader = find_prefill_leader(&cands, idx);
if c.lane == 1 {
assert_eq!(leader, None, "lane 1 must immediately become leader after lane 0 cancels");
} else if n_past[c.lane] < 8192 {
assert_eq!(leader, Some(1), "lanes 2 and 3 must follow promoted lane 1");
}
if leader.is_some() {
deferred[c.lane] = true;
}
}
let inputs: Vec<ServeLaneInput> = (0..nlanes)
.map(|i| ServeLaneInput {
runnable: active[i] && n_past[i] < toks_list[i].len() && !deferred[i],
n_past: n_past[i],
pf_end: effective_pf_target(n_past[i], toks_list[i].len()),
has_pending_decode: false,
})
.collect();
let Some(ServeStepPlan::Prefill(spans)) = planner.plan_and_begin_step(&inputs, 4096, BLOCK) else {
panic!("expected prefill after leader promotion");
};
let before_starts = cache.stats().start_points_saved;
for (i, p0, t) in spans {
cache.ensure_span_blocks(&mut pools, &mut tbls[i], p0, t).unwrap();
cache
.finish_prefill_span(&mut pools, &mut tbls[i], &mut blocks[i], &toks_list[i], p0, t, || fake_cs(1));
n_past[i] = p0 + t;
}
if cache.stats().start_points_saved > before_starts {
checkpoints_sealed = true;
}
assert!(planner.complete_step().is_empty());
}
assert_eq!(cached[1], 2048);
assert_eq!(cached[2], 8192);
assert_eq!(cached[3], 8192);
for i in 1..nlanes {
cache.release_lane(&mut pools, &mut tbls[i], &mut blocks[i]);
}
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn singleflight_short_or_diverged_prompt_never_waits() {
let leader_toks: Vec<u32> = (0..8500u32).map(|i| i + 1).collect();
let short_toks: Vec<u32> = leader_toks[..1500].to_vec();
let mut diverged_toks = leader_toks.clone();
diverged_toks[100] ^= 0xffff;
let cands = vec![
InflightPrefillLane {
lane: 0,
namespace: 0,
toks: &leader_toks,
block_hashes: None,
n_past: 0,
pf_end: leader_toks.len(),
runnable: true,
eligible_follower: true,
},
InflightPrefillLane {
lane: 1,
namespace: 0,
toks: &short_toks,
block_hashes: None,
n_past: 0,
pf_end: short_toks.len(),
runnable: true,
eligible_follower: true,
},
InflightPrefillLane {
lane: 2,
namespace: 0,
toks: &diverged_toks,
block_hashes: None,
n_past: 0,
pf_end: diverged_toks.len(),
runnable: true,
eligible_follower: true,
},
];
assert_eq!(find_prefill_leader(&cands, 0), None);
assert_eq!(find_prefill_leader(&cands, 1), None, "prompt < EARLY_EVERY_TOKENS must never wait");
assert_eq!(find_prefill_leader(&cands, 2), None, "diverged prefix must never wait");
assert_eq!(inflight_shared_checkpoint(&cands[1], &cands[..1]), 0);
assert_eq!(inflight_shared_checkpoint(&cands[2], &cands[..1]), 0);
let mut matching = leader_toks.clone();
matching.extend(90000..90300);
let longer = InflightPrefillLane { lane: 1, toks: &matching, pf_end: matching.len(), ..cands[0] };
assert_eq!(
inflight_shared_checkpoint(&longer, &cands[..1]),
8192,
"only the common periodic boundary is promised"
);
let equal = InflightPrefillLane { lane: 1, ..cands[0] };
assert_eq!(inflight_shared_checkpoint(&equal, &cands[..1]), 8448);
}
#[test]
fn simultaneous_burst_admission_guard_prevents_midflight_exhaustion() {
let mut pools = BlockPools::with_capacities(130, 128, 1).unwrap();
let mut cache = ServeBlockCache::new();
let chunk = 2048usize;
let max_gen = 512usize;
struct BurstLane {
toks: Vec<u32>,
tbl: BlockTable,
blocks: LaneBlockState,
n_past: usize,
gen: usize,
active: bool,
}
let mut requests: Vec<Vec<u32>> =
(0..6u32).map(|r| (0..2000u32).map(|i| (r + 1) * 100_000 + i).collect()).collect();
let mut lanes: Vec<BurstLane> = Vec::new();
let mut queue: std::collections::VecDeque<Vec<u32>> = requests.drain(..).collect();
let mut admitted_wave1 = 0usize;
while let Some(toks) = queue.front() {
let reserves: Vec<InflightLaneReserve<'_>> = lanes
.iter()
.enumerate()
.filter(|(_, l)| l.active)
.map(|(idx, l)| InflightLaneReserve {
lane: idx,
namespace: 0,
toks: &l.toks,
block_hashes: None,
n_past: l.n_past,
pf_end: l.toks.len(),
cached: 0,
written: l.blocks.written,
gen: l.gen,
max_gen,
runnable: true,
})
.collect();
if !cache.can_admit(&pools, &reserves, lanes.len(), toks, max_gen, chunk) {
break;
}
let toks = queue.pop_front().unwrap();
let mut tbl = BlockTable::new(128).unwrap();
let mut blocks = LaneBlockState::default();
assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut blocks, &toks).is_none());
lanes.push(BurstLane { toks, tbl, blocks, n_past: 0, gen: 0, active: true });
admitted_wave1 += 1;
}
assert_eq!(admitted_wave1, 3, "must admit only the 3 requests that fit inside 130 Full slots");
assert_eq!(queue.len(), 3, "remaining 3 requests must stay queued, not admit and 500 later");
assert_eq!(cache.stats().admit_deferred_pool_pressure, 1);
loop {
let mut progressed = false;
for l in &mut lanes {
if !l.active {
continue;
}
progressed = true;
if l.n_past < l.toks.len() {
let next = effective_pf_target(l.n_past, l.toks.len());
cache
.ensure_span_blocks(&mut pools, &mut l.tbl, l.n_past, next - l.n_past)
.expect("admitted lane must never hit PoolExhausted during prefill");
cache.finish_prefill_span(
&mut pools,
&mut l.tbl,
&mut l.blocks,
&l.toks,
l.n_past,
next - l.n_past,
|| fake_cs(1),
);
l.n_past = next;
} else if l.gen < max_gen {
cache
.ensure_span_blocks(&mut pools, &mut l.tbl, l.n_past, 1)
.expect("admitted lane must never hit PoolExhausted during decode");
cache.finish_decode_span(&mut pools, &mut l.tbl, &mut l.blocks, l.n_past);
l.n_past += 1;
l.gen += 1;
} else {
cache.release_lane(&mut pools, &mut l.tbl, &mut l.blocks);
l.active = false;
}
}
while let Some(toks) = queue.front() {
let reserves: Vec<InflightLaneReserve<'_>> = lanes
.iter()
.enumerate()
.filter(|(_, l)| l.active)
.map(|(idx, l)| InflightLaneReserve {
lane: idx,
namespace: 0,
toks: &l.toks,
block_hashes: None,
n_past: l.n_past,
pf_end: l.toks.len(),
cached: 0,
written: l.blocks.written,
gen: l.gen,
max_gen,
runnable: true,
})
.collect();
if !cache.can_admit(&pools, &reserves, lanes.len(), toks, max_gen, chunk) {
break;
}
let toks = queue.pop_front().unwrap();
let mut tbl = BlockTable::new(128).unwrap();
let mut blocks = LaneBlockState::default();
let _ = cache.match_and_bind(&mut pools, &mut tbl, &mut blocks, &toks);
lanes.push(BurstLane { toks, tbl, blocks, n_past: 0, gen: 0, active: true });
}
if !progressed && queue.is_empty() {
break;
}
}
assert_eq!(lanes.len(), 6);
assert!(lanes.iter().all(|l| !l.active && l.gen == max_gen));
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn transactional_ensure_span_blocks_and_zero_500_deferral_drain() {
use crate::scheduler::{LaneState, ServeLaneInput, ServeStepPlan, ServeStepPlanner};
let mut pools = BlockPools::with_capacities(3, 8, 1).unwrap();
let mut cache = ServeBlockCache::new();
let mut tbl = BlockTable::new(16).unwrap();
assert_eq!(
cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 256),
Err(CacheError::PoolExhausted(BlockKind::Full))
);
for b in 0..4u32 {
let bi = BlockIndex::new(b);
assert_eq!(tbl.get(BlockKind::Full, bi).unwrap(), None, "block {b} Full must be rolled back");
assert_eq!(tbl.get(BlockKind::Window, bi).unwrap(), None, "block {b} Window must be rolled back");
}
assert_eq!(cache.free_plus_evictable_slots(&pools, BlockKind::Full), 3);
assert_eq!(cache.free_plus_evictable_slots(&pools, BlockKind::Window), 8);
assert_zero_pool_leaks(&pools);
let mut pools = BlockPools::with_capacities(10, 16, 1).unwrap();
let mut cache = ServeBlockCache::new();
let mut planner = ServeStepPlanner::new(2, 2);
let toks0: Vec<u32> = (0..384u32).collect(); let toks1: Vec<u32> = (1000..1512u32).collect(); let mut tbls = [BlockTable::new(32).unwrap(), BlockTable::new(32).unwrap()];
let mut blocks = [LaneBlockState::default(), LaneBlockState::default()];
let _ = cache.match_and_bind(&mut pools, &mut tbls[0], &mut blocks[0], &toks0);
cache.ensure_span_blocks(&mut pools, &mut tbls[0], 0, 384).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbls[0], &mut blocks[0], &toks0, 0, 384, || fake_cs(1));
let _ = cache.match_and_bind(&mut pools, &mut tbls[1], &mut blocks[1], &toks1);
planner.on_admit(0);
planner.on_admit(1);
let mut n_past = [384usize, 0usize];
let pf_end = [384usize, 512usize];
let mut gen = [0usize, 0usize];
let max_gen = [4usize, 1usize];
let mut active = [true, true];
let mut pool_deferred = [false, false];
let mut prev_released = cache.stats().lanes_released;
for _step in 0..32 {
if cache.stats().lanes_released != prev_released {
pool_deferred.fill(false);
prev_released = cache.stats().lanes_released;
}
if !active[0] && !active[1] {
break;
}
let inputs: Vec<ServeLaneInput> = (0..2)
.map(|i| ServeLaneInput {
runnable: active[i] && !pool_deferred[i],
n_past: n_past[i],
pf_end: if n_past[i] < pf_end[i] { effective_pf_target(n_past[i], pf_end[i]) } else { pf_end[i] },
has_pending_decode: active[i] && n_past[i] >= pf_end[i],
})
.collect();
let Some(plan) = planner.plan_and_begin_step(&inputs, 1024, BLOCK) else {
panic!("deadlock: no runnable step while lanes remain active");
};
match plan {
ServeStepPlan::Prefill(sp_list) => {
let mut live_sp = Vec::new();
for (i, p0, t) in sp_list {
match cache.ensure_span_blocks(&mut pools, &mut tbls[i], p0, t) {
Ok(()) => live_sp.push((i, p0, t)),
Err(CacheError::PoolExhausted(_)) => {
cache.record_step_deferred_pool_pressure();
pool_deferred[i] = true;
}
}
}
for (i, p0, t) in live_sp {
let toks = if i == 0 { &toks0 } else { &toks1 };
cache.finish_prefill_span(&mut pools, &mut tbls[i], &mut blocks[i], toks, p0, t, || fake_cs(2));
n_past[i] = p0 + t;
}
}
ServeStepPlan::Decode(need_dec) => {
for i in need_dec {
cache.ensure_span_blocks(&mut pools, &mut tbls[i], n_past[i], 1).unwrap();
cache.finish_decode_span(&mut pools, &mut tbls[i], &mut blocks[i], n_past[i]);
n_past[i] += 1;
gen[i] += 1;
if gen[i] >= max_gen[i] {
cache.release_lane(&mut pools, &mut tbls[i], &mut blocks[i]);
active[i] = false;
planner.on_finish(i);
}
}
}
ServeStepPlan::Mixed { .. } => unreachable!("mixed_steps defaults to false"),
}
assert!(planner.complete_step().is_empty());
for (i, &is_active) in active.iter().enumerate() {
if is_active {
assert_eq!(planner.state(i), LaneState::Ready);
}
}
}
assert!(!active[0] && !active[1], "both lanes must complete without HTTP 500");
assert!(cache.stats().step_deferred_pool_pressure >= 1);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
struct ScratchDir(std::path::PathBuf);
impl ScratchDir {
fn new(name: &str) -> Self {
let p = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("target")
.join("block-cache-spill-tests")
.join(format!("{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&p);
std::fs::create_dir_all(&p).unwrap();
Self(p)
}
}
impl Drop for ScratchDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn retain_test_prompt(
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
}
#[test]
#[ignore = "slow: runs in nightly unit-extras"]
fn long_spill_restore_keeps_source_and_accepts_early_fork() {
let dir = ScratchDir::new("long-fork");
let store = SpillStore::open(&dir.0, 100 * 1024 * 1024).unwrap();
let mut cache = ServeBlockCache::with_spill(store);
let mut pools = BlockPools::with_capacities(18, 18, 1).unwrap();
let mut tbl = BlockTable::new(20).unwrap();
let mut state = LaneBlockState::default();
let end = WINDOW + BLOCK;
let long: Vec<u32> = (0..=end as u32).collect();
let tip = retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut state, &long, 3);
assert!(cache.evict_start(&mut pools, tip));
let unrelated: Vec<u32> = (0..=128).map(|i| 20_000 + i).collect();
retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut state, &unrelated, 4);
assert_eq!(cache.match_and_bind(&mut pools, &mut tbl, &mut state, &long), Some((end, fake_cs(3))));
let root = state.sealed[0];
let root_full = cache.tree.handle(root).unwrap().full();
assert!(cache.tree.handle(root).unwrap().window().is_none());
cache.release_lane(&mut pools, &mut tbl, &mut state);
let mut fork = long[..BLOCK].to_vec();
fork.push(99_000);
assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut state, &fork).is_none());
cache.ensure_span_blocks(&mut pools, &mut tbl, 0, BLOCK).unwrap();
let recomputed_window = tbl.get(BlockKind::Window, BlockIndex::new(0)).unwrap().unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut state, &fork, 0, BLOCK, || fake_cs(5));
assert_eq!(state.sealed[0], root);
assert_eq!(cache.tree.handle(root).unwrap(), BlockHandles::new(root_full, Some(recomputed_window)));
assert_eq!(tbl.get(BlockKind::Full, BlockIndex::new(0)).unwrap(), Some(root_full));
cache.ensure_span_blocks(&mut pools, &mut tbl, BLOCK, 1).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut state, &fork, BLOCK, 1, || fake_cs(6));
cache.release_lane(&mut pools, &mut tbl, &mut state);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
#[ignore = "slow: runs in nightly unit-extras"]
fn spill_read_failure_releases_provisional_blocks_and_preserves_resident_match() {
let dir = ScratchDir::new("stream-rollback");
let store = SpillStore::open(&dir.0, 64 * 1024 * 1024).unwrap();
let mut cache = ServeBlockCache::with_spill(store);
let mut pools = BlockPools::with_capacities(16, 16, 1).unwrap();
let mut tbl = BlockTable::new(16).unwrap();
let mut state = LaneBlockState::default();
let long: Vec<u32> = (0..=6 * BLOCK as u32).collect();
let short = &long[..BLOCK + 1];
retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut state, short, 1);
let tip = retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut state, &long, 2);
assert!(cache.evict_start(&mut pools, tip));
let checkpoint = cache.spilled_starts.values().next().unwrap();
let (_, _, last_file) = *checkpoint.entries.last().unwrap();
std::fs::remove_file(cache.spill_store().unwrap().block_path(last_file)).unwrap();
let before = cache.stats().slots_taken;
assert_eq!(cache.match_and_bind(&mut pools, &mut tbl, &mut state, &long), Some((BLOCK, fake_cs(1))));
assert!(cache.stats().slots_taken > before, "earlier files used bounded provisional slots");
assert_eq!(cache.stats().starts_restored, 0);
assert_eq!(cache.retained_start_count(), 1);
assert_eq!(cache.spilled_start_count(), 0);
cache.release_lane(&mut pools, &mut tbl, &mut state);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
#[ignore = "slow: runs in nightly unit-extras"]
fn spill_store_eviction_restore_and_corrupt_fallback() {
let dir = ScratchDir::new("e2e");
let store = SpillStore::open_with_kvb(&dir.0, 256 * 1024 * 1024, 1).unwrap();
let mut pools = BlockPools::with_capacities(24, 16, 1).unwrap();
let mut cache = ServeBlockCache::with_spill(store);
let mut tbl = BlockTable::new(32).unwrap();
let mut st = LaneBlockState::default();
let prompt0: Vec<u32> = (0..576u32).map(|i| 10_000 + i).collect();
let prompt1: Vec<u32> = (0..576u32).map(|i| 20_000 + i).collect();
let prompt2: Vec<u32> = (0..576u32).map(|i| 30_000 + i).collect();
let run_prompt = |cache: &mut ServeBlockCache,
pools: &mut BlockPools,
tbl: &mut BlockTable,
st: &mut LaneBlockState,
toks: &[u32],
tag: u8| {
assert!(cache.match_and_bind(pools, tbl, st, toks).is_none());
let mut p = 0;
while p < toks.len() {
let next = effective_pf_target(p, toks.len());
cache.ensure_span_blocks(pools, tbl, p, next - p).unwrap();
for b in (p / BLOCK)..=((next - 1) / BLOCK) {
let bi = BlockIndex::new(b as u32);
for kind in KINDS {
let e = tbl.get(kind, bi).unwrap().unwrap();
if !pools.of(kind).record(e.slot()).unwrap().sealed() {
let bytes = pools.of_mut(kind).slot_bytes_mut(e.slot()).unwrap();
bytes[0] = tag;
bytes[1] = b as u8;
bytes[bytes.len() - 1] = tag.wrapping_add(b as u8);
}
}
}
cache.finish_prefill_span(pools, tbl, st, toks, p, next - p, || fake_cs(tag));
p = next;
}
cache.release_lane(pools, tbl, st);
};
run_prompt(&mut cache, &mut pools, &mut tbl, &mut st, &prompt0, 0xA1);
run_prompt(&mut cache, &mut pools, &mut tbl, &mut st, &prompt1, 0xB2);
run_prompt(&mut cache, &mut pools, &mut tbl, &mut st, &prompt2, 0xC3);
assert!(cache.stats().starts_spilled >= 1, "LRU eviction must spill prompt0 to SpillStore");
assert!(cache.spilled_start_count() >= 1);
assert!(cache.spill_store().unwrap().entry_count() > 0);
let mut prompt0_ext = prompt0[..512].to_vec();
prompt0_ext.extend(99_000..99_040);
assert_eq!(cache.peek_match_len(&pools, &prompt0_ext), 0);
let (matched_at, cs) = cache
.match_and_bind(&mut pools, &mut tbl, &mut st, &prompt0_ext)
.expect("must restore spilled prompt0 checkpoint from SSD");
assert_eq!(matched_at, 512);
assert_eq!(cs, fake_cs(0xA1));
assert_eq!(cache.stats().starts_restored, 1);
for b in 0..8usize {
let bi = BlockIndex::new(b as u32);
for kind in KINDS {
let e = tbl.get(kind, bi).unwrap().unwrap();
let bytes = pools.of(kind).slot_bytes(e.slot()).unwrap();
assert_eq!(bytes[0], 0xA1);
assert_eq!(bytes[1], b as u8);
assert_eq!(bytes[bytes.len() - 1], 0xA1u8.wrapping_add(b as u8));
}
}
cache.release_lane(&mut pools, &mut tbl, &mut st);
let prompt3: Vec<u32> = (0..576u32).map(|i| 40_000 + i).collect();
run_prompt(&mut cache, &mut pools, &mut tbl, &mut st, &prompt3, 0xD4);
assert!(cache.spilled_start_count() >= 1);
let mut corrupted_one = false;
for entry in std::fs::read_dir(&dir.0).unwrap() {
let path = entry.unwrap().path();
if path.extension().and_then(|e| e.to_str()) == Some("blk") {
let mut data = std::fs::read(&path).unwrap();
let last = data.len() - 1;
data[last] ^= 0xff;
std::fs::write(&path, data).unwrap();
corrupted_one = true;
break;
}
}
assert!(corrupted_one);
let mut prompt1_ext = prompt1[..512].to_vec();
prompt1_ext.extend(88_000..88_040);
let m1 = cache.match_and_bind(&mut pools, &mut tbl, &mut st, &prompt1_ext);
cache.release_lane(&mut pools, &mut tbl, &mut st);
let mut prompt2_ext = prompt2[..512].to_vec();
prompt2_ext.extend(77_000..77_040);
let m2 = cache.match_and_bind(&mut pools, &mut tbl, &mut st, &prompt2_ext);
cache.release_lane(&mut pools, &mut tbl, &mut st);
assert!(m1.is_none() || m2.is_none(), "corrupted .blk must fall back to clean cache miss");
assert!(cache.spill_store().unwrap().stats().corrupt_files_removed >= 1);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
#[ignore = "slow: runs in nightly unit-extras"]
fn maintain_spill_during_gpu_trims_excess_spilled_starts_without_touching_pools() {
let dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("target")
.join(format!("block-cache-maint-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let store = SpillStore::open_with_kvb(&dir, 256 * 1024 * 1024, 1).unwrap();
let mut pools = BlockPools::with_capacities(16, 16, 1).unwrap();
let mut cache = ServeBlockCache::with_spill(store);
let mut tbl = BlockTable::new(16).unwrap();
let mut st = LaneBlockState::default();
for base in [1000u32, 2000u32, 3000u32] {
let p: Vec<u32> = (0..576u32).map(|i| base + i).collect();
assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &p).is_none());
let mut pos = 0;
while pos < p.len() {
let next = effective_pf_target(pos, p.len());
cache.ensure_span_blocks(&mut pools, &mut tbl, pos, next - pos).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &p, pos, next - pos, || {
fake_cs((base / 1000) as u8)
});
pos = next;
}
cache.release_lane(&mut pools, &mut tbl, &mut st);
}
assert!(cache.spilled_start_count() >= 1);
let used_slots = |p: &crate::blocks::BlockPool| {
(1..=p.len()).filter(|&i| p.record(Slot::new(i as u32).unwrap()).unwrap().refs() > 0).count()
};
let used_before = used_slots(&pools.full);
cache.max_spilled_starts = 0;
let trimmed = cache.maintain_spill_during_gpu();
assert!(trimmed >= 1);
assert_eq!(cache.spilled_start_count(), 0);
assert_eq!(cache.spill_store().unwrap().entry_count(), 0);
assert_eq!(cache.stats().spill_maint_passes, 1);
assert_eq!(used_slots(&pools.full), used_before, "RAM pool slots must not be mutated during GPU overlap");
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn doomed_allocation_and_mid_span_rollback_preserve_cached_starts_without_spill() {
let dir = ScratchDir::new("u105-bounded-evict");
let store = SpillStore::open_with_kvb(&dir.0, 64 * 1024 * 1024, 1).unwrap();
let mut pools = BlockPools::with_capacities(10, 16, 1).unwrap();
let mut cache = ServeBlockCache::with_spill(store);
let mut tbl_active = BlockTable::new(32).unwrap();
let mut st_active = LaneBlockState::default();
let mut tbl = BlockTable::new(32).unwrap();
let mut st = LaneBlockState::default();
let p_a: Vec<u32> = (0..=192u32).map(|i| 1_000 + i).collect();
let p_b: Vec<u32> = (0..=192u32).map(|i| 2_000 + i).collect();
retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut st, &p_a, 0x11);
retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut st, &p_b, 0x22);
assert_eq!(cache.retained_start_count(), 2);
cache.ensure_span_blocks(&mut pools, &mut tbl_active, 0, 128).unwrap();
assert_eq!(cache.free_plus_evictable_slots(&pools, BlockKind::Full), 8);
assert_eq!(cache.stats().start_points_evicted, 0);
assert_eq!(cache.stats().starts_spilled, 0);
let mut doomed_tbl = BlockTable::new(32).unwrap();
assert_eq!(
cache.ensure_span_blocks(&mut pools, &mut doomed_tbl, 0, 9 * BLOCK),
Err(CacheError::PoolExhausted(BlockKind::Full))
);
assert_eq!(cache.retained_start_count(), 2, "doomed span must not empty cached start points");
assert_eq!(cache.stats().start_points_evicted, 0, "zero start points evicted on doomed span");
assert_eq!(cache.stats().starts_spilled, 0, "zero start points spilled on doomed span");
assert_eq!(cache.spilled_start_count(), 0);
assert_eq!(cache.peek_match_len(&pools, &p_a), 192);
assert_eq!(cache.peek_match_len(&pools, &p_b), 192);
let mut pin_a_tbl = BlockTable::new(32).unwrap();
let mut pin_a_st = LaneBlockState::default();
let mut pin_b_tbl = BlockTable::new(32).unwrap();
let mut pin_b_st = LaneBlockState::default();
assert_eq!(cache.match_and_bind(&mut pools, &mut pin_a_tbl, &mut pin_a_st, &p_a).unwrap().0, 192);
assert_eq!(cache.match_and_bind(&mut pools, &mut pin_b_tbl, &mut pin_b_st, &p_b).unwrap().0, 192);
cache.ensure_span_blocks(&mut pools, &mut tbl_active, 128, 128).unwrap();
assert_eq!(cache.free_plus_evictable_slots(&pools, BlockKind::Full), 0);
assert_eq!(
cache.take_zeroed_slot(&mut pools, BlockKind::Full),
Err(CacheError::PoolExhausted(BlockKind::Full))
);
assert_eq!(cache.retained_start_count(), 2, "active-pinned starts must not be evicted on exhaustion");
assert_eq!(cache.stats().start_points_evicted, 0);
cache.release_lane(&mut pools, &mut pin_a_tbl, &mut pin_a_st);
cache.release_lane(&mut pools, &mut pin_b_tbl, &mut pin_b_st);
cache.release_lane(&mut pools, &mut tbl_active, &mut st_active);
cache.ensure_span_blocks(&mut pools, &mut tbl_active, 0, 128).unwrap();
assert_eq!(cache.free_plus_evictable_slots(&pools, BlockKind::Full), 8);
let mut rb_tbl = BlockTable::new(32).unwrap();
assert_eq!(
cache.try_ensure_span_blocks_with(&mut pools, &mut rb_tbl, 0, 4 * BLOCK, |blk, kind| {
if blk == 2 && kind == BlockKind::Full {
Err(CacheError::PoolExhausted(BlockKind::Full))
} else {
Ok(())
}
}),
Err(CacheError::PoolExhausted(BlockKind::Full))
);
for b in 0..4u32 {
assert_eq!(rb_tbl.get(BlockKind::Full, BlockIndex::new(b)).unwrap(), None);
assert_eq!(rb_tbl.get(BlockKind::Window, BlockIndex::new(b)).unwrap(), None);
}
assert_eq!(cache.retained_start_count(), 2, "rolled-back span must leave both cached starts intact");
assert_eq!(cache.stats().start_points_evicted, 0);
assert_eq!(cache.stats().starts_spilled, 0);
cache.ensure_span_blocks(&mut pools, &mut rb_tbl, 0, 4 * BLOCK).unwrap();
assert_eq!(cache.retained_start_count(), 1, "only the 1 needed LRU victim may be evicted");
assert_eq!(cache.stats().start_points_evicted, 1);
assert_eq!(cache.peek_match_len(&pools, &p_b), 192, "newer start p_b must remain warm in RAM");
cache.release_lane(&mut pools, &mut rb_tbl, &mut st);
cache.release_lane(&mut pools, &mut tbl_active, &mut st_active);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn failed_rebind_leaves_lane_prior_bindings_intact() {
let mut pools = BlockPools::with_capacities(32, 32, 1).unwrap();
let mut cache = ServeBlockCache::new();
let mut tbl = BlockTable::new(2).unwrap();
let mut st = LaneBlockState::default();
let full_prompt: Vec<u32> = (0..=256u32).map(|i| 5000 + i).collect();
let short_prompt = &full_prompt[..=128]; let _tip128 = retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut st, short_prompt, 0x11);
let (matched, cs) = cache.match_and_bind(&mut pools, &mut tbl, &mut st, &full_prompt).unwrap();
assert_eq!(matched, 128);
assert_eq!(cs, fake_cs(0x11));
let prior_b0_full = tbl.get(BlockKind::Full, BlockIndex::new(0)).unwrap().unwrap();
let prior_b1_full = tbl.get(BlockKind::Full, BlockIndex::new(1)).unwrap().unwrap();
let prior_sealed = st.sealed.clone();
let mut tbl2 = BlockTable::new(8).unwrap();
let mut st2 = LaneBlockState::default();
let tip256 = retain_test_prompt(&mut cache, &mut pools, &mut tbl2, &mut st2, &full_prompt, 0x33);
assert_eq!(cache.rebind_if_deeper_match(&mut pools, &mut tbl, &mut st, &full_prompt, 128), None);
assert_eq!(st.written, 128);
assert_eq!(st.sealed, prior_sealed);
assert_eq!(tbl.get(BlockKind::Full, BlockIndex::new(0)).unwrap(), Some(prior_b0_full));
assert_eq!(tbl.get(BlockKind::Full, BlockIndex::new(1)).unwrap(), Some(prior_b1_full));
cache.release_lane(&mut pools, &mut tbl, &mut st);
let mut tbl_wide = BlockTable::new(8).unwrap();
assert!(cache.evict_start(&mut pools, tip256));
let (matched_w, _) = cache.match_and_bind(&mut pools, &mut tbl_wide, &mut st, &full_prompt).unwrap();
assert_eq!(matched_w, 128);
let tip256_stale = retain_test_prompt(&mut cache, &mut pools, &mut tbl2, &mut st2, &full_prompt, 0x44);
{
let bad = cache.starts.get_mut(&tip256_stale).unwrap().entries.last_mut().unwrap();
pools.of_mut(bad.0).record_mut(bad.2.slot()).unwrap().drop_ref().unwrap();
bad.2 = BlockEntry::new(bad.2.slot(), bad.2.generation() + 99, bad.2.offset(), bad.0, bad.2.kvb());
}
assert_eq!(cache.rebind_if_deeper_match(&mut pools, &mut tbl_wide, &mut st, &full_prompt, 128), None);
assert_eq!(st.written, 128);
assert_eq!(st.sealed, prior_sealed);
assert_eq!(tbl_wide.get(BlockKind::Full, BlockIndex::new(0)).unwrap(), Some(prior_b0_full));
assert_eq!(tbl_wide.get(BlockKind::Full, BlockIndex::new(1)).unwrap(), Some(prior_b1_full));
cache.release_lane(&mut pools, &mut tbl_wide, &mut st);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
#[ignore = "slow: runs in nightly unit-extras"]
fn spill_retained_start_owns_reused_disk_blocks_across_trim_and_same_tip_overwrite() {
let dir = ScratchDir::new("reused-disk-ownership");
let store = SpillStore::open_with_kvb(&dir.0, 256 * 1024 * 1024, 1).unwrap();
let mut pools = BlockPools::with_capacities(32, 32, 1).unwrap();
let mut cache = ServeBlockCache::with_spill(store);
cache.max_spilled_starts = 1;
let mut tbl = BlockTable::new(32).unwrap();
let mut st = LaneBlockState::default();
let prompt_a: Vec<u32> = (0..=128u32).map(|i| 70_000 + i).collect();
let mut prompt_b: Vec<u32> = prompt_a[..64].to_vec();
prompt_b.extend((0..=128u32).map(|i| 80_000 + i));
let tip_a = retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut st, &prompt_a, 0x41);
let tip_b = retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut st, &prompt_b, 0x42);
assert!(cache.evict_start(&mut pools, tip_a));
assert_eq!(cache.spilled_start_count(), 1);
assert!(cache.evict_start(&mut pools, tip_b));
assert_eq!(cache.spilled_start_count(), 1);
let (matched_b, cs_b) = cache
.match_and_bind(&mut pools, &mut tbl, &mut st, &prompt_b)
.expect("Prompt B must restore cleanly including shared reused block 0");
assert_eq!(matched_b, 192);
assert_eq!(cs_b, fake_cs(0x42));
cache.max_spilled_starts = 4;
let tip_b_restored = *st.sealed.last().unwrap();
assert!(cache.evict_start(&mut pools, tip_b_restored));
assert_eq!(cache.spilled_start_count(), 1);
let mut tbl2 = BlockTable::new(32).unwrap();
let mut st2 = LaneBlockState { prompt_len: prompt_b.len(), ..Default::default() };
cache.ensure_span_blocks(&mut pools, &mut tbl2, 0, 192).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl2, &mut st2, &prompt_b, 0, 192, || fake_cs(0x43));
let tip_b_dup = *st2.sealed.last().unwrap();
cache.release_lane(&mut pools, &mut tbl2, &mut st2);
cache.release_lane(&mut pools, &mut tbl, &mut st);
assert!(cache.evict_start(&mut pools, tip_b_dup));
assert_eq!(cache.spilled_start_count(), 1);
let (matched_b3, cs_b3) = cache
.match_and_bind(&mut pools, &mut tbl, &mut st, &prompt_b)
.expect("same-tip re-spilled start must retain its reused disk blocks");
assert_eq!(matched_b3, 192);
assert_eq!(cs_b3, fake_cs(0x43));
cache.release_lane(&mut pools, &mut tbl, &mut st);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
#[ignore = "slow: runs in nightly unit-extras"]
fn spill_index_persists_across_reopen_and_async_restore_keeps_decoding_responsive() {
let dir = ScratchDir::new("persist-and-async");
{
let store = SpillStore::open_with_kvb(&dir.0, 128 * 1024 * 1024, 1).unwrap();
let mut pools = BlockPools::with_capacities(16, 16, 1).unwrap();
let mut cache = ServeBlockCache::with_spill(store);
let mut tbl = BlockTable::new(32).unwrap();
let mut st = LaneBlockState::default();
let p0: Vec<u32> = (0..=512u32).map(|i| 10_000 + i).collect();
let tip0 = retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut st, &p0, 0x5A);
assert!(cache.evict_start(&mut pools, tip0));
assert_eq!(cache.spilled_start_count(), 1);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
let store = SpillStore::open_with_kvb(&dir.0, 128 * 1024 * 1024, 1).unwrap();
let mut pools = BlockPools::with_capacities(24, 24, 1).unwrap();
let mut cache = ServeBlockCache::with_spill(store);
assert_eq!(cache.spilled_start_count(), 1, "spilled start index must reload across restart");
let target_dir = dir.0.clone();
let entered = Arc::new((Mutex::new(false), Condvar::new()));
let release = Arc::new((Mutex::new(false), Condvar::new()));
let entered_bg = entered.clone();
let release_bg = release.clone();
struct ReadHookGuard(Vec<Arc<(Mutex<bool>, Condvar)>>);
impl Drop for ReadHookGuard {
fn drop(&mut self) {
crate::spill::set_test_spill_read_hook(None);
for b in &self.0 {
*b.0.lock().unwrap() = true;
b.1.notify_all();
}
}
}
let hold = Arc::new((Mutex::new(false), Condvar::new()));
let _hook_guard = ReadHookGuard(vec![release.clone(), hold.clone()]);
crate::spill::set_test_spill_read_hook(Some(Arc::new(move |d, _key| {
if d == target_dir {
let mut e = entered_bg.0.lock().unwrap();
if !*e {
*e = true;
entered_bg.1.notify_all();
drop(e);
let mut r = release_bg.0.lock().unwrap();
while !*r {
r = release_bg.1.wait(r).unwrap();
}
}
}
})));
let mut planner = crate::scheduler::ServeStepPlanner::new(3, 16);
let mut tbl0 = BlockTable::new(32).unwrap();
let mut st0 = LaneBlockState::default();
let p_dec: Vec<u32> = (0..=64u32).map(|i| 90_000 + i).collect();
retain_test_prompt(&mut cache, &mut pools, &mut tbl0, &mut st0, &p_dec, 0x33);
let _ = cache.match_and_bind(&mut pools, &mut tbl0, &mut st0, &p_dec);
planner.on_admit(0);
let mut tbl1 = BlockTable::new(32).unwrap();
let mut st1 = LaneBlockState::default();
let mut p0_cont: Vec<u32> = (0..=512u32).map(|i| 10_000 + i).collect();
p0_cont.extend(70_000..70_020);
match cache.begin_admit_bind(&mut pools, 1, &mut tbl1, &mut st1, &p0_cont) {
AdmitBindOutcome::Restoring { target_pos } => {
assert_eq!(target_pos, 512);
planner.admit_queued(1, crate::scheduler::LaneState::Queued);
planner.start_restore(1);
}
other => panic!("expected Restoring from reloaded spill index, got {other:?}"),
}
{
let e = entered.0.lock().unwrap();
let (_guard, timeout) = entered
.1
.wait_timeout_while(e, crate::serve::TEST_HANG_GUARD, |entered| !*entered)
.unwrap();
assert!(!timeout.timed_out(), "hang guard: background restore worker did not enter read");
}
for dec_pos in 64usize..72 {
let done = cache.poll_restores(&mut pools, |_| None);
assert!(done.is_empty(), "restore is still held on barrier");
let inputs = [
crate::scheduler::ServeLaneInput {
runnable: true,
n_past: dec_pos,
pf_end: 64,
has_pending_decode: true,
},
crate::scheduler::ServeLaneInput {
runnable: true,
n_past: 0,
pf_end: p0_cont.len(),
has_pending_decode: false,
},
crate::scheduler::ServeLaneInput { runnable: false, n_past: 0, pf_end: 0, has_pending_decode: false },
];
let plan = planner.plan_and_begin_step(&inputs, 2048, BLOCK).unwrap();
assert_eq!(plan, crate::scheduler::ServeStepPlan::Decode(vec![0]));
cache.ensure_span_blocks(&mut pools, &mut tbl0, dec_pos, 1).unwrap();
cache.finish_decode_span(&mut pools, &mut tbl0, &mut st0, dec_pos);
assert!(planner.complete_step().is_empty());
}
assert!(!*release.0.lock().unwrap(), "restore barrier stayed closed across all 8 decode steps");
{
*release.0.lock().unwrap() = true;
release.1.notify_all();
}
crate::spill::set_test_spill_read_hook(None);
let began = Instant::now();
let mut finished = None;
while began.elapsed() < crate::serve::TEST_HANG_GUARD {
let tbl1_ptr: *mut BlockTable = &mut tbl1;
let st1_ptr: *mut LaneBlockState = &mut st1;
let mut done = cache.poll_restores(&mut pools, |l| (l == 1).then_some((&(), tbl1_ptr, st1_ptr)));
if let Some(c) = done.pop() {
finished = Some(c);
break;
}
cache.wait_restore_activity(Duration::from_millis(5));
}
let c = finished.expect("restore must finish after barrier release");
assert!(!c.corrupt_fallback);
assert_eq!(c.matched, Some((512, fake_cs(0x5A))));
planner.finish_restore(1);
assert_eq!(planner.state(1), crate::scheduler::LaneState::Ready);
assert_eq!(cache.stats().starts_restored, 1);
let p2: Vec<u32> = (0..=256u32).map(|i| 40_000 + i).collect();
let mut tbl2 = BlockTable::new(32).unwrap();
let mut st2 = LaneBlockState::default();
let tip2 = retain_test_prompt(&mut cache, &mut pools, &mut tbl2, &mut st2, &p2, 0x77);
assert!(cache.evict_start(&mut pools, tip2));
let hold_bg = hold.clone();
let dir2 = dir.0.clone();
crate::spill::set_test_spill_read_hook(Some(Arc::new(move |d, _| {
if d == dir2 {
let mut h = hold_bg.0.lock().unwrap();
while !*h {
h = hold_bg.1.wait(h).unwrap();
}
}
})));
let mut p2_cont = p2.clone();
p2_cont.push(999);
assert!(matches!(
cache.begin_admit_bind(&mut pools, 2, &mut tbl2, &mut st2, &p2_cont),
AdmitBindOutcome::Restoring { target_pos: 256 }
));
planner.admit_queued(2, crate::scheduler::LaneState::Queued);
planner.start_restore(2);
assert!(planner.request_cancel(2));
assert!(cache.cancel_restore(&mut pools, 2));
*hold.0.lock().unwrap() = true;
hold.1.notify_all();
crate::spill::set_test_spill_read_hook(None);
cache.release_lane(&mut pools, &mut tbl0, &mut st0);
cache.release_lane(&mut pools, &mut tbl1, &mut st1);
cache.release_lane(&mut pools, &mut tbl2, &mut st2);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn retained_host_copy_budget_and_spill_deadline_bound_host_work() {
let dir = ScratchDir::new("host-budget-and-deadline");
let store = SpillStore::open_with_kvb(&dir.0, 128 * 1024 * 1024, 1).unwrap();
let mut pools = BlockPools::with_capacities(32, 32, 1).unwrap();
let mut cache = ServeBlockCache::with_spill(store);
let mut tbl = BlockTable::new(32).unwrap();
let mut st = LaneBlockState::default();
cache.set_max_retained_host_bytes(6 * 1024);
let p0: Vec<u32> = (0..=64u32).map(|i| 1000 + i).collect();
let p1: Vec<u32> = (0..=64u32).map(|i| 2000 + i).collect();
for (p, tag) in [(&p0, 0x10u8), (&p1, 0x20u8)] {
let _ = cache.match_and_bind(&mut pools, &mut tbl, &mut st, p);
cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 64).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, p, 0, 64, || vec![tag; 4096]);
cache.release_lane(&mut pools, &mut tbl, &mut st);
}
assert_eq!(cache.retained_start_count(), 1, "host byte budget must evict older retained start");
assert!(cache.retained_host_bytes() <= 6 * 1024);
assert_eq!(cache.spilled_start_count(), 1, "evicted checkpoint spills within deadline");
cache.set_spill_write_timeout(Duration::ZERO);
let p2: Vec<u32> = (0..=64u32).map(|i| 3000 + i).collect();
let _ = cache.match_and_bind(&mut pools, &mut tbl, &mut st, &p2);
cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 64).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &p2, 0, 64, || vec![0x30; 4096]);
cache.release_lane(&mut pools, &mut tbl, &mut st);
assert_eq!(cache.stats().spill_write_timeouts, 1);
assert_eq!(cache.retained_start_count(), 1);
cache.shutdown(&mut pools);
assert_eq!(cache.retained_host_bytes(), 0);
assert_zero_pool_leaks(&pools);
}
#[test]
fn cache_namespace_isolates_ram_singleflight_and_ssd_restore() {
let dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("target")
.join(format!("block-cache-ns-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let store = SpillStore::open_with_kvb(&dir, 128 * 1024 * 1024, 1).unwrap();
let mut pools = BlockPools::with_capacities(6, 6, 1).unwrap();
let mut cache = ServeBlockCache::with_spill(store);
let mut tbl_a = BlockTable::new(16).unwrap();
let mut st_a = LaneBlockState::default();
let mut tbl_b = BlockTable::new(16).unwrap();
let mut st_b = LaneBlockState::default();
let prompt: Vec<u32> = (0..2100u32).map(|i| i * 31 + 7).collect();
let ext_prompt: Vec<u32> = (0..2200u32).map(|i| i * 31 + 7).collect();
let cands = [
InflightPrefillLane {
lane: 0,
namespace: 0xAAAA,
toks: &prompt,
block_hashes: None,
n_past: 0,
pf_end: prompt.len(),
runnable: true,
eligible_follower: true,
},
InflightPrefillLane {
lane: 1,
namespace: 0xBBBB,
toks: &prompt,
block_hashes: None,
n_past: 0,
pf_end: prompt.len(),
runnable: true,
eligible_follower: true,
},
InflightPrefillLane {
lane: 2,
namespace: 0xAAAA,
toks: &prompt,
block_hashes: None,
n_past: 0,
pf_end: prompt.len(),
runnable: true,
eligible_follower: true,
},
];
assert_eq!(find_prefill_leader(&cands, 1), None, "different namespace must never singleflight-wait");
assert_eq!(find_prefill_leader(&cands, 2), Some(0), "same namespace shares leader");
let short_p = prompt[..135].to_vec();
let short_ext = ext_prompt[..195].to_vec();
assert!(cache.match_and_bind_in_namespace(&mut pools, &mut tbl_a, &mut st_a, 0xAAAA, &short_p).is_none());
cache.ensure_span_blocks(&mut pools, &mut tbl_a, 0, 128).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_a, &mut st_a, &short_p, 0, 128, || fake_cs(0x41));
cache.ensure_span_blocks(&mut pools, &mut tbl_a, 128, 7).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_a, &mut st_a, &short_p, 128, 7, || fake_cs(0x42));
cache.release_lane(&mut pools, &mut tbl_a, &mut st_a);
assert!(
cache.match_and_bind_in_namespace(&mut pools, &mut tbl_b, &mut st_b, 0xBBBB, &short_ext).is_none(),
"cross-principal RAM lookup must miss"
);
cache.release_lane(&mut pools, &mut tbl_b, &mut st_b);
let (hit_a, cs_a) = cache
.match_and_bind_in_namespace(&mut pools, &mut tbl_a, &mut st_a, 0xAAAA, &short_ext)
.expect("same-principal warm hit");
assert_eq!(hit_a, 128);
assert_eq!(cs_a, fake_cs(0x41));
cache.release_lane(&mut pools, &mut tbl_a, &mut st_a);
assert!(cache.evict_one_lru_start_inner(&mut pools, true, None));
assert_eq!(cache.retained_start_count(), 0);
assert_eq!(cache.spilled_start_count(), 1);
assert!(
cache.match_and_bind_in_namespace(&mut pools, &mut tbl_b, &mut st_b, 0xBBBB, &short_ext).is_none(),
"cross-principal SSD lookup must miss without restoring"
);
assert_eq!(cache.stats().starts_restored, 0);
assert_eq!(cache.spilled_start_count(), 1);
cache.release_lane(&mut pools, &mut tbl_b, &mut st_b);
let (restored_a, restored_cs) = cache
.match_and_bind_in_namespace(&mut pools, &mut tbl_a, &mut st_a, 0xAAAA, &short_ext)
.expect("same-principal SSD restore hit");
assert_eq!(restored_a, 128);
assert_eq!(restored_cs, fake_cs(0x41));
assert_eq!(cache.stats().starts_restored, 1);
cache.release_lane(&mut pools, &mut tbl_a, &mut st_a);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn verify_span_tracking_and_rollback_preserve_ownership_across_block_and_window_boundaries() {
let mut pools = BlockPools::with_capacities(32, 32, 2).unwrap();
let mut cache = ServeBlockCache::new();
let mut tbl = BlockTable::new(32).unwrap();
let mut st = LaneBlockState::default();
let prompt: Vec<u32> = (0..1022).map(|i| (i % 997) as u32 + 1).collect();
let _ = cache.begin_admit_bind(&mut pools, 0, &mut tbl, &mut st, &prompt);
cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 1022).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &prompt, 0, 1022, || fake_cs(1));
assert_eq!(st.written, 1022);
assert!(tbl.get(BlockKind::Window, BlockIndex::new(0)).unwrap().is_some());
let alloc = cache.ensure_span_blocks_tracking(&mut pools, &mut tbl, 1022, 4).unwrap();
assert_eq!(alloc.len(), 2, "must track newly allocated Full + Window block 16");
assert!(tbl.get(BlockKind::Full, BlockIndex::new(16)).unwrap().is_some());
assert!(tbl.get(BlockKind::Window, BlockIndex::new(16)).unwrap().is_some());
cache.finish_verify_span(&mut pools, &mut tbl, &mut st, &alloc, 1022, 2);
assert_eq!(st.written, 1024);
assert!(tbl.get(BlockKind::Full, BlockIndex::new(16)).unwrap().is_none());
assert!(tbl.get(BlockKind::Window, BlockIndex::new(16)).unwrap().is_none());
let b15_full = tbl.get(BlockKind::Full, BlockIndex::new(15)).unwrap().unwrap();
let rec15 = pools.full.record(b15_full.slot()).unwrap();
assert!(!rec15.sealed(), "verify must never seal block 15");
assert_eq!(rec15.length(), 64);
let alloc2 = cache.ensure_span_blocks_tracking(&mut pools, &mut tbl, 1024, 4).unwrap();
assert_eq!(alloc2.len(), 2);
cache.finish_verify_span(&mut pools, &mut tbl, &mut st, &alloc2, 1024, 0);
assert_eq!(st.written, 1024);
assert!(tbl.get(BlockKind::Full, BlockIndex::new(16)).unwrap().is_none());
assert!(tbl.get(BlockKind::Window, BlockIndex::new(16)).unwrap().is_none());
cache.release_lane(&mut pools, &mut tbl, &mut st);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
#[ignore = "slow: runs in nightly unit-extras"]
fn spill_index_rejects_full_attn_budget_and_model_fingerprint_mismatches() {
let dir = ScratchDir::new("spill-compat-header");
let prompt: Vec<u32> = (0..=128u32).map(|i| 20_000 + i).collect();
{
let mut pools = BlockPools::with_capacities(8, 8, 2).unwrap();
let store = SpillStore::open_with_kvb(&dir.0, 64 * 1024 * 1024, 2).unwrap();
let mut cache = ServeBlockCache::with_spill_compat(store, Some(1024), 0x1111);
let mut tbl = BlockTable::new(8).unwrap();
let mut st = LaneBlockState::default();
let tip = retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut st, &prompt, 9);
assert!(cache.evict_start(&mut pools, tip));
assert_eq!(cache.spilled_start_count(), 1);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
{
let store = SpillStore::open_with_kvb(&dir.0, 64 * 1024 * 1024, 2).unwrap();
let cache = ServeBlockCache::with_spill_compat(store, Some(1024), 0x1111);
assert_eq!(cache.spilled_start_count(), 1);
assert!(cache.spill_store().unwrap().entry_count() >= 1);
}
{
let store = SpillStore::open_with_kvb(&dir.0, 64 * 1024 * 1024, 2).unwrap();
let cache = ServeBlockCache::with_spill_compat(store, Some(2048), 0x1111);
assert_eq!(cache.spilled_start_count(), 0);
assert_eq!(cache.spill_store().unwrap().entry_count(), 0);
}
{
let mut pools = BlockPools::with_capacities(8, 8, 2).unwrap();
let store = SpillStore::open_with_kvb(&dir.0, 64 * 1024 * 1024, 2).unwrap();
let mut cache = ServeBlockCache::with_spill_compat(store, None, 0xAAAA);
let mut tbl = BlockTable::new(8).unwrap();
let mut st = LaneBlockState::default();
let tip = retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut st, &prompt, 9);
assert!(cache.evict_start(&mut pools, tip));
assert_eq!(cache.spilled_start_count(), 1);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
{
let store = SpillStore::open_with_kvb(&dir.0, 64 * 1024 * 1024, 2).unwrap();
let cache = ServeBlockCache::with_spill_compat(store, None, 0xBBBB);
assert_eq!(cache.spilled_start_count(), 0);
assert_eq!(cache.spill_store().unwrap().entry_count(), 0);
}
}
#[test]
fn kv4_serve_block_cache_keeps_exact_fp32_cs_and_binds_dc_digest_fingerprint() {
use crate::blocks::{KvMode, KVB_KV4};
use crate::spill::{Sha256, SpillError};
const CS_FLOATS: usize = 958_464; const CS_F32_BYTES: usize = CS_FLOATS * 4;
let mut raw_cs = Vec::with_capacity(CS_F32_BYTES);
for i in 0..CS_FLOATS {
let v = ((i as f32) * 0.001_37 - 400.0).sin() * 3.25;
raw_cs.extend_from_slice(&v.to_le_bytes());
}
let prompt: Vec<u32> = (0..=64u32).map(|i| 50_000 + i).collect();
let mut h_cal = Sha256::new();
h_cal.update(b"inky-kv4-codec-v1\0");
h_cal.update(&[1u8, 1u8, 1u8]);
h_cal.update(&vec![0x5au8; 98_304]);
let dc_digest = h_cal.finalize();
let model_fp = 0x1234_5678_9abc_def0u64 ^ u64::from_le_bytes(dc_digest[0..8].try_into().unwrap());
let dir = ScratchDir::new("kv4-cs-fp32-exact");
{
let mut pools = BlockPools::with_capacities_mode(4, 4, KvMode::Kv4).unwrap();
let store = SpillStore::open_with_kv4_digest(&dir.0, 64 * 1024 * 1024, dc_digest).unwrap();
let mut cache = ServeBlockCache::with_spill_compat(store, None, model_fp);
let mut tbl = BlockTable::new(4).unwrap();
let mut st = LaneBlockState { prompt_len: prompt.len(), ..Default::default() };
cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 64).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &prompt, 0, 64, || raw_cs.clone());
let tip = *st.sealed.last().unwrap();
cache.release_lane(&mut pools, &mut tbl, &mut st);
assert!(cache.retained_host_bytes() >= CS_F32_BYTES as u64);
let (matched_ram, cs_ram) = cache.match_and_bind(&mut pools, &mut tbl, &mut st, &prompt).unwrap();
assert_eq!(matched_ram, 64);
assert_eq!(cs_ram, raw_cs);
cache.release_lane(&mut pools, &mut tbl, &mut st);
assert!(cache.evict_start(&mut pools, tip));
assert_eq!(cache.spilled_start_count(), 1);
let ssd_used = cache.spill_store().unwrap().used_bytes();
let expected_ssd = crate::blocks::KV4_FULL_STRIDE
+ crate::blocks::KV4_WINDOW_STRIDE
+ CS_F32_BYTES as u64
+ 3 * (crate::spill::SPILL_HEADER_LEN as u64);
assert_eq!(ssd_used, expected_ssd);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
let mut wrong_digest = dc_digest;
wrong_digest[0] ^= 0xff;
assert!(matches!(
SpillStore::open_with_kv4_digest(&dir.0, 64 * 1024 * 1024, wrong_digest),
Err(SpillError::ModeMismatch { expected, found }) if expected == KVB_KV4 && found == KVB_KV4
));
{
let mut pools = BlockPools::with_capacities_mode(4, 4, KvMode::Kv4).unwrap();
let store = SpillStore::open_with_kv4_digest(&dir.0, 64 * 1024 * 1024, dc_digest).unwrap();
let mut cache = ServeBlockCache::with_spill_compat(store, None, model_fp);
assert_eq!(cache.spilled_start_count(), 1);
let mut tbl = BlockTable::new(4).unwrap();
let mut st = LaneBlockState { prompt_len: 64, ..Default::default() };
let (matched_ssd, cs_ssd) = cache.match_and_bind(&mut pools, &mut tbl, &mut st, &prompt).unwrap();
assert_eq!(matched_ssd, 64);
assert_eq!(cs_ssd, raw_cs);
cache.release_lane(&mut pools, &mut tbl, &mut st);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
}
#[test]
fn sparse_topk_spill_compat_and_restore_sketch_recompute() {
let dir = ScratchDir::new("sparse-topk-spill-compat");
let prompt: Vec<u32> = (0..=64u32).map(|i| 30_000 + i).collect();
let default_pools = BlockPools::with_capacities(2, 2, 1).unwrap();
assert!(!default_pools.full.has_sketches());
let spill_once = || {
let mut pools = BlockPools::with_capacities_and_sketches(2, 2, 1, true).unwrap();
let store = SpillStore::open_with_kvb(&dir.0, 32 * 1024 * 1024, 1).unwrap();
let mut cache = ServeBlockCache::with_spill_compat_sparse(store, None, Some(128), 4, 0xCCCC);
let mut tbl = BlockTable::new(4).unwrap();
let mut st = LaneBlockState::default();
let start = cache.match_and_bind(&mut pools, &mut tbl, &mut st, &prompt).map_or(0, |(p, _)| p);
let end = prompt.len() - 1;
cache.ensure_span_blocks(&mut pools, &mut tbl, start, end - start).unwrap();
let orig_slot = tbl.get(BlockKind::Full, BlockIndex::new(0)).unwrap().unwrap().slot();
for (i, b) in pools.full.slot_bytes_mut(orig_slot).unwrap().iter_mut().enumerate() {
*b = ((i.wrapping_mul(37).wrapping_add(13)) & 0x7f) as u8;
}
let mut expected_sketch = vec![0u8; crate::blocks::FULL_SKETCH_BYTES];
crate::blocks::compute_full_slot_wht2_sketch_cpu(
pools.full.slot_bytes(orig_slot).unwrap(),
1,
BLOCK,
&mut expected_sketch,
);
assert!(expected_sketch.iter().any(|&b| b != 0), "expected sketch must be non-trivial");
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &prompt, start, end - start, || fake_cs(9));
let tip = *st.sealed.last().unwrap();
cache.release_lane(&mut pools, &mut tbl, &mut st);
assert!(cache.evict_start(&mut pools, tip));
assert_eq!(cache.spilled_start_count(), 1);
for idx in 1..=2u32 {
let s = crate::blocks::Slot::new(idx).unwrap();
pools.full.slot_bytes_mut(s).unwrap().fill(0);
pools.full.slot_sketch_bytes_mut(s).unwrap().fill(0x5A);
}
let mut tbl2 = BlockTable::new(4).unwrap();
let mut st2 = LaneBlockState::default();
let matched = cache.match_and_bind(&mut pools, &mut tbl2, &mut st2, &prompt);
assert_eq!(matched.as_ref().map(|(at, _)| *at), Some(64));
let entry = tbl2.get(BlockKind::Full, BlockIndex::new(0)).unwrap().unwrap();
assert_eq!(pools.full.slot_sketch_valid_len(entry.slot()).unwrap(), BLOCK as u8);
assert_eq!(pools.full.slot_sketch_bytes(entry.slot()).unwrap(), expected_sketch.as_slice());
let restored_tip = *st2.sealed.last().unwrap();
cache.release_lane(&mut pools, &mut tbl2, &mut st2);
assert!(cache.evict_start(&mut pools, restored_tip));
assert_eq!(cache.spilled_start_count(), 1);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
};
spill_once();
{
let store = SpillStore::open_with_kvb(&dir.0, 32 * 1024 * 1024, 1).unwrap();
let cache = ServeBlockCache::with_spill_compat_sparse(store, None, Some(128), 4, 0xCCCC);
assert_eq!(cache.spilled_start_count(), 1);
}
{
let store = SpillStore::open_with_kvb(&dir.0, 32 * 1024 * 1024, 1).unwrap();
let cache = ServeBlockCache::with_spill_compat_sparse(store, None, Some(128), 8, 0xCCCC);
assert_eq!(cache.spilled_start_count(), 0);
assert_eq!(cache.spill_store().unwrap().entry_count(), 0);
}
spill_once();
{
let store = SpillStore::open_with_kvb(&dir.0, 32 * 1024 * 1024, 1).unwrap();
let cache = ServeBlockCache::with_spill_compat_sparse(store, None, Some(64), 4, 0xCCCC);
assert_eq!(cache.spilled_start_count(), 0);
assert_eq!(cache.spill_store().unwrap().entry_count(), 0);
}
spill_once();
{
let store = SpillStore::open_with_kvb(&dir.0, 32 * 1024 * 1024, 1).unwrap();
let cache = ServeBlockCache::with_spill_compat_sparse(store, None, None, 4, 0xCCCC);
assert_eq!(cache.spilled_start_count(), 0);
assert_eq!(cache.spill_store().unwrap().entry_count(), 0);
}
}
#[test]
fn kv4_and_sparse_topk_spill_restore_recomputes_wht2_sketch() {
use crate::blocks::{KvMode, KVB_KV4};
use crate::spill::Sha256;
let dir = ScratchDir::new("kv4-sparse-topk-spill");
let prompt: Vec<u32> = (0..=64u32).map(|i| 42_000 + i).collect();
let mut h_cal = Sha256::new();
h_cal.update(b"inky-kv4-codec-v1\0");
h_cal.update(&[1u8, 1u8, 1u8]);
h_cal.update(&vec![0x33u8; 98_304]);
let dc_digest = h_cal.finalize();
let model_fp = 0xCAFE_BABE_1234_5678u64 ^ u64::from_le_bytes(dc_digest[0..8].try_into().unwrap());
let mut pools = BlockPools::with_capacities_mode_and_sketches(2, 2, KvMode::Kv4, true).unwrap();
let store = SpillStore::open_with_kv4_digest(&dir.0, 64 * 1024 * 1024, dc_digest).unwrap();
let mut cache = ServeBlockCache::with_spill_compat_sparse(store, None, Some(4), 2, model_fp);
let mut tbl = BlockTable::new(4).unwrap();
let mut st = LaneBlockState::default();
let start = cache.match_and_bind(&mut pools, &mut tbl, &mut st, &prompt).map_or(0, |(p, _)| p);
let end = prompt.len() - 1;
cache.ensure_span_blocks(&mut pools, &mut tbl, start, end - start).unwrap();
let orig_slot = tbl.get(BlockKind::Full, BlockIndex::new(0)).unwrap().unwrap().slot();
{
let bytes = pools.full.slot_bytes_mut(orig_slot).unwrap();
let row_len = crate::blocks::KV4_ROW_BYTES as usize;
for (row_idx, chunk) in bytes.chunks_exact_mut(row_len).enumerate() {
for (j, b) in chunk[..64].iter_mut().enumerate() {
let lo = ((row_idx + j) % 16) as u8;
let hi = ((row_idx * 3 + j + 5) % 16) as u8;
*b = lo | (hi << 4);
}
let sc_bits = crate::blocks::f32_to_f16_bits(0.5 + ((row_idx % 7) as f32) * 0.125);
chunk[64..66].copy_from_slice(&sc_bits.to_le_bytes());
}
}
let mut expected_sketch = vec![0u8; crate::blocks::FULL_SKETCH_BYTES];
crate::blocks::compute_full_slot_wht2_sketch_cpu(
pools.full.slot_bytes(orig_slot).unwrap(),
KVB_KV4,
BLOCK,
&mut expected_sketch,
);
assert!(expected_sketch.iter().any(|&b| b != 0));
let raw_cs = fake_cs(77);
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &prompt, start, end - start, || raw_cs.clone());
let tip = *st.sealed.last().unwrap();
cache.release_lane(&mut pools, &mut tbl, &mut st);
assert!(cache.evict_start(&mut pools, tip));
assert_eq!(cache.spilled_start_count(), 1);
for idx in 1..=2u32 {
let s = crate::blocks::Slot::new(idx).unwrap();
pools.full.slot_bytes_mut(s).unwrap().fill(0);
pools.full.slot_sketch_bytes_mut(s).unwrap().fill(0xCC);
}
let mut tbl2 = BlockTable::new(4).unwrap();
let mut st2 = LaneBlockState::default();
let (matched, cs_out) = cache.match_and_bind(&mut pools, &mut tbl2, &mut st2, &prompt).unwrap();
assert_eq!(matched, 64);
assert_eq!(cs_out, raw_cs);
let entry = tbl2.get(BlockKind::Full, BlockIndex::new(0)).unwrap().unwrap();
assert_eq!(pools.full.slot_sketch_valid_len(entry.slot()).unwrap(), BLOCK as u8);
assert_eq!(pools.full.slot_sketch_bytes(entry.slot()).unwrap(), expected_sketch.as_slice());
cache.release_lane(&mut pools, &mut tbl2, &mut st2);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
fn stamp_test_full_block_rows(slot_bytes: &mut [u8], blk_toks: &[u32], kvb: u32) {
use crate::blocks::{key_row, kv4_key_row, Kv, KvMode};
assert_eq!(blk_toks.len(), BLOCK);
let mode = KvMode::from_kvb_tag(kvb).unwrap();
let row_bytes = mode.row_bytes() as usize;
for pass in 0..(FULL_PASSES as u32) {
for (plane, kv) in [(0u32, Kv::Key), (1u32, Kv::Value)] {
for head in 0..(NKV as u32) {
for (ib, &tok) in blk_toks.iter().enumerate() {
let off = if mode == KvMode::Kv4 {
kv4_key_row(0, BlockKind::Full, pass, kv, head, ib as u32).unwrap().0 as usize
} else {
key_row(0, BlockKind::Full, kvb, pass, kv, head, ib as u32).unwrap() as usize
};
for d in 0..row_bytes {
let v = tok
.wrapping_mul(131)
.wrapping_add(pass * 37)
.wrapping_add(plane * 19)
.wrapping_add(head * 7)
.wrapping_add(d as u32);
slot_bytes[off + d] = (v ^ (v >> 8) ^ (v >> 16)) as u8;
}
}
}
}
}
}
fn assert_test_full_block_rows_match(slot_bytes: &[u8], blk_toks: &[u32], kvb: u32) {
let mut expected = vec![0u8; slot_bytes.len()];
stamp_test_full_block_rows(&mut expected, blk_toks, kvb);
assert_eq!(slot_bytes, expected.as_slice(), "stitched Full block K/V rows diverged from token-exact reference");
}
#[test]
fn rolling_stitch_hash_64_matches_full_recompute_and_default_kv_stitch_is_disabled() {
let toks: Vec<u32> = (0..2600u32).map(|i| i.wrapping_mul(2654435761) % 65000).collect();
let mut h = stitch_hash_64(&toks[0..BLOCK]);
for i in 0..(toks.len() - BLOCK) {
assert_eq!(h, stitch_hash_64(&toks[i..i + BLOCK]), "rolling hash mismatch at {i}");
h = slide_stitch_hash_64(h, toks[i], toks[i + BLOCK]);
}
assert_eq!(h, stitch_hash_64(&toks[toks.len() - BLOCK..]));
let mut pools = BlockPools::with_capacities(96, 64, 1).unwrap();
let mut cache = ServeBlockCache::new();
assert!(!cache.kv_stitch_enabled(), "Decision 4 exactness requires --kv-stitch disabled by default");
let mut tbl = BlockTable::new(96).unwrap();
let mut st = LaneBlockState::default();
let _ = retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut st, &toks[..2049], 5);
let mut shifted = vec![77777u32; 83];
shifted.extend_from_slice(&toks[..2048]);
shifted.extend_from_slice(&[88888u32; 64]);
assert!(
cache.plan_stitches(&pools, 0, &shifted, 0).is_empty(),
"plan_stitches must return empty when kv_stitch is disabled"
);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn kv_stitch_disabled_touches_zero_stitch_state_and_matches_baseline_identically() {
let run_workload = |toggle_on_then_off: bool| -> (CacheStats, usize, u64) {
let mut pools = BlockPools::with_capacities(96, 64, 1).unwrap();
let mut cache = ServeBlockCache::new();
if toggle_on_then_off {
cache.set_kv_stitch(true);
cache.set_kv_stitch(false);
}
assert!(!cache.kv_stitch_enabled());
assert!(cache.stitch_index.is_empty());
let shared_doc: Vec<u32> = (0..2048u32).map(|i| 15_000 + i).collect();
let mut p1: Vec<u32> = (0..128u32).map(|i| 100 + i).collect();
p1.extend_from_slice(&shared_doc);
p1.push(99_999);
let mut tbl = BlockTable::new(96).unwrap();
let mut st = LaneBlockState::default();
let sid = retain_test_prompt(&mut cache, &mut pools, &mut tbl, &mut st, &p1, 0x77);
assert!(cache.stitch_index.is_empty(), "kv_stitch=false must never populate stitch_index");
assert!(
cache.starts.get(&sid).unwrap().toks.is_empty(),
"kv_stitch=false without spill_store must not retain token vectors in RAM"
);
let mut p1_followup = p1[..2176].to_vec();
p1_followup.extend_from_slice(&[55_555u32; 65]);
let matched = cache.match_and_bind(&mut pools, &mut tbl, &mut st, &p1_followup);
assert_eq!(matched.map(|m| m.0), Some(2176));
cache.release_lane(&mut pools, &mut tbl, &mut st);
let mut shifted: Vec<u32> = (0..147u32).map(|i| 800 + i).collect();
shifted.extend_from_slice(&shared_doc);
shifted.extend_from_slice(&[44_444u32; 129]);
assert!(cache.plan_stitches(&pools, 0, &shifted, 0).is_empty());
let forged = StitchSpanPlan {
span_start: 0,
stitch_start: 1024,
heal_start: 1536,
span_end: 3072,
source: StitchSource::Retained { sid, src_start: 1152 },
};
assert_eq!(
cache.apply_stitch_plan(&mut pools, &mut tbl, &mut st, &shifted, &forged),
StitchApplyOutcome::SourceGone
);
assert!(!st.stitched_approx);
assert_eq!(cache.stats().stitch_hits, 0);
assert_eq!(cache.stats().stitched_tokens_total, 0);
let stats = cache.stats();
let tree_len = cache.tree.entries().len();
let host_bytes = cache.retained_host_bytes;
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
(stats, tree_len, host_bytes)
};
let (stats_fresh, tree_fresh, host_fresh) = run_workload(false);
let (stats_toggled, tree_toggled, host_toggled) = run_workload(true);
assert_eq!(stats_fresh, stats_toggled);
assert_eq!(tree_fresh, tree_toggled);
assert_eq!(host_fresh, host_toggled);
}
#[test]
fn kv_stitch_provenance_isolation_keeps_entry_tree_exact_and_prevents_chained_stitches() {
let kvb = 1u32;
let mut pools = BlockPools::with_capacities(256, 96, kvb).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_kv_stitch(true);
let file_span: Vec<u32> = (0..3200u32).map(|i| 10_000 + i).collect(); let mut prompt_a: Vec<u32> = (0..128u32).map(|i| 1_000 + i).collect(); prompt_a.extend_from_slice(&file_span);
prompt_a.extend((0..257u32).map(|i| 40_000 + i));
let mut tbl_a = BlockTable::new(128).unwrap();
let mut st_a = LaneBlockState { prompt_len: prompt_a.len(), ..Default::default() };
for b in 0..56usize {
let p0 = b * BLOCK;
cache.ensure_span_blocks(&mut pools, &mut tbl_a, p0, BLOCK).unwrap();
let fe = tbl_a.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().unwrap();
stamp_test_full_block_rows(pools.full.slot_bytes_mut(fe.slot()).unwrap(), &prompt_a[p0..p0 + BLOCK], kvb);
cache.finish_prefill_span(&mut pools, &mut tbl_a, &mut st_a, &prompt_a, p0, BLOCK, || fake_cs(0x11));
}
cache.ensure_span_blocks(&mut pools, &mut tbl_a, 3584, 1).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_a, &mut st_a, &prompt_a, 3584, 1, || fake_cs(0x12));
let a_slots: Vec<Slot> = (0..56u32)
.map(|b| tbl_a.get(BlockKind::Full, BlockIndex::new(b)).unwrap().unwrap().slot())
.collect();
cache.release_lane(&mut pools, &mut tbl_a, &mut st_a);
let mut prompt_b: Vec<u32> = (0..256u32).map(|i| 2_000 + i).collect(); prompt_b.extend_from_slice(&file_span);
prompt_b.extend((0..129u32).map(|i| 50_000 + i));
let plans_b = cache.plan_stitches(&pools, 0, &prompt_b, 0);
assert_eq!(plans_b.len(), 1);
assert_eq!(plans_b[0].span_start, 256);
assert_eq!(plans_b[0].stitch_start, 1280);
assert_eq!(plans_b[0].heal_start, 1920);
assert_eq!(plans_b[0].span_end, 3456);
let mut tbl_b = BlockTable::new(128).unwrap();
let mut st_b = LaneBlockState { prompt_len: prompt_b.len(), ..Default::default() };
cache.ensure_span_blocks(&mut pools, &mut tbl_b, 0, 1280).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_b, &mut st_b, &prompt_b, 0, 1280, || fake_cs(0x21));
let out_b = cache.apply_stitch_plan(&mut pools, &mut tbl_b, &mut st_b, &prompt_b, &plans_b[0]);
assert_eq!(out_b, StitchApplyOutcome::Applied { stitched_tokens: 640, zero_copy_blocks: 10 });
assert!(st_b.stitched_approx);
assert_eq!(st_b.sealed.len(), 20, "post-stitch blocks must NEVER enter state.sealed / EntryTree");
for k in 0..10usize {
let slot_b = tbl_b.get(BlockKind::Full, BlockIndex::new((20 + k) as u32)).unwrap().unwrap().slot();
assert_eq!(slot_b, a_slots[18 + k], "aligned stitch block {k} must zero-copy share source Full slot");
}
cache.release_lane(&mut pools, &mut tbl_b, &mut st_b);
assert!(!st_b.stitched_approx, "release_lane must reset stitched_approx");
let unique_post_stitch_tail: Vec<u32> = (0..2817u32).map(|i| 60_000 + i).collect();
let mut prompt_c: Vec<u32> = (0..147u32).map(|i| 3_000 + i).collect();
prompt_c.extend_from_slice(&file_span); prompt_c.extend_from_slice(&unique_post_stitch_tail); let plans_c = cache.plan_stitches(&pools, 0, &prompt_c, 0);
assert_eq!(plans_c.len(), 1);
assert_eq!(plans_c[0].span_start, 147);
assert_eq!(plans_c[0].stitch_start, 1216);
assert_eq!(plans_c[0].heal_start, 1792);
assert_eq!(plans_c[0].span_end, 3347);
let mut tbl_c = BlockTable::new(128).unwrap();
let mut st_c = LaneBlockState { prompt_len: prompt_c.len(), ..Default::default() };
cache.ensure_span_blocks(&mut pools, &mut tbl_c, 0, 1216).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_c, &mut st_c, &prompt_c, 0, 1216, || fake_cs(0x31));
let starts_before = cache.stats().start_points_saved;
let tree_before = cache.tree.entries().len();
let stitch_buckets_before = cache.stitch_index.len();
let cached_total_before = cache.stats().cached_tokens_total;
let out_c = cache.apply_stitch_plan(&mut pools, &mut tbl_c, &mut st_c, &prompt_c, &plans_c[0]);
assert_eq!(out_c, StitchApplyOutcome::Applied { stitched_tokens: 576, zero_copy_blocks: 0 });
assert!(st_c.stitched_approx);
assert_eq!(st_c.written, 1792);
assert_eq!(cache.stats().cached_tokens_total, cached_total_before, "stitches must not inflate cached_tokens_total");
for b in 19..28usize {
let fe = tbl_c.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().unwrap();
assert_test_full_block_rows_match(
pools.full.slot_bytes(fe.slot()).unwrap(),
&prompt_c[b * BLOCK..(b + 1) * BLOCK],
kvb,
);
}
for b in 0..12u32 {
assert!(tbl_c.get(BlockKind::Window, BlockIndex::new(b)).unwrap().is_none(), "expired win {b} pruned");
}
for b in 12..28u32 {
assert!(tbl_c.get(BlockKind::Window, BlockIndex::new(b)).unwrap().is_some(), "healing win {b} present");
}
cache.ensure_span_blocks(&mut pools, &mut tbl_c, 1792, 2048 - 1792).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_c, &mut st_c, &prompt_c, 1792, 2048 - 1792, || fake_cs(0x32));
cache.ensure_span_blocks(&mut pools, &mut tbl_c, 2048, 4096 - 2048).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_c, &mut st_c, &prompt_c, 2048, 4096 - 2048, || fake_cs(0x33));
cache.ensure_span_blocks(&mut pools, &mut tbl_c, 4096, 6144 - 4096).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_c, &mut st_c, &prompt_c, 4096, 6144 - 4096, || fake_cs(0x34));
cache.ensure_span_blocks(&mut pools, &mut tbl_c, 6144, 6164 - 6144).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_c, &mut st_c, &prompt_c, 6144, 6164 - 6144, || fake_cs(0x35));
assert_eq!(cache.stats().start_points_saved, starts_before, "stitched lane must save zero RetainedStarts");
assert_eq!(cache.tree.entries().len(), tree_before, "stitched lane must insert zero post-stitch EntryTree nodes");
assert_eq!(cache.stitch_index.len(), stitch_buckets_before, "stitched lane must never index approximate blocks");
cache.release_lane(&mut pools, &mut tbl_c, &mut st_c);
cache.set_kv_stitch(false);
let mut tbl_exact = BlockTable::new(128).unwrap();
let mut st_exact = LaneBlockState::default();
assert_eq!(
cache.match_and_bind(&mut pools, &mut tbl_exact, &mut st_exact, &prompt_c),
None,
"exact request must never match a checkpoint from a prior stitched lane"
);
let dedups_before = cache.stats().shared_dedups;
cache.ensure_span_blocks(&mut pools, &mut tbl_exact, 0, 1408).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_exact, &mut st_exact, &prompt_c, 0, 1408, || fake_cs(0x55));
assert_eq!(
cache.stats().shared_dedups,
dedups_before,
"exact request must compute fresh blocks rather than deduping onto prior stitched blocks"
);
cache.release_lane(&mut pools, &mut tbl_exact, &mut st_exact);
cache.set_kv_stitch(true);
let mut chain_probe: Vec<u32> = (0..128u32).map(|i| 95_000 + i).collect();
chain_probe.extend_from_slice(&unique_post_stitch_tail);
chain_probe.extend((0..128u32).map(|i| 98_000 + i));
assert!(
cache.plan_stitches(&pools, 0, &chain_probe, 0).is_empty(),
"stitches must never chain onto spans seen only in a stitched lane"
);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn kv_stitch_plans_and_applies_multiple_spans_in_single_prompt() {
let kvb = 1u32;
let mut pools = BlockPools::with_capacities(320, 96, kvb).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_kv_stitch(true);
let file_1: Vec<u32> = (0..2944u32).map(|i| 110_000 + i).collect();
let file_2: Vec<u32> = (0..2944u32).map(|i| 210_000 + i).collect();
for (tag, file_toks) in [(0x11u8, &file_1), (0x22u8, &file_2)] {
let mut donor: Vec<u32> = (0..128u32).map(|i| u32::from(tag) * 1000 + i).collect();
donor.extend_from_slice(file_toks);
donor.push(777_777); let mut tbl = BlockTable::new(128).unwrap();
let mut st = LaneBlockState { prompt_len: donor.len(), ..Default::default() };
for b in 0..48usize {
let p0 = b * BLOCK;
cache.ensure_span_blocks(&mut pools, &mut tbl, p0, BLOCK).unwrap();
let fe = tbl.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().unwrap();
stamp_test_full_block_rows(pools.full.slot_bytes_mut(fe.slot()).unwrap(), &donor[p0..p0 + BLOCK], kvb);
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &donor, p0, BLOCK, || fake_cs(tag));
}
cache.ensure_span_blocks(&mut pools, &mut tbl, 3072, 1).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &donor, 3072, 1, || fake_cs(tag));
cache.release_lane(&mut pools, &mut tbl, &mut st);
}
let mut combined: Vec<u32> = (0..128u32).map(|i| 310_000 + i).collect();
combined.extend_from_slice(&file_1); combined.extend((0..151u32).map(|i| 320_000 + i)); combined.extend_from_slice(&file_2); combined.extend((0..128u32).map(|i| 330_000 + i));
let plans = cache.plan_stitches(&pools, 0, &combined, 0);
assert_eq!(plans.len(), 2, "must plan 2 non-overlapping stitch spans in a single prompt");
assert!(plans[0].span_end <= plans[1].stitch_start, "stitch spans must not overlap");
for p in &plans {
assert!(
p.stitch_start - p.span_start >= LEFT_HEAL_TOKENS,
"each span must reserve >= 1024 left-healing tokens"
);
assert!(
p.span_end - p.heal_start >= MIN_HEAL_TOKENS,
"each span must reserve >= 1536 right-healing tokens"
);
}
let mut tbl = BlockTable::new(128).unwrap();
let mut st = LaneBlockState { prompt_len: combined.len(), ..Default::default() };
let mut cur = 0usize;
for (idx, plan) in plans.iter().enumerate() {
if cur < plan.stitch_start {
cache.ensure_span_blocks(&mut pools, &mut tbl, cur, plan.stitch_start - cur).unwrap();
cache.finish_prefill_span(
&mut pools,
&mut tbl,
&mut st,
&combined,
cur,
plan.stitch_start - cur,
|| fake_cs(0x60 + idx as u8),
);
}
let out = cache.apply_stitch_plan(&mut pools, &mut tbl, &mut st, &combined, plan);
match (idx, out) {
(0, StitchApplyOutcome::Applied { zero_copy_blocks, .. }) => assert!(zero_copy_blocks > 0),
(1, StitchApplyOutcome::Applied { zero_copy_blocks: 0, .. }) => {}
other => panic!("unexpected multi-span stitch outcome: {other:?}"),
}
for b in (plan.stitch_start / BLOCK)..(plan.heal_start / BLOCK) {
let fe = tbl.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().unwrap();
assert_test_full_block_rows_match(
pools.full.slot_bytes(fe.slot()).unwrap(),
&combined[b * BLOCK..(b + 1) * BLOCK],
kvb,
);
}
cur = plan.heal_start;
}
cache.ensure_span_blocks(&mut pools, &mut tbl, cur, combined.len() - cur).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &combined, cur, combined.len() - cur, || fake_cs(0x77));
assert_eq!(cache.stats().stitch_hits, 2);
cache.release_lane(&mut pools, &mut tbl, &mut st);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn kv_stitch_enforces_strict_namespace_isolation_and_eviction_cleanup() {
let mut pools = BlockPools::with_capacities(192, 64, 1).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_kv_stitch(true);
let shared_file: Vec<u32> = (0..3072u32).map(|i| 30_000 + i).collect();
let mut tenant_a_prompt: Vec<u32> = (0..128u32).map(|i| 500 + i).collect();
tenant_a_prompt.extend_from_slice(&shared_file);
tenant_a_prompt.extend((0..129u32).map(|i| 70_000 + i));
let mut tbl_a = BlockTable::new(96).unwrap();
let mut st_a = LaneBlockState { namespace: 0xAAAA, prompt_len: tenant_a_prompt.len(), ..Default::default() };
let _ = cache.begin_admit_bind_in_namespace(&mut pools, 0, &mut tbl_a, &mut st_a, 0xAAAA, &tenant_a_prompt);
cache.ensure_span_blocks(&mut pools, &mut tbl_a, 0, 3328).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_a, &mut st_a, &tenant_a_prompt, 0, 3328, || fake_cs(0xAA));
cache.ensure_span_blocks(&mut pools, &mut tbl_a, 3328, 1).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_a, &mut st_a, &tenant_a_prompt, 3328, 1, || fake_cs(0xAB));
cache.release_lane(&mut pools, &mut tbl_a, &mut st_a);
let mut shifted_prompt: Vec<u32> = (0..147u32).map(|i| 9_000 + i).collect();
shifted_prompt.extend_from_slice(&shared_file);
shifted_prompt.extend((0..129u32).map(|i| 80_000 + i));
assert!(
cache.plan_stitches(&pools, 0xBBBB, &shifted_prompt, 0).is_empty(),
"Tenant B must never see Tenant A's stitch index entries"
);
assert!(
cache.plan_stitches(&pools, 0, &shifted_prompt, 0).is_empty(),
"Default namespace must never see Tenant A's stitch index entries"
);
let plans_a = cache.plan_stitches(&pools, 0xAAAA, &shifted_prompt, 0);
assert_eq!(plans_a.len(), 1, "Same tenant 0xAAAA must match shifted file span");
let mut tbl_b = BlockTable::new(96).unwrap();
let mut st_b = LaneBlockState { namespace: 0xBBBB, prompt_len: shifted_prompt.len(), ..Default::default() };
cache.ensure_span_blocks(&mut pools, &mut tbl_b, 0, plans_a[0].stitch_start).unwrap();
cache.finish_prefill_span(
&mut pools,
&mut tbl_b,
&mut st_b,
&shifted_prompt,
0,
plans_a[0].stitch_start,
|| fake_cs(0xBB),
);
assert_eq!(
cache.apply_stitch_plan(&mut pools, &mut tbl_b, &mut st_b, &shifted_prompt, &plans_a[0]),
StitchApplyOutcome::SourceGone,
"cross-namespace stitch plan application must fail closed"
);
cache.release_lane(&mut pools, &mut tbl_b, &mut st_b);
cache.shutdown(&mut pools);
assert!(cache.stitch_index.is_empty(), "evicting all starts must remove all stitch_index entries");
assert!(cache.plan_stitches(&pools, 0xAAAA, &shifted_prompt, 0).is_empty());
assert_zero_pool_leaks(&pools);
}
#[test]
fn ikv_catalog_async_staging_and_corrupt_page_quarantine_preserve_invariants() {
use std::io::{Seek, SeekFrom, Write};
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
let dir = ScratchDir::new("ikv-block-cache");
#[cfg(unix)]
std::fs::set_permissions(&dir.0, std::fs::Permissions::from_mode(0o700)).unwrap();
let kvb = 1u32;
let vocab = 262_144u32;
let model_fp = 0xfeed_face_cafe_beefu64;
let hmac_key = crate::ikv::IkvHmacKey::from_bytes(b"block-cache-test-hmac-key-32byte").unwrap();
let page_bytes = crate::blocks::BlockKind::Full.stride_bytes(kvb).unwrap() as usize;
let cart_toks: Vec<u32> = (0..3200u32).map(|i| 120_000 + i).collect();
let mut full_pages: Vec<Vec<u8>> = Vec::with_capacity(50);
for p in 0..50usize {
let mut page = vec![0u8; page_bytes];
stamp_test_full_block_rows(&mut page, &cart_toks[p * BLOCK..(p + 1) * BLOCK], kvb);
full_pages.push(page);
}
let ikv_path = dir.0.join("sample.ikv");
let hdr = crate::ikv::write_ikv_cartridge_raw(
&ikv_path,
"src/sample.rs",
kvb,
vocab,
model_fp,
false,
16,
&cart_toks,
&full_pages,
Some(&hmac_key),
)
.unwrap();
let cat = Arc::new(
crate::ikv::IkvCatalog::load_dir(&dir.0, kvb, vocab, model_fp, false, &hmac_key).unwrap(),
);
assert_eq!(cat.len(), 1);
let mut pools = BlockPools::with_capacities(192, 64, kvb).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_kv_stitch(true);
cache.set_ikv_catalog(cat);
assert_eq!(cache.stats().ikv_cartridges_loaded, 1);
assert_eq!(cache.stats().ikv_quarantined, 0);
let mut prompt: Vec<u32> = (0..83u32).map(|i| 4_000 + i).collect();
prompt.extend_from_slice(&cart_toks);
prompt.extend((0..128u32).map(|i| 90_000 + i));
assert!(cache.plan_stitches(&pools, 7, &prompt, 0).is_empty());
let plans = cache.plan_stitches(&pools, 0, &prompt, 0);
assert_eq!(plans.len(), 1);
assert_eq!(plans[0].span_start, 83);
assert_eq!(plans[0].stitch_start, 1152);
assert_eq!(plans[0].heal_start, 1728);
assert_eq!(plans[0].span_end, 3283);
let mut tbl = BlockTable::new(96).unwrap();
let mut st = LaneBlockState { namespace: 0, prompt_len: prompt.len(), ..Default::default() };
let _ = cache.begin_admit_bind(&mut pools, 0, &mut tbl, &mut st, &prompt);
cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 1152).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &prompt, 0, 1152, || fake_cs(1));
assert_eq!(
cache.start_stitch_plan(&mut pools, 0, &mut tbl, &mut st, &prompt, &plans[0]),
StitchStartOutcome::Staging
);
assert!(cache.has_pending_ikv_stage(0) && cache.has_inflight_restores());
let done = loop {
let tbl_ptr: *mut BlockTable = &mut tbl;
let st_ptr: *mut LaneBlockState = &mut st;
let mut batch = cache.poll_ikv_stages(&mut pools, |l| (l == 0).then_some((&(), tbl_ptr, st_ptr)));
if let Some(c) = batch.pop() {
break c;
}
cache.wait_restore_activity(Duration::from_millis(50));
};
assert_eq!(done.stitched_tokens, Some(576));
assert!(!done.corrupt_fallback);
assert!(st.stitched_approx);
assert_eq!(st.written, 1728);
for b in 18..27usize {
let fe = tbl.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().unwrap();
assert_test_full_block_rows_match(
pools.full.slot_bytes(fe.slot()).unwrap(),
&prompt[b * BLOCK..(b + 1) * BLOCK],
kvb,
);
}
cache.release_lane(&mut pools, &mut tbl, &mut st);
{
let mut f = std::fs::OpenOptions::new().read(true).write(true).open(&ikv_path).unwrap();
f.seek(SeekFrom::Start(hdr.full_pages_off + 20 * (page_bytes as u64) + 333)).unwrap();
f.write_all(&[0xFF]).unwrap();
f.sync_all().unwrap();
}
let mut tbl2 = BlockTable::new(96).unwrap();
let mut st2 = LaneBlockState { namespace: 0, prompt_len: prompt.len(), ..Default::default() };
let _ = cache.begin_admit_bind(&mut pools, 1, &mut tbl2, &mut st2, &prompt);
cache.ensure_span_blocks(&mut pools, &mut tbl2, 0, 1152).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl2, &mut st2, &prompt, 0, 1152, || fake_cs(2));
assert_eq!(
cache.start_stitch_plan(&mut pools, 1, &mut tbl2, &mut st2, &prompt, &plans[0]),
StitchStartOutcome::Staging
);
let aborted = loop {
let tbl_ptr: *mut BlockTable = &mut tbl2;
let st_ptr: *mut LaneBlockState = &mut st2;
let mut batch = cache.poll_ikv_stages(&mut pools, |l| (l == 1).then_some((&(), tbl_ptr, st_ptr)));
if let Some(c) = batch.pop() {
break c;
}
cache.wait_restore_activity(Duration::from_millis(50));
};
assert!(aborted.corrupt_fallback && aborted.stitched_tokens.is_none());
assert_eq!(cache.stats().corrupt_fallbacks, 1);
assert_eq!(cache.stats().ikv_quarantined, 1, "corrupt runtime page must quarantine cartridge");
assert_eq!(st2.written, 1152, "lane cursor must remain at stitch_start for clean fallback prefill");
assert!(tbl2.get(BlockKind::Full, BlockIndex::new(18)).unwrap().is_none(), "staged slots must be rolled back");
assert!(
cache.plan_stitches(&pools, 0, &prompt, 0).is_empty(),
"quarantined .ikv cartridge must never be planned again"
);
assert_eq!(
cache.apply_stitch_plan(&mut pools, &mut tbl2, &mut st2, &prompt, &plans[0]),
StitchApplyOutcome::SourceGone
);
cache.release_lane(&mut pools, &mut tbl2, &mut st2);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn kv_stitch_revisits_same_diagonal_past_single_token_edit_for_retained_and_ikv() {
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
let kvb = 1u32;
let vocab = 262_144u32;
let model_fp = 0xabcd_ef01_2345_6789u64;
let hmac_key = crate::ikv::IkvHmacKey::from_bytes(b"diag-edit-test-hmac-key-32-bytes").unwrap();
let page_bytes = crate::blocks::BlockKind::Full.stride_bytes(kvb).unwrap() as usize;
let orig_file: Vec<u32> = (0..3584u32).map(|i| 150_000 + i).collect();
let mut edited_file = orig_file.clone();
edited_file[64] = 999_999;
let mut query_prompt: Vec<u32> = (0..83u32).map(|i| 7_000 + i).collect();
query_prompt.extend_from_slice(&edited_file); query_prompt.extend((0..128u32).map(|i| 8_000 + i));
{
let mut pools = BlockPools::with_capacities(224, 64, kvb).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_kv_stitch(true);
let mut donor_prompt: Vec<u32> = (0..128u32).map(|i| 5_000 + i).collect();
donor_prompt.extend_from_slice(&orig_file);
donor_prompt.push(555_555);
let mut tbl_d = BlockTable::new(96).unwrap();
let mut st_d = LaneBlockState { prompt_len: donor_prompt.len(), ..Default::default() };
for b in 0..58usize {
let p0 = b * BLOCK;
cache.ensure_span_blocks(&mut pools, &mut tbl_d, p0, BLOCK).unwrap();
let fe = tbl_d.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().unwrap();
stamp_test_full_block_rows(
pools.full.slot_bytes_mut(fe.slot()).unwrap(),
&donor_prompt[p0..p0 + BLOCK],
kvb,
);
cache.finish_prefill_span(&mut pools, &mut tbl_d, &mut st_d, &donor_prompt, p0, BLOCK, || fake_cs(0x44));
}
cache.ensure_span_blocks(&mut pools, &mut tbl_d, 3712, 1).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_d, &mut st_d, &donor_prompt, 3712, 1, || fake_cs(0x45));
cache.release_lane(&mut pools, &mut tbl_d, &mut st_d);
let ret_plans = cache.plan_stitches(&pools, 0, &query_prompt, 0);
assert_eq!(
ret_plans.len(),
1,
"RetainedStart planner must revisit same diagonal past 1-token edit and stitch the 3,519-token suffix"
);
assert_eq!(ret_plans[0].span_start, 148);
assert_eq!(ret_plans[0].stitch_start, 1216);
assert_eq!(ret_plans[0].heal_start, 2112);
assert_eq!(ret_plans[0].span_end, 3667);
let mut tbl_q = BlockTable::new(96).unwrap();
let mut st_q = LaneBlockState { prompt_len: query_prompt.len(), ..Default::default() };
cache.ensure_span_blocks(&mut pools, &mut tbl_q, 0, 1216).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_q, &mut st_q, &query_prompt, 0, 1216, || fake_cs(0x46));
let out = cache.apply_stitch_plan(&mut pools, &mut tbl_q, &mut st_q, &query_prompt, &ret_plans[0]);
assert_eq!(out, StitchApplyOutcome::Applied { stitched_tokens: 896, zero_copy_blocks: 0 });
for b in 19..33usize {
let fe = tbl_q.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().unwrap();
assert_test_full_block_rows_match(
pools.full.slot_bytes(fe.slot()).unwrap(),
&query_prompt[b * BLOCK..(b + 1) * BLOCK],
kvb,
);
}
cache.release_lane(&mut pools, &mut tbl_q, &mut st_q);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
{
let dir = ScratchDir::new("ikv-diag-edit");
#[cfg(unix)]
std::fs::set_permissions(&dir.0, std::fs::Permissions::from_mode(0o700)).unwrap();
let mut full_pages: Vec<Vec<u8>> = Vec::with_capacity(56);
for p in 0..56usize {
let mut page = vec![0u8; page_bytes];
stamp_test_full_block_rows(&mut page, &orig_file[p * BLOCK..(p + 1) * BLOCK], kvb);
full_pages.push(page);
}
let ikv_path = dir.0.join("orig.ikv");
crate::ikv::write_ikv_cartridge_raw(
&ikv_path,
"src/orig.rs",
kvb,
vocab,
model_fp,
false,
16,
&orig_file,
&full_pages,
Some(&hmac_key),
)
.unwrap();
let cat = Arc::new(
crate::ikv::IkvCatalog::load_dir(&dir.0, kvb, vocab, model_fp, false, &hmac_key).unwrap(),
);
let mut pools = BlockPools::with_capacities(224, 64, kvb).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_kv_stitch(true);
cache.set_ikv_catalog(cat);
let ikv_plans = cache.plan_stitches(&pools, 0, &query_prompt, 0);
assert_eq!(
ikv_plans.len(),
1,
"MountedIkv planner must revisit same diagonal past 1-token edit and stitch the 3,519-token suffix"
);
assert_eq!(ikv_plans[0].span_start, 148);
assert_eq!(ikv_plans[0].stitch_start, 1216);
assert_eq!(ikv_plans[0].heal_start, 2112);
assert_eq!(ikv_plans[0].span_end, 3667);
let mut tbl_q = BlockTable::new(96).unwrap();
let mut st_q = LaneBlockState { prompt_len: query_prompt.len(), ..Default::default() };
cache.ensure_span_blocks(&mut pools, &mut tbl_q, 0, 1216).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_q, &mut st_q, &query_prompt, 0, 1216, || fake_cs(0x47));
let out = cache.apply_stitch_plan(&mut pools, &mut tbl_q, &mut st_q, &query_prompt, &ikv_plans[0]);
assert_eq!(out, StitchApplyOutcome::Applied { stitched_tokens: 896, zero_copy_blocks: 0 });
for b in 19..33usize {
let fe = tbl_q.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().unwrap();
assert_test_full_block_rows_match(
pools.full.slot_bytes(fe.slot()).unwrap(),
&query_prompt[b * BLOCK..(b + 1) * BLOCK],
kvb,
);
}
cache.release_lane(&mut pools, &mut tbl_q, &mut st_q);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
}
#[test]
fn kv4_and_sparse_topk_stitch_recomputes_wht2_sketches_for_retained_and_ikv() {
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use crate::blocks::{KvMode, FULL_SKETCH_BYTES, KVB_KV4};
let kvb = KVB_KV4;
let vocab = 262_144u32;
let kv4_digest_tag = 0x5152_5354_5556_5758u64;
let model_fp = 0xabcd_ef01_2345_6789u64 ^ kv4_digest_tag;
let hmac_key = crate::ikv::IkvHmacKey::from_bytes(b"kv4-sparse-stitch-hmac-key-32byt").unwrap();
let page_bytes = KvMode::Kv4.stride_bytes(BlockKind::Full) as usize;
let shared_file: Vec<u32> = (0..3200u32).map(|i| 160_000 + i).collect();
let mut query_prompt: Vec<u32> = (0..83u32).map(|i| 7_500 + i).collect(); query_prompt.extend_from_slice(&shared_file);
query_prompt.extend((0..128u32).map(|i| 8_500 + i));
{
let mut pools = BlockPools::with_capacities_mode_and_sketches(160, 48, KvMode::Kv4, true).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_kv_stitch(true);
let mut donor_prompt: Vec<u32> = (0..128u32).map(|i| 4_200 + i).collect();
donor_prompt.extend_from_slice(&shared_file);
donor_prompt.push(555_555);
let mut tbl_d = BlockTable::new(96).unwrap();
let mut st_d = LaneBlockState { prompt_len: donor_prompt.len(), ..Default::default() };
let full_blks = (donor_prompt.len() - 1) / BLOCK;
for b in 0..full_blks {
let p0 = b * BLOCK;
cache.ensure_span_blocks(&mut pools, &mut tbl_d, p0, BLOCK).unwrap();
let fe = tbl_d.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().unwrap();
stamp_test_full_block_rows(
pools.full.slot_bytes_mut(fe.slot()).unwrap(),
&donor_prompt[p0..p0 + BLOCK],
kvb,
);
pools.full.on_slot_restored_from_spill(fe.slot());
cache.finish_prefill_span(&mut pools, &mut tbl_d, &mut st_d, &donor_prompt, p0, BLOCK, || fake_cs(b as u8));
}
cache.release_lane(&mut pools, &mut tbl_d, &mut st_d);
let plans = cache.plan_stitches(&pools, 0, &query_prompt, 0);
assert_eq!(plans.len(), 1);
let mut tbl_q = BlockTable::new(96).unwrap();
let mut st_q = LaneBlockState { prompt_len: query_prompt.len(), ..Default::default() };
let p0_end = plans[0].stitch_start;
cache.ensure_span_blocks(&mut pools, &mut tbl_q, 0, p0_end).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_q, &mut st_q, &query_prompt, 0, p0_end, || fake_cs(1));
assert!(matches!(
cache.apply_stitch_plan(&mut pools, &mut tbl_q, &mut st_q, &query_prompt, &plans[0]),
StitchApplyOutcome::Applied { zero_copy_blocks: 0, .. }
));
let lo_b = plans[0].stitch_start / BLOCK;
let hi_b = plans[0].heal_start / BLOCK;
for b in lo_b..hi_b {
let fe = tbl_q.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().unwrap();
assert_test_full_block_rows_match(
pools.full.slot_bytes(fe.slot()).unwrap(),
&query_prompt[b * BLOCK..(b + 1) * BLOCK],
kvb,
);
assert_eq!(pools.full.slot_sketch_valid_len(fe.slot()).unwrap(), BLOCK as u8);
let mut exp_sk = vec![0u8; FULL_SKETCH_BYTES];
crate::blocks::compute_full_slot_wht2_sketch_cpu(
pools.full.slot_bytes(fe.slot()).unwrap(),
kvb,
BLOCK,
&mut exp_sk,
);
assert_eq!(pools.full.slot_sketch_bytes(fe.slot()).unwrap(), exp_sk.as_slice());
}
cache.release_lane(&mut pools, &mut tbl_q, &mut st_q);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
let dir = ScratchDir::new("kv4-sparse-ikv-stitch");
#[cfg(unix)]
std::fs::set_permissions(&dir.0, std::fs::Permissions::from_mode(0o700)).unwrap();
let n_pages = shared_file.len().div_ceil(BLOCK);
let mut pages = Vec::with_capacity(n_pages);
for p in 0..n_pages {
let mut page = vec![0u8; page_bytes];
stamp_test_full_block_rows(&mut page, &shared_file[p * BLOCK..(p + 1) * BLOCK], kvb);
pages.push(page);
}
let ikv_path = dir.0.join("shared_kv4.ikv");
crate::ikv::write_ikv_cartridge_raw(
&ikv_path,
"shared_kv4.rs",
kvb,
vocab,
model_fp,
false,
16,
&shared_file,
&pages,
Some(&hmac_key),
)
.unwrap();
assert!(
crate::ikv::IkvCatalog::load_dir(&dir.0, 1, vocab, model_fp, false, &hmac_key)
.unwrap_err()
.contains("rule kvb_match")
);
assert!(
crate::ikv::IkvCatalog::load_dir(&dir.0, kvb, vocab, model_fp ^ 1, false, &hmac_key)
.unwrap_err()
.contains("rule model_fingerprint")
);
let cat = std::sync::Arc::new(
crate::ikv::IkvCatalog::load_dir(&dir.0, kvb, vocab, model_fp, false, &hmac_key).unwrap(),
);
let mut pools = BlockPools::with_capacities_mode_and_sketches(160, 48, KvMode::Kv4, true).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_kv_stitch(true);
cache.set_ikv_catalog(cat);
let plans = cache.plan_stitches(&pools, 0, &query_prompt, 0);
assert_eq!(plans.len(), 1);
let mut tbl_q = BlockTable::new(96).unwrap();
let mut st_q = LaneBlockState { prompt_len: query_prompt.len(), ..Default::default() };
let p0_end = plans[0].stitch_start;
cache.ensure_span_blocks(&mut pools, &mut tbl_q, 0, p0_end).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_q, &mut st_q, &query_prompt, 0, p0_end, || fake_cs(2));
assert!(matches!(
cache.apply_stitch_plan(&mut pools, &mut tbl_q, &mut st_q, &query_prompt, &plans[0]),
StitchApplyOutcome::Applied { .. }
));
let lo_b = plans[0].stitch_start / BLOCK;
let hi_b = plans[0].heal_start / BLOCK;
for b in lo_b..hi_b {
let fe = tbl_q.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().unwrap();
assert_eq!(pools.full.slot_sketch_valid_len(fe.slot()).unwrap(), BLOCK as u8);
let mut exp_sk = vec![0u8; FULL_SKETCH_BYTES];
crate::blocks::compute_full_slot_wht2_sketch_cpu(
pools.full.slot_bytes(fe.slot()).unwrap(),
kvb,
BLOCK,
&mut exp_sk,
);
assert_eq!(pools.full.slot_sketch_bytes(fe.slot()).unwrap(), exp_sk.as_slice());
}
cache.release_lane(&mut pools, &mut tbl_q, &mut st_q);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
fn own(ns: u64, card: &str) -> u64 {
approx_twin("test-salt", ns, Some(card))
}
fn seed_stitch_donor(cache: &mut ServeBlockCache, pools: &mut BlockPools, ns: u64, kvb: u32) -> Vec<u32> {
seed_stitch_donor_span(cache, pools, ns, kvb, 3200)
}
fn seed_stitch_donor_span(
cache: &mut ServeBlockCache,
pools: &mut BlockPools,
ns: u64,
kvb: u32,
span_len: u32,
) -> Vec<u32> {
let file_span: Vec<u32> = (0..span_len).map(|i| 10_000 + i).collect();
let mut prompt_a: Vec<u32> = (0..128u32).map(|i| 1_000 + i).collect();
prompt_a.extend_from_slice(&file_span);
prompt_a.extend((0..257u32).map(|i| 40_000 + i));
let whole = prompt_a.len() / BLOCK;
assert_eq!(prompt_a.len(), whole * BLOCK + 1, "the donor prompt ends one token past a block boundary");
let mut tbl = BlockTable::new(128).unwrap();
let mut st = LaneBlockState { namespace: ns, prompt_len: prompt_a.len(), ..Default::default() };
for b in 0..whole {
let p0 = b * BLOCK;
cache.ensure_span_blocks(pools, &mut tbl, p0, BLOCK).unwrap();
let fe = tbl.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().unwrap();
stamp_test_full_block_rows(pools.full.slot_bytes_mut(fe.slot()).unwrap(), &prompt_a[p0..p0 + BLOCK], kvb);
cache.finish_prefill_span(pools, &mut tbl, &mut st, &prompt_a, p0, BLOCK, || fake_cs(0x11));
}
cache.ensure_span_blocks(pools, &mut tbl, whole * BLOCK, 1).unwrap();
cache.finish_prefill_span(pools, &mut tbl, &mut st, &prompt_a, whole * BLOCK, 1, || fake_cs(0x12));
cache.release_lane(pools, &mut tbl, &mut st);
file_span
}
fn stitched_turn_one(
cache: &mut ServeBlockCache,
pools: &mut BlockPools,
ns: u64,
owner: u64,
file_span: &[u32],
reply_len: usize,
) -> (Vec<u32>, Vec<u32>) {
let mut prompt: Vec<u32> = (0..147u32).map(|i| 3_000 + i).collect();
prompt.extend_from_slice(file_span); prompt.extend((0..2817u32).map(|i| 60_000 + i)); let mut tbl = BlockTable::new(160).unwrap();
let mut st = LaneBlockState { namespace: ns, owner, prompt_len: prompt.len(), ..Default::default() };
assert!(cache.match_and_bind(pools, &mut tbl, &mut st, &prompt).is_none(), "turn 1 starts cold");
let plans = cache.plan_stitches(pools, ns, &prompt, 0);
assert_eq!(plans.len(), 1, "turn 1 stitches the donor's file span");
cache.ensure_span_blocks(pools, &mut tbl, 0, plans[0].stitch_start).unwrap();
cache.finish_prefill_span(pools, &mut tbl, &mut st, &prompt, 0, plans[0].stitch_start, || fake_cs(0x31));
let out = cache.apply_stitch_plan(pools, &mut tbl, &mut st, &prompt, &plans[0]);
assert!(matches!(out, StitchApplyOutcome::Applied { .. }));
assert!(st.stitched_approx);
let mut p = st.written;
while p < prompt.len() {
let next = effective_pf_target(p, prompt.len());
cache.ensure_span_blocks(pools, &mut tbl, p, next - p).unwrap();
cache.finish_prefill_span(pools, &mut tbl, &mut st, &prompt, p, next - p, || fake_cs((next / BLOCK) as u8));
p = next;
}
let reply: Vec<u32> = (0..reply_len as u32).map(|i| 70_000 + i).collect();
let mut history = prompt.clone();
for (d, &tok) in reply.iter().enumerate() {
let pos = prompt.len() + d;
history.push(tok);
cache.ensure_span_blocks(pools, &mut tbl, pos, 1).unwrap();
cache.finish_decode_span(pools, &mut tbl, &mut st, pos);
cache.seal_decode_block(pools, &tbl, &mut st, &history, pos, || fake_cs(0x77));
}
cache.release_lane(pools, &mut tbl, &mut st);
(prompt, reply)
}
fn turn_two(prompt: &[u32], reply: &[u32]) -> Vec<u32> {
let mut t = prompt.to_vec();
t.extend_from_slice(reply);
t.extend((0..300u32).map(|i| 80_000 + i)); t
}
#[test]
fn stitched_turn_resumes_from_its_own_saved_work_with_stitch_on() {
for approx_retain in [false, true] {
let kvb = 1u32;
let mut pools = BlockPools::with_capacities(512, 160, kvb).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_kv_stitch(true);
cache.set_approx_retain(approx_retain);
let ns = 7;
let file_span = seed_stitch_donor(&mut cache, &mut pools, ns, kvb);
let (prompt, reply) = stitched_turn_one(&mut cache, &mut pools, ns, own(ns, "card-a"), &file_span, 100);
let t2 = turn_two(&prompt, &reply);
let mut tbl = BlockTable::new(160).unwrap();
let mut st = LaneBlockState { namespace: ns, owner: own(ns, "card-a"), ..Default::default() };
let bound = cache.match_and_bind(&mut pools, &mut tbl, &mut st, &t2);
if !approx_retain {
assert!(bound.is_none(), "v2.0.4: a stitched turn leaves nothing to resume from");
cache.release_lane(&mut pools, &mut tbl, &mut st);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
continue;
}
let (at, cs) = bound.expect("turn 2 resumes from turn 1's own saved work");
assert_eq!(at, 6208, "the credit covers turn 1's prompt and its reply up to the last full block");
assert_eq!(cs, fake_cs(0x77), "the start carries the reply boundary's cs");
assert!(at >= prompt.len(), "credit covers the whole of turn 1's prompt");
assert!(st.stitched_approx && st.approx_path, "a resumed lane is approximate and keeps sealing in its twin");
let new_tokens = t2.len() - prompt.len() - reply.len();
let rows_to_prefill = t2.len() - at;
assert!(rows_to_prefill <= new_tokens + BLOCK, "turn 2 prefills its new tokens (+ < 1 block of reply)");
let s = cache.stats();
assert_eq!(s.approx_start_matches, 1);
assert_eq!(s.approx_cached_tokens_total, at as u64);
assert_eq!(s.cached_tokens_total, 0, "exact cached tokens never count an approximate resume");
assert_eq!(s.approx_starts_saved, 2, "the twin keeps PROMPT and the turn end only, never EVERY");
let mut approx_pos: Vec<usize> = cache.starts.values().filter(|s| s.approx).map(|s| s.pos).collect();
approx_pos.sort_unstable();
assert_eq!(approx_pos, vec![6144, 6208], "an approximate lane retains only its PROMPT and turn-end starts");
cache.release_lane(&mut pools, &mut tbl, &mut st);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
}
#[test]
fn approximate_starts_are_bound_to_owner_and_auth_scope_and_never_exact() {
let kvb = 1u32;
let cases: [(&str, u64, u64, bool, bool); 5] = [
("same conversation, same key", own(7, "card-a"), 7, true, true),
("another conversation in the same namespace", own(7, "card-b"), 7, true, false),
("the same conversation under another key", own(8, "card-a"), 8, true, false),
("no conversation header", 0, 7, true, false),
("exact mode (no approximate reuse)", own(7, "card-a"), 7, false, false),
];
for (name, owner, ns2, approx_retain2, expect) in cases {
let mut pools = BlockPools::with_capacities(512, 160, kvb).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_kv_stitch(true);
cache.set_approx_retain(true);
let file_span = seed_stitch_donor(&mut cache, &mut pools, 7, kvb);
let (prompt, reply) = stitched_turn_one(&mut cache, &mut pools, 7, own(7, "card-a"), &file_span, 100);
let t2 = turn_two(&prompt, &reply);
cache.set_approx_retain(approx_retain2);
let mut tbl = BlockTable::new(160).unwrap();
let mut st = LaneBlockState { namespace: ns2, owner, ..Default::default() };
let bound = cache.match_and_bind(&mut pools, &mut tbl, &mut st, &t2);
let approx = bound.is_some() && st.stitched_approx;
assert_eq!(approx, expect, "{name}");
if !expect {
assert!(!st.approx_path, "{name}: never an approximate start");
}
cache.release_lane(&mut pools, &mut tbl, &mut st);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
}
#[test]
fn approximate_saves_stay_out_of_the_exact_chain_and_are_never_stitch_donors() {
let kvb = 1u32;
let mut pools = BlockPools::with_capacities(512, 160, kvb).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_kv_stitch(true);
cache.set_approx_retain(true);
let file_span = seed_stitch_donor(&mut cache, &mut pools, 7, kvb);
let exact_before = cache.starts.values().filter(|s| !s.approx).count();
let (prompt, reply) = stitched_turn_one(&mut cache, &mut pools, 7, own(7, "card-a"), &file_span, 100);
assert_eq!(cache.starts.values().filter(|s| !s.approx).count(), exact_before, "no exact start from a stitched lane");
assert_eq!(cache.tree.deepest_start_in_namespace(7, &prompt).at, 0, "an exact lookup never finds turn 1's work");
assert!(cache.starts.values().any(|s| s.approx), "turn 1 saved approximate starts");
for bucket in cache.stitch_index.values() {
for (sid, _) in bucket {
assert!(!cache.starts.get(sid).is_some_and(|s| s.approx), "an approximate start is never a donor");
}
}
let t2 = turn_two(&prompt, &reply);
let mut tbl = BlockTable::new(160).unwrap();
let mut st = LaneBlockState { namespace: 7, owner: own(7, "card-a"), ..Default::default() };
assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &t2).is_some());
assert!(st.stitched_approx && st.approx_path);
let at = st.written;
cache.ensure_span_blocks(&mut pools, &mut tbl, at, t2.len() - at).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &t2, at, t2.len() - at, || fake_cs(0x99));
assert_eq!(cache.tree.deepest_start_in_namespace(7, &t2).at, 0, "turn 2's work stays out of the exact chain");
cache.release_lane(&mut pools, &mut tbl, &mut st);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
struct SiblingStitch {
pools: BlockPools,
cache: ServeBlockCache,
prompt_a: Vec<u32>,
prompt_b: Vec<u32>,
tbl_a: BlockTable,
st_a: LaneBlockState,
tbl_b: BlockTable,
st_b: LaneBlockState,
guard_a: BlockEntry,
guard_b: BlockEntry,
}
fn sibling_lanes_stitched_to_different_depths() -> SiblingStitch {
let kvb = 1u32;
let ns = 7;
let owner = own(ns, "card-a");
let mut pools = BlockPools::with_capacities(512, 160, kvb).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_kv_stitch(true);
cache.set_approx_retain(true);
let file_span = seed_stitch_donor_span(&mut cache, &mut pools, ns, kvb, 4096);
let mut prompt_a: Vec<u32> = (0..147u32).map(|i| 3_000 + i).collect();
prompt_a.extend_from_slice(&file_span);
prompt_a.extend((0..2817u32).map(|i| 60_000 + i));
let mut prompt_b: Vec<u32> = prompt_a[..2880].to_vec();
prompt_b.extend((0..600u32).map(|i| 90_000 + i));
let mut tbl_a = BlockTable::new(160).unwrap();
let mut st_a = LaneBlockState { namespace: ns, owner, prompt_len: prompt_a.len(), ..Default::default() };
let mut tbl_b = BlockTable::new(160).unwrap();
let mut st_b = LaneBlockState { namespace: ns, owner, prompt_len: prompt_b.len(), ..Default::default() };
assert!(cache.match_and_bind(&mut pools, &mut tbl_a, &mut st_a, &prompt_a).is_none(), "lane A starts cold");
assert!(cache.match_and_bind(&mut pools, &mut tbl_b, &mut st_b, &prompt_b).is_none(), "lane B starts cold");
let plans_a = cache.plan_stitches(&pools, ns, &prompt_a, 0);
let plans_b = cache.plan_stitches(&pools, ns, &prompt_b, 0);
assert_eq!((plans_a.len(), plans_b.len()), (1, 1));
assert_eq!((plans_a[0].stitch_start, plans_a[0].heal_start, plans_a[0].span_end), (1216, 2688, 4243));
assert_eq!((plans_b[0].stitch_start, plans_b[0].heal_start, plans_b[0].span_end), (1216, 1344, 2880));
for (tbl, st, prompt, plan) in
[(&mut tbl_a, &mut st_a, &prompt_a, &plans_a[0]), (&mut tbl_b, &mut st_b, &prompt_b, &plans_b[0])]
{
cache.ensure_span_blocks(&mut pools, tbl, 0, plan.stitch_start).unwrap();
cache.finish_prefill_span(&mut pools, tbl, st, prompt, 0, plan.stitch_start, || fake_cs(0x31));
let out = cache.apply_stitch_plan(&mut pools, tbl, st, prompt, plan);
assert!(matches!(out, StitchApplyOutcome::Applied { .. }));
assert!(st.stitched_approx && st.approx_path, "a stitched lane seals into its conversation's twin");
}
assert_eq!((st_a.written, st_b.written), (2688, 1344));
let win = |tbl: &BlockTable, b: u32| tbl.get(BlockKind::Window, BlockIndex::new(b)).unwrap();
let guard_a = win(&tbl_a, 41).expect("lane A's guard");
let guard_b = win(&tbl_b, 20).expect("lane B's guard");
assert_ne!(guard_a, guard_b);
for b in 0..42u32 {
assert_eq!(win(&tbl_a, b), (b >= 26).then_some(guard_a), "lane A window block {b}");
}
assert_eq!(win(&tbl_b, 19), Some(guard_b));
for g in [guard_a, guard_b] {
assert!(entry_is_live_sealed(&pools, BlockKind::Window, g));
assert!(pools.window.slot_bytes(g.slot()).unwrap().iter().all(|&x| x == 0), "a guard slot is zeros");
}
assert_eq!((st_a.sealed.len(), st_b.sealed.len()), (42, 21));
assert_eq!(st_a.sealed[..21], st_b.sealed[..]);
SiblingStitch { pools, cache, prompt_a, prompt_b, tbl_a, st_a, tbl_b, st_b, guard_a, guard_b }
}
const LANE_B_WINDOW: u8 = 0xB1;
impl SiblingStitch {
fn lane_b_heals(&mut self, blocks: std::ops::Range<usize>) {
for b in blocks {
let (p0, bi) = (b * BLOCK, BlockIndex::new(b as u32));
self.cache.ensure_span_blocks(&mut self.pools, &mut self.tbl_b, p0, BLOCK).unwrap();
let own = self.tbl_b.get(BlockKind::Window, bi).unwrap().expect("lane B's own window block");
self.pools.window.slot_bytes_mut(own.slot()).unwrap().fill(LANE_B_WINDOW);
let (tbl, st) = (&mut self.tbl_b, &mut self.st_b);
self.cache.finish_prefill_span(&mut self.pools, tbl, st, &self.prompt_b, p0, BLOCK, || fake_cs(0x41));
}
}
fn assert_lane_b_reads_its_own_window(&self, b: usize) {
let bi = BlockIndex::new(b as u32);
let we = self.tbl_b.get(BlockKind::Window, bi).unwrap().expect("a live window block");
assert_ne!(we, self.guard_a, "block {b}: lane B bound lane A's zero guard slot");
assert!(
self.pools.window.slot_bytes(we.slot()).unwrap().iter().all(|&x| x == LANE_B_WINDOW),
"block {b}: lane B reads Window K/V it did not compute"
);
let twin = self.cache.tree.handle(self.st_b.sealed[b]).expect("lane B's twin block");
assert_eq!(twin.window(), Some(we), "block {b}: the twin names the K/V lane B computed");
}
fn release_both_and_check_leaks(mut self) {
self.cache.release_lane(&mut self.pools, &mut self.tbl_a, &mut self.st_a);
self.cache.release_lane(&mut self.pools, &mut self.tbl_b, &mut self.st_b);
self.cache.shutdown(&mut self.pools);
assert_zero_pool_leaks(&self.pools);
}
}
#[test]
fn a_stitch_never_publishes_its_zero_guard_slot_as_a_tree_window_handle() {
let s = sibling_lanes_stitched_to_different_depths();
for (b, &id) in s.st_a.sealed.iter().enumerate() {
let h = s.cache.tree.handle(id).expect("a pinned twin block");
assert_ne!(h.window(), Some(s.guard_a), "block {b}: lane A's zero guard is published as its Window K/V");
assert_ne!(h.window(), Some(s.guard_b), "block {b}: lane B's zero guard is published as its Window K/V");
let fe = s.tbl_a.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().expect("lane A full block");
assert_eq!(h.full(), fe, "block {b}: lane A's Full block is the twin's");
}
for b in 26..42u32 {
assert_eq!(s.tbl_a.get(BlockKind::Window, BlockIndex::new(b)).unwrap(), Some(s.guard_a));
}
for b in 19..21u32 {
assert_eq!(s.tbl_b.get(BlockKind::Window, BlockIndex::new(b)).unwrap(), Some(s.guard_b));
}
s.release_both_and_check_leaks();
}
#[test]
fn a_lane_healing_across_a_siblings_stitch_guard_keeps_its_own_window_kv() {
let mut s = sibling_lanes_stitched_to_different_depths();
s.lane_b_heals(21..45);
assert_eq!(s.st_a.written, 2688);
assert!(entry_is_live_sealed(&s.pools, BlockKind::Window, s.guard_a));
assert_eq!(s.st_b.written, 2880);
assert_eq!(s.prompt_a[..2880], s.prompt_b[..2880]);
assert_ne!(s.prompt_a[2880], s.prompt_b[2880]);
let first_live = (s.st_b.written - (WINDOW - 1)) / BLOCK;
assert_eq!(first_live, 29);
for b in first_live..45 {
s.assert_lane_b_reads_its_own_window(b);
}
s.release_both_and_check_leaks();
}
#[test]
fn a_sealing_lane_never_binds_a_stitch_guard_the_tree_names() {
let mut s = sibling_lanes_stitched_to_different_depths();
let node = s.st_a.sealed[26];
let full = s.cache.tree.handle(node).expect("lane A's twin block 26").full();
assert!(s.cache.tree.set_handle(node, BlockHandles::new(full, Some(s.guard_a))));
s.lane_b_heals(21..27);
assert_eq!(s.st_b.sealed[26], node, "lane B sealed the block lane A published");
s.assert_lane_b_reads_its_own_window(26);
s.release_both_and_check_leaks();
}
#[test]
fn a_stitch_guard_never_enters_retained_starts_turn_end_starts_or_spills() {
let kvb = 1u32;
let ns = 7;
let owner = own(ns, "card-short");
let dir = ScratchDir::new("stitch-guard-spill");
let store = SpillStore::open_with_kvb(&dir.0, 64 * 1024 * 1024, kvb).unwrap();
let mut pools = BlockPools::with_capacities(256, 128, kvb).unwrap();
let mut cache = ServeBlockCache::with_spill(store);
cache.set_kv_stitch(true);
cache.set_approx_retain(true);
let file_span = seed_stitch_donor_span(&mut cache, &mut pools, ns, kvb, 3200);
let (&donor_sid, _) = cache
.starts
.iter()
.find(|(_, s)| !s.approx && s.pos == 3584)
.expect("donor PROMPT start at 3584");
let mut prompt: Vec<u32> = (0..128u32).map(|i| 3_000 + i).collect();
prompt.extend_from_slice(&file_span[..2433]);
assert_eq!(prompt.len(), 2561);
let plan = StitchSpanPlan {
span_start: 128,
stitch_start: 1024,
heal_start: 2048,
span_end: 2561,
source: StitchSource::Retained { sid: donor_sid, src_start: 1024 },
};
let mut tbl = BlockTable::new(128).unwrap();
let mut st = LaneBlockState { namespace: ns, owner, prompt_len: prompt.len(), ..Default::default() };
cache.ensure_span_blocks(&mut pools, &mut tbl, 0, plan.stitch_start).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &prompt, 0, plan.stitch_start, || fake_cs(0x31));
let out = cache.apply_stitch_plan(&mut pools, &mut tbl, &mut st, &prompt, &plan);
assert!(matches!(out, StitchApplyOutcome::Applied { stitched_tokens: 1024, .. }));
let guard = tbl.get(BlockKind::Window, BlockIndex::new(31)).unwrap().expect("stitch guard at block 31");
assert!(pools.window.slot_bytes(guard.slot()).unwrap().iter().all(|&x| x == 0));
for b in 32..40usize {
let p0 = b * BLOCK;
cache.ensure_span_blocks(&mut pools, &mut tbl, p0, BLOCK).unwrap();
let we = tbl.get(BlockKind::Window, BlockIndex::new(b as u32)).unwrap().unwrap();
pools.window.slot_bytes_mut(we.slot()).unwrap().fill(LANE_B_WINDOW);
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &prompt, p0, BLOCK, || fake_cs(0x42));
}
assert_eq!(st.written, 2560);
for s in cache.starts.values() {
assert!(
s.entries.iter().all(|&(_, _, e)| e != guard),
"a PROMPT start at 2560 must never retain a zero stitch guard slot"
);
}
cache.ensure_span_blocks(&mut pools, &mut tbl, 2560, 1).unwrap();
let we40 = tbl.get(BlockKind::Window, BlockIndex::new(40)).unwrap().unwrap();
pools.window.slot_bytes_mut(we40.slot()).unwrap().fill(LANE_B_WINDOW);
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &prompt, 2560, 1, || fake_cs(0x43));
let mut hist = prompt.clone();
for i in 0..63u32 {
let pos = 2561 + i as usize;
hist.push(80_000 + i);
cache.ensure_span_blocks(&mut pools, &mut tbl, pos, 1).unwrap();
cache.finish_decode_span(&mut pools, &mut tbl, &mut st, pos);
cache.seal_decode_block(&mut pools, &tbl, &mut st, &hist, pos, || fake_cs(0x44));
}
assert_eq!(st.written, 2624);
cache.release_lane_with_toks(&mut pools, &mut tbl, &mut st, Some(&hist), false);
for s in cache.starts.values() {
assert!(
s.entries.iter().all(|&(_, _, e)| e != guard),
"a turn-end start at 2624 must never retain a zero stitch guard slot"
);
}
for (_, h) in cache.tree.entries() {
assert_ne!(h.window(), Some(guard), "EntryTree must never hold a zero stitch guard handle");
}
assert_eq!(
pools.window.record(guard.slot()).unwrap().refs(),
0,
"once the stitched lane releases, zero references to its guard slot may remain"
);
assert!(cache.spilled_starts.is_empty(), "an approximate lane never spills to SSD");
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn exact_lane_reply_is_sealed_and_resumed_by_its_next_turn() {
for approx_retain in [false, true] {
let mut pools = BlockPools::with_capacities(512, 256, 2).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_approx_retain(approx_retain);
let turn1: Vec<u32> = (0..8266u32).map(|i| (i * 17 + 3) % 50000).collect();
let mut tbl = BlockTable::new(512).unwrap();
let mut st = LaneBlockState { owner: own(0, "card-a"), ..Default::default() };
assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &turn1).is_none());
let mut p = 0;
while p < turn1.len() {
let next = effective_pf_target(p, turn1.len());
cache.ensure_span_blocks(&mut pools, &mut tbl, p, next - p).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &turn1, p, next - p, || {
fake_cs((next / BLOCK) as u8)
});
p = next;
}
let mut history = turn1.clone();
for d in 0..200u32 {
let pos = turn1.len() + d as usize;
history.push(90_000 + d);
cache.ensure_span_blocks(&mut pools, &mut tbl, pos, 1).unwrap();
cache.finish_decode_span(&mut pools, &mut tbl, &mut st, pos);
cache.seal_decode_block(&mut pools, &tbl, &mut st, &history, pos, || fake_cs(0x55));
}
cache.release_lane(&mut pools, &mut tbl, &mut st);
let mut turn2 = history.clone();
turn2.extend((0..140u32).map(|i| 60000 + i));
let mut st2 = LaneBlockState { owner: own(0, "card-a"), ..Default::default() };
let (at, _) = cache.match_and_bind(&mut pools, &mut tbl, &mut st2, &turn2).expect("a start");
if approx_retain {
assert_eq!(at, 8448, "the next turn resumes past the reply");
assert!(st2.stitched_approx, "decode-written K/V makes the resumed lane approximate");
} else {
assert_eq!(at, 8256, "v2.0.4: only turn 1's PROMPT start");
assert!(!st2.stitched_approx);
}
assert_eq!(cache.tree.deepest_start_in_namespace(0, &turn2).at, 8256);
cache.release_lane(&mut pools, &mut tbl, &mut st2);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
}
struct CardTurn {
tbl: BlockTable,
st: LaneBlockState,
history: Vec<u32>,
resumed_at: usize,
}
fn card_turn_open(
cache: &mut ServeBlockCache,
pools: &mut BlockPools,
ns: u64,
owner: u64,
prompt: &[u32],
reply_len: usize,
) -> CardTurn {
let mut tbl = BlockTable::new(2048).unwrap();
let mut st = LaneBlockState { namespace: ns, owner, ..Default::default() };
let resumed_at = cache.match_and_bind(pools, &mut tbl, &mut st, prompt).map_or(0, |(at, _)| at);
let mut p = resumed_at;
while p < prompt.len() {
let next = effective_pf_target(p, prompt.len());
cache.ensure_span_blocks(pools, &mut tbl, p, next - p).unwrap();
cache.finish_prefill_span(pools, &mut tbl, &mut st, prompt, p, next - p, || fake_cs(1));
p = next;
}
let mut history = prompt.to_vec();
for _ in 0..reply_len {
let pos = history.len();
history.push(0x4000_0000 | pos as u32);
cache.ensure_span_blocks(pools, &mut tbl, pos, 1).unwrap();
cache.finish_decode_span(pools, &mut tbl, &mut st, pos);
cache.seal_decode_block(pools, &tbl, &mut st, &history, pos, || fake_cs(2));
}
CardTurn { tbl, st, history, resumed_at }
}
fn card_turn_close(cache: &mut ServeBlockCache, pools: &mut BlockPools, mut turn: CardTurn, cancelled: bool) -> Vec<u32> {
cache.release_lane_with_toks(pools, &mut turn.tbl, &mut turn.st, Some(&turn.history), cancelled);
turn.history
}
fn card_turn(
cache: &mut ServeBlockCache,
pools: &mut BlockPools,
owner: u64,
prompt: &[u32],
reply_len: usize,
) -> (usize, Vec<u32>) {
let turn = card_turn_open(cache, pools, 0, owner, prompt, reply_len);
let resumed_at = turn.resumed_at;
(resumed_at, card_turn_close(cache, pools, turn, false))
}
fn start_positions(cache: &ServeBlockCache, approx: bool) -> Vec<usize> {
let mut pos: Vec<usize> = cache.starts.values().filter(|s| s.approx == approx).map(|s| s.pos).collect();
pos.sort_unstable();
pos
}
fn extended(history: &[u32], new_tokens: usize, tag: u32) -> Vec<u32> {
let mut prompt = history.to_vec();
prompt.extend((0..new_tokens as u32).map(|i| tag + i));
prompt
}
#[test]
fn completed_turn_releases_its_conversations_earlier_starts_and_no_kv() {
let cases: [(bool, [&[usize]; 2]); 2] =
[(true, [&[9536, 9664], &[10560, 10688]]), (false, [&[8448, 9536, 9664], &[8448, 9536, 9664, 10560, 10688]])];
let mut used = Vec::new();
for (supersede, want) in cases {
let mut pools = BlockPools::records_only_with_capacities(512, 256, 1).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_approx_retain(true);
cache.set_release_superseded_starts(supersede);
let card = own(0, "card-a");
let turn1: Vec<u32> = (0..8266u32).map(|i| 1_000 + i).collect();
let (at1, h1) = card_turn(&mut cache, &mut pools, card, &turn1, 200);
assert_eq!(at1, 0);
assert_eq!(start_positions(&cache, false), [2048, 4096, 6144, 8192, 8256]);
assert_eq!(start_positions(&cache, true), [8448], "turn 1's turn-end start");
let (at2, h2) = card_turn(&mut cache, &mut pools, card, &extended(&h1, 1100, 200_000), 150);
assert_eq!(at2, 8448);
assert_eq!(start_positions(&cache, true), want[0], "supersede {supersede}");
let turn3 = extended(&h2, 900, 300_000);
let (at3, h3) = card_turn(&mut cache, &mut pools, card, &turn3, 100);
assert_eq!(at3, 9664);
assert_eq!(start_positions(&cache, true), want[1], "supersede {supersede}");
assert_eq!(start_positions(&cache, false), [2048, 4096, 6144, 8192, 8256], "exact starts are the LRU's");
assert_eq!(cache.stats().evictions_superseded, if supersede { 3 } else { 0 });
assert_eq!(cache.stats().evictions_pool_pressure, 0);
used.push((cache.pool_occupancy(&pools, BlockKind::Window).0, cache.pool_occupancy(&pools, BlockKind::Full).0));
let mut tbl = BlockTable::new(2048).unwrap();
let mut st = LaneBlockState { owner: card, ..Default::default() };
assert_eq!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &turn3).map(|(at, _)| at), Some(10560));
cache.release_lane(&mut pools, &mut tbl, &mut st);
let (at4, _) = card_turn(&mut cache, &mut pools, card, &extended(&h3, 500, 400_000), 0);
assert_eq!(at4, 10688);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
let [(win_on, full_on), (win_off, full_off)] = used[..] else { unreachable!() };
assert_eq!(full_on, full_off, "the kept starts hold the whole chain");
assert_eq!(full_off, 10688 / BLOCK);
assert_eq!(win_on, 4 * 16 + 1 + 18);
assert_eq!(win_off, win_on + 3 + 16);
}
#[test]
fn superseded_starts_are_only_the_completed_turns_own_chain() {
let mut pools = BlockPools::records_only_with_capacities(512, 256, 1).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_approx_retain(true);
cache.set_release_superseded_starts(true);
let card = own(0, "card-a");
let turn1: Vec<u32> = (0..8266u32).map(|i| 1_000 + i).collect();
let (_, h1) = card_turn(&mut cache, &mut pools, card, &turn1, 200);
let (_, h2) = card_turn(&mut cache, &mut pools, card, &extended(&h1, 1100, 200_000), 150);
assert_eq!(start_positions(&cache, true), [9536, 9664]);
let turn3 = extended(&h2, 900, 300_000);
let open = card_turn_open(&mut cache, &mut pools, 0, card, &turn3, 100);
assert_eq!(open.resumed_at, 9664);
card_turn_close(&mut cache, &mut pools, open, true);
assert_eq!(start_positions(&cache, true), [9536, 9664, 10560, 10688], "a cancelled turn releases nothing");
assert_eq!(cache.stats().evictions_superseded, 1);
let (at3, h3) = card_turn(&mut cache, &mut pools, card, &turn3, 100);
assert_eq!(at3, 10560);
assert_eq!(start_positions(&cache, true), [10560, 10688]);
assert_eq!(cache.stats().evictions_superseded, 3);
let unfinished = extended(&h3, 20, 0x0045_0000);
let mut tbl = BlockTable::new(2048).unwrap();
let mut st = LaneBlockState { owner: card, ..Default::default() };
assert_eq!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &unfinished).map(|(at, _)| at), Some(10688));
assert!(st.prompt_saved_id.is_some() && st.written < st.prompt_len);
cache.release_lane_with_toks(&mut pools, &mut tbl, &mut st, None, false);
assert_eq!(start_positions(&cache, true), [10560, 10688]);
assert_eq!(cache.stats().evictions_superseded, 3);
let sibling1 = extended(&turn1, 700, 500_000);
let (at_s1, hs1) = card_turn(&mut cache, &mut pools, card, &sibling1, 100);
assert_eq!(at_s1, 8256, "the sibling starts from turn 1's exact PROMPT start");
assert_eq!(start_positions(&cache, true), [9024, 10560, 10688]);
let (at4, h4) = card_turn(&mut cache, &mut pools, card, &extended(&h3, 500, 400_000), 70);
assert_eq!(at4, 10688);
assert_eq!(start_positions(&cache, true), [9024, 11200, 11264], "the sibling's start outlives the first's turn");
let (at_s2, _) = card_turn(&mut cache, &mut pools, card, &extended(&hs1, 300, 600_000), 0);
assert_eq!(at_s2, 9024);
let (at5, _) = card_turn(&mut cache, &mut pools, card, &extended(&h4, 200, 700_000), 0);
assert_eq!(at5, 11264);
let before = cache.stats().evictions_superseded;
let other: Vec<u32> = (0..3000u32).map(|i| 800_000 + i).collect();
let (_, ho) = card_turn(&mut cache, &mut pools, 0, &other, 200);
let (at_o, _) = card_turn(&mut cache, &mut pools, 0, &extended(&ho, 300, 900_000), 0);
assert_eq!(at_o, 2944, "an anonymous turn resumes at its exact PROMPT start");
assert_eq!(cache.stats().evictions_superseded, before);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
#[ignore = "slow: runs in nightly unit-extras"]
fn kv8_64_gib_window_slots_are_not_held_by_earlier_turns_while_full_slots_are_free() {
const LANES: usize = 24;
const ROUNDS: usize = 7;
const IDLE_FROM: usize = 3; #[cfg(not(standalone_blocks))]
let (n_window, n_full) = {
let gib = 1u64 << 30;
crate::engine::Engine::plan_serve_block_pools_for(
64 * gib,
crate::blocks::KVB_KV8,
4096,
131_072,
LANES,
64 * gib,
15,
true,
true,
)
.unwrap()
};
#[cfg(standalone_blocks)]
let (n_window, n_full) = (1_966usize, 54_796usize);
assert_eq!((n_window, n_full), (1_966, 54_796), "the 64 GiB --kv8 pool of 2026-12-02");
assert_eq!(n_window - LANES * 17, 1_558);
let mut seen = Vec::new();
for supersede in [false, true] {
let mut pools = BlockPools::records_only_with_capacities(n_full, n_window, crate::blocks::KVB_KV8).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_approx_retain(true);
cache.set_max_retained_host_bytes(28 << 30);
cache.set_release_superseded_starts(supersede);
let shared: Vec<u32> = (0..4_224u32).map(|i| 1_000 + i).collect();
let mut history: Vec<Vec<u32>> = (0..LANES as u32).map(|c| extended(&shared, 876, (c + 1) << 20)).collect();
let mut open: Vec<Option<CardTurn>> = (0..LANES).map(|_| None).collect();
let mut card0_turn_end = 0usize;
for round in 0..ROUNDS {
for c in 0..LANES {
if let Some(turn) = open[c].take() {
history[c] = card_turn_close(&mut cache, &mut pools, turn, false);
history[c] = extended(&history[c], 800, ((c as u32 + 1) << 20) | ((round as u32) << 12));
}
if c == 0 && round >= IDLE_FROM {
continue;
}
let turn = card_turn_open(&mut cache, &mut pools, 0, own(0, &format!("card-{c}")), &history[c], 134);
if c == 0 {
card0_turn_end = (turn.history.len() / BLOCK) * BLOCK;
}
open[c] = Some(turn);
}
}
let (win_used, win_cap) = cache.pool_occupancy(&pools, BlockKind::Window);
let (full_used, full_cap) = cache.pool_occupancy(&pools, BlockKind::Full);
let stats = cache.stats();
let back = card_turn_open(&mut cache, &mut pools, 0, own(0, "card-0"), &history[0], 0);
let starts = cache.retained_start_count();
let wanted = LANES * 17 + starts * (WINDOW / BLOCK);
seen.push((win_used, full_used, stats.evictions_pool_pressure, starts, back.resumed_at));
assert_eq!((win_cap, full_cap), (1_966, 54_796));
assert_eq!(stats.admit_deferred_pool_pressure, 0);
if supersede {
assert_eq!(back.resumed_at, card0_turn_end, "card 0 resumes where its last turn ended");
assert_eq!(stats.evictions_pool_pressure, 0, "no start is evicted for a window slot");
assert!(win_used * 100 <= win_cap * 75, "window slots {win_used} of {win_cap}");
assert!(stats.evictions_superseded > 0);
assert!(starts <= 5 * LANES, "{starts} starts");
assert!(wanted <= win_cap + LANES * 2, "{wanted} window slots wanted of {win_cap}");
} else {
assert!(starts >= 8 * LANES, "{starts} starts");
assert!(wanted > win_cap * 3 / 2, "{wanted} window slots wanted of {win_cap}");
assert!(win_used + 16 > win_cap, "window slots {win_used} of {win_cap}");
assert!(full_used * 100 < full_cap * 40, "full slots {full_used} of {full_cap}");
assert!(stats.evictions_pool_pressure > 0);
assert!(back.resumed_at < card0_turn_end, "card 0 resumed at {} of {card0_turn_end}", back.resumed_at);
}
card_turn_close(&mut cache, &mut pools, back, true);
for turn in open.into_iter().flatten() {
card_turn_close(&mut cache, &mut pools, turn, true);
}
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
eprintln!(
"kv8 64 GiB, 24 cards (window used, full used, pool-pressure evictions, starts, card 0 resumed at): off {:?}, on (the serve default) {:?}",
seen[0], seen[1]
);
}
#[test]
fn an_echoed_thinking_block_keeps_the_previous_reply_reusable() {
use serde_json::json;
let tk = crate::tokenizer::Tokenizer::for_byte_test();
let sp = crate::serve::Specials::try_from_tokenizer(&tk).unwrap();
let render_chat = |req: &serde_json::Value| crate::serve::prompt::render_limited(&tk, &sp, req, "low", usize::MAX, &[]).unwrap();
let render_msgs = |req: &serde_json::Value| {
let (chat, cont) = crate::serve::messages::translate_messages(req).unwrap();
crate::serve::prompt::render_limited(&tk, &sp, &chat, "low", usize::MAX, &cont).unwrap()
};
let system = "You-are-a-coding-agent.".repeat(300);
let task = "Fix-the-failing-test-in-the-repo.".repeat(8);
let schema = json!({"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]});
let result = "drwxr-xr-x-src-tests-Cargo.toml-".repeat(16);
let thinking = "t".repeat(600);
let msgs1 = json!({"max_tokens": 20480, "thinking": {"type": "adaptive"}, "output_config": {"effort": "low"},
"tools": [{"name": "bash", "description": "Run a command", "input_schema": schema}],
"system": [{"type": "text", "text": system, "cache_control": {"type": "ephemeral"}}],
"messages": [{"role": "user", "content": [{"type": "text", "text": task}]}]});
let p1 = render_msgs(&msgs1);
let mut reply: Vec<u32> = vec![sp.msg_model, sp.c_think];
tk.encode_plain_limited(&thinking, &mut reply, usize::MAX);
reply.push(sp.end);
reply.push(sp.msg_model);
tk.encode_plain_limited("bash", &mut reply, usize::MAX);
reply.push(sp.c_tool);
tk.encode_plain_limited("{\"name\":\"bash\",\"args\":{\"command\":\"ls-la\"}}", &mut reply, usize::MAX);
reply.extend([sp.end, sp.end_sampling]);
let mut history = p1.clone();
history.extend_from_slice(&reply);
let sent = crate::serve::reply::anthropic_content(&tk, &sp, &reply, "n", 1);
assert_eq!(sent.iter().map(|b| b["type"].as_str().unwrap()).collect::<Vec<_>>(), ["thinking", "tool_use"]);
let turn2 = |assistant: Vec<serde_json::Value>| {
let mut m = msgs1.clone();
m["messages"].as_array_mut().unwrap().extend([
json!({"role": "assistant", "content": assistant}),
json!({"role": "user", "content": [{"type": "tool_result", "tool_use_id": sent[1]["id"], "content": result}]})]);
render_msgs(&m)
};
let echoed = turn2(sent.clone());
let mut unsigned = sent.clone();
unsigned[0].as_object_mut().unwrap().remove("signature");
let dropped = turn2(unsigned);
let mut edited = sent.clone();
edited[0]["thinking"] = json!(format!("{thinking}."));
assert_eq!(turn2(edited), dropped, "an edited block is dropped like an unsigned one");
let chat2 = json!({"tools": [{"type": "function", "function": {"name": "bash", "description": "Run a command", "parameters": schema}}],
"messages": [{"role": "system", "content": [{"type": "text", "text": system}]}, {"role": "user", "content": [{"type": "text", "text": task}]},
{"role": "assistant", "content": "", "reasoning_content": thinking, "tool_calls": [{"id": sent[1]["id"], "type": "function",
"function": {"name": "bash", "arguments": "{\"command\":\"ls-la\"}"}}]},
{"role": "tool", "tool_call_id": sent[1]["id"], "content": result}]});
assert_eq!(echoed, render_chat(&chat2), "an echoed block renders as the chat route's reasoning_content");
assert!(echoed.starts_with(&history), "turn 2 holds the whole previous reply, token for token");
let common = |t: &[u32]| t.iter().zip(&history).take_while(|(a, b)| a == b).count();
assert_eq!(common(&dropped), p1.len() + 1, "dropped: the prompt leaves the lane at the thinking");
assert_eq!(common(&echoed), history.len());
let resume = |turn: &[u32], approx_retain: bool| {
let mut pools = BlockPools::with_capacities(512, 256, 2).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_approx_retain(approx_retain);
let mut tbl = BlockTable::new(512).unwrap();
let mut st = LaneBlockState { owner: own(0, "card-a"), ..Default::default() };
assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &p1).is_none());
let mut p = 0;
while p < p1.len() {
let next = effective_pf_target(p, p1.len());
cache.ensure_span_blocks(&mut pools, &mut tbl, p, next - p).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &p1, p, next - p, || fake_cs((next / BLOCK) as u8));
p = next;
}
for pos in p1.len()..history.len() {
cache.ensure_span_blocks(&mut pools, &mut tbl, pos, 1).unwrap();
cache.finish_decode_span(&mut pools, &mut tbl, &mut st, pos);
cache.seal_decode_block(&mut pools, &tbl, &mut st, &history[..=pos], pos, || fake_cs(0x55));
}
cache.release_lane(&mut pools, &mut tbl, &mut st);
let mut st2 = LaneBlockState { owner: own(0, "card-a"), ..Default::default() };
let at = cache.match_and_bind(&mut pools, &mut tbl, &mut st2, turn).map_or(0, |(at, _)| at);
cache.release_lane(&mut pools, &mut tbl, &mut st2);
cache.shutdown(&mut pools);
at
};
let floor = |n: usize| n / BLOCK * BLOCK;
for approx_retain in [false, true] {
let (before, after) = (resume(&dropped, approx_retain), resume(&echoed, approx_retain));
eprintln!(
"REUSE approx_retain={approx_retain}: prompt1={} reply={} (thinking {}) | dropped: turn2={} reused={before} reprefill={} | echoed: turn2={} reused={after} reprefill={}",
p1.len(), reply.len(), thinking.len(), dropped.len(), dropped.len() - before, echoed.len(), echoed.len() - after
);
assert_eq!(before, floor(p1.len()), "dropped: the lane resumes at the previous prompt's last block");
let expect = if approx_retain { floor(history.len()) } else { floor(p1.len()) };
assert_eq!(after, expect, "echoed: an approximate lane resumes at the previous reply's last block");
}
}
#[test]
fn a_large_retained_host_cap_keeps_starts_past_512_mib() {
assert_eq!(ServeBlockCache::recommended_host_budget_bytes(u64::MAX), DEFAULT_MAX_RETAINED_HOST_BYTES);
for (cap, kept) in [(DEFAULT_MAX_RETAINED_HOST_BYTES, false), (1u64 << 30, true)] {
let mut pools = BlockPools::with_capacities(256, 128, 2).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_max_retained_host_bytes(cap);
let big_cs = 300usize << 20;
for prompt in 0..2u32 {
let toks: Vec<u32> = (0..2048u32).map(|i| prompt * 10_000 + i).collect();
let mut tbl = BlockTable::new(64).unwrap();
let mut st = LaneBlockState::default();
for b in 0..(2048 / BLOCK) {
cache.ensure_span_blocks(&mut pools, &mut tbl, b * BLOCK, BLOCK).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &toks, b * BLOCK, BLOCK, || vec![0u8; big_cs]);
}
cache.release_lane(&mut pools, &mut tbl, &mut st);
}
assert_eq!(cache.retained_start_count() == 2, kept, "cap {cap}");
if kept {
assert!(cache.retained_host_bytes_now() > DEFAULT_MAX_RETAINED_HOST_BYTES);
}
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
}
#[test]
fn approx_twin_is_keyed_by_the_secret_salt_and_never_the_exact_namespace() {
let a = approx_twin("salt-one", 7, Some("card-a"));
assert_ne!(a, approx_twin("salt-two", 7, Some("card-a")), "the twin depends on the server's secret salt");
assert_ne!(a, approx_twin("salt-one", 8, Some("card-a")), "and on the auth namespace");
assert_ne!(a, approx_twin("salt-one", 7, Some("card-b")), "and on the conversation id");
assert_ne!(a, 7);
assert_eq!(approx_twin("salt-one", 7, None), 0, "no conversation id, no twin");
assert_eq!(approx_twin("salt-one", 7, Some("")), 0);
assert_ne!(approx_twin("ab", 7, Some("c")), approx_twin("a", 7, Some("bc")));
}
#[test]
fn exact_bind_paths_refuse_an_approximate_start_even_in_their_own_namespace() {
let mut pools = BlockPools::with_capacities(512, 256, 2).unwrap();
let mut cache = ServeBlockCache::new();
let toks: Vec<u32> = (0..2100u32).collect();
let mut tbl = BlockTable::new(512).unwrap();
let mut st = LaneBlockState { namespace: 5, ..Default::default() };
let mut p = 0;
while p < toks.len() {
let next = effective_pf_target(p, toks.len());
cache.ensure_span_blocks(&mut pools, &mut tbl, p, next - p).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &toks, p, next - p, || fake_cs(1));
p = next;
}
cache.release_lane(&mut pools, &mut tbl, &mut st);
for s in cache.starts.values_mut() {
s.approx = true;
}
let mut st2 = LaneBlockState { namespace: 5, ..Default::default() };
let mut longer = toks.clone();
longer.extend(0..40u32);
assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut st2, &longer).is_none(), "match_and_bind");
let mut st3 = LaneBlockState { namespace: 5, ..Default::default() };
assert!(
matches!(cache.begin_admit_bind(&mut pools, 0, &mut tbl, &mut st3, &longer), AdmitBindOutcome::Immediate(None)),
"begin_admit_bind"
);
cache.release_lane(&mut pools, &mut tbl, &mut st3);
for s in cache.starts.values_mut() {
s.approx = false;
}
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn approximate_bind_gives_up_rather_than_spin_on_an_index_desync() {
let kvb = 1u32;
let mut pools = BlockPools::with_capacities(512, 160, kvb).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_kv_stitch(true);
cache.set_approx_retain(true);
let file_span = seed_stitch_donor(&mut cache, &mut pools, 7, kvb);
let (prompt, reply) = stitched_turn_one(&mut cache, &mut pools, 7, own(7, "card-a"), &file_span, 100);
let approx: Vec<SealedId> = cache.starts.iter().filter(|(_, s)| s.approx).map(|(&id, _)| id).collect();
let removed: Vec<(SealedId, RetainedStart)> =
approx.iter().map(|id| (*id, cache.starts.remove(id).unwrap())).collect();
let t2 = turn_two(&prompt, &reply);
let mut tbl = BlockTable::new(160).unwrap();
let mut st = LaneBlockState { namespace: 7, owner: own(7, "card-a"), ..Default::default() };
assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &t2).is_none(), "returns, never spins");
for (id, s) in removed {
cache.starts.insert(id, s);
}
cache.release_lane(&mut pools, &mut tbl, &mut st);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn reply_sealing_resumes_after_a_step_that_skipped_a_boundary() {
let mut pools = BlockPools::with_capacities(512, 256, 2).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_approx_retain(true);
let turn1: Vec<u32> = (0..8266u32).map(|i| (i * 17 + 3) % 50000).collect();
let mut tbl = BlockTable::new(512).unwrap();
let mut st = LaneBlockState { owner: own(0, "card-a"), ..Default::default() };
let mut p = 0;
while p < turn1.len() {
let next = effective_pf_target(p, turn1.len());
cache.ensure_span_blocks(&mut pools, &mut tbl, p, next - p).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &turn1, p, next - p, || fake_cs(2));
p = next;
}
let mut history = turn1.clone();
for d in 0..200u32 {
let pos = turn1.len() + d as usize;
history.push(90_000 + d);
cache.ensure_span_blocks(&mut pools, &mut tbl, pos, 1).unwrap();
cache.finish_decode_span(&mut pools, &mut tbl, &mut st, pos);
if pos == 8319 {
continue; }
cache.seal_decode_block(&mut pools, &tbl, &mut st, &history, pos, || fake_cs(0x56));
}
cache.release_lane(&mut pools, &mut tbl, &mut st);
let mut turn2 = history.clone();
turn2.extend((0..140u32).map(|i| 60000 + i));
let mut st2 = LaneBlockState { owner: own(0, "card-a"), ..Default::default() };
let (at, _) = cache.match_and_bind(&mut pools, &mut tbl, &mut st2, &turn2).expect("a start");
assert_eq!(at, 8448, "sealing caught up after the skipped boundary");
cache.release_lane(&mut pools, &mut tbl, &mut st2);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn one_scope_churning_conversations_cannot_evict_another_scopes_approximate_work() {
let kvb = 1u32;
let mut pools = BlockPools::with_capacities(2048, 640, kvb).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_kv_stitch(true);
cache.set_approx_retain(true);
cache.set_max_approx_starts_per_scope(8);
let file_span = seed_stitch_donor(&mut cache, &mut pools, 7, kvb);
let _ = seed_stitch_donor(&mut cache, &mut pools, 9, kvb);
let (prompt, reply) = stitched_turn_one(&mut cache, &mut pools, 9, own(9, "victim"), &file_span, 100);
let victim_starts = cache.approx_per_scope.get(&9).copied().unwrap_or(0);
assert!(victim_starts > 0);
for i in 0..6 {
let card = format!("churn-{i}");
stitched_turn_one(&mut cache, &mut pools, 7, own(7, &card), &file_span, 100);
assert!(cache.approx_per_scope.get(&7).copied().unwrap_or(0) <= 8, "scope 7 is held to its cap");
}
assert_eq!(cache.approx_per_scope.get(&9).copied().unwrap_or(0), victim_starts, "scope 9 is untouched");
let mut tbl = BlockTable::new(160).unwrap();
let mut st = LaneBlockState { namespace: 9, owner: own(9, "victim"), ..Default::default() };
assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &turn_two(&prompt, &reply)).is_some());
cache.release_lane(&mut pools, &mut tbl, &mut st);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn async_ikv_stitch_gets_the_same_approximate_provenance_as_a_ram_stitch() {
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
let dir = ScratchDir::new("ikv-approx-provenance");
#[cfg(unix)]
std::fs::set_permissions(&dir.0, std::fs::Permissions::from_mode(0o700)).unwrap();
let kvb = 1u32;
let vocab = 262_144u32;
let model_fp = 0xfeed_face_cafe_beefu64;
let hmac_key = crate::ikv::IkvHmacKey::from_bytes(b"block-cache-test-hmac-key-32byte").unwrap();
let page_bytes = crate::blocks::BlockKind::Full.stride_bytes(kvb).unwrap() as usize;
let cart_toks: Vec<u32> = (0..3200u32).map(|i| 120_000 + i).collect();
let mut full_pages: Vec<Vec<u8>> = Vec::with_capacity(50);
for p in 0..50usize {
let mut page = vec![0u8; page_bytes];
stamp_test_full_block_rows(&mut page, &cart_toks[p * BLOCK..(p + 1) * BLOCK], kvb);
full_pages.push(page);
}
let ikv_path = dir.0.join("sample.ikv");
crate::ikv::write_ikv_cartridge_raw(
&ikv_path,
"src/sample.rs",
kvb,
vocab,
model_fp,
false,
16,
&cart_toks,
&full_pages,
Some(&hmac_key),
)
.unwrap();
let cat =
Arc::new(crate::ikv::IkvCatalog::load_dir(&dir.0, kvb, vocab, model_fp, false, &hmac_key).unwrap());
let mut pools = BlockPools::with_capacities(256, 96, kvb).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_kv_stitch(true);
cache.set_approx_retain(true);
cache.set_ikv_catalog(cat);
let owner = own(0, "card-ikv");
let mut prompt: Vec<u32> = (0..83u32).map(|i| 4_000 + i).collect();
prompt.extend_from_slice(&cart_toks);
prompt.extend((0..128u32).map(|i| 90_000 + i)); let plans = cache.plan_stitches(&pools, 0, &prompt, 0);
assert_eq!(plans.len(), 1);
let mut tbl = BlockTable::new(96).unwrap();
let mut st = LaneBlockState { namespace: 0, owner, prompt_len: prompt.len(), ..Default::default() };
let _ = cache.begin_admit_bind(&mut pools, 0, &mut tbl, &mut st, &prompt);
cache.ensure_span_blocks(&mut pools, &mut tbl, 0, plans[0].stitch_start).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &prompt, 0, plans[0].stitch_start, || fake_cs(1));
assert_eq!(
cache.start_stitch_plan(&mut pools, 0, &mut tbl, &mut st, &prompt, &plans[0]),
StitchStartOutcome::Staging
);
let done = loop {
let tbl_ptr: *mut BlockTable = &mut tbl;
let st_ptr: *mut LaneBlockState = &mut st;
let mut batch = cache.poll_ikv_stages(&mut pools, |l| (l == 0).then_some((&(), tbl_ptr, st_ptr)));
if let Some(c) = batch.pop() {
break c;
}
cache.wait_restore_activity(Duration::from_millis(50));
};
assert!(done.stitched_tokens.is_some());
assert!(st.stitched_approx && st.approx_path, "a completed .ikv install enters the twin path");
let mut p = st.written;
while p < prompt.len() {
let next = effective_pf_target(p, prompt.len());
cache.ensure_span_blocks(&mut pools, &mut tbl, p, next - p).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &prompt, p, next - p, || fake_cs(0x44));
p = next;
}
cache.release_lane(&mut pools, &mut tbl, &mut st);
assert!(cache.starts.values().any(|s| s.approx && s.pos == 3392), "its PROMPT start was saved in the twin");
assert_eq!(cache.tree.deepest_start_in_namespace(0, &prompt).at, 0, "and never in the exact chain");
let mut turn2 = prompt.clone();
turn2.extend((0..200u32).map(|i| 95_000 + i));
let mut tbl2 = BlockTable::new(96).unwrap();
let mut st2 = LaneBlockState { namespace: 0, owner, ..Default::default() };
let (at, _) = cache.match_and_bind(&mut pools, &mut tbl2, &mut st2, &turn2).expect("turn 2 resumes");
assert_eq!(at, 3392);
assert!(st2.stitched_approx && st2.approx_path, "classified approximate, as a RAM stitch is");
cache.release_lane(&mut pools, &mut tbl2, &mut st2);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn finalize_verify_span_then_seal_decode_block_across_boundary_retains_later_reply_start() {
let mut pools = BlockPools::with_capacities(64, 64, 2).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_approx_retain(true);
let owner = approx_twin("srv-salt", 0, Some("card-verify-seal"));
let prompt: Vec<u32> = (0..60u32).map(|i| 5_000 + i).collect();
let mut tbl = BlockTable::new(16).unwrap();
let mut fg = vec![crate::blocks::CLEARED_GPU_TABLE_ENTRY; 16];
let mut wg = vec![crate::blocks::CLEARED_GPU_TABLE_ENTRY; 16];
let mut st = LaneBlockState { namespace: 0, owner, prompt_len: prompt.len(), ..Default::default() };
cache.ensure_span_blocks(&mut pools, &mut tbl, 0, prompt.len()).unwrap();
tbl.sync_dirty_to_slice(BlockKind::Full, &pools.full, &mut fg).unwrap();
tbl.sync_dirty_to_slice(BlockKind::Window, &pools.window, &mut wg).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &prompt, 0, prompt.len(), || fake_cs(0x10));
let mut history = prompt.clone();
history.push(6_000); for pos in [60usize, 61] {
cache.ensure_span_blocks(&mut pools, &mut tbl, pos, 1).unwrap();
tbl.sync_dirty_to_slice(BlockKind::Full, &pools.full, &mut fg).unwrap();
tbl.sync_dirty_to_slice(BlockKind::Window, &pools.window, &mut wg).unwrap();
cache.finish_decode_span(&mut pools, &mut tbl, &mut st, pos);
cache.seal_decode_block(&mut pools, &tbl, &mut st, &history, pos, || fake_cs(0x20));
history.push(6_001 + (pos - 60) as u32);
}
let alloc = cache.ensure_span_blocks_tracking(&mut pools, &mut tbl, 62, 4).unwrap();
tbl.sync_dirty_to_slice(BlockKind::Full, &pools.full, &mut fg).unwrap();
tbl.sync_dirty_to_slice(BlockKind::Window, &pools.window, &mut wg).unwrap();
let fin = cache
.finish_verify_span_to_slices(&mut pools, &mut tbl, &mut st, &alloc, 62, 4, &mut fg, &mut wg)
.expect("finalize_verify_blocks_at across block 0 -> 1");
assert_eq!(fin.committed_len, 66);
history.extend_from_slice(&[7_000, 7_001, 7_002, 7_003]);
cache.seal_decode_block(&mut pools, &tbl, &mut st, &history, 65, || fake_cs(0xAA));
assert!(st.approx_path, "crossing block 0 inside verify enters twin path and seals block 0");
assert_eq!(st.sealed.len(), 1);
assert!(st.turn_ckpt.is_none(), "non-aligned end=66 must not record a misaligned cs at 64");
for pos in 66usize..128 {
cache.ensure_span_blocks(&mut pools, &mut tbl, pos, 1).unwrap();
cache.finish_decode_span(&mut pools, &mut tbl, &mut st, pos);
cache.seal_decode_block(&mut pools, &tbl, &mut st, &history, pos, || fake_cs(0xBB));
history.push(8_000 + pos as u32);
}
assert_eq!(st.sealed.len(), 2);
cache.release_lane(&mut pools, &mut tbl, &mut st);
let mut turn2 = history[..128].to_vec();
turn2.extend((0..40u32).map(|i| 9_000 + i));
let mut tbl2 = BlockTable::new(16).unwrap();
let mut st2 = LaneBlockState { namespace: 0, owner, ..Default::default() };
let (at, cs) = cache.match_and_bind(&mut pools, &mut tbl2, &mut st2, &turn2).expect("turn 2 resumes at 128");
assert_eq!(at, 128);
assert_eq!(cs, fake_cs(0xBB));
cache.release_lane(&mut pools, &mut tbl2, &mut st2);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn card_lease_protects_latest_turn_prompt_and_turn_end_starts_until_expiry() {
let mut pools = BlockPools::with_capacities(4, 4, 2).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_approx_retain(true);
cache.set_card_lease(Duration::from_secs(30));
cache.set_test_clock_ms(1_000);
let owner_a = approx_twin("lease-salt", 1, Some("card-a"));
let prompt_a: Vec<u32> = (0..64u32).map(|i| 10_000 + i).collect();
let mut tbl_a = BlockTable::new(8).unwrap();
let mut st_a = LaneBlockState { namespace: 1, owner: owner_a, ..Default::default() };
let _ = cache.match_and_bind(&mut pools, &mut tbl_a, &mut st_a, &prompt_a);
st_a.stitched_approx = true;
cache.enter_approx_path(&pools, &tbl_a, &mut st_a, &prompt_a);
cache.ensure_span_blocks(&mut pools, &mut tbl_a, 0, 64).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_a, &mut st_a, &prompt_a, 0, 64, || fake_cs(0xA1));
assert_eq!(cache.stats().approx_starts_saved, 1);
let mut hist_a = prompt_a.clone();
hist_a.push(11_000);
for pos in 64usize..128 {
cache.ensure_span_blocks(&mut pools, &mut tbl_a, pos, 1).unwrap();
cache.finish_decode_span(&mut pools, &mut tbl_a, &mut st_a, pos);
cache.seal_decode_block(&mut pools, &tbl_a, &mut st_a, &hist_a, pos, || fake_cs(0xA2));
hist_a.push(11_001 + (pos - 64) as u32);
}
cache.release_lane(&mut pools, &mut tbl_a, &mut st_a);
assert_eq!(cache.stats().approx_starts_saved, 2, "both PROMPT@64 and turn_end@128 saved");
cache.advance_test_clock_ms(4_000);
let anon1: Vec<u32> = (0..128u32).map(|i| 20_000 + i).collect();
let mut tbl_u1 = BlockTable::new(8).unwrap();
let mut st_u1 = LaneBlockState { namespace: 1, owner: 0, ..Default::default() };
let _ = cache.match_and_bind(&mut pools, &mut tbl_u1, &mut st_u1, &anon1);
cache.ensure_span_blocks(&mut pools, &mut tbl_u1, 0, 128).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_u1, &mut st_u1, &anon1, 0, 128, || fake_cs(0xB1));
cache.release_lane(&mut pools, &mut tbl_u1, &mut st_u1);
assert_eq!(cache.retained_start_count(), 3);
cache.advance_test_clock_ms(5_000);
let anon2: Vec<u32> = (0..128u32).map(|i| 30_000 + i).collect();
let mut tbl_u2 = BlockTable::new(8).unwrap();
let mut st_u2 = LaneBlockState { namespace: 1, owner: 0, ..Default::default() };
let _ = cache.match_and_bind(&mut pools, &mut tbl_u2, &mut st_u2, &anon2);
cache.ensure_span_blocks(&mut pools, &mut tbl_u2, 0, 128).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_u2, &mut st_u2, &anon2, 0, 128, || fake_cs(0xB2));
cache.release_lane(&mut pools, &mut tbl_u2, &mut st_u2);
let mut probe_anon1 = anon1.clone();
probe_anon1.push(99);
assert_eq!(cache.peek_match_len_in_namespace(&pools, 1, &probe_anon1), 0, "unleased anon1 must be evicted first");
let twin_a = approx_namespace(1, owner_a);
let mut a_positions: Vec<usize> =
cache.starts.values().filter(|st| st.namespace == twin_a).map(|st| st.pos).collect();
a_positions.sort_unstable();
assert_eq!(
a_positions,
vec![64, 128],
"both Card A PROMPT@64 and turn_end@128 starts must remain resident under active lease"
);
cache.advance_test_clock_ms(21_000);
let anon3: Vec<u32> = (0..128u32).map(|i| 40_000 + i).collect();
let mut tbl_u3 = BlockTable::new(8).unwrap();
let mut st_u3 = LaneBlockState { namespace: 1, owner: 0, ..Default::default() };
let _ = cache.match_and_bind(&mut pools, &mut tbl_u3, &mut st_u3, &anon3);
cache.ensure_span_blocks(&mut pools, &mut tbl_u3, 0, 128).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_u3, &mut st_u3, &anon3, 0, 128, || fake_cs(0xB3));
cache.release_lane(&mut pools, &mut tbl_u3, &mut st_u3);
let mut probe_anon2 = anon2.clone();
probe_anon2.push(99);
assert_eq!(cache.peek_match_len_in_namespace(&pools, 1, &probe_anon2), 128, "newer anon2 survives after Card A expiry");
assert_eq!(
cache.starts.values().filter(|st| st.namespace == twin_a).count(),
0,
"expired Card A starts are evicted by LRU"
);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn card_lease_unleases_prior_turn_immediately_and_never_causes_false_exhaustion() {
{
let mut pools = BlockPools::with_capacities(16, 16, 2).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_approx_retain(true);
cache.set_card_lease(Duration::from_secs(30));
cache.set_max_approx_starts_per_scope(2);
cache.set_test_clock_ms(1_000);
let owner_a = approx_twin("lease-salt", 7, Some("card-a"));
let owner_b = approx_twin("lease-salt", 7, Some("card-b"));
let pb1: Vec<u32> = (0..64u32).map(|i| 1_000 + i).collect();
let mut tbl = BlockTable::new(8).unwrap();
let mut stb1 = LaneBlockState { namespace: 7, owner: owner_b, ..Default::default() };
let _ = cache.match_and_bind(&mut pools, &mut tbl, &mut stb1, &pb1);
stb1.stitched_approx = true;
cache.enter_approx_path(&pools, &tbl, &mut stb1, &pb1);
cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 64).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut stb1, &pb1, 0, 64, || fake_cs(0x11));
cache.release_lane(&mut pools, &mut tbl, &mut stb1);
cache.advance_test_clock_ms(1_000);
let pa1: Vec<u32> = (0..64u32).map(|i| 2_000 + i).collect();
let mut sta1 = LaneBlockState { namespace: 7, owner: owner_a, ..Default::default() };
let _ = cache.match_and_bind(&mut pools, &mut tbl, &mut sta1, &pa1);
sta1.stitched_approx = true;
cache.enter_approx_path(&pools, &tbl, &mut sta1, &pa1);
cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 64).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut sta1, &pa1, 0, 64, || fake_cs(0x22));
cache.release_lane(&mut pools, &mut tbl, &mut sta1);
cache.advance_test_clock_ms(1_000);
let mut pb2 = pb1.clone();
pb2.extend((0..64u32).map(|i| 3_000 + i));
let mut stb2 = LaneBlockState { namespace: 7, owner: owner_b, ..Default::default() };
let (bound_at, _) = cache.match_and_bind(&mut pools, &mut tbl, &mut stb2, &pb2).expect("bind S_B1");
assert_eq!(bound_at, 64);
cache.ensure_span_blocks(&mut pools, &mut tbl, 64, 64).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut stb2, &pb2, 64, 64, || fake_cs(0x33));
cache.release_lane(&mut pools, &mut tbl, &mut stb2);
assert_eq!(cache.retained_start_count(), 2, "scope cap kept exactly 2 approx starts");
let mut probe_a = pa1.clone();
probe_a.push(99);
let mut sta2 = LaneBlockState { namespace: 7, owner: owner_a, ..Default::default() };
let bound_a = cache.match_and_bind(&mut pools, &mut tbl, &mut sta2, &probe_a);
assert_eq!(
bound_a.as_ref().map(|(at, _)| *at),
Some(64),
"Card A's leased S_A1 must survive when Card B's prior-turn S_B1 is unleased"
);
cache.release_lane(&mut pools, &mut tbl, &mut sta2);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
{
let mut pools = BlockPools::with_capacities(2, 2, 2).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_card_lease(Duration::from_secs(30));
cache.set_test_clock_ms(5_000);
let owner_a = approx_twin("lease-salt", 3, Some("card-a"));
let owner_b = approx_twin("lease-salt", 3, Some("card-b"));
let pa: Vec<u32> = (0..64u32).map(|i| 50_000 + i).collect();
let mut tbl = BlockTable::new(4).unwrap();
let mut sta = LaneBlockState { namespace: 3, owner: owner_a, ..Default::default() };
let _ = cache.match_and_bind(&mut pools, &mut tbl, &mut sta, &pa);
cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 64).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut sta, &pa, 0, 64, || vec![0xAA; 4096]);
cache.release_lane(&mut pools, &mut tbl, &mut sta);
cache.advance_test_clock_ms(1_000);
let pb: Vec<u32> = (0..64u32).map(|i| 60_000 + i).collect();
let mut stb = LaneBlockState { namespace: 3, owner: owner_b, ..Default::default() };
let _ = cache.match_and_bind(&mut pools, &mut tbl, &mut stb, &pb);
cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 64).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut stb, &pb, 0, 64, || vec![0xBB; 4096]);
cache.release_lane(&mut pools, &mut tbl, &mut stb);
let mut tbl_c = BlockTable::new(4).unwrap();
assert!(cache.can_satisfy_span(&pools, &tbl_c, 0, 64), "leased starts must remain reclaimable");
cache
.ensure_span_blocks(&mut pools, &mut tbl_c, 0, 64)
.expect("soft lease must evict oldest-tick leased start rather than PoolExhausted");
tbl_c.clear_entries(&mut pools).unwrap();
let mut probe_b = pb.clone();
probe_b.push(1);
assert_eq!(
cache.peek_match_len_in_namespace(&pools, 3, &probe_b),
64,
"newer leased start Card B survives when oldest leased start Card A is reclaimed"
);
let pu1: Vec<u32> = (0..64u32).map(|i| 70_000 + i).collect();
let mut stu1 = LaneBlockState { namespace: 3, owner: 0, ..Default::default() };
let _ = cache.match_and_bind(&mut pools, &mut tbl, &mut stu1, &pu1);
cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 64).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut stu1, &pu1, 0, 64, || vec![0xCC; 4096]);
cache.release_lane(&mut pools, &mut tbl, &mut stu1);
cache.set_max_retained_host_bytes(5_000);
cache.enforce_retained_host_budget(&mut pools, None);
assert_eq!(cache.retained_start_count(), 1);
assert_eq!(
cache.peek_match_len_in_namespace(&pools, 3, &probe_b),
64,
"enforce_retained_host_budget must evict unleased start before leased Card B"
);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
}
#[test]
fn card_lease_survives_same_owner_short_missed_and_unsaved_admissions() {
let mut pools = BlockPools::with_capacities(7, 7, 2).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_approx_retain(true);
cache.set_card_lease(Duration::from_secs(30));
cache.set_test_clock_ms(1_000);
let owner_a = approx_twin("lease-salt", 1, Some("card-a"));
let owner_b = approx_twin("lease-salt", 1, Some("card-b"));
let owner_c = approx_twin("lease-salt", 1, Some("card-c"));
let twin_a = approx_namespace(1, owner_a);
let prompt_a: Vec<u32> = (0..64u32).map(|i| 10_000 + i).collect();
let mut tbl_a = BlockTable::new(8).unwrap();
let mut st_a = LaneBlockState { namespace: 1, owner: owner_a, ..Default::default() };
let _ = cache.match_and_bind(&mut pools, &mut tbl_a, &mut st_a, &prompt_a);
st_a.stitched_approx = true;
cache.enter_approx_path(&pools, &tbl_a, &mut st_a, &prompt_a);
cache.ensure_span_blocks(&mut pools, &mut tbl_a, 0, 64).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_a, &mut st_a, &prompt_a, 0, 64, || fake_cs(0xA1));
let mut hist_a = prompt_a.clone();
hist_a.push(11_000);
for pos in 64usize..128 {
cache.ensure_span_blocks(&mut pools, &mut tbl_a, pos, 1).unwrap();
cache.finish_decode_span(&mut pools, &mut tbl_a, &mut st_a, pos);
cache.seal_decode_block(&mut pools, &tbl_a, &mut st_a, &hist_a, pos, || fake_cs(0xA2));
hist_a.push(11_001 + (pos - 64) as u32);
}
cache.release_lane(&mut pools, &mut tbl_a, &mut st_a);
cache.advance_test_clock_ms(1_000);
let pb1: Vec<u32> = (0..128u32).map(|i| 20_000 + i).collect();
let mut tbl_b = BlockTable::new(8).unwrap();
let mut st_b1 = LaneBlockState { namespace: 1, owner: owner_b, ..Default::default() };
let _ = cache.match_and_bind(&mut pools, &mut tbl_b, &mut st_b1, &pb1);
cache.ensure_span_blocks(&mut pools, &mut tbl_b, 0, 128).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_b, &mut st_b1, &pb1, 0, 128, || fake_cs(0xB1));
cache.release_lane(&mut pools, &mut tbl_b, &mut st_b1);
cache.advance_test_clock_ms(1_000);
let pb2: Vec<u32> = (0..128u32).map(|i| 30_000 + i).collect();
let mut st_b2 = LaneBlockState { namespace: 1, owner: owner_b, ..Default::default() };
let _ = cache.match_and_bind(&mut pools, &mut tbl_b, &mut st_b2, &pb2);
cache.ensure_span_blocks(&mut pools, &mut tbl_b, 0, 128).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_b, &mut st_b2, &pb2, 0, 128, || fake_cs(0xB2));
cache.release_lane(&mut pools, &mut tbl_b, &mut st_b2);
cache.advance_test_clock_ms(1_000);
let mut tbl_short = BlockTable::new(8).unwrap();
let mut st_short = LaneBlockState { namespace: 1, owner: owner_a, ..Default::default() };
assert!(matches!(
cache.begin_admit_bind_in_namespace(&mut pools, 0, &mut tbl_short, &mut st_short, 1, &[777]),
AdmitBindOutcome::Immediate(None)
));
cache.release_lane(&mut pools, &mut tbl_short, &mut st_short);
st_short.owner = owner_a;
assert!(cache.match_and_bind_in_namespace(&mut pools, &mut tbl_short, &mut st_short, 1, &[888]).is_none());
cache.release_lane(&mut pools, &mut tbl_short, &mut st_short);
let miss_toks: Vec<u32> = (0..20u32).map(|i| 80_000 + i).collect();
let mut tbl_miss = BlockTable::new(8).unwrap();
let mut st_miss = LaneBlockState { namespace: 1, owner: owner_a, ..Default::default() };
assert!(cache.match_and_bind_in_namespace(&mut pools, &mut tbl_miss, &mut st_miss, 1, &miss_toks).is_none());
cache.ensure_span_blocks(&mut pools, &mut tbl_miss, 0, 20).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_miss, &mut st_miss, &miss_toks, 0, 20, || fake_cs(0xEE));
cache.release_lane(&mut pools, &mut tbl_miss, &mut st_miss);
cache.set_test_clock_ms(20_000);
let mut hit_cancel = hist_a[..128].to_vec();
hit_cancel.extend_from_slice(&[90_001, 90_002]);
let mut tbl_hit = BlockTable::new(8).unwrap();
let mut st_hit = LaneBlockState { namespace: 1, owner: owner_a, ..Default::default() };
assert!(matches!(
cache.begin_admit_bind_in_namespace(&mut pools, 0, &mut tbl_hit, &mut st_hit, 1, &hit_cancel),
AdmitBindOutcome::Immediate(Some((128, _)))
));
cache.release_lane(&mut pools, &mut tbl_hit, &mut st_hit);
cache.set_test_clock_ms(22_000);
let mut tbl_c = BlockTable::new(8).unwrap();
let mut st_c = LaneBlockState { namespace: 1, owner: owner_c, ..Default::default() };
let pc: Vec<u32> = (0..192u32).map(|i| 95_000 + i).collect();
let _ = cache.match_and_bind_in_namespace(&mut pools, &mut tbl_c, &mut st_c, 1, &pc);
cache.ensure_span_blocks(&mut pools, &mut tbl_c, 0, 192).unwrap();
cache.release_lane(&mut pools, &mut tbl_c, &mut st_c);
let mut a_positions: Vec<usize> =
cache.starts.values().filter(|st| st.namespace == twin_a).map(|st| st.pos).collect();
a_positions.sort_unstable();
assert_eq!(
a_positions,
vec![64, 128],
"Card A Turn 1 PROMPT@64 and turn_end@128 must stay leased across short, missed, and cancelled returns"
);
cache.set_test_clock_ms(35_000);
let leased_at_35s = cache.leased_starts();
let sid_64 = *cache.starts.iter().find(|(_, st)| st.namespace == twin_a && st.pos == 64).unwrap().0;
let sid_128 = *cache.starts.iter().find(|(_, st)| st.namespace == twin_a && st.pos == 128).unwrap().0;
assert!(!leased_at_35s.contains(&sid_64), "PROMPT@64 expires 30 s after its 1_000 ms save");
assert!(leased_at_35s.contains(&sid_128), "turn_end@128 TTL was extended to 50_000 ms on the 20_000 ms bind");
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn card_lease_excludes_every_only_checkpoints_and_keeps_zero_lease_noop() {
{
let mut pools = BlockPools::with_capacities(64, 24, 2).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_approx_retain(true);
cache.set_card_lease(Duration::from_secs(30));
cache.set_test_clock_ms(1_000);
let owner_a = approx_twin("lease-salt", 1, Some("card-every"));
let owner_b = approx_twin("lease-salt", 1, Some("card-rival"));
let twin_a = approx_namespace(1, owner_a);
let prompt_a: Vec<u32> = (0..2200u32).map(|i| 10_000 + i).collect();
let mut tbl_a = BlockTable::new(64).unwrap();
let mut st_a = LaneBlockState { namespace: 1, owner: owner_a, ..Default::default() };
let _ = cache.match_and_bind(&mut pools, &mut tbl_a, &mut st_a, &prompt_a);
for b in 0..(2176 / BLOCK) {
cache.ensure_span_blocks(&mut pools, &mut tbl_a, b * BLOCK, BLOCK).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_a, &mut st_a, &prompt_a, b * BLOCK, BLOCK, || {
fake_cs((b & 0xff) as u8)
});
}
cache.ensure_span_blocks(&mut pools, &mut tbl_a, 2176, 2200 - 2176).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_a, &mut st_a, &prompt_a, 2176, 2200 - 2176, || fake_cs(0xEE));
let mut hist_a = prompt_a.clone();
hist_a.push(30_000);
for pos in 2200usize..2240 {
cache.ensure_span_blocks(&mut pools, &mut tbl_a, pos, 1).unwrap();
cache.finish_decode_span(&mut pools, &mut tbl_a, &mut st_a, pos);
cache.seal_decode_block(&mut pools, &tbl_a, &mut st_a, &hist_a, pos, || fake_cs(0xFF));
hist_a.push(30_001 + (pos - 2200) as u32);
}
cache.release_lane(&mut pools, &mut tbl_a, &mut st_a);
let mut saved_pos: Vec<usize> = cache.starts.values().map(|st| st.pos).collect();
saved_pos.sort_unstable();
assert_eq!(saved_pos, vec![2048, 2176, 2240]);
cache.advance_test_clock_ms(1_000);
let unleased_toks: Vec<u32> = (0..128u32).map(|i| 50_000 + i).collect();
let mut tbl_u = BlockTable::new(8).unwrap();
let mut st_u = LaneBlockState { namespace: 1, owner: 0, ..Default::default() };
let _ = cache.match_and_bind(&mut pools, &mut tbl_u, &mut st_u, &unleased_toks);
cache.ensure_span_blocks(&mut pools, &mut tbl_u, 0, 128).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl_u, &mut st_u, &unleased_toks, 0, 128, || fake_cs(0xCC));
cache.release_lane(&mut pools, &mut tbl_u, &mut st_u);
cache.advance_test_clock_ms(3_000);
let free_win = pools.window.count_free_up_to(usize::MAX);
assert!(free_win + 2 <= WINDOW / BLOCK);
let mut tbl_b1 = BlockTable::new(32).unwrap();
let mut st_b1 = LaneBlockState { namespace: 1, owner: owner_b, ..Default::default() };
let pb1: Vec<u32> = (0..((free_win + 2) * BLOCK) as u32).map(|i| 60_000 + i).collect();
let _ = cache.match_and_bind(&mut pools, &mut tbl_b1, &mut st_b1, &pb1);
cache.ensure_span_blocks(&mut pools, &mut tbl_b1, 0, (free_win + 2) * BLOCK).unwrap();
assert!(
!cache.starts.values().any(|st| st.pos == 2048),
"EVERY-only checkpoint at 2048 must be Tier-0 unleased and evicted first"
);
assert!(cache.starts.values().any(|st| st.pos == 128), "newer unleased start survives first eviction");
assert!(cache.starts.values().any(|st| st.namespace == 1 && st.pos == 2176), "PROMPT@2176 survives");
assert!(cache.starts.values().any(|st| st.namespace == twin_a && st.pos == 2240), "turn_end@2240 survives");
let mut tbl_b2 = BlockTable::new(16).unwrap();
cache.ensure_span_blocks(&mut pools, &mut tbl_b2, 0, 2 * BLOCK).unwrap();
assert!(!cache.starts.values().any(|st| st.pos == 128), "Tier-0 unleased@128 evicted next");
assert!(cache.starts.values().any(|st| st.namespace == 1 && st.pos == 2176), "leased PROMPT@2176 survives");
assert!(
cache.starts.values().any(|st| st.namespace == twin_a && st.pos == 2240),
"leased turn_end@2240 survives"
);
tbl_b2.clear_entries(&mut pools).unwrap();
cache.release_lane(&mut pools, &mut tbl_b1, &mut st_b1);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
{
let mut pools = BlockPools::with_capacities(8, 8, 2).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_approx_retain(true);
cache.set_test_clock_ms(5_000);
let owner = approx_twin("lease-salt", 1, Some("card-zero"));
let prompt: Vec<u32> = (0..64u32).map(|i| 1_000 + i).collect();
let mut tbl = BlockTable::new(8).unwrap();
let mut st = LaneBlockState { namespace: 1, owner, ..Default::default() };
let _ = cache.match_and_bind(&mut pools, &mut tbl, &mut st, &prompt);
st.stitched_approx = true;
cache.enter_approx_path(&pools, &tbl, &mut st, &prompt);
cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 64).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &prompt, 0, 64, || fake_cs(0x01));
let mut hist = prompt.clone();
hist.push(2_000);
for pos in 64usize..128 {
cache.ensure_span_blocks(&mut pools, &mut tbl, pos, 1).unwrap();
cache.finish_decode_span(&mut pools, &mut tbl, &mut st, pos);
cache.seal_decode_block(&mut pools, &tbl, &mut st, &hist, pos, || fake_cs(0x02));
hist.push(2_001 + (pos - 64) as u32);
}
cache.release_lane(&mut pools, &mut tbl, &mut st);
assert_eq!(cache.next_owner_turn, 0, "disabled card lease must not advance next_owner_turn");
assert!(cache.latest_owner_turn.is_empty(), "disabled card lease must not populate latest_owner_turn");
assert!(
cache.starts.values().all(|s| s.last_owner == 0 && s.owner_turn == 0 && s.last_used_ms == 0),
"disabled card lease must leave per-start lease fields zeroed"
);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
}
const LEASE_NS: u64 = 5;
const LEASE_CS_BYTES: usize = 4096;
fn lease_prefill(
cache: &mut ServeBlockCache,
pools: &mut BlockPools,
tbl: &mut BlockTable,
st: &mut LaneBlockState,
toks: &[u32],
t: usize,
tag: u8,
) -> usize {
let at = cache.match_and_bind(pools, tbl, st, toks).map(|(at, _)| at).unwrap_or(0);
cache.ensure_span_blocks(pools, tbl, at, t).unwrap();
cache.finish_prefill_span(pools, tbl, st, toks, at, t, || vec![tag; LEASE_CS_BYTES]);
at
}
fn lease_decode(
cache: &mut ServeBlockCache,
pools: &mut BlockPools,
tbl: &mut BlockTable,
st: &mut LaneBlockState,
from: usize,
to: usize,
ms_per_token: u64,
) {
for pos in from..to {
cache.ensure_span_blocks(pools, tbl, pos, 1).unwrap();
cache.finish_decode_span(pools, tbl, st, pos);
cache.advance_test_clock_ms(ms_per_token);
}
}
fn lease_save_anon(
cache: &mut ServeBlockCache,
pools: &mut BlockPools,
base: u32,
len: usize,
tag: u8,
) -> Vec<u32> {
let toks: Vec<u32> = (0..len as u32).map(|i| base + i).collect();
let mut tbl = BlockTable::new(8).unwrap();
let mut st = LaneBlockState { namespace: LEASE_NS, owner: 0, ..Default::default() };
let _ = lease_prefill(cache, pools, &mut tbl, &mut st, &toks, len, tag);
cache.release_lane(pools, &mut tbl, &mut st);
toks
}
fn lease_resident(cache: &ServeBlockCache, pools: &BlockPools, toks: &[u32]) -> usize {
let mut probe = toks.to_vec();
probe.push(7);
cache.peek_match_len_in_namespace(pools, LEASE_NS, &probe)
}
fn lease_squeeze_to_one(cache: &mut ServeBlockCache, pools: &mut BlockPools) {
cache.set_max_retained_host_bytes(LEASE_CS_BYTES as u64 + 1_000);
cache.enforce_retained_host_budget(pools, None);
assert_eq!(cache.retained_start_count(), 1);
cache.set_max_retained_host_bytes(DEFAULT_MAX_RETAINED_HOST_BYTES);
}
#[test]
fn card_lease_counts_from_release_so_a_card_back_after_a_long_decode_hits_its_prompt_start() {
let mut pools = BlockPools::with_capacities(3, 3, 2).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_card_lease(Duration::from_secs(30));
cache.set_test_clock_ms(1_000);
let owner_a = approx_twin("lease-salt", LEASE_NS, Some("card-a"));
let pa: Vec<u32> = (0..64u32).map(|i| 10_000 + i).collect();
let mut tbl_a = BlockTable::new(8).unwrap();
let mut sta = LaneBlockState { namespace: LEASE_NS, owner: owner_a, ..Default::default() };
lease_prefill(&mut cache, &mut pools, &mut tbl_a, &mut sta, &pa, 64, 0xA1);
assert_eq!(cache.retained_start_count(), 1, "PROMPT start @64 saved at t = 1 s");
lease_decode(&mut cache, &mut pools, &mut tbl_a, &mut sta, 64, 104, 1_000);
cache.release_lane(&mut pools, &mut tbl_a, &mut sta);
cache.advance_test_clock_ms(2_000); let anon1 = lease_save_anon(&mut cache, &mut pools, 20_000, 128, 0xB1);
let _ = lease_save_anon(&mut cache, &mut pools, 30_000, 128, 0xB2);
assert_eq!(lease_resident(&cache, &pools, &anon1), 0, "unleased anon1 is evicted first");
cache.advance_test_clock_ms(2_000); let mut turn2 = pa.clone();
turn2.extend((0..30u32).map(|i| 11_000 + i));
let mut tbl2 = BlockTable::new(8).unwrap();
let mut st2 = LaneBlockState { namespace: LEASE_NS, owner: owner_a, ..Default::default() };
let bound = cache.match_and_bind(&mut pools, &mut tbl2, &mut st2, &turn2);
assert_eq!(
bound.map(|(at, cs)| (at, cs == vec![0xA1; LEASE_CS_BYTES])),
Some((64, true)),
"the card's PROMPT start must survive: its lease counts from release, not from prefill"
);
cache.release_lane(&mut pools, &mut tbl2, &mut st2);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn card_lease_holds_an_in_flight_lanes_prompt_start_past_the_lease_window() {
let mut pools = BlockPools::with_capacities(8, 8, 2).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_card_lease(Duration::from_secs(30));
cache.set_test_clock_ms(1_000);
let owner_a = approx_twin("lease-salt", LEASE_NS, Some("card-a"));
let pa: Vec<u32> = (0..64u32).map(|i| 10_000 + i).collect();
let mut tbl_a = BlockTable::new(8).unwrap();
let mut sta = LaneBlockState { namespace: LEASE_NS, owner: owner_a, ..Default::default() };
lease_prefill(&mut cache, &mut pools, &mut tbl_a, &mut sta, &pa, 64, 0xA1);
lease_decode(&mut cache, &mut pools, &mut tbl_a, &mut sta, 64, 104, 1_000);
let anon1 = lease_save_anon(&mut cache, &mut pools, 20_000, 64, 0xB1);
lease_squeeze_to_one(&mut cache, &mut pools);
assert_eq!(lease_resident(&cache, &pools, &anon1), 0, "the unleased anonymous start is evicted");
assert_eq!(lease_resident(&cache, &pools, &pa), 64, "the in-flight card's PROMPT start is held");
cache.release_lane(&mut pools, &mut tbl_a, &mut sta);
assert!(cache.held_starts.is_empty() && sta.lease_holds.is_empty(), "release drops every hold");
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn card_lease_holds_a_bound_start_while_prefill_has_not_reached_the_next_block() {
let mut pools = BlockPools::with_capacities(8, 8, 2).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_card_lease(Duration::from_secs(30));
cache.set_test_clock_ms(1_000);
let owner_a = approx_twin("lease-salt", LEASE_NS, Some("card-a"));
let pa: Vec<u32> = (0..64u32).map(|i| 10_000 + i).collect();
let mut tbl = BlockTable::new(8).unwrap();
let mut st1 = LaneBlockState { namespace: LEASE_NS, owner: owner_a, ..Default::default() };
lease_prefill(&mut cache, &mut pools, &mut tbl, &mut st1, &pa, 64, 0xA1);
cache.release_lane(&mut pools, &mut tbl, &mut st1);
cache.advance_test_clock_ms(1_000); let mut turn2 = pa.clone();
turn2.extend((0..70u32).map(|i| 11_000 + i));
let mut st2 = LaneBlockState { namespace: LEASE_NS, owner: owner_a, ..Default::default() };
let at = lease_prefill(&mut cache, &mut pools, &mut tbl, &mut st2, &turn2, 36, 0xA2);
assert_eq!(at, 64);
assert_eq!(st2.prompt_saved_id, None, "no prompt checkpoint at the bound position");
cache.advance_test_clock_ms(40_000);
let anon1 = lease_save_anon(&mut cache, &mut pools, 20_000, 64, 0xB1);
lease_squeeze_to_one(&mut cache, &mut pools);
assert_eq!(lease_resident(&cache, &pools, &anon1), 0);
assert_eq!(lease_resident(&cache, &pools, &pa), 64, "the bound start is held while its lane is in flight");
cache.release_lane(&mut pools, &mut tbl, &mut st2);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn card_lease_short_turn_that_saves_nothing_refreshes_its_bound_start_at_release() {
let mut pools = BlockPools::with_capacities(8, 8, 2).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_card_lease(Duration::from_secs(30));
cache.set_test_clock_ms(1_000);
let owner_a = approx_twin("lease-salt", LEASE_NS, Some("card-a"));
let pa: Vec<u32> = (0..64u32).map(|i| 10_000 + i).collect();
let mut tbl = BlockTable::new(8).unwrap();
let mut st1 = LaneBlockState { namespace: LEASE_NS, owner: owner_a, ..Default::default() };
lease_prefill(&mut cache, &mut pools, &mut tbl, &mut st1, &pa, 64, 0xA1);
cache.release_lane(&mut pools, &mut tbl, &mut st1);
cache.advance_test_clock_ms(1_000); let mut turn2 = pa.clone();
turn2.extend((0..20u32).map(|i| 11_000 + i));
let mut st2 = LaneBlockState { namespace: LEASE_NS, owner: owner_a, ..Default::default() };
assert_eq!(lease_prefill(&mut cache, &mut pools, &mut tbl, &mut st2, &turn2, 20, 0xA2), 64);
lease_decode(&mut cache, &mut pools, &mut tbl, &mut st2, 84, 124, 1_000);
assert_eq!(st2.save_owner_turn, 0, "the short turn saved nothing");
cache.release_lane(&mut pools, &mut tbl, &mut st2);
cache.advance_test_clock_ms(2_000); let anon1 = lease_save_anon(&mut cache, &mut pools, 20_000, 64, 0xB1);
lease_squeeze_to_one(&mut cache, &mut pools);
assert_eq!(lease_resident(&cache, &pools, &anon1), 0);
cache.advance_test_clock_ms(2_000); let mut turn3 = turn2.clone();
turn3.extend((0..10u32).map(|i| 12_000 + i));
let mut st3 = LaneBlockState { namespace: LEASE_NS, owner: owner_a, ..Default::default() };
let bound = cache.match_and_bind(&mut pools, &mut tbl, &mut st3, &turn3).map(|(at, _)| at);
assert_eq!(bound, Some(64), "turn 3 binds the start turn 2 used");
cache.release_lane(&mut pools, &mut tbl, &mut st3);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn card_lease_admission_progresses_when_every_start_is_leased() {
let mut pools = BlockPools::with_capacities(3, 3, 2).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_card_lease(Duration::from_secs(30));
cache.set_test_clock_ms(1_000);
let owner_a = approx_twin("lease-salt", LEASE_NS, Some("card-a"));
let owner_b = approx_twin("lease-salt", LEASE_NS, Some("card-b"));
let pa: Vec<u32> = (0..64u32).map(|i| 10_000 + i).collect();
let mut tbl_a = BlockTable::new(8).unwrap();
let mut sta = LaneBlockState { namespace: LEASE_NS, owner: owner_a, ..Default::default() };
lease_prefill(&mut cache, &mut pools, &mut tbl_a, &mut sta, &pa, 64, 0xA1);
cache.advance_test_clock_ms(40_000);
let pb: Vec<u32> = (0..64u32).map(|i| 40_000 + i).collect();
let mut tbl_b = BlockTable::new(8).unwrap();
let mut stb = LaneBlockState { namespace: LEASE_NS, owner: owner_b, ..Default::default() };
lease_prefill(&mut cache, &mut pools, &mut tbl_b, &mut stb, &pb, 64, 0xB1);
cache.release_lane(&mut pools, &mut tbl_b, &mut stb);
assert_eq!(cache.leased_starts().len(), cache.retained_start_count(), "every resident start is leased");
let mut tbl_c = BlockTable::new(8).unwrap();
assert!(cache.can_satisfy_span(&pools, &tbl_c, 0, 128), "leased starts stay reclaimable");
cache.ensure_span_blocks(&mut pools, &mut tbl_c, 0, 128).expect("a lease never blocks admission");
tbl_c.clear_entries(&mut pools).unwrap();
assert_eq!(lease_resident(&cache, &pools, &pb), 0, "the released card's leased start yields");
assert_eq!(lease_resident(&cache, &pools, &pa), 64, "the in-flight card's start stays");
cache.release_lane(&mut pools, &mut tbl_a, &mut sta);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn card_lease_ends_one_lease_window_after_release() {
let mut pools = BlockPools::with_capacities(8, 8, 2).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_card_lease(Duration::from_secs(30));
cache.set_test_clock_ms(1_000);
let owner_a = approx_twin("lease-salt", LEASE_NS, Some("card-a"));
let pa: Vec<u32> = (0..64u32).map(|i| 10_000 + i).collect();
let mut tbl_a = BlockTable::new(8).unwrap();
let mut sta = LaneBlockState { namespace: LEASE_NS, owner: owner_a, ..Default::default() };
lease_prefill(&mut cache, &mut pools, &mut tbl_a, &mut sta, &pa, 64, 0xA1);
lease_decode(&mut cache, &mut pools, &mut tbl_a, &mut sta, 64, 104, 1_000);
cache.release_lane(&mut pools, &mut tbl_a, &mut sta);
cache.advance_test_clock_ms(29_999); let anon1 = lease_save_anon(&mut cache, &mut pools, 20_000, 64, 0xB1);
lease_squeeze_to_one(&mut cache, &mut pools);
assert_eq!(lease_resident(&cache, &pools, &anon1), 0);
assert_eq!(lease_resident(&cache, &pools, &pa), 64, "leased until release + lease window");
let anon2 = lease_save_anon(&mut cache, &mut pools, 30_000, 64, 0xB2);
cache.advance_test_clock_ms(1); lease_squeeze_to_one(&mut cache, &mut pools);
assert_eq!(lease_resident(&cache, &pools, &pa), 0, "an expired lease no longer protects the start");
assert_eq!(lease_resident(&cache, &pools, &anon2), 64);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn card_lease_cancelled_release_drops_the_cards_lease() {
let mut pools = BlockPools::with_capacities(8, 8, 2).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_card_lease(Duration::from_secs(30));
cache.set_test_clock_ms(1_000);
let owner_a = approx_twin("lease-salt", LEASE_NS, Some("card-a"));
let pa: Vec<u32> = (0..64u32).map(|i| 10_000 + i).collect();
let mut tbl_a = BlockTable::new(8).unwrap();
let mut sta = LaneBlockState { namespace: LEASE_NS, owner: owner_a, ..Default::default() };
lease_prefill(&mut cache, &mut pools, &mut tbl_a, &mut sta, &pa, 64, 0xA1);
cache.advance_test_clock_ms(1_000);
cache.release_lane_with_toks(&mut pools, &mut tbl_a, &mut sta, None, true); assert!(cache.leased_starts().is_empty(), "a cancelled card keeps no lease");
cache.advance_test_clock_ms(1_000); let anon1 = lease_save_anon(&mut cache, &mut pools, 20_000, 64, 0xB1);
lease_squeeze_to_one(&mut cache, &mut pools);
assert_eq!(lease_resident(&cache, &pools, &pa), 0, "the cancelled card's start is evicted by plain LRU");
assert_eq!(lease_resident(&cache, &pools, &anon1), 64);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn a_lane_failed_on_invalid_logits_leaves_no_start_over_its_blocks() {
let mut pools = BlockPools::with_capacities(16, 16, 2).unwrap();
let mut cache = ServeBlockCache::new();
let head: Vec<u32> = (0..64u32).map(|i| 10_000 + i).collect();
let with_tail = |base: u32| -> Vec<u32> { head.iter().copied().chain((0..64u32).map(|i| base + i)).collect() };
let (pa, pb) = (with_tail(20_000), with_tail(30_000));
let full_slots = |tbl: &BlockTable| -> Vec<Slot> {
(0..2u32).map(|b| tbl.get(BlockKind::Full, BlockIndex::new(b)).unwrap().unwrap().slot()).collect()
};
let mut tbl_b = BlockTable::new(8).unwrap();
let mut stb = LaneBlockState { namespace: LEASE_NS, ..Default::default() };
lease_prefill(&mut cache, &mut pools, &mut tbl_b, &mut stb, &pb, 128, 0xB1);
let shared = full_slots(&tbl_b)[0];
cache.release_lane(&mut pools, &mut tbl_b, &mut stb);
let pc = lease_save_anon(&mut cache, &mut pools, 40_000, 128, 0xC1);
assert_eq!((lease_resident(&cache, &pools, &pb), lease_resident(&cache, &pools, &pc)), (128, 128));
let mut tbl_a = BlockTable::new(8).unwrap();
let mut sta = LaneBlockState { namespace: LEASE_NS, ..Default::default() };
assert_eq!(lease_prefill(&mut cache, &mut pools, &mut tbl_a, &mut sta, &pa, 128, 0xA1), 0);
let held = full_slots(&tbl_a);
let held_entries: Vec<BlockEntry> = tbl_a.entries().map(|(_, e)| e).collect();
assert_eq!(held[0], shared, "pa shares pb's first block");
assert_eq!(lease_resident(&cache, &pools, &pa), 128);
for &s in &held {
for w in pools.full.slot_bytes_mut(s).unwrap().chunks_exact_mut(2) {
w.copy_from_slice(&0x7e00u16.to_le_bytes());
}
}
assert_eq!(cache.release_lane_invalid(&mut pools, &mut tbl_a, &mut sta), 2, "pa's start and pb's");
assert_eq!(lease_resident(&cache, &pools, &pa), 0, "the failed prompt has no start left to bind");
assert_eq!(lease_resident(&cache, &pools, &pb), 0, "nor has the prompt that shares a block with it");
assert_eq!(lease_resident(&cache, &pools, &pc), 128, "a start over other blocks stays");
assert_eq!(cache.stats().evictions_stale_invalid, 2);
for &s in &held {
assert_eq!(pools.full.record(s).unwrap().refs(), 0, "nothing holds the failed lane's blocks");
}
let mut tbl_r = BlockTable::new(8).unwrap();
let mut str_ = LaneBlockState { namespace: LEASE_NS, ..Default::default() };
assert!(cache.match_and_bind(&mut pools, &mut tbl_r, &mut str_, &pa).is_none());
cache.ensure_span_blocks(&mut pools, &mut tbl_r, 0, 128).unwrap();
for b in 0..2u32 {
let e = tbl_r.get(BlockKind::Full, BlockIndex::new(b)).unwrap().unwrap();
assert!(!held_entries.contains(&e), "the retry holds none of the failed lane's blocks");
}
cache.finish_prefill_span(&mut pools, &mut tbl_r, &mut str_, &pa, 0, 128, || vec![0xA2; LEASE_CS_BYTES]);
cache.release_lane(&mut pools, &mut tbl_r, &mut str_);
assert_eq!(lease_resident(&cache, &pools, &pa), 128, "and the retry's own start is kept as usual");
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn multi_span_retained_stitches_retain_approx_prompt_and_reply_starts() {
let kvb = 1u32;
let ns = 5u64;
let mut pools = BlockPools::with_capacities(640, 256, kvb).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_kv_stitch(true);
cache.set_approx_retain(true);
let prefill_to = |cache: &mut ServeBlockCache,
pools: &mut BlockPools,
tbl: &mut BlockTable,
st: &mut LaneBlockState,
toks: &[u32],
from: usize,
to: usize,
cs_tag: u8| {
let mut p = from;
while p < to {
let next = effective_pf_target(p, to).min(p + 512);
cache.ensure_span_blocks(pools, tbl, p, next - p).unwrap();
let lo_blk = p / BLOCK;
let hi_blk = (next - 1) / BLOCK;
for b in lo_blk..=hi_blk {
let p0 = b * BLOCK;
if p0 + BLOCK <= next {
let fe = tbl.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().unwrap();
stamp_test_full_block_rows(
pools.full.slot_bytes_mut(fe.slot()).unwrap(),
&toks[p0..p0 + BLOCK],
kvb,
);
}
}
cache.finish_prefill_span(pools, tbl, st, toks, p, next - p, || fake_cs(cs_tag));
p = next;
}
};
let donor_a: Vec<u32> = (0..3200u32).map(|i| 100_000 + i).collect();
let donor_b: Vec<u32> = (0..3200u32).map(|i| 200_000 + i).collect();
for (idx, (lead_base, donor, tail_base)) in
[(10_000u32, &donor_a, 40_000u32), (20_000u32, &donor_b, 50_000u32)].into_iter().enumerate()
{
let mut seed: Vec<u32> = (0..128u32).map(|i| lead_base + i).collect();
seed.extend_from_slice(donor);
seed.extend((0..129u32).map(|i| tail_base + i)); let mut tbl_s = BlockTable::new(96).unwrap();
let mut st_s = LaneBlockState { namespace: ns, owner: 0, prompt_len: seed.len(), ..Default::default() };
prefill_to(&mut cache, &mut pools, &mut tbl_s, &mut st_s, &seed, 0, seed.len(), 0x10 + idx as u8);
cache.release_lane(&mut pools, &mut tbl_s, &mut st_s);
}
assert_eq!(cache.stats().start_points_saved, 4);
let build_prompt = |prefix_base: u32| -> Vec<u32> {
let mut p: Vec<u32> = (0..256u32).map(|i| prefix_base + i).collect();
p.extend_from_slice(&donor_a);
p.extend((0..147u32).map(|i| 400_000 + i));
p.extend_from_slice(&donor_b);
p.extend((0..145u32).map(|i| 500_000 + i));
p
};
let run_two_span_turn1 = |cache: &mut ServeBlockCache,
pools: &mut BlockPools,
owner: u64,
prompt: &[u32],
reply_len: usize|
-> Vec<u32> {
let plans = cache.plan_stitches(pools, ns, prompt, 0);
assert_eq!(plans.len(), 2, "must plan 2 disjoint stitch spans");
assert_eq!((plans[0].stitch_start, plans[0].heal_start), (1280, 1920));
assert_eq!((plans[1].stitch_start, plans[1].heal_start), (4672, 5248));
let mut tbl = BlockTable::new(160).unwrap();
let mut st = LaneBlockState { namespace: ns, owner, prompt_len: prompt.len(), ..Default::default() };
assert!(matches!(
cache.begin_admit_bind_in_namespace(pools, 0, &mut tbl, &mut st, ns, prompt),
AdmitBindOutcome::Immediate(None)
));
prefill_to(cache, pools, &mut tbl, &mut st, prompt, 0, plans[0].stitch_start, 0x21);
let out1 = cache.apply_stitch_plan(pools, &mut tbl, &mut st, prompt, &plans[0]);
assert_eq!(out1, StitchApplyOutcome::Applied { stitched_tokens: 640, zero_copy_blocks: 10 });
assert!(st.stitched_approx && st.approx_path);
assert_eq!(st.sealed.len(), plans[0].heal_start / BLOCK);
prefill_to(cache, pools, &mut tbl, &mut st, prompt, plans[0].heal_start, plans[1].stitch_start, 0x22);
assert_eq!(st.sealed.len(), plans[1].stitch_start / BLOCK);
let out2 = cache.apply_stitch_plan(pools, &mut tbl, &mut st, prompt, &plans[1]);
assert_eq!(out2, StitchApplyOutcome::Applied { stitched_tokens: 576, zero_copy_blocks: 0 });
assert!(st.stitched_approx && st.approx_path);
assert_eq!(
st.sealed.len(),
plans[1].heal_start / BLOCK,
"second stitch span must extend state.sealed in twin approx_namespace"
);
for b in (plans[1].stitch_start / BLOCK)..(plans[1].heal_start / BLOCK) {
let fe = tbl.get(BlockKind::Full, BlockIndex::new(b as u32)).unwrap().unwrap();
assert_test_full_block_rows_match(
pools.full.slot_bytes(fe.slot()).unwrap(),
&prompt[b * BLOCK..(b + 1) * BLOCK],
kvb,
);
}
prefill_to(cache, pools, &mut tbl, &mut st, prompt, plans[1].heal_start, prompt.len(), 0x23);
assert_eq!(st.prompt_saved_pos, 6912, "Turn 1 must retain PROMPT start at 6912 after 2 stitches");
let mut hist = prompt.to_vec();
for step in 0..reply_len {
let pos = prompt.len() + step;
hist.push(800_000 + step as u32);
cache.ensure_span_blocks(pools, &mut tbl, pos, 1).unwrap();
cache.finish_decode_span(pools, &mut tbl, &mut st, pos);
cache.seal_decode_block(pools, &tbl, &mut st, &hist, pos, || fake_cs(0x24));
}
cache.release_lane_with_toks(pools, &mut tbl, &mut st, Some(&hist), false);
hist
};
let owner_a = approx_twin("multi-stitch", ns, Some("card-a"));
let prompt_a1 = build_prompt(300_000);
let hist_a1 = run_two_span_turn1(&mut cache, &mut pools, owner_a, &prompt_a1, 20);
let mut turn_a2 = hist_a1.clone();
turn_a2.extend(900_000u32..900_080);
let obs_a2 = cache.observe_prior(owner_a, &turn_a2);
let mut tbl_a2 = BlockTable::new(160).unwrap();
let mut st_a2 = LaneBlockState { namespace: ns, owner: owner_a, ..Default::default() };
let out_a2 = cache.begin_admit_bind_in_namespace(&mut pools, 0, &mut tbl_a2, &mut st_a2, ns, &turn_a2);
let matched_a2 = match out_a2 {
AdmitBindOutcome::Immediate(Some((at, _))) => at,
other => panic!("expected Turn 2 approx bind at 6912, got {other:?}"),
};
assert_eq!(matched_a2, 6912);
assert!(st_a2.stitched_approx && st_a2.approx_path);
let (reason_a2, div_a2) =
ServeBlockCache::classify_observed_reuse(owner_a, matched_a2, false, obs_a2, &st_a2.sealed);
assert_eq!(reason_a2, "hit_prompt_end");
assert_eq!(div_a2, None);
cache.release_lane(&mut pools, &mut tbl_a2, &mut st_a2);
let owner_b = approx_twin("multi-stitch", ns, Some("card-b"));
let prompt_b1 = build_prompt(310_000);
let hist_b1 = run_two_span_turn1(&mut cache, &mut pools, owner_b, &prompt_b1, 100);
let mut turn_b2 = hist_b1.clone();
turn_b2.extend(910_000u32..910_080);
let obs_b2 = cache.observe_prior(owner_b, &turn_b2);
let mut tbl_b2 = BlockTable::new(160).unwrap();
let mut st_b2 = LaneBlockState { namespace: ns, owner: owner_b, ..Default::default() };
let out_b2 = cache.begin_admit_bind_in_namespace(&mut pools, 0, &mut tbl_b2, &mut st_b2, ns, &turn_b2);
let matched_b2 = match out_b2 {
AdmitBindOutcome::Immediate(Some((at, _))) => at,
other => panic!("expected Turn 2 approx bind at 7040, got {other:?}"),
};
assert_eq!(matched_b2, 7040);
assert!(matched_b2 > prompt_b1.len());
assert!(st_b2.stitched_approx && st_b2.approx_path);
let (reason_b2, div_b2) =
ServeBlockCache::classify_observed_reuse(owner_b, matched_b2, false, obs_b2, &st_b2.sealed);
assert_eq!(reason_b2, "hit_reply_end");
assert_eq!(div_b2, None);
cache.release_lane(&mut pools, &mut tbl_b2, &mut st_b2);
let mut tbl_exact = BlockTable::new(160).unwrap();
let mut st_exact = LaneBlockState { namespace: ns, owner: 0, ..Default::default() };
assert_eq!(cache.match_and_bind_in_namespace(&mut pools, &mut tbl_exact, &mut st_exact, ns, &turn_b2), None);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
#[test]
fn multi_span_ikv_staged_stitches_extend_approx_chain_and_retain_reply_start() {
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
let dir = ScratchDir::new("ikv-multi-stitch");
#[cfg(unix)]
std::fs::set_permissions(&dir.0, std::fs::Permissions::from_mode(0o700)).unwrap();
let kvb = 1u32;
let vocab = 262_144u32;
let model_fp = 0xfeed_face_cafe_beefu64;
let hmac_key = crate::ikv::IkvHmacKey::from_bytes(b"multi-stitch-ikv-hmac-key-32byte").unwrap();
let page_bytes = crate::blocks::BlockKind::Full.stride_bytes(kvb).unwrap() as usize;
let cart1_toks: Vec<u32> = (0..3200u32).map(|i| 120_000 + i).collect();
let cart2_toks: Vec<u32> = (0..3200u32).map(|i| 180_000 + i).collect();
for (fname, src_name, ctoks) in
[("alpha.ikv", "src/alpha.rs", &cart1_toks), ("beta.ikv", "src/beta.rs", &cart2_toks)]
{
let mut full_pages: Vec<Vec<u8>> = Vec::with_capacity(50);
for p in 0..50usize {
let mut page = vec![0u8; page_bytes];
stamp_test_full_block_rows(&mut page, &ctoks[p * BLOCK..(p + 1) * BLOCK], kvb);
full_pages.push(page);
}
crate::ikv::write_ikv_cartridge_raw(
&dir.0.join(fname),
src_name,
kvb,
vocab,
model_fp,
false,
16,
ctoks,
&full_pages,
Some(&hmac_key),
)
.unwrap();
}
let cat = Arc::new(crate::ikv::IkvCatalog::load_dir(&dir.0, kvb, vocab, model_fp, false, &hmac_key).unwrap());
assert_eq!(cat.len(), 2);
let mut pools = BlockPools::with_capacities(512, 192, kvb).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_kv_stitch(true);
cache.set_approx_retain(true);
cache.set_ikv_catalog(cat);
let owner = own(0, "card-ikv-multi");
let mut prompt: Vec<u32> = (0..83u32).map(|i| 4_000 + i).collect();
prompt.extend_from_slice(&cart1_toks);
prompt.extend((0..140u32).map(|i| 50_000 + i));
prompt.extend_from_slice(&cart2_toks);
prompt.extend((0..150u32).map(|i| 90_000 + i));
let plans = cache.plan_stitches(&pools, 0, &prompt, 0);
assert_eq!(plans.len(), 2, "must plan 2 staged .ikv stitch spans");
assert!(plans.iter().all(|p| matches!(p.source, StitchSource::Ikv { .. })));
let mut tbl = BlockTable::new(160).unwrap();
let mut st = LaneBlockState { namespace: 0, owner, prompt_len: prompt.len(), ..Default::default() };
let _ = cache.begin_admit_bind(&mut pools, 0, &mut tbl, &mut st, &prompt);
let prefill_step = |cache: &mut ServeBlockCache,
pools: &mut BlockPools,
tbl: &mut BlockTable,
st: &mut LaneBlockState,
from: usize,
to: usize| {
let mut p = from;
while p < to {
let next = effective_pf_target(p, to).min(p + 512);
cache.ensure_span_blocks(pools, tbl, p, next - p).unwrap();
cache.finish_prefill_span(pools, tbl, st, &prompt, p, next - p, || fake_cs(0x55));
p = next;
}
};
prefill_step(&mut cache, &mut pools, &mut tbl, &mut st, 0, plans[0].stitch_start);
assert_eq!(
cache.start_stitch_plan(&mut pools, 0, &mut tbl, &mut st, &prompt, &plans[0]),
StitchStartOutcome::Staging
);
let done1 = loop {
let tbl_ptr: *mut BlockTable = &mut tbl;
let st_ptr: *mut LaneBlockState = &mut st;
let mut batch = cache.poll_ikv_stages(&mut pools, |l| (l == 0).then_some((&(), tbl_ptr, st_ptr)));
if let Some(c) = batch.pop() {
break c;
}
cache.wait_restore_activity(Duration::from_millis(50));
};
assert!(done1.stitched_tokens.is_some() && !done1.corrupt_fallback);
assert!(st.stitched_approx && st.approx_path);
assert_eq!(st.sealed.len(), plans[0].heal_start / BLOCK);
let resume1 = st.written;
prefill_step(&mut cache, &mut pools, &mut tbl, &mut st, resume1, plans[1].stitch_start);
assert_eq!(
cache.start_stitch_plan(&mut pools, 0, &mut tbl, &mut st, &prompt, &plans[1]),
StitchStartOutcome::Staging
);
let done2 = loop {
let tbl_ptr: *mut BlockTable = &mut tbl;
let st_ptr: *mut LaneBlockState = &mut st;
let mut batch = cache.poll_ikv_stages(&mut pools, |l| (l == 0).then_some((&(), tbl_ptr, st_ptr)));
if let Some(c) = batch.pop() {
break c;
}
cache.wait_restore_activity(Duration::from_millis(50));
};
assert!(done2.stitched_tokens.is_some() && !done2.corrupt_fallback);
assert!(st.stitched_approx && st.approx_path);
assert_eq!(
st.sealed.len(),
plans[1].heal_start / BLOCK,
"second staged .ikv stitch must extend state.sealed in twin approx_namespace"
);
let resume2 = st.written;
prefill_step(&mut cache, &mut pools, &mut tbl, &mut st, resume2, prompt.len());
assert_eq!(st.prompt_saved_pos, 6720);
let mut hist1 = prompt.clone();
for step in 0..90usize {
let pos = prompt.len() + step;
hist1.push(950_000 + step as u32);
cache.ensure_span_blocks(&mut pools, &mut tbl, pos, 1).unwrap();
cache.finish_decode_span(&mut pools, &mut tbl, &mut st, pos);
cache.seal_decode_block(&mut pools, &tbl, &mut st, &hist1, pos, || fake_cs(0x56));
}
cache.release_lane_with_toks(&mut pools, &mut tbl, &mut st, Some(&hist1), false);
let mut turn2 = hist1.clone();
turn2.extend(960_000u32..960_064);
let obs2 = cache.observe_prior(owner, &turn2);
let mut tbl2 = BlockTable::new(160).unwrap();
let mut st2 = LaneBlockState { namespace: 0, owner, ..Default::default() };
let out2 = cache.begin_admit_bind(&mut pools, 0, &mut tbl2, &mut st2, &turn2);
let matched2 = match out2 {
AdmitBindOutcome::Immediate(Some((at, _))) => at,
other => panic!("expected Turn 2 approx bind at 6848 after 2-span .ikv stitch, got {other:?}"),
};
assert_eq!(matched2, 6848);
assert!(st2.stitched_approx && st2.approx_path);
let (reason2, div2) = ServeBlockCache::classify_observed_reuse(owner, matched2, false, obs2, &st2.sealed);
assert_eq!(reason2, "hit_reply_end");
assert_eq!(div2, None);
cache.release_lane(&mut pools, &mut tbl2, &mut st2);
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
}
#[cfg(test)]
mod admission_tests;
#[cfg(test)]
#[path = "block_cache/retention_tests.rs"]
mod retention_tests;