diff --git a/README.md b/README.md index 88d6700..b466fe9 100644 --- a/README.md +++ b/README.md @@ -291,7 +291,7 @@ later adaptation round. ## Status -Working and tested (158 tests, plus 3 real-file tests run on demand). Text, images, +Working and tested (162 tests, plus 3 real-file tests run on demand). Text, images, the full client-side tool loop, the Anthropic endpoint, the web GUI (session context, streaming, stats, **file/image upload**, assistant **Markdown/LaTeX rendering** with native MathML) and **agent mode** (the model using `shell_exec` @@ -302,7 +302,12 @@ verified against the real chat template. A per-session **notepad** (agent-curate `` entries via the `notepad` tool) and a **sliding DIALOG window** (message-count main area + buffer headroom, stepped KV-cache-friendly eviction at turn boundaries, `window_start` persisted per session, full history never deleted) -are implemented and dogfooded live. +are implemented and dogfooded live. A best-effort **cache pre-warm** (`GEN 0` over +the next turn's shared prefix during idle GPU time) hides the re-prefill on a +pending window rotation **or a notepad change** (pre-warm-on-change: the model +always sees a fresh notepad, no frozen header, no schema migration). The joint +`GEN 0 → RESUME` measurement on HIP (`examples/prewarm_bench.rs`) **passed**: +`cached_tokens == L == 385`, only the 35 new user tokens prefilled. Not yet implemented (honest gaps): forced `tool_choice` (`required` / named function returns a clear 400), multi-slot batching, logprobs / structured output, automatic @@ -371,8 +376,8 @@ Both are **implemented and validated live**: the per-session notepad (store, `notepad` tool, `` injection, read-only GUI panel) and the **sliding DIALOG window** (`src/window.rs`). The compositor no longer injects the full history: `window::select` retains the most recent messages **by count**, in two -tiers — a **main area** (`MAIN_AREA = 40` recent messages always kept) plus a -**buffer** (`BUFFER = 10` messages of headroom above it). The cut lands on +tiers — a **main area** (`MAIN_AREA = 30` recent messages always kept) plus a +**buffer** (`BUFFER = 20` messages of headroom above it). The cut lands on **user-turn boundaries**, so a `tool_call`/`tool_result` pair is never split, and the full history stays in SQLite (evicted turns remain recallable). @@ -384,8 +389,10 @@ turn-to-turn and the engine reuses its cached KV. When occupancy crosses user-turn boundaries down to `MAIN_AREA`, amortizing one re-prefill over several append-only turns, and a new buffer starts filling. The chosen start id is persisted per session (`sessions.window_start`, idempotent migration) and respected on the -next turn. The counts are a starting point (40 main + 10 buffer); both will shrink -at regime. A **total-size (char/token) cut** is deliberately deferred — it interacts +next turn. The counts are a starting point (30 main + 20 buffer, same 50 cap); +the wider buffer halves the rotation frequency (fewer re-prefills) at the cost of +a lower post-rotation floor, and both will shrink at regime. A **total-size +(char/token) cut** is deliberately deferred — it interacts with the stepped anchor and is not as simple as a second cap; the notepad preserves what matters beyond the window. @@ -394,6 +401,9 @@ suffix (SQL-filtered by `window_start`, so a months-long history — potentially of millions of tokens — is never loaded whole or shipped to the client), plus the total count so the GUI shows a banner noting older turns are preserved server-side. A full-chat export/download command is deferred; the live view is windowed by design. +The inference path (`session_chat`) loads the same SQL-filtered subset +(`message_window`), so a turn never reads the whole history either — both the +browser and the model are bounded to the retained window. To survive what slides out, each session has a **notepad**: a small, agent-curated set of **labelled entries** (`key → short text`, e.g. `goal`, diff --git a/examples/prewarm_bench.rs b/examples/prewarm_bench.rs new file mode 100644 index 0000000..5aceae9 --- /dev/null +++ b/examples/prewarm_bench.rs @@ -0,0 +1,170 @@ +//! Joint GEN 0 -> RESUME bench against the REAL engine (HIP/GPU). +//! +//! Proves the pre-warm property the engine coder confirmed on ink_serve.h: a +//! `GEN 0` over the next turn's prefix saves it in the conversation cache +//! (`cached_prefix` = L, checkpoint = L-1), and the real turn then `RESUME`s the +//! whole prefix (`cached_tokens == L`), prefilling only the new user tokens. +//! +//! Run it with the engine idle (it spawns its own engine child from the config): +//! +//! cargo run --release --example prewarm_bench +//! cargo run --release --example prewarm_bench -- --config /path/to/strata-inkling.json +//! +//! Loads the same config as `strata-ctl --serve` (engine exe/args, tokenizer, +//! reasoning_effort). Builds a synthetic conversation in memory (no DB), pre-warms +//! its prefix, then runs one real turn and asserts `cached_tokens == L`. This is +//! the ground-truth measurement for the strata-ctl <-> strata-inkling joint test: +//! the number comes from the engine's RESUME, not from an assumption. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Instant; + +use strata_ctl::api::types::ChatRequest; +use strata_ctl::api::ChatService; +use strata_ctl::config::Config; +use strata_ctl::context; +use strata_ctl::engine::Engine; +use strata_ctl::inkling::{ChatTemplate, InklingFormatter, InklingTokenizer}; +use strata_ctl::store::{ContextSection, NotepadEntry, Session, SessionSettings, StoredMessage}; + +#[tokio::main] +async fn main() { + let mut path = Config::default_path(); + let args: Vec = std::env::args().skip(1).collect(); + if let Some(i) = args.iter().position(|a| a == "--config") { + if let Some(p) = args.get(i + 1) { + path = PathBuf::from(p); + } + } + let cfg = Config::load(&path).expect("config loads"); + strata_ctl::i18n::init(&cfg.language()); + + let dir = cfg.tokenizer.clone().expect("config has a tokenizer dir"); + let tok = Arc::new(InklingTokenizer::load_dir(Path::new(&dir)).expect("tokenizer loads")); + let src = std::fs::read_to_string(Path::new(&dir).join("chat_template.jinja")) + .expect("template read"); + let template = ChatTemplate::new(&src).expect("template compiles"); + let fmt = Arc::new(InklingFormatter::new( + tok, + template, + cfg.model_name().to_string(), + cfg.reasoning_effort.clone(), + cfg.sampling.to_sampling(), + )); + + let engine = Arc::new( + Engine::start( + &cfg.exe, + &cfg.engine_argv(), + cfg.cwd.as_deref(), + cfg.startup_timeout(), + ) + .await + .expect("engine starts") + .with_silence(cfg.silence_timeout()), + ); + println!( + "engine READY (context {} tokens), effort={:?}", + engine.ready().max_context, + cfg.reasoning_effort + ); + let svc = ChatService::new(engine.clone(), fmt); + + // Synthetic conversation: a session, a static section, a notepad, and a few + // history turns. No DB needed — compose works on in-memory values, exactly as + // session_chat does after loading the window subset. + let sess = Session { + id: "bench".into(), + title: "Bench".into(), + model: cfg.model_name().to_string(), + settings: SessionSettings::default(), + name_locked: true, + folder: None, + created_at: 0, + updated_at: 0, + }; + let sections = vec![ContextSection { + name: "SYSTEM_PROMPT".into(), + content: "Sei un assistente di prova. {identity}".into(), + position: 0, + }]; + let notepad = vec![NotepadEntry { + key: "goal".into(), + text: "misurare GEN 0 -> RESUME".into(), + updated_at: 0, + }]; + let history: Vec = (0..6) + .map(|i| StoredMessage { + id: i + 1, + role: if i % 2 == 0 { "user" } else { "assistant" }.into(), + content: format!("turno di prova numero {i}, contenuto stabile per il prefisso"), + reasoning_content: None, + tool_calls_json: None, + tool_call_id: None, + prompt_tokens: 0, + completion_tokens: 0, + created_at: 1_700_000_000 + i, + }) + .collect(); + + // 1) Pre-warm the prefix (GEN 0): pinned + DIALOG + history, NO user turn, + // NO generation opener. This is what schedule_prewarm sends when idle. + let prefix = context::compose_prefix(&sess, &history, "Federico", §ions, ¬epad); + let prefix_req = ChatRequest { + model: cfg.model_name().to_string(), + messages: prefix, + ..Default::default() + }; + let t0 = Instant::now(); + let out = svc.prewarm(&prefix_req).await.expect("prewarm GEN 0"); + let l = out.done.as_ref().map(|d| d.prompt_tokens).unwrap_or(0); + println!( + "GEN 0: prefilled L={l} tokens in {:?} (resumed={})", + t0.elapsed(), + out.resumed + ); + + // 2) Real turn: the SAME prefix + a new user message. Must RESUME the whole L. + let full = context::compose( + &sess, + &history, + "questo e' il turno reale dopo il pre-warm", + &[], + "Federico", + §ions, + ¬epad, + ); + let full_req = ChatRequest { + model: cfg.model_name().to_string(), + messages: full, + max_tokens: Some(8), + ..Default::default() + }; + let t1 = Instant::now(); + let resp = svc.complete(&full_req).await.expect("real turn"); + let cached = resp.usage.cached_tokens.unwrap_or(0); + println!( + "real turn: prompt_tokens={}, cached_tokens={cached} (RESUME), prompt_ms={:?}, wall {:?}", + resp.usage.prompt_tokens, + resp.usage.prompt_ms, + t1.elapsed() + ); + + // 3) The joint measurement: the whole pre-warmed prefix was reused, and only + // the new user tokens (plus any opener) were prefilled on top of it. + assert_eq!( + cached, l, + "RESUME must reuse the entire pre-warmed prefix (cached={cached}, L={l})" + ); + assert!( + resp.usage.prompt_tokens > l, + "the real turn adds new user tokens on top of L" + ); + println!( + "PASS: cached_tokens == L == {l}; only {} new tokens prefilled", + resp.usage.prompt_tokens - l + ); + + engine.shutdown().await.unwrap(); +} diff --git a/src/api/formatter.rs b/src/api/formatter.rs index c7e2d05..5cb6e3e 100644 --- a/src/api/formatter.rs +++ b/src/api/formatter.rs @@ -79,6 +79,16 @@ pub trait Formatter: Send + Sync { /// Errors map straight to an HTTP 400. fn build_prompt(&self, req: &ChatRequest) -> Result; + /// 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, ApiErrorEnvelope> { + Ok(self.build_prompt(req)?.ids) + } + /// A fresh output decoder for one request. fn decoder(&self) -> Box; } diff --git a/src/api/service.rs b/src/api/service.rs index fe6e7d8..b086452 100644 --- a/src/api/service.rs +++ b/src/api/service.rs @@ -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 { + 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 { let mut prompt = self.build_prompt_blocking(req).await?; diff --git a/src/api/sessions.rs b/src/api/sessions.rs index 1f444ed..24559a7 100644 --- a/src/api/sessions.rs +++ b/src/api/sessions.rs @@ -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(¬epad); 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, 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, + 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(¬epad) != notepad_fp; + if !rotation_pending && !notepad_dirty { + return; + } + let prefix = context::compose_prefix( + &sess, + &history[sel.start..], + &user_name, + §ions, + ¬epad, + ); + 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::*; diff --git a/src/api/types.rs b/src/api/types.rs index 5f75c32..6975833 100644 --- a/src/api/types.rs +++ b/src/api/types.rs @@ -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, diff --git a/src/context.rs b/src/context.rs index 4ad615a..547e237 100644 --- a/src/context.rs +++ b/src/context.rs @@ -24,6 +24,66 @@ pub fn compose( ) -> Vec { // 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 { + 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 { // Pinned prefix: static sections + notepad, always present above the window. let mut messages = pinned_messages(sess, sections, notepad); // The interactive region opens with 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::>() - .join("\n"); + let body = notepad_fingerprint(notepad); messages.push(text_message( Role::System, format!("\n{body}\n\n\n"), @@ -127,6 +162,20 @@ pub fn pinned_messages( messages } +/// The rendered `` 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::>() + .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", §ions, ¬epad); + let full = compose( + &sess, + &history, + "nuovo turno", + &[], + "Federico", + §ions, + ¬epad, + ); + // 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 = prefix + .iter() + .map(|m| serde_json::to_value(m).unwrap()) + .collect(); + let fj: Vec = 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(&[]), ""); + } } diff --git a/src/inkling/formatter.rs b/src/inkling/formatter.rs index deef379..a8946e2 100644 --- a/src/inkling/formatter.rs +++ b/src/inkling/formatter.rs @@ -135,6 +135,23 @@ impl Formatter for InklingFormatter { }) } + fn build_prefix_ids(&self, req: &ChatRequest) -> Result, 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 { Box::new(InklingDecoder { tok: self.tok.clone(), diff --git a/src/window.rs b/src/window.rs index 7472e64..115898c 100644 --- a/src/window.rs +++ b/src/window.rs @@ -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] diff --git a/tests/engine_supervisor.rs b/tests/engine_supervisor.rs index 80f2102..b430bf7 100644 --- a/tests/engine_supervisor.rs +++ b/tests/engine_supervisor.rs @@ -153,3 +153,22 @@ async fn request_stop_signals_the_owner_without_taking_the_lock() { assert!(engine.is_idle()); engine.shutdown().await.unwrap(); } + +#[tokio::test] +async fn gen_zero_prefills_without_generating() { + // The cache pre-warm primitive: GEN 0 prefills the ids and emits one DONE + // with zero generated tokens (no T lines), prompt_tokens = the prefix length. + let engine = start_mock().await; + let out = engine + .generate(0, &Sampling::default(), &[1, 2, 3, 4], |_| {}) + .await + .unwrap(); + assert!(out.tokens.is_empty(), "GEN 0 generates no tokens"); + let done = out.done.unwrap(); + assert_eq!(done.generated, 0); + assert_eq!(done.prompt_tokens, 4); + assert_eq!(done.finish, "length"); + // the wires are free again: a real turn queues/runs normally after the warm + assert!(engine.is_idle()); + engine.shutdown().await.unwrap(); +} diff --git a/tests/inkling_formatter.rs b/tests/inkling_formatter.rs index a2d136f..4ae460c 100644 --- a/tests/inkling_formatter.rs +++ b/tests/inkling_formatter.rs @@ -268,3 +268,50 @@ fn config_sampling_defaults_are_applied_and_overridable() { assert!(s2.keys().contains("top_k=64")); let _ = std::fs::remove_file(&path); } + +#[test] +fn build_prefix_ids_skips_opener_and_is_token_prefix() { + let (tok, path) = fixture_tokenizer(); + // A template emitting the effort-none line, so finish_prompt WOULD append the + // generation opener on build_prompt; build_prefix_ids must skip it. + let tmpl = ChatTemplate::new( + "{%- for m in messages -%}{%- if loop.first -%}<|content_text|>Thinking effort level: 0<|end_message|>{%- endif -%}<|content_text|>{{ m.content }}<|end_message|>{%- endfor -%}", + ) + .unwrap(); + let fmt = InklingFormatter::new( + tok.clone(), + tmpl, + "m".into(), + Some("none".into()), + Sampling::default(), + ); + let prefix_req: ChatRequest = serde_json::from_value(json!({ + "model": "m", + "messages": [ + {"role": "user", "content": "hello"}, + {"role": "assistant", "content": "answer"} + ] + })) + .unwrap(); + let full_req: ChatRequest = serde_json::from_value(json!({ + "model": "m", + "messages": [ + {"role": "user", "content": "hello"}, + {"role": "assistant", "content": "answer"}, + {"role": "user", "content": "hello"} + ] + })) + .unwrap(); + let prefix_ids = fmt.build_prefix_ids(&prefix_req).unwrap(); + let full_ids = fmt.build_prompt(&full_req).unwrap().ids; + // The pre-warm ids are a byte-exact token prefix of the real turn's ids (the + // message boundary is a special token, so the BPE/WordLevel span never merges + // across it). + assert!(full_ids.len() > prefix_ids.len()); + assert_eq!(&full_ids[..prefix_ids.len()], &prefix_ids[..]); + // build_prompt on the SAME prefix appends the opener -> longer than the + // prefix-only build (this is exactly what the pre-warm must NOT include). + let prefix_with_opener = fmt.build_prompt(&prefix_req).unwrap().ids; + assert!(prefix_with_opener.len() > prefix_ids.len()); + let _ = std::fs::remove_file(&path); +} diff --git a/tests/mock_engine.py b/tests/mock_engine.py index 46623be..66d7429 100644 --- a/tests/mock_engine.py +++ b/tests/mock_engine.py @@ -94,8 +94,16 @@ while True: out(f"DONE {n} {len(ids)} 1.0 2.0 {'abort' if stopped else 'length'}") continue + # GEN 0 (max_new = 0): prefill only, no generation — the cache pre-warm + # primitive. One DONE, zero tokens, prompt_tokens = len(ids), finish "length". + max_new = int(parts[1]) if parts[1].lstrip("-").isdigit() else 0 + if max_new == 0: + out("RESUME 0") + out(f"DONE 0 {len(ids)} 5.0 0.0 length 0 0 0") + continue + out("RESUME 1") out("PP 2 4 0.9 2222.2") for t in (101, 102, 103, 104, 105): out(f"T {t}") - out("DONE 5 4 12.5 34.0 stop 3 4 1") + out("DONE 5 4 12.5 34.0 stop 3 4 1") \ No newline at end of file