//! The context window: how big the conversation is, when to compact it, and what the next request //! carries. //! //! Pure data in, data out. [`Agent`](crate::agent::Agent) owns the provider call and the session; //! this module owns every decision about size: the token count (the provider's real reading plus an //! estimate of what was added since), the compaction trigger, and the masking schedule (old, large //! tool results become one-line stubs in the request; the session file keeps the originals). //! //! Invariants: //! - A reading and the masking boundary each describe one specific history. [`reset`](ContextWindow::reset) //! drops both; call it whenever the history is replaced or rewritten (new session, fork, clear, //! compaction). Until the next [`record`](ContextWindow::record) the count is a pure estimate. //! - The boundary only moves forward, and only once the context passes a third of the compaction //! threshold (at most [`MASK_FROM_MAX`] tokens): every move rewrites the prompt cache from the //! first changed result on, so the saving has to beat that. While it stays put the request prefix is byte-stable. use crate::mask; use hx_ai::Message; /// The messages to send for one request. #[derive(Debug, Clone)] pub struct View { pub messages: Vec, /// Masking boundary these messages were built with. Store it next to the assistant reply /// (`Session::append_masked`) so [`ContextWindow::masked`] can replay the request later. pub mask: usize, } /// Context size above which old tool results start to be masked, at most. const MASK_FROM_MAX: usize = 60_000; /// Where the compaction threshold comes from. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ContextPolicy { /// Compact above exactly this many tokens (config `compact_at`). Fixed(usize), /// Derived from the model's context window, leaving room for a reply. FromModel { window: u64 }, } pub struct ContextWindow { policy: ContextPolicy, /// Room kept free for the reply (the request's `max_tokens`). reserve: u32, /// `(real tokens, messages they covered)` from the last request. reading: Option<(usize, usize)>, /// Assistant turns whose big tool results are masked. boundary: usize, } impl ContextWindow { /// Compact once the context exceeds `compact_at` tokens. pub fn new(compact_at: usize) -> Self { Self { policy: ContextPolicy::Fixed(compact_at), reserve: 0, reading: None, boundary: 0, } } pub fn compact_at(&self) -> usize { match self.policy { ContextPolicy::Fixed(n) => n, ContextPolicy::FromModel { window } => { hx_ai::models::compact_threshold(window, self.reserve) } } } pub fn set_policy(&mut self, p: ContextPolicy) { self.policy = p; } /// Room for the reply; only matters for [`ContextPolicy::FromModel`], and any call order works. pub fn set_reserve(&mut self, tokens: u32) { self.reserve = tokens; } /// The model changed: follow its window unless the threshold is fixed. pub fn set_model_window(&mut self, window: u64) { if let ContextPolicy::FromModel { window: w } = &mut self.policy { *w = window; } } /// Context size of `msgs`: the last real reading plus an estimate of what was added since; /// a pure estimate when there is no (applicable) reading. The one number behind the compaction /// trigger and every display of it. pub fn tokens(&self, msgs: &[Message]) -> usize { match self.reading { Some((t, n)) if n <= msgs.len() => t + estimate_tokens(&msgs[n..]), _ => estimate_tokens(msgs), } } pub fn should_compact(&self, msgs: &[Message]) -> bool { self.tokens(msgs) > self.compact_at() } /// Masking starts once the context passes a third of the compaction threshold, but never later /// than `MASK_FROM_MAX` tokens: with a 1M window a third is ~300k, far beyond where old results /// already cost more to resend than one cache rewrite. // ponytail: 60k comes from two real sessions (contexts of 72k and 105k); tune with `hx stats`. fn mask_from(&self) -> usize { (self.compact_at() / 3).min(MASK_FROM_MAX) } /// What to send for the next request. Advances the masking boundary if it is due, so call it /// once per request, after any compaction. pub fn view(&mut self, msgs: Vec) -> View { let target = mask::target_boundary(&msgs); if target > self.boundary && self.tokens(&msgs) > self.mask_from() { self.boundary = target; } View { mask: self.boundary, messages: mask::mask_old_results(msgs, self.boundary), } } /// `total` real tokens (input + output) after a request; the history then held `msg_count` /// messages, the reply included. pub fn record(&mut self, total: usize, msg_count: usize) { self.reading = Some((total, msg_count)); } /// The history was replaced or rewritten: forget the reading and the masking boundary. pub fn reset(&mut self) { self.reading = None; self.boundary = 0; } /// Replay an earlier request over `msgs` (the messages before the reply). `stored` is the /// boundary recorded with the reply; files written before it was recorded used the stepwise rule. pub fn masked(msgs: &[Message], stored: Option) -> Vec { let b = stored.unwrap_or_else(|| mask::target_boundary(msgs)); mask::mask_old_results(msgs.to_vec(), b) } } /// Rough token estimate (bytes / 4). fn estimate_tokens(msgs: &[Message]) -> usize { serde_json::to_string(msgs).map_or(0, |s| s.len() / 4) } #[cfg(test)] mod tests { use super::*; use hx_ai::{ContentBlock, Role}; fn assistant_turn(i: usize, size: usize) -> [Message; 2] { [ Message { role: Role::Assistant, content: vec![ContentBlock::ToolUse { id: format!("t{i}"), name: "bash".into(), input: serde_json::json!({}), }], }, Message { role: Role::User, content: vec![ContentBlock::ToolResult { tool_use_id: format!("t{i}"), content: "x".repeat(size), is_error: false, }], }, ] } fn history(turns: usize) -> Vec { let mut v = vec![Message::user("go")]; for i in 0..turns { v.extend(assistant_turn(i, 5_000)); } v } fn elided(msgs: &[Message]) -> usize { msgs.iter() .flat_map(|m| &m.content) .filter(|b| matches!(b, ContentBlock::ToolResult { content, .. } if content.starts_with("[elided"))) .count() } #[test] fn counts_real_usage_plus_what_came_after() { let m = vec![ Message::user("x".repeat(400)), Message::user("y".repeat(40)), ]; let mut w = ContextWindow::new(1_000_000); assert_eq!(w.tokens(&m), estimate_tokens(&m)); // 1000 real tokens covered the first message; only the second is estimated w.record(1000, 1); assert_eq!(w.tokens(&m), 1000 + estimate_tokens(&m[1..])); // a reading that covers more messages than exist is stale w.record(1000, 5); assert_eq!(w.tokens(&m), estimate_tokens(&m)); } #[test] fn compaction_trigger_follows_the_threshold() { let m = history(2); let size = estimate_tokens(&m); assert!(ContextWindow::new(size - 1).should_compact(&m)); assert!(!ContextWindow::new(size).should_compact(&m)); } #[test] fn masking_waits_for_a_big_context_then_only_moves_forward() { let m = history(16); // target boundary 8 // far below a third of the threshold: nothing masked let mut w = ContextWindow::new(10_000_000); let v = w.view(m.clone()); assert_eq!((v.mask, elided(&v.messages)), (0, 0)); // past it: the first 8 big results are stubbed, and the boundary is reported let mut w = ContextWindow::new(30_000); let v = w.view(m.clone()); assert_eq!((v.mask, elided(&v.messages)), (8, 8)); // the same history again: same boundary, same bytes let again = w.view(m.clone()); assert_eq!(again.mask, 8); assert_eq!( serde_json::to_string(&again.messages).unwrap(), serde_json::to_string(&v.messages).unwrap() ); // a shorter history (target 0) does not move it back assert_eq!(w.view(history(2)).mask, 8); } #[test] fn mask_threshold_is_capped() { assert_eq!(ContextWindow::new(900_000).mask_from(), MASK_FROM_MAX); assert_eq!(ContextWindow::new(90_000).mask_from(), 30_000); } #[test] fn reset_forgets_the_reading_and_the_boundary() { let m = history(16); let mut w = ContextWindow::new(30_000); w.record(500_000, m.len()); assert_eq!(w.view(m.clone()).mask, 8); assert!(w.tokens(&m) >= 500_000); w.reset(); assert_eq!(w.tokens(&m), estimate_tokens(&m)); assert_eq!(w.view(history(2)).mask, 0, "boundary starts over"); } #[test] fn replay_uses_the_stored_boundary_or_the_stepwise_rule() { let m = history(16); assert_eq!(elided(&ContextWindow::masked(&m, Some(0))), 0); assert_eq!(elided(&ContextWindow::masked(&m, Some(4))), 4); assert_eq!(elided(&ContextWindow::masked(&m, None)), 8); } }