| 1 | //! Process-local memoization for [`crate::compaction::estimate_input_tokens_for_pressure`]. |
| 2 | //! |
| 3 | //! This is the engine's one pressure number: the same un-inflated estimate the |
| 4 | //! auto-compaction gate, the compaction preflight, the TUI context meter and |
| 5 | //! the `/context` headline read, so compaction receipts and the context-budget |
| 6 | //! snapshot agree with them (0.10.1 item 9). The 1.5x-inflated |
| 7 | //! `estimate_input_tokens_conservative` is request-overflow protection only |
| 8 | //! and is deliberately not cached here. |
| 9 | //! |
| 10 | //! The token estimator walks the full [`codewhale_models::Message`] history and the |
| 11 | //! active system prompt, which is by far the most expensive per-turn CPU cost |
| 12 | //! in the engine hot path. The same input data is queried from at least five |
| 13 | //! sites per turn: capacity pre/post tool checkpoints, error escalation, |
| 14 | //! the seam manager, and the trimmed-message budget check, plus four more |
| 15 | //! from the TUI footer, `/status`, `/debug`, and the context inspector. |
| 16 | //! |
| 17 | //! Without memoization, a 200-message history with 5 KB of tool results costs |
| 18 | //! ~2 ms per call; that is 20 ms of pure waste on a single turn. The estimator |
| 19 | //! itself is a pure function of `(messages, system_prompt)`, so a |
| 20 | //! content-versioned cache is safe: the caller bumps `messages_revision` |
| 21 | //! on every mutation, and we also include a fast fingerprint of the system |
| 22 | //! prompt as part of the key. |
| 23 | //! |
| 24 | //! The cache is process-local only — cross-session persistence is intentionally |
| 25 | //! out of scope (see PR #2520 for the cross-session prompt-base disk cache). |
| 26 | |
| 27 | use std::collections::hash_map::DefaultHasher; |
| 28 | use std::hash::{Hash, Hasher}; |
| 29 | |
| 30 | use crate::compaction::estimate_input_tokens_for_pressure; |
| 31 | use codewhale_models::{Message, SystemPrompt}; |
| 32 | |
| 33 | /// Process-local memoization for `estimate_input_tokens_for_pressure`. |
| 34 | /// |
| 35 | /// The cache is keyed on the `(messages_revision, system_fingerprint)` |
| 36 | /// pair, both of which the engine bumps on every content change. On a hit |
| 37 | /// the previously stored token estimate is returned without re-walking the |
| 38 | /// message list. On a miss, the estimator runs and the result is stored |
| 39 | /// for the next lookup. |
| 40 | #[derive(Debug, Default, Clone)] |
| 41 | pub struct TokenEstimateCache { |
| 42 | /// Monotonic counter bumped by the engine on every message mutation. |
| 43 | messages_revision: u64, |
| 44 | /// Stable 64-bit hash of the current system prompt text. Computed once |
| 45 | /// per `lookup_or_compute` call when the cache misses. |
| 46 | system_fingerprint: u64, |
| 47 | /// Cached token count, valid iff both keys match the current inputs. |
| 48 | cached_tokens: Option<usize>, |
| 49 | /// Number of cache hits since the cache was last cleared. Saturates at |
| 50 | /// `u64::MAX` (effectively never in practice). |
| 51 | hits: u64, |
| 52 | /// Number of cache misses since the cache was last cleared. |
| 53 | misses: u64, |
| 54 | } |
| 55 | |
| 56 | impl TokenEstimateCache { |
| 57 | /// Construct a fresh, empty cache. `messages_revision` defaults to 0; the |
| 58 | /// engine must call [`bump_messages_revision`](Self::bump_messages_revision) |
| 59 | /// whenever a mutation occurs so the next lookup correctly invalidates. |
| 60 | #[must_use] |
| 61 | pub fn new() -> Self { |
| 62 | Self::default() |
| 63 | } |
| 64 | |
| 65 | /// Returns the cached token estimate, recomputing on miss. |
| 66 | /// |
| 67 | /// `messages_revision` is the engine's monotonic counter; bump it on |
| 68 | /// every add/remove/clear. `system_prompt` may be `None`. `messages` is |
| 69 | /// borrowed for the duration of the call so a miss can re-tokenize. |
| 70 | pub fn lookup_or_compute( |
| 71 | &mut self, |
| 72 | messages_revision: u64, |
| 73 | system_prompt: Option<&SystemPrompt>, |
| 74 | messages: &[Message], |
| 75 | ) -> usize { |
| 76 | let system_fingerprint = fingerprint_system_prompt(system_prompt); |
| 77 | |
| 78 | if self.messages_revision == messages_revision |
| 79 | && self.system_fingerprint == system_fingerprint |
| 80 | && let Some(tokens) = self.cached_tokens |
| 81 | { |
| 82 | self.hits = self.hits.saturating_add(1); |
| 83 | return tokens; |
| 84 | } |
| 85 | |
| 86 | let tokens = estimate_input_tokens_for_pressure(messages, system_prompt); |
| 87 | self.messages_revision = messages_revision; |
| 88 | self.system_fingerprint = system_fingerprint; |
| 89 | self.cached_tokens = Some(tokens); |
| 90 | self.misses = self.misses.saturating_add(1); |
| 91 | tokens |
| 92 | } |
| 93 | |
| 94 | /// Record a messages-revision bump. The engine calls this whenever |
| 95 | /// `session.messages` is mutated. Calling it with a value smaller than |
| 96 | /// the current value is a no-op (the cache is monotonic). |
| 97 | pub fn bump_messages_revision(&mut self, revision: u64) { |
| 98 | if revision > self.messages_revision { |
| 99 | self.messages_revision = revision; |
| 100 | self.cached_tokens = None; |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | /// Forget all cached state. Used by `/clear` and session reset paths. |
| 105 | pub fn invalidate(&mut self) { |
| 106 | self.cached_tokens = None; |
| 107 | self.system_fingerprint = 0; |
| 108 | self.hits = 0; |
| 109 | self.misses = 0; |
| 110 | } |
| 111 | |
| 112 | /// Returns `(hits, misses)` counters since the last `invalidate` call. |
| 113 | #[must_use] |
| 114 | pub fn stats(&self) -> (u64, u64) { |
| 115 | (self.hits, self.misses) |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | /// Stable 64-bit hash of the system prompt text. Walks the same shape the |
| 120 | /// estimator consumes: a `Text` variant or a list of `Blocks`. Returns 0 |
| 121 | /// for `None` so the empty case is distinguishable but cheap to compare. |
| 122 | fn fingerprint_system_prompt(system: Option<&SystemPrompt>) -> u64 { |
| 123 | let Some(system) = system else { |
| 124 | return 0; |
| 125 | }; |
| 126 | let mut hasher = DefaultHasher::new(); |
| 127 | match system { |
| 128 | SystemPrompt::Text(text) => { |
| 129 | "text".hash(&mut hasher); |
| 130 | text.hash(&mut hasher); |
| 131 | } |
| 132 | SystemPrompt::Blocks(blocks) => { |
| 133 | "blocks".hash(&mut hasher); |
| 134 | blocks.len().hash(&mut hasher); |
| 135 | for block in blocks { |
| 136 | block.block_type.hash(&mut hasher); |
| 137 | block.text.hash(&mut hasher); |
| 138 | } |
| 139 | } |
| 140 | } |
| 141 | hasher.finish() |
| 142 | } |
| 143 | |
| 144 | #[cfg(test)] |
| 145 | mod tests { |
| 146 | use super::*; |
| 147 | use codewhale_models::Role; |
| 148 | use codewhale_models::{ContentBlock, SystemBlock}; |
| 149 | |
| 150 | fn user_text(s: &str) -> Message { |
| 151 | Message { |
| 152 | role: Role::User, |
| 153 | content: vec![ContentBlock::Text { |
| 154 | text: s.to_string(), |
| 155 | cache_control: None, |
| 156 | }], |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | fn sys_text(s: &str) -> SystemPrompt { |
| 161 | SystemPrompt::Text(s.to_string()) |
| 162 | } |
| 163 | |
| 164 | #[test] |
| 165 | fn first_call_is_a_miss() { |
| 166 | let mut cache = TokenEstimateCache::new(); |
| 167 | let messages = vec![user_text("hello world")]; |
| 168 | let tokens = cache.lookup_or_compute(1, None, &messages); |
| 169 | let (hits, misses) = cache.stats(); |
| 170 | assert!(tokens > 0); |
| 171 | assert_eq!(hits, 0); |
| 172 | assert_eq!(misses, 1); |
| 173 | } |
| 174 | |
| 175 | #[test] |
| 176 | fn repeated_call_with_same_revision_is_a_hit() { |
| 177 | let mut cache = TokenEstimateCache::new(); |
| 178 | let messages = vec![user_text("hello world")]; |
| 179 | let _ = cache.lookup_or_compute(1, None, &messages); |
| 180 | let _ = cache.lookup_or_compute(1, None, &messages); |
| 181 | let (hits, misses) = cache.stats(); |
| 182 | assert_eq!(hits, 1); |
| 183 | assert_eq!(misses, 1); |
| 184 | } |
| 185 | |
| 186 | #[test] |
| 187 | fn revision_bump_invalidates() { |
| 188 | let mut cache = TokenEstimateCache::new(); |
| 189 | let messages = vec![user_text("hi")]; |
| 190 | let a = cache.lookup_or_compute(1, None, &messages); |
| 191 | let b = cache.lookup_or_compute(2, None, &messages); |
| 192 | let (hits, misses) = cache.stats(); |
| 193 | // Both calls were misses (different revisions), neither hit the cache. |
| 194 | assert_eq!(a, b); |
| 195 | assert_eq!(hits, 0); |
| 196 | assert_eq!(misses, 2); |
| 197 | } |
| 198 | |
| 199 | #[test] |
| 200 | fn system_prompt_change_invalidates() { |
| 201 | let mut cache = TokenEstimateCache::new(); |
| 202 | let messages = vec![user_text("hi")]; |
| 203 | let _ = cache.lookup_or_compute(1, Some(&sys_text("alpha")), &messages); |
| 204 | let _ = cache.lookup_or_compute(1, Some(&sys_text("beta")), &messages); |
| 205 | let (hits, misses) = cache.stats(); |
| 206 | assert_eq!(hits, 0); |
| 207 | assert_eq!(misses, 2); |
| 208 | } |
| 209 | |
| 210 | #[test] |
| 211 | fn bump_messages_revision_clears_cache() { |
| 212 | let mut cache = TokenEstimateCache::new(); |
| 213 | let messages = vec![user_text("x")]; |
| 214 | let _ = cache.lookup_or_compute(1, None, &messages); |
| 215 | cache.bump_messages_revision(2); |
| 216 | let _ = cache.lookup_or_compute(2, None, &messages); |
| 217 | let (hits, misses) = cache.stats(); |
| 218 | assert_eq!(hits, 0); |
| 219 | assert_eq!(misses, 2); |
| 220 | } |
| 221 | |
| 222 | #[test] |
| 223 | fn bump_to_smaller_revision_is_noop() { |
| 224 | let mut cache = TokenEstimateCache::new(); |
| 225 | let messages = vec![user_text("x")]; |
| 226 | let _ = cache.lookup_or_compute(5, None, &messages); |
| 227 | cache.bump_messages_revision(2); |
| 228 | // revision went down, cache should still be valid for revision 5 |
| 229 | let _ = cache.lookup_or_compute(5, None, &messages); |
| 230 | let (hits, _) = cache.stats(); |
| 231 | assert_eq!(hits, 1, "downward revision bumps must not invalidate"); |
| 232 | } |
| 233 | |
| 234 | #[test] |
| 235 | fn invalidate_resets_state() { |
| 236 | let mut cache = TokenEstimateCache::new(); |
| 237 | let messages = vec![user_text("x")]; |
| 238 | let _ = cache.lookup_or_compute(1, None, &messages); |
| 239 | let _ = cache.lookup_or_compute(1, None, &messages); |
| 240 | cache.invalidate(); |
| 241 | let (hits, misses) = cache.stats(); |
| 242 | assert_eq!(hits, 0); |
| 243 | assert_eq!(misses, 0); |
| 244 | } |
| 245 | |
| 246 | #[test] |
| 247 | fn blocks_system_prompt_yields_distinct_fingerprint() { |
| 248 | let blocks_a = SystemPrompt::Blocks(vec![SystemBlock { |
| 249 | block_type: "text".to_string(), |
| 250 | text: "alpha".to_string(), |
| 251 | cache_control: None, |
| 252 | }]); |
| 253 | let blocks_b = SystemPrompt::Blocks(vec![SystemBlock { |
| 254 | block_type: "text".to_string(), |
| 255 | text: "beta".to_string(), |
| 256 | cache_control: None, |
| 257 | }]); |
| 258 | let mut cache = TokenEstimateCache::new(); |
| 259 | let messages = vec![user_text("hi")]; |
| 260 | let _ = cache.lookup_or_compute(1, Some(&blocks_a), &messages); |
| 261 | let _ = cache.lookup_or_compute(1, Some(&blocks_b), &messages); |
| 262 | let (hits, misses) = cache.stats(); |
| 263 | assert_eq!(hits, 0); |
| 264 | assert_eq!(misses, 2); |
| 265 | } |
| 266 | } |
| 267 |