//! 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(); }