//! Measure the REAL static prompt prefix (in tokens) across the live GUI sessions. //! //! Answers the engine coder's auto-ckpt anchor question: how big is the pure //! static prefix (tool_declare + SYSTEM_PROMPT + TOOL_USE, before ) and //! with included, in real chats? Also measures the CROSS-SESSION common //! static prefix (the deepest anchor that survives a session switch on --parallel 1). //! //! cargo run --release --example prefix_measure //! cargo run --release --example prefix_measure -- --config /path/to.json //! //! Reads the same SQLite store the server uses (WAL: safe concurrent reader). //! No engine, no generation: pure formatter token counts via build_prefix_ids. use std::path::{Path, PathBuf}; use std::sync::Arc; use strata_ctl::api::types::ChatRequest; use strata_ctl::api::Formatter; use strata_ctl::config::Config; use strata_ctl::context; use strata_ctl::inkling::{ChatTemplate, InklingFormatter, InklingTokenizer}; use strata_ctl::store::{SqliteStore, Store}; use strata_ctl::window; fn lcp(a: &[u32], b: &[u32]) -> usize { a.iter().zip(b.iter()).take_while(|(x, y)| x == y).count() } 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"); 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 db = cfg.gui_db_path(); let store = SqliteStore::open(&db).expect("store opens"); println!("db: {}", db.display()); let user_name = store .get_defaults() .ok() .flatten() .and_then(|d| d.user_name) .map(|n| n.trim().to_string()) .filter(|n| !n.is_empty()) .unwrap_or_else(|| "User".to_string()); let sections = store.context_sections().expect("sections"); println!("user_name: {user_name}"); println!("sections (store order):"); for s in §ions { println!(" [{}] {} ({} chars)", s.position, s.name, s.content.len()); } let tools = strata_ctl::agent::agent_tools(); let mkreq = |msgs: Vec| ChatRequest { model: cfg.model_name().to_string(), messages: msgs, tools: Some(tools.clone()), tool_choice: Some(serde_json::json!("auto")), ..Default::default() }; let ids = |msgs: Vec| -> Vec { fmt.build_prefix_ids(&mkreq(msgs)).expect("prefix ids") }; let sessions = store.list_sessions().expect("sessions"); println!("\n=== PER-SESSION STATIC PREFIX (tokens, agent tools ON) ==="); println!( "{:<28} {:>8} {:>8} {:>10} {:>8} {:>6}", "session", "static", "np_delta", "static+np", "full", "hist" ); let mut statics: Vec<(String, Vec)> = Vec::new(); let mut tool_declare_delta: Option = None; for sess in &sessions { let notepad = store.notepad(&sess.id).unwrap_or_default(); let ws = store.window_start(&sess.id).unwrap_or(0); let (history, _total) = store.message_window(&sess.id, ws).unwrap_or((vec![], 0)); let sel = window::select(&history, ws); let hist = &history[sel.start..]; let static_msgs = context::pinned_messages(sess, §ions, &[]); let np_msgs = context::pinned_messages(sess, §ions, ¬epad); let full_msgs = context::compose_prefix(sess, hist, &user_name, §ions, ¬epad); let i_static = ids(static_msgs.clone()); let i_np = ids(np_msgs); let i_full = ids(full_msgs); // The static boundary is TEXT-level (the template concatenates system // messages), so the last token(s) before / can re-merge // when the following block changes. Measure the COMMON LEADING tokens // (lcp) — exactly the prefix the engine's auto-ckpt lcp sees in the real // prompt — instead of assuming a clean special-token boundary. let static_pure = lcp(&i_static, &i_np); let static_np = lcp(&i_np, &i_full); if tool_declare_delta.is_none() { println!( " [boundary] sections render={} lcp->notepad={} (re-merge {}); pinned render={} lcp->dialog={} (re-merge {})", i_static.len(), static_pure, i_static.len() - static_pure, i_np.len(), static_np, i_np.len() - static_np ); } // Isolate tool_declare overhead once (sections rendered WITHOUT tools). if tool_declare_delta.is_none() { let no_tools = ChatRequest { model: cfg.model_name().to_string(), messages: static_msgs, ..Default::default() }; let i_nt = fmt.build_prefix_ids(&no_tools).expect("no-tools ids"); tool_declare_delta = Some(i_static.len().saturating_sub(i_nt.len())); } let title: String = sess.title.chars().take(28).collect(); println!( "{:<28} {:>8} {:>8} {:>10} {:>8} {:>6}", title, static_pure, static_np - static_pure, static_np, i_full.len(), hist.len() ); statics.push((sess.title.clone(), i_static[..static_pure].to_vec())); } if let Some(d) = tool_declare_delta { println!("\ntool_declare overhead (tools ON vs OFF, sections only): {d} tokens"); } // Cross-session common static prefix: the deepest anchor that survives a // session switch on --parallel 1 (one conversation cache). Bounded by where // session-specific content ({identity} = title/folder inside SYSTEM_PROMPT) // first diverges. if statics.len() >= 2 { let mut global = statics[0].1.clone(); let mut min_pair = usize::MAX; let mut max_pair = 0usize; for i in 0..statics.len() { for j in (i + 1)..statics.len() { let l = lcp(&statics[i].1, &statics[j].1); min_pair = min_pair.min(l); max_pair = max_pair.max(l); } let l = lcp(&global, &statics[i].1); global.truncate(l); } println!("\n=== CROSS-SESSION STATIC COMMON PREFIX ==="); println!("sessions compared: {}", statics.len()); println!("common to ALL sessions: {} tokens", global.len()); println!("pairwise min: {min_pair} pairwise max: {max_pair}"); } }