Sliding window 30+20 + GEN 0 cache pre-warm (pre-warm-on-change)

Window: MAIN_AREA 30 + BUFFER 20 (same 50 cap) halves rotation frequency. context: shared compose_prefix (byte-exact prefix of compose) + notepad_fingerprint (rendered header body, excludes updated_at). inkling: build_prefix_ids renders without finish_prompt. service: prewarm() sends GEN 0 directly (no PerfMeter/DB). sessions: schedule_prewarm at turn end on pending rotation OR notepad-dirty (ws=0 normalized); session_chat loads only the window subset.

examples/prewarm_bench.rs: joint GEN 0 -> RESUME bench, PASS on HIP (cached==L==385). Verified live all-agent: notepad write -> pre-warm 1468 -> next turn cached_tokens==1468. Tests: prefix property, opener-skip, GEN 0 primitive, notepad fingerprint. Suite 162 passed + 3 ignored.
This commit is contained in:
adm committed 2026-11-26 19:12:59 +01:00
1 parent 0ce84581a4
commit a52bec97d4
12 files changed
+650 -59

No files matched your search

+10
View File
@@ -79,6 +79,16 @@ pub trait Formatter: Send + Sync {
/// Errors map straight to an HTTP 400.
fn build_prompt(&self, req: &ChatRequest) -> Result<Prompt, ApiErrorEnvelope>;
/// Render only the conversation prefix to prompt ids, for cache pre-warming
/// (`GEN 0`): the same messages/tools/effort as the real turn but WITHOUT the
/// generation opener, so the ids are a byte-exact token prefix of the real
/// prompt and the engine's `RESUME` hits. Default: a dialect with no
/// generation suffix already yields the prefix from `build_prompt`; dialects
/// that append an opener (Inkling's `finish_prompt`) override this to skip it.
fn build_prefix_ids(&self, req: &ChatRequest) -> Result<Vec<u32>, ApiErrorEnvelope> {
Ok(self.build_prompt(req)?.ids)
}
/// A fresh output decoder for one request.
fn decoder(&self) -> Box<dyn Decoder>;
}
+29 -1
View File
@@ -14,7 +14,7 @@ use futures::Stream;
use tokio::sync::mpsc::UnboundedSender;
use tokio_stream::wrappers::UnboundedReceiverStream;
use crate::engine::{Engine, EngineLine, Outcome};
use crate::engine::{Engine, EngineLine, Outcome, Sampling};
use super::formatter::{self, Formatter, Piece, Prompt};
use super::stop::StopFilter;
@@ -112,6 +112,34 @@ impl ChatService {
self.engine.is_idle()
}
/// Pre-warm the engine's conversation cache with a prompt PREFIX, no generation:
/// `GEN 0` prefills the ids and saves them (`cached_prefix` = L, checkpoint =
/// L-1) so the next real turn `RESUME`s L and prefills only the new user tokens.
/// Best-effort warming during idle GPU time: it does NOT feed the PerfMeter and
/// persists nothing (it is not a user turn). `req.messages` must be the prefix
/// only (see `context::compose_prefix`), with the same tools/effort as the real
/// turn. Returns the outcome so a caller can read `resumed` / `done.prompt_tokens`
/// (the joint GEN 0 -> RESUME measurement).
pub async fn prewarm(&self, req: &ChatRequest) -> Result<Outcome, ApiErrorEnvelope> {
let fmt = self.fmt.clone();
let req = req.clone();
let ids = tokio::task::spawn_blocking(move || fmt.build_prefix_ids(&req))
.await
.map_err(|e| {
ApiErrorEnvelope::new(
format!("prefix build task failed: {e}"),
"engine_error",
None,
)
})??;
// max_new = 0: prefill only. No sampling keys (generation knobs are moot),
// and notably no `ckpt=` key, so the engine keeps its default checkpoint.
self.engine
.generate(0, &Sampling::default(), &ids, |_| {})
.await
.map_err(formatter_error)
}
/// One-shot completion.
pub async fn complete(&self, req: &ChatRequest) -> Result<ChatResponse, ApiErrorEnvelope> {
let mut prompt = self.build_prompt_blocking(req).await?;
+132 -11
View File
@@ -16,7 +16,7 @@ use futures::StreamExt;
use serde::{Deserialize, Serialize};
use super::routes::{AppState, Error};
use super::service::PerfSnapshot;
use super::service::{ChatService, PerfSnapshot};
use super::types::{
completion_id, now_unix, ChatChunk, ChatMessage, ChatRequest, ChatResponse, Choice,
FinishReason, FunctionCall, Role, ToolCall, Usage,
@@ -413,9 +413,22 @@ pub(crate) async fn session_chat(
Ok(None) => return Error::not_found("session not found").into_response(),
Err(e) => return e.into_response(),
};
// Load only the sliding-window suffix (id >= window_start), never the whole
// history: a session active for months must not be loaded whole every turn.
// The subset is bounded (the retained window plus at most one turn's new
// appends), so window::select runs over a small slice, not the full history.
let window_start = match with_store(&st, {
let id = id.clone();
move |s| s.window_start(&id)
})
.await
{
Ok(v) => v,
Err(e) => return e.into_response(),
};
let history = match with_store(&st, {
let id = id.clone();
move |s| s.messages(&id)
move |s| s.message_window(&id, window_start).map(|(m, _)| m)
})
.await
{
@@ -489,15 +502,10 @@ pub(crate) async fn session_chat(
// for KV-cache reuse. Full history stays in SQLite; the agent pins what
// matters in the notepad. A total-size (char/token) cut is deferred.
let user_content = format!("{}{}", body.content, extra);
let window_start = match with_store(&st, {
let id = id.clone();
move |s| s.window_start(&id)
})
.await
{
Ok(v) => v,
Err(e) => return e.into_response(),
};
// Fingerprint of the notepad header as used by THIS turn's prompt: the pre-warm
// trigger compares it against the notepad at turn end to detect a header change
// (pre-warm-on-change, chosen over freezing the header).
let notepad_fp = context::notepad_fingerprint(&notepad);
let sel = window::select(&history, window_start);
if sel.start_id != window_start {
let start_id = sel.start_id;
@@ -552,6 +560,9 @@ pub(crate) async fn session_chat(
let sid = id.clone();
let folder = sess.folder.clone();
let tx_model = tx.clone();
let svc_pw = st.service.clone();
let store_pw = store.clone();
let notepad_fp_pw = notepad_fp.clone();
tokio::spawn(async move {
// Streaming model step: emit Delta events while generating (so the GUI
// shows thinking + final answer live), then return the accumulated
@@ -633,6 +644,7 @@ pub(crate) async fn session_chat(
message: env.error.message,
});
}
schedule_prewarm(svc_pw, store_pw, sid.clone(), true, notepad_fp_pw);
});
let events = UnboundedReceiverStream::new(rx)
.map(|ev| {
@@ -693,9 +705,13 @@ pub(crate) async fn session_chat(
});
let acc_end = acc.clone();
let sid = id.clone();
let svc_pw = st.service.clone();
let agent_pw = body.agent;
let notepad_fp_pw = notepad_fp.clone();
let tail = futures::stream::once(async move {
let a = acc_end.lock().unwrap().clone();
persist_assistant(&store, &sid, &a, prompt_len).await;
schedule_prewarm(svc_pw, store.clone(), sid.clone(), agent_pw, notepad_fp_pw);
Ok::<_, std::convert::Infallible>(Event::default().data("[DONE]"))
});
Sse::new(events.chain(tail))
@@ -726,6 +742,13 @@ pub(crate) async fn session_chat(
usage: Some(resp.usage.clone()),
};
persist_assistant(&store, &id, &a, resp.usage.prompt_tokens).await;
schedule_prewarm(
st.service.clone(),
store.clone(),
id.clone(),
body.agent,
notepad_fp.clone(),
);
Json(resp).into_response()
}
Err(env) => Error::from_envelope(env).into_response(),
@@ -769,6 +792,104 @@ async fn persist_assistant(store: &Arc<dyn Store>, sid: &str, a: &Accum, prompt_
.await;
}
/// After a turn completes, pre-warm the NEXT turn's prefix into the engine cache
/// during idle GPU time — but only when a window rotation is pending, i.e. the
/// next prefix will differ from what the engine just cached. Best-effort: skipped
/// when the engine is busy, and it never STOPs a running pre-warm (a real turn
/// queues on the engine mutex behind it). Not a user turn: no persistence, no
/// PerfMeter. Triggers on a pending rotation OR a notepad header change during the
/// turn (pre-warm-on-change: the model always sees a fresh notepad, no frozen
/// header, no schema migration). Within an agent tool loop the header is composed
/// once and `req.messages` is append-only, so mid-loop notepad writes never
/// invalidate intermediate steps — this fires once, at turn end, in the idle gap.
fn schedule_prewarm(
service: ChatService,
store: Arc<dyn Store>,
sid: String,
agent_mode: bool,
notepad_fp: String,
) {
tokio::spawn(async move {
if !service.is_idle() {
return;
}
// Re-load the current state fresh (the turn just appended messages): the
// pre-warm must match what the NEXT turn's session_chat will select.
let sid_load = sid.clone();
let loaded = tokio::task::spawn_blocking(move || {
let sess = store.get_session(&sid_load).ok()??;
let ws = store.window_start(&sid_load).ok()?;
let history = store.message_window(&sid_load, ws).ok()?.0;
let sections = store.context_sections().ok()?;
let notepad = store.notepad(&sid_load).ok()?;
let user_name = store
.get_defaults()
.ok()?
.and_then(|d| d.user_name)
.map(|n| n.trim().to_string())
.filter(|n| !n.is_empty())
.unwrap_or_else(|| "User".to_string());
Some((sess, ws, history, sections, notepad, user_name))
})
.await
.ok()
.flatten();
let Some((sess, ws, history, sections, notepad, user_name)) = loaded else {
return;
};
let sel = window::select(&history, ws);
// Pre-warm only when the next turn's prefix will differ from what the engine
// just cached: a pending window rotation, OR a notepad header change during
// the turn (the agent wrote/removed an entry). Otherwise the next turn is
// append-only with a stable header and RESUME already hits — warming would be
// wasted work. The fingerprint is the rendered header body, so an
// updated_at-only change (identical text) does not count as dirty.
// Normalize ws=0 ("from the beginning") to the first retained id, so the
// initial resolution 0 -> first-id is not mistaken for a rotation.
let cur_start = if ws == 0 {
history.first().map(|m| m.id).unwrap_or(0)
} else {
ws
};
let rotation_pending = sel.start_id != cur_start;
let notepad_dirty = context::notepad_fingerprint(&notepad) != notepad_fp;
if !rotation_pending && !notepad_dirty {
return;
}
let prefix = context::compose_prefix(
&sess,
&history[sel.start..],
&user_name,
&sections,
&notepad,
);
let mut req = ChatRequest {
model: sess.model.clone(),
messages: prefix,
..Default::default()
};
if agent_mode {
req.tools = Some(agent::agent_tools());
req.tool_choice = Some(serde_json::json!("auto"));
}
// Re-check idle right before warming: a real turn may have started while we
// loaded. If so, skip — it caches its own prefix, so warming a stale one is
// pointless. A tiny race remains but is benign (best-effort optimization).
if !service.is_idle() {
return;
}
match service.prewarm(&req).await {
Ok(out) => {
let l = out.done.as_ref().map(|d| d.prompt_tokens).unwrap_or(0);
tracing::info!(session = %sid, prefix_tokens = l, resumed = out.resumed, "pre-warmed next-turn prefix (GEN 0)");
}
Err(e) => {
tracing::warn!(session = %sid, error = %e.error.message, "pre-warm failed");
}
}
});
}
#[cfg(test)]
mod tests {
use super::*;
+1 -1
View File
@@ -97,7 +97,7 @@ impl Stop {
}
/// `POST /v1/chat/completions` body (the fields we recognise).
#[derive(Debug, Clone, Deserialize)]
#[derive(Debug, Clone, Default, Deserialize)]
pub struct ChatRequest {
#[serde(default)]
pub model: String,