STRA-338 size2 en5: prefix serve begin/after_chunk/admit_tail split under the limits

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 22:31:37 +01:00
parent de9e9c9821
commit 5353fff27a
2 changed files with 226 additions and 114 deletions
@@ -2,6 +2,19 @@
#[allow(unused_imports)]
use super::*;
use crate::prefix_cache::store::Match;
/// Where a prefix hit lands in the positional buffer.
struct ImportPlan {
/// Cells the buffer already holds for this hit.
common: usize,
/// Whether blocks are copied back from host memory.
copy: bool,
switched: bool,
branch: bool,
full: usize,
first_block: usize,
}
impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
/// `identity`: whatever makes two runtimes' caches interchangeable (model digest, KV format...), hashed with the
@@ -10,12 +23,7 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
let block_tokens = cfg.resolved_block(capacity);
let namespace =
fingerprint(&format!("{identity}|block={block_tokens}|chain={}", crate::prefix_cache::CHAIN_VERSION));
let store = PrefixStore::new(StoreConfig {
block_tokens,
budget_bytes: usize::try_from(budget_bytes).unwrap_or(usize::MAX),
max_nodes: cfg.max_nodes,
policy: cfg.policy.clone(),
});
let store = Self::new_store(&cfg, block_tokens, budget_bytes);
Self {
cfg,
block_tokens,
@@ -37,6 +45,14 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
clock: Stopwatch::start(AnyClock::System),
}
}
fn new_store(cfg: &PrefixConfig, block_tokens: usize, budget_bytes: u64) -> PrefixStore<S, B> {
PrefixStore::new(StoreConfig {
block_tokens,
budget_bytes: usize::try_from(budget_bytes).unwrap_or(usize::MAX),
max_nodes: cfg.max_nodes,
policy: cfg.policy.clone(),
})
}
/// The same cache on another clock: the retention scale and the phase timers follow it from now on.
pub(in super::super::super) fn with_clock(mut self, clock: AnyClock) -> Self {
@@ -57,22 +73,7 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
governor: &leleka_memory::Governor,
) -> usize {
match target {
Some(bytes) => {
let bytes = usize::try_from(bytes).unwrap_or(usize::MAX).min(self.configured_budget);
if bytes >= self.store.config().budget_bytes {
return 0;
}
let before = self.store.bytes();
self.store.set_budget(bytes);
self.shed = true;
let freed = before.saturating_sub(self.store.bytes());
governor.note_evicted(freed as u64);
if freed > 0 {
// the freed blocks sit in the allocator's arenas until they are returned: without this the shed would not move MemAvailable
leleka_memory::heap::trim();
}
freed
}
Some(bytes) => self.shed_to(bytes, governor),
None => {
if self.shed {
self.store.set_budget(self.configured_budget);
@@ -82,6 +83,23 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
}
}
}
fn shed_to(&mut self, bytes: u64, governor: &leleka_memory::Governor) -> usize {
let bytes = usize::try_from(bytes).unwrap_or(usize::MAX).min(self.configured_budget);
if bytes >= self.store.config().budget_bytes {
return 0;
}
let before = self.store.bytes();
self.store.set_budget(bytes);
self.shed = true;
let freed = before.saturating_sub(self.store.bytes());
governor.note_evicted(freed as u64);
if freed > 0 {
// the freed blocks sit in the allocator's arenas until they are returned: without this the shed would
// not move MemAvailable
leleka_memory::heap::trim();
}
freed
}
/// (import, draft re-anchoring) milliseconds of the last hit.
pub(in super::super::super) fn last_import_split(&self) -> (f64, f64) {
@@ -174,44 +192,83 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
self.live.clear();
return Ok(None);
};
// Cells of the positional buffer that already hold this prefix. A request that extends everything the buffer
// holds is the session's own continuation (no copy needed beyond what the buffer lacks); one that leaves it
// somewhere inside came after another session. Whether the HIT is shared evidence is a different question: it is
// when histories fork below the node (`is_branch_point`), whichever session ran last.
let common_full = lcp(&self.live, &prompt[..limit]);
self.import_hit(device, prompt, (hit, limit), match_us)
}
/// Where a hit lands in the positional buffer: how much of it the buffer already holds and what is copied back.
fn import_plan(&self, hit: &Match, head: &[i32]) -> ImportPlan {
let g = self.block_tokens;
// Cells of the positional buffer that already hold this prefix. A request that extends everything the
// buffer holds is the session's own continuation (no copy needed beyond what the buffer lacks); one that
// leaves it somewhere inside came after another session. Whether the HIT is shared evidence is a different
// question: it is when histories fork below the node (`is_branch_point`), whichever session ran last.
let common_full = lcp(&self.live, head);
let continuation = !self.live.is_empty() && common_full == self.live.len();
let switched = !continuation;
let branch = self.store.is_branch_point(hit.key);
let common = common_full.min(hit.tokens);
let copy = common < hit.tokens;
let started = self.clock.now();
let full = hit.tokens / g;
let first_block = (common / g).min(full);
let mut blocks = if copy {
self.store.blocks_from(hit.key, first_block).ok_or(Error::IdentityMismatch)?
} else {
Vec::new()
};
if copy {
// a request-end checkpoint also carries the cells after its last full block
if let Some((tail, _, _)) = self.store.tail_of(hit.key) {
blocks.push((full, tail));
}
ImportPlan {
common,
copy: common < hit.tokens,
switched: !continuation,
branch,
full,
first_block: (common / g).min(full),
}
let state = self.store.node_payload(hit.key).ok_or(Error::IdentityMismatch)?;
// the import overwrites every cell from the first named block on
self.live.truncate(if blocks.is_empty() { common } else { first_block * g });
device.import(state, &blocks)?;
let imported_ms = self.clock.since(started).as_secs_f64() * 1e3;
device.restore_draft(state, hit.tokens)?;
let copied_tokens: usize = blocks.iter().map(|(j, _)| if *j < full { g } else { hit.tokens - full * g }).sum();
}
fn import_hit<D: PrefixDevice<State = S, Block = B>>(
&mut self,
device: &mut D,
prompt: &[i32],
(hit, limit): (Match, usize),
match_us: f64,
) -> Result<Option<Start>, Error> {
let plan = self.import_plan(&hit, &prompt[..limit]);
let started = self.clock.now();
let (imported_ms, copied_tokens) = self.install_hit(device, &hit, &plan, started)?;
let import_ms = self.clock.since(started).as_secs_f64() * 1e3;
self.last_import_split = (imported_ms, import_ms - imported_ms);
self.live.clear();
self.live.extend_from_slice(&prompt[..hit.tokens]);
self.last_match_us = match_us;
self.store.record_hit_as(&hit, branch);
Ok(Some(Start { resume: hit.tokens, switched, branch, copied_tokens, import_ms, match_us }))
self.store.record_hit_as(&hit, plan.branch);
Ok(Some(Start {
resume: hit.tokens,
switched: plan.switched,
branch: plan.branch,
copied_tokens,
import_ms,
match_us,
}))
}
/// Writes the hit's cells back to the device; returns the import milliseconds and the copied token count.
fn install_hit<D: PrefixDevice<State = S, Block = B>>(
&mut self,
device: &mut D,
hit: &Match,
plan: &ImportPlan,
started: std::time::Instant,
) -> Result<(f64, usize), Error> {
let g = self.block_tokens;
let mut blocks = if plan.copy {
self.store.blocks_from(hit.key, plan.first_block).ok_or(Error::IdentityMismatch)?
} else {
Vec::new()
};
if plan.copy {
// a request-end checkpoint also carries the cells after its last full block
if let Some((tail, _, _)) = self.store.tail_of(hit.key) {
blocks.push((plan.full, tail));
}
}
let state = self.store.node_payload(hit.key).ok_or(Error::IdentityMismatch)?;
// the import overwrites every cell from the first named block on
self.live.truncate(if blocks.is_empty() { plan.common } else { plan.first_block * g });
device.import(state, &blocks)?;
let imported_ms = self.clock.since(started).as_secs_f64() * 1e3;
device.restore_draft(state, hit.tokens)?;
let copied_tokens =
blocks.iter().map(|(j, _)| if *j < plan.full { g } else { hit.tokens - plan.full * g }).sum();
Ok((imported_ms, copied_tokens))
}
/// The prefill is about to write the cells from `first` on.
@@ -2,6 +2,14 @@
#[allow(unused_imports)]
use super::*;
use crate::prefix_cache::store::Candidate;
use std::ops::ControlFlow;
/// Which kind of checkpoint position a verdict is about: a grid point, or a request-end tail of that many tokens.
enum Point {
Grid(usize),
Tail(usize),
}
impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
/// A chunk ending at `end` was published: the cells below `end` are this prompt's; maybe checkpoint there.
@@ -12,7 +20,6 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
prompt: &[i32],
end: usize,
) -> Result<ChunkOutcome, Error> {
let g = self.block_tokens;
// a long prefill can outlast a change of memory pressure: follow the governor between chunks, not only between requests
if let Some(governor) = leleka_memory::Governor::global() {
let directive = governor.directive(self.store.bytes() as u64);
@@ -22,30 +29,30 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
let have = self.live.len();
self.live.extend_from_slice(&prompt[have..end]);
}
let Some(req) = self.req.as_ref() else { return Ok(ChunkOutcome::Nothing) };
self.note = None;
if end == 0 || end % g != 0 || end > req.limit {
return Ok(ChunkOutcome::Nothing);
}
let frontier = end == req.last_grid;
let (est_state, est_block) = device.estimate(g);
let est_state = self.seen_state_bytes.unwrap_or(est_state);
let est_block = self.seen_block_bytes.unwrap_or(est_block);
let considering = self.clock.now();
let verdict = self.store.consider(&prompt[..end], frontier, est_state, est_block);
self.consider_ms_request += self.clock.since(considering).as_secs_f64() * 1e3;
let candidate = match verdict {
Consider::Exists => return Ok(ChunkOutcome::Exists),
Consider::Rejected(why) => {
self.note = Some(format!(
"grid point {end} rejected by the policy: {why:?} (store {} MiB of {} MiB)",
self.store.bytes() >> 20,
self.configured_budget >> 20
));
return Ok(ChunkOutcome::Rejected(why));
}
Consider::Admit(candidate) => candidate,
let candidate = match self.plan_chunk(device, prompt, end) {
ControlFlow::Break(outcome) => return Ok(outcome),
ControlFlow::Continue(candidate) => candidate,
};
self.park_chunk(device, candidate, prompt, end)
}
/// The checkpoint a grid point `end` may take: `Break` when there is nothing to build (not a grid point, exists,
/// rejected, low memory).
fn plan_chunk<D: PrefixDevice<State = S, Block = B>>(
&mut self,
device: &D,
prompt: &[i32],
end: usize,
) -> ControlFlow<ChunkOutcome, Candidate> {
let g = self.block_tokens;
let Some(req) = self.req.as_ref() else { return ControlFlow::Break(ChunkOutcome::Nothing) };
let (limit, last_grid) = (req.limit, req.last_grid);
self.note = None;
if end == 0 || end % g != 0 || end > limit {
return ControlFlow::Break(ChunkOutcome::Nothing);
}
let (est_state, est_block) = self.estimate_blocks(device);
let verdict = self.timed(|store| store.consider(&prompt[..end], end == last_grid, est_state, est_block));
let candidate = self.resolve(verdict, Point::Grid(end))?;
let additional = (est_state + candidate.missing.len() * est_block) as u64;
let available = admission_reading(device.available_memory(), additional, self.cfg.memory_floor);
if !budget::admit_growth(available, additional, self.cfg.memory_floor) {
@@ -56,17 +63,19 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
additional >> 20,
self.cfg.memory_floor >> 20
));
return Ok(ChunkOutcome::LowMemory);
return ControlFlow::Break(ChunkOutcome::LowMemory);
}
ControlFlow::Continue(candidate)
}
fn park_chunk<D: PrefixDevice<State = S, Block = B>>(
&mut self,
device: &mut D,
candidate: Candidate,
prompt: &[i32],
end: usize,
) -> Result<ChunkOutcome, Error> {
let started = self.clock.now();
let state = device.park_state()?;
if device.position()? != end as u64 {
return Err(Error::IdentityMismatch);
}
let mut blocks = Vec::with_capacity(candidate.missing.len());
for &j in &candidate.missing {
blocks.push((j, device.park_block(j * g, g)?));
}
let (state, blocks) = self.park_missing(device, &candidate.missing, end as u64)?;
self.seen_state_bytes = Some(state.byte_size());
if let Some((_, block)) = blocks.first() {
self.seen_block_bytes = Some(block.byte_size());
@@ -79,6 +88,56 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
self.admitted_request += 1;
Ok(ChunkOutcome::Admitted { tokens: end, new_blocks, bytes, park_ms })
}
/// The cell state and the missing blocks of the session standing at `expected`, parked to host memory.
fn park_missing<D: PrefixDevice<State = S, Block = B>>(
&self,
device: &mut D,
missing: &[usize],
expected: u64,
) -> Result<(S, Vec<(usize, B)>), Error> {
let g = self.block_tokens;
let state = device.park_state()?;
if device.position()? != expected {
return Err(Error::IdentityMismatch);
}
let mut blocks = Vec::with_capacity(missing.len());
for &j in missing {
blocks.push((j, device.park_block(j * g, g)?));
}
Ok((state, blocks))
}
/// The state and block sizes an admission is estimated with: what the last checkpoint measured, else the device's guess.
fn estimate_blocks<D: PrefixDevice<State = S, Block = B>>(&self, device: &D) -> (usize, usize) {
let (est_state, est_block) = device.estimate(self.block_tokens);
(self.seen_state_bytes.unwrap_or(est_state), self.seen_block_bytes.unwrap_or(est_block))
}
/// Runs a store policy decision and charges its time to the request.
fn timed<T>(&mut self, decide: impl FnOnce(&mut PrefixStore<S, B>) -> T) -> T {
let considering = self.clock.now();
let verdict = decide(&mut self.store);
self.consider_ms_request += self.clock.since(considering).as_secs_f64() * 1e3;
verdict
}
/// The candidate of an admitted verdict; `Break` carries the outcome (and the note) of every other verdict.
fn resolve(&mut self, verdict: Consider, point: Point) -> ControlFlow<ChunkOutcome, Candidate> {
match verdict {
Consider::Exists => {
if let Point::Tail(tokens) = point {
self.note = Some(format!("a checkpoint at {tokens} tokens exists already"));
}
ControlFlow::Break(ChunkOutcome::Exists)
}
Consider::Rejected(why) => {
let stat = format!("(store {} MiB of {} MiB)", self.store.bytes() >> 20, self.configured_budget >> 20);
self.note = Some(match point {
Point::Grid(end) => format!("grid point {end} rejected by the policy: {why:?} {stat}"),
Point::Tail(tokens) => format!("rejected by the policy at {tokens} tokens: {why:?} {stat}"),
});
ControlFlow::Break(ChunkOutcome::Rejected(why))
}
Consider::Admit(candidate) => ControlFlow::Continue(candidate),
}
}
/// The end of the prompt's prefill: the session stands at `prompt.len() - 1`. With `TailMode::Prompt` or `Reply`, checkpoint
/// there (a request-end checkpoint), unless that is a grid point.
@@ -145,35 +204,29 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
));
return Ok(ChunkOutcome::Nothing);
}
let (est_state, est_block) = device.estimate(g);
let est_state = self.seen_state_bytes.unwrap_or(est_state);
let est_block = self.seen_block_bytes.unwrap_or(est_block);
let considering = self.clock.now();
let verdict = self.store.consider_tail(tokens, true, est_state, est_block);
self.consider_ms_request += self.clock.since(considering).as_secs_f64() * 1e3;
let candidate = match verdict {
Consider::Exists => {
self.note = Some(format!("a checkpoint at {} tokens exists already", tokens.len()));
return Ok(ChunkOutcome::Exists);
}
Consider::Rejected(why) => {
self.note = Some(format!(
"rejected by the policy at {} tokens: {why:?} (store {} MiB of {} MiB)",
tokens.len(),
self.store.bytes() >> 20,
self.configured_budget >> 20
));
return Ok(ChunkOutcome::Rejected(why));
}
Consider::Admit(candidate) => candidate,
let candidate = match self.plan_tail(device, tokens) {
ControlFlow::Break(outcome) => return Ok(outcome),
ControlFlow::Continue(candidate) => candidate,
};
self.park_tail_checkpoint(device, candidate, (tokens, keep_end))
}
/// The request-end checkpoint a tail may take: `Break` when there is nothing to build.
fn plan_tail<D: PrefixDevice<State = S, Block = B>>(
&mut self,
device: &D,
tokens: &[i32],
) -> ControlFlow<ChunkOutcome, Candidate> {
let (est_state, est_block) = self.estimate_blocks(device);
let verdict = self.timed(|store| store.consider_tail(tokens, true, est_state, est_block));
let candidate = self.resolve(verdict, Point::Tail(tokens.len()))?;
let additional = (est_state + candidate.missing.len() * est_block + est_block) as u64;
let available = admission_reading(device.available_memory(), additional, self.cfg.memory_floor);
let missing = candidate.missing.len();
if !budget::admit_growth(available, additional, self.cfg.memory_floor) {
self.store.abort(candidate);
self.note = Some(format!(
"low memory at {} tokens: available {} MiB, additional {} MiB (state {} + {} new blocks of {} MiB + the tail), floor {} MiB",
"low memory at {} tokens: available {} MiB, additional {} MiB (state {} + {} new blocks of {} MiB + \
the tail), floor {} MiB",
tokens.len(),
available.map_or_else(|| "unknown".to_owned(), |b| (b >> 20).to_string()),
additional >> 20,
@@ -182,17 +235,19 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
est_block >> 20,
self.cfg.memory_floor >> 20
));
return Ok(ChunkOutcome::LowMemory);
return ControlFlow::Break(ChunkOutcome::LowMemory);
}
ControlFlow::Continue(candidate)
}
fn park_tail_checkpoint<D: PrefixDevice<State = S, Block = B>>(
&mut self,
device: &mut D,
candidate: Candidate,
(tokens, keep_end): (&[i32], Option<usize>),
) -> Result<ChunkOutcome, Error> {
let g = self.block_tokens;
let started = self.clock.now();
let state = device.park_state()?;
if device.position()? != tokens.len() as u64 {
return Err(Error::IdentityMismatch);
}
let mut blocks = Vec::with_capacity(candidate.missing.len());
for &j in &candidate.missing {
blocks.push((j, device.park_block(j * g, g)?));
}
let (state, blocks) = self.park_missing(device, &candidate.missing, tokens.len() as u64)?;
let full = tokens.len() / g;
let tail = device.park_tail(full * g, tokens.len() - full * g)?;
self.seen_state_bytes = Some(state.byte_size());