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,
+184 -26
View File
@@ -24,6 +24,66 @@ pub fn compose(
) -> Vec<ChatMessage> {
// Server-local timezone offset, computed once for every turn in this request.
let tz_offset = server_utc_offset_secs();
// The shared prefix (pinned + DIALOG + history), then the new user turn.
let mut messages = prefix_messages(sess, history, user_name, sections, notepad, tz_offset);
// The user turn: typed text + attachment context. Images become multipart
// image_url parts that the Vision bridge materializes; else a plain string.
let user_text = format!(
"{}{}",
speaker_prefix(user_name, now_unix() as i64, tz_offset),
user_content
);
if images.is_empty() {
messages.push(text_message(Role::User, user_text));
} else {
let mut parts = vec![serde_json::json!({"type": "text", "text": user_text})];
parts.extend(images.iter().cloned());
messages.push(ChatMessage {
role: Role::User,
content: Some(serde_json::Value::Array(parts)),
tool_call_id: None,
tool_calls: None,
name: None,
reasoning_content: None,
});
}
messages
}
/// The prompt prefix WITHOUT the new user turn: pinned sections + notepad + the
/// open DIALOG region + the retained history (with `[SPEAKER]` stamps). This is
/// exactly what [`compose`] builds before appending the user turn, so a cache
/// pre-warm (`GEN 0`) over `compose_prefix` is a byte-exact token prefix of the
/// real turn's prompt and the engine's `RESUME` hits. The real turn must reuse
/// this same prefix (it does, via [`compose`]) — never a parallel rebuild.
pub fn compose_prefix(
sess: &Session,
history: &[StoredMessage],
user_name: &str,
sections: &[ContextSection],
notepad: &[NotepadEntry],
) -> Vec<ChatMessage> {
prefix_messages(
sess,
history,
user_name,
sections,
notepad,
server_utc_offset_secs(),
)
}
/// The shared prefix builder: pinned prefix + the open DIALOG region + the
/// retained history. `tz_offset` is the server UTC offset, passed in so [`compose`]
/// stamps the history and the new user turn with one consistent offset.
fn prefix_messages(
sess: &Session,
history: &[StoredMessage],
user_name: &str,
sections: &[ContextSection],
notepad: &[NotepadEntry],
tz_offset: i64,
) -> Vec<ChatMessage> {
// Pinned prefix: static sections + notepad, always present above the window.
let mut messages = pinned_messages(sess, sections, notepad);
// The interactive region opens with <DIALOG> and is left OPEN: a trailing
@@ -63,27 +123,6 @@ pub fn compose(
.and_then(|s| serde_json::from_str(s).ok());
messages.push(msg);
}
// The user turn: typed text + attachment context. Images become multipart
// image_url parts that the Vision bridge materializes; else a plain string.
let user_text = format!(
"{}{}",
speaker_prefix(user_name, now_unix() as i64, tz_offset),
user_content
);
if images.is_empty() {
messages.push(text_message(Role::User, user_text));
} else {
let mut parts = vec![serde_json::json!({"type": "text", "text": user_text})];
parts.extend(images.iter().cloned());
messages.push(ChatMessage {
role: Role::User,
content: Some(serde_json::Value::Array(parts)),
tool_call_id: None,
tool_calls: None,
name: None,
reasoning_content: None,
});
}
messages
}
@@ -114,11 +153,7 @@ pub fn pinned_messages(
));
}
if !notepad.is_empty() {
let body = notepad
.iter()
.map(|e| format!("{}: {}", e.key, e.text.replace('\n', " ")))
.collect::<Vec<_>>()
.join("\n");
let body = notepad_fingerprint(notepad);
messages.push(text_message(
Role::System,
format!("<NOTEPAD>\n{body}\n</NOTEPAD>\n\n"),
@@ -127,6 +162,20 @@ pub fn pinned_messages(
messages
}
/// The rendered `<NOTEPAD>` body: one `key: text` line per entry (newlines in text
/// normalized to spaces), in store order. This is exactly what the header injects,
/// so it doubles as a fingerprint: if it is unchanged across a turn, the notepad
/// header is byte-identical and the prefix cache still holds (no pre-warm needed).
/// `updated_at` is deliberately excluded — it does not affect the rendered header,
/// so re-setting identical text does not trigger a wasted pre-warm.
pub fn notepad_fingerprint(notepad: &[NotepadEntry]) -> String {
notepad
.iter()
.map(|e| format!("{}: {}", e.key, e.text.replace('\n', " ")))
.collect::<Vec<_>>()
.join("\n")
}
fn role_of(s: &str) -> Role {
match s {
"system" | "developer" => Role::System,
@@ -385,4 +434,113 @@ mod tests {
assert!(a[da + 1].text().unwrap().ends_with("\n\n"));
assert_eq!(a[da + 1].text().unwrap(), b[db + 1].text().unwrap());
}
#[test]
fn compose_prefix_is_exact_prefix_of_compose() {
let sess = Session {
id: "s".into(),
title: "Nebula".into(),
model: "m".into(),
settings: crate::store::SessionSettings::default(),
name_locked: true,
folder: None,
created_at: 0,
updated_at: 0,
};
let sections = vec![ContextSection {
name: "TOOL_USE".into(),
content: "manuale".into(),
position: 1,
}];
let notepad = vec![NotepadEntry {
key: "goal".into(),
text: "ship it".into(),
updated_at: 0,
}];
let history = vec![
StoredMessage {
id: 1,
role: "user".into(),
content: "ciao".into(),
reasoning_content: None,
tool_calls_json: None,
tool_call_id: None,
prompt_tokens: 0,
completion_tokens: 0,
created_at: 1_700_000_000,
},
StoredMessage {
id: 2,
role: "assistant".into(),
content: "ciao a te".into(),
reasoning_content: None,
tool_calls_json: None,
tool_call_id: None,
prompt_tokens: 0,
completion_tokens: 0,
created_at: 1_700_000_001,
},
];
let prefix = compose_prefix(&sess, &history, "Federico", &sections, &notepad);
let full = compose(
&sess,
&history,
"nuovo turno",
&[],
"Federico",
&sections,
&notepad,
);
// compose == prefix + exactly one new user turn: the pre-warm prefix is a
// byte-exact prefix of the real turn (ChatMessage has no PartialEq, so
// compare the serialized form, which is what the template renders).
assert_eq!(full.len(), prefix.len() + 1);
let pj: Vec<serde_json::Value> = prefix
.iter()
.map(|m| serde_json::to_value(m).unwrap())
.collect();
let fj: Vec<serde_json::Value> = full[..prefix.len()]
.iter()
.map(|m| serde_json::to_value(m).unwrap())
.collect();
assert_eq!(pj, fj, "pre-warm prefix must equal the real turn's prefix");
assert!(matches!(full.last().unwrap().role, Role::User));
assert!(full
.last()
.unwrap()
.text()
.unwrap()
.ends_with("nuovo turno"));
}
#[test]
fn notepad_fingerprint_tracks_header_not_updated_at() {
let a = vec![NotepadEntry {
key: "goal".into(),
text: "ship it".into(),
updated_at: 1,
}];
let b = vec![NotepadEntry {
key: "goal".into(),
text: "ship it".into(),
updated_at: 999,
}];
// updated_at differs but the rendered header is identical -> same fingerprint
// (re-setting identical text must not trigger a wasted pre-warm).
assert_eq!(notepad_fingerprint(&a), notepad_fingerprint(&b));
let c = vec![NotepadEntry {
key: "goal".into(),
text: "ship it now".into(),
updated_at: 1,
}];
assert_ne!(notepad_fingerprint(&a), notepad_fingerprint(&c));
// newline normalization matches the header body exactly.
let d = vec![NotepadEntry {
key: "state".into(),
text: "coding\nnow".into(),
updated_at: 0,
}];
assert_eq!(notepad_fingerprint(&d), "state: coding now");
assert_eq!(notepad_fingerprint(&[]), "");
}
}
+17
View File
@@ -135,6 +135,23 @@ impl Formatter for InklingFormatter {
})
}
fn build_prefix_ids(&self, req: &ChatRequest) -> Result<Vec<u32>, ApiErrorEnvelope> {
let mut msgs = Self::messages_json(req);
prepare_messages(&mut msgs);
let tools = tools_for_choice(req)?;
let rendered = self
.template
.render(&msgs, tools, self.effort.as_deref())
.map_err(|e| ApiErrorEnvelope::new(e.to_string(), "invalid_request_error", None))?;
// No finish_prompt: the pre-warm prefix must end after the last history
// message, WITHOUT the generation opener, to be a byte-exact token prefix
// of the real turn (whose opener sits after the new user turn). Same
// tools/effort as the real turn so tool_declare and the effort line match.
self.tok
.encode(&rendered)
.map_err(|e| ApiErrorEnvelope::new(e.to_string(), "invalid_request_error", None))
}
fn decoder(&self) -> Box<dyn Decoder> {
Box::new(InklingDecoder {
tok: self.tok.clone(),
+16 -13
View File
@@ -19,11 +19,13 @@ use crate::store::StoredMessage;
/// Main dialogic area: the most recent messages always retained. This is the
/// low-water mark the window drops to after an eviction.
pub const MAIN_AREA: usize = 40;
pub const MAIN_AREA: usize = 30;
/// Buffer headroom above the main area. While the retained count is at most
/// MAIN_AREA + BUFFER the window is append-only; crossing it clears the buffer
/// (evict down to MAIN_AREA) and starts a new one.
pub const BUFFER: usize = 10;
/// (evict down to MAIN_AREA) and starts a new one. A wider buffer (same 50 cap)
/// halves the rotation frequency: fewer re-prefills, at the cost of a lower
/// post-rotation floor (the agent pins what matters in the notepad).
pub const BUFFER: usize = 20;
/// The window selection: where the retained history suffix begins.
pub struct Selection {
@@ -111,7 +113,7 @@ mod tests {
#[test]
fn buffer_fills_then_clears_to_main() {
// 51 messages > MAIN(40) + BUFFER(10) = 50 -> clear down to <= 40.
// 51 messages > MAIN(30) + BUFFER(20) = 50 -> clear down to <= 30.
let h = exchanges(51);
let sel = select(&h, 0);
assert_eq!(h[sel.start].role, "user");
@@ -124,22 +126,23 @@ mod tests {
let h = exchanges(60);
let sel = select(&h, 0);
assert_eq!(h[sel.start].role, "user");
// 60 - start <= 40 -> start >= 20; id 21 is a user turn.
assert_eq!(sel.start, 20);
assert_eq!(sel.start_id, 21);
// 60 - start <= 30 -> start >= 30; id 31 is a user turn.
assert_eq!(sel.start, 30);
assert_eq!(sel.start_id, 31);
}
#[test]
fn never_starts_mid_tool_exchange() {
let mut h = exchanges(60);
// Turn id 20 into an assistant tool_call and id 21 into its tool result,
// so the cut must skip past them to the next user turn (id 23).
h[19].role = "assistant".into();
h[19].tool_calls_json = Some(r#"[{"id":"c1"}]"#.into());
h[20].role = "tool".into();
// Turn id 30 into an assistant tool_call and id 31 into its tool result,
// right at the low-water boundary, so the cut must skip past them to the
// next user turn (id 33).
h[29].role = "assistant".into();
h[29].tool_calls_json = Some(r#"[{"id":"c1"}]"#.into());
h[30].role = "tool".into();
let sel = select(&h, 0);
assert_eq!(h[sel.start].role, "user");
assert_eq!(sel.start_id, 23);
assert_eq!(sel.start_id, 33);
}
#[test]