| 1 | //! Prefix-cache stability manager (inspired by Reasonix's Pillar 1). |
| 2 | //! |
| 3 | //! DeepSeek's automatic prefix caching activates only when the *exact* |
| 4 | //! byte prefix of a request matches the prior request. Any system-prompt |
| 5 | //! drift, tool-list reordering, or message-rewriting busts the cache |
| 6 | //! for every token after the changed byte. |
| 7 | //! |
| 8 | //! This module provides a `PrefixStabilityManager` that: |
| 9 | //! |
| 10 | //! 1. **Fingerprints** the immutable prefix (system prompt + tool specs) |
| 11 | //! at session start, using SHA-256 for strong collision resistance. |
| 12 | //! 2. **Verifies** the current prefix against the pinned fingerprint before |
| 13 | //! every request. |
| 14 | //! 3. **Attributes** every change: a header change the engine declared |
| 15 | //! (`/model`, `/mode`, goal edits, MCP or deferred-tool activation, |
| 16 | //! session sync) re-pins under a logged reason; an undeclared change is |
| 17 | //! *drift* — it is recorded and reported, and the original pin stays so |
| 18 | //! later checks keep counting the miss instead of quietly adopting it. |
| 19 | //! 4. **Emits events** so the TUI can surface stability to the user. |
| 20 | //! |
| 21 | //! The invariant this guards: after session start, system and tools are |
| 22 | //! frozen bytes; history only grows; a miss is allowed only when we log why. |
| 23 | //! |
| 24 | //! ## Three-region model (from Reasonix) |
| 25 | //! |
| 26 | //! ```text |
| 27 | //! ┌─────────────────────────────────────────┐ |
| 28 | //! │ IMMUTABLE PREFIX │ ← fixed for session |
| 29 | //! │ system + tool_specs │ cache hit candidate |
| 30 | //! ├─────────────────────────────────────────┤ |
| 31 | //! │ APPEND-ONLY HISTORY │ ← grows monotonically |
| 32 | //! │ [assistant₁][tool₁][assistant₂]... │ preserves prefix of prior turns |
| 33 | //! ├─────────────────────────────────────────┤ |
| 34 | //! │ LATEST USER TURN │ ← the only new content per request |
| 35 | //! └─────────────────────────────────────────┘ |
| 36 | //! ``` |
| 37 | |
| 38 | use std::collections::hash_map::DefaultHasher; |
| 39 | use std::collections::{HashMap, VecDeque}; |
| 40 | use std::hash::{Hash, Hasher}; |
| 41 | |
| 42 | use serde::{Deserialize, Serialize}; |
| 43 | |
| 44 | use crate::request::{SystemPrompt, Tool}; |
| 45 | |
| 46 | /// A snapshot of the immutable prefix's fingerprint. |
| 47 | /// |
| 48 | /// Matching hashes show stable system text and the normalized OpenAI-style |
| 49 | /// tool catalog. They do not measure provider cache hits or fingerprint every |
| 50 | /// provider-specific wire transformation; request replay tests cover those. |
| 51 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 52 | pub struct PrefixFingerprint { |
| 53 | /// SHA-256 of the system prompt text. |
| 54 | pub system_sha256: String, |
| 55 | /// SHA-256 of the full tool catalog JSON (names, descriptions, schemas). |
| 56 | pub tools_sha256: String, |
| 57 | /// SHA-256 of system_sha256 ++ tools_sha256 (combined). |
| 58 | pub combined_sha256: String, |
| 59 | } |
| 60 | |
| 61 | impl PrefixFingerprint { |
| 62 | /// Compute a fingerprint from system prompt text and tool list. |
| 63 | /// |
| 64 | /// Tools are serialized to the same JSON shape the chat API receives |
| 65 | /// (`type`, `name`, `description`, `parameters`, `strict`) **in provider |
| 66 | /// wire order**, then SHA-256 hashed. Order is load-bearing: the provider |
| 67 | /// KV cache is order-sensitive, so sorting before hashing could read a |
| 68 | /// false-green while the real prefix cache misses every turn (ops C1, |
| 69 | /// DSH invariant). This also catches schema/description drift that |
| 70 | /// actually affects the API prefix, while ignoring internal-only fields |
| 71 | /// like `allowed_callers` (#2264). |
| 72 | /// |
| 73 | /// This entry point shares a process-local [`ToolCatalogCache`] with |
| 74 | /// every other call, so a stable tool set (the common case after the |
| 75 | /// first turn of a session) avoids the per-tool JSON serialization |
| 76 | /// and join entirely. Callers that hold their own cache — e.g. |
| 77 | /// [`PrefixStabilityManager`] — should use |
| 78 | /// [`Self::compute_with_tool_cache`] to share *that* cache instead |
| 79 | /// and avoid the thread-local lookup. |
| 80 | #[cfg(test)] |
| 81 | pub fn compute(system_text: &str, tools: Option<&[Tool]>) -> Self { |
| 82 | let mut cache = ToolCatalogCache::new(); |
| 83 | Self::compute_with_tool_cache(system_text, tools, &mut cache) |
| 84 | } |
| 85 | |
| 86 | /// Compute a fingerprint while reusing a [`ToolCatalogCache`] for the |
| 87 | /// tool-side work. The cache holds the joined+SHA-256'd catalog |
| 88 | /// under a content-derived identity so the per-tool JSON serialization |
| 89 | /// and the join only run on the first call for a given tool set. |
| 90 | /// |
| 91 | /// On a cache hit this function avoids the entire tool serialization |
| 92 | /// path, which can be 100+ microseconds for a 60-tool catalog. |
| 93 | pub fn compute_with_tool_cache( |
| 94 | system_text: &str, |
| 95 | tools: Option<&[Tool]>, |
| 96 | cache: &mut ToolCatalogCache, |
| 97 | ) -> Self { |
| 98 | let system_sha256 = sha256_hex(system_text.as_bytes()); |
| 99 | |
| 100 | let tools_sha256 = match tools { |
| 101 | Some(tools) if !tools.is_empty() => { |
| 102 | // `fingerprint_for` consults the cache first; on a hit |
| 103 | // it returns the pre-computed hex digest directly. |
| 104 | cache.fingerprint_for(tools).sha256_hex |
| 105 | } |
| 106 | _ => sha256_hex(b""), |
| 107 | }; |
| 108 | |
| 109 | let combined = format!("{system_sha256}:{tools_sha256}"); |
| 110 | let combined_sha256 = sha256_hex(combined.as_bytes()); |
| 111 | Self { |
| 112 | system_sha256, |
| 113 | tools_sha256, |
| 114 | combined_sha256, |
| 115 | } |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | /// A change record describing what drifted in the prefix. |
| 120 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 121 | pub struct PrefixChange { |
| 122 | /// The old fingerprint (before the change). |
| 123 | pub old: PrefixFingerprint, |
| 124 | /// The new fingerprint (after the change). |
| 125 | pub new: PrefixFingerprint, |
| 126 | /// Whether the system prompt component changed. |
| 127 | pub system_changed: bool, |
| 128 | /// Whether the tool set component changed. |
| 129 | pub tools_changed: bool, |
| 130 | } |
| 131 | |
| 132 | impl PrefixChange { |
| 133 | /// Returns a human-readable description of what changed. |
| 134 | pub fn description(&self) -> String { |
| 135 | let mut parts = Vec::new(); |
| 136 | if self.system_changed { |
| 137 | parts.push("system prompt"); |
| 138 | } |
| 139 | if self.tools_changed { |
| 140 | parts.push("tool set"); |
| 141 | } |
| 142 | if parts.is_empty() { |
| 143 | return "unknown (fingerprint mismatch but no component detected)".to_string(); |
| 144 | } |
| 145 | format!("prefix cache invalidated: {} changed", parts.join(" and ")) |
| 146 | } |
| 147 | |
| 148 | /// Returns a short label for TUI chip display. |
| 149 | pub fn label(&self) -> &'static str { |
| 150 | if self.system_changed && self.tools_changed { |
| 151 | "sys+tools" |
| 152 | } else if self.system_changed { |
| 153 | "sys" |
| 154 | } else if self.tools_changed { |
| 155 | "tools" |
| 156 | } else { |
| 157 | "prefix" |
| 158 | } |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | /// Monitors and manages prefix-cache stability across turns. |
| 163 | /// |
| 164 | /// This is the core abstraction, mirroring Reasonix's `ImmutablePrefix` |
| 165 | /// concept but adapted to CodeWhale's existing architecture where the |
| 166 | /// system prompt is rebuilt each turn and tools are registered at startup. |
| 167 | /// |
| 168 | /// Usage: |
| 169 | /// ```ignore |
| 170 | /// let mgr = PrefixStabilityManager::new(system_text, tools); |
| 171 | /// if mgr.check_and_update(system_text, tools) { |
| 172 | /// println!("Prefix is stable (cache-friendly)"); |
| 173 | /// } else { |
| 174 | /// let change = mgr.last_change().unwrap(); |
| 175 | /// println!("Prefix drifted: {}", change.description()); |
| 176 | /// } |
| 177 | /// ``` |
| 178 | #[derive(Debug, Clone)] |
| 179 | pub struct PrefixStabilityManager { |
| 180 | /// The pinned fingerprint from session start or last stabilization. |
| 181 | pinned: Option<PrefixFingerprint>, |
| 182 | /// The most recent fingerprint (computed during last check). |
| 183 | current: Option<PrefixFingerprint>, |
| 184 | /// The last detected change, if any. |
| 185 | last_change: Option<PrefixChange>, |
| 186 | /// Total number of prefix changes detected this session. |
| 187 | change_count: u64, |
| 188 | /// Total number of stability checks performed. |
| 189 | check_count: u64, |
| 190 | /// Why the current pin exists: `initial`, `resume`, or `change:<what>`. |
| 191 | pin_reason: Option<String>, |
| 192 | /// Bounded log of every attributed change and every undeclared drift. |
| 193 | history: VecDeque<PrefixHistoryEntry>, |
| 194 | /// Explanation of the most recent expected cache miss (a declared header |
| 195 | /// change, a history reset such as compaction, or undeclared drift). |
| 196 | last_miss_reason: Option<String>, |
| 197 | /// `<context_update>` snapshots appended this session (workspace drift |
| 198 | /// delivered as history, with the pinned header untouched). |
| 199 | context_update_count: u64, |
| 200 | /// Process-local cache for the tool-catalog JSON serialization. Avoids |
| 201 | /// re-running `logical_tool_fingerprint_json` + join on every `check_and_update` |
| 202 | /// when the tool set is unchanged (the common case once tools are |
| 203 | /// registered at session start). |
| 204 | tool_catalog_cache: ToolCatalogCache, |
| 205 | } |
| 206 | |
| 207 | /// Maximum retained [`PrefixHistoryEntry`] records per session. |
| 208 | const PREFIX_HISTORY_CAP: usize = 32; |
| 209 | |
| 210 | /// One attributed prefix event: a declared header change (re-pinned) or an |
| 211 | /// undeclared drift (pin kept). |
| 212 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 213 | pub struct PrefixHistoryEntry { |
| 214 | /// `change:<what>` for declared header changes, `drift:<component>` for |
| 215 | /// undeclared changes, `reset:<what>` for history resets. |
| 216 | pub reason: String, |
| 217 | /// Whether the pin was replaced by this event. |
| 218 | pub repinned: bool, |
| 219 | /// Combined SHA-256 before the event. |
| 220 | pub from_sha256: String, |
| 221 | /// Combined SHA-256 the request actually carried. |
| 222 | pub to_sha256: String, |
| 223 | } |
| 224 | |
| 225 | /// Outcome of [`PrefixStabilityManager::check`]. |
| 226 | #[derive(Debug, Clone)] |
| 227 | pub enum PrefixCheck { |
| 228 | /// The request prefix matches the pin byte-for-byte. |
| 229 | Stable, |
| 230 | /// The prefix changed and the engine declared why; the pin moved. |
| 231 | Repinned { |
| 232 | reason: String, |
| 233 | change: PrefixChange, |
| 234 | }, |
| 235 | /// The prefix changed with no declared reason. The pin did NOT move. |
| 236 | Drift { change: PrefixChange }, |
| 237 | } |
| 238 | |
| 239 | /// Default capacity for the tool-catalog serialization cache. Sized for |
| 240 | /// "session + 1 or 2 forked subagent catalogs" without unbounded growth. |
| 241 | const TOOL_CATALOG_CACHE_CAPACITY: usize = 8; |
| 242 | |
| 243 | /// Bounded LRU cache of `(tool_set_identity) -> sha256_hex`. |
| 244 | /// |
| 245 | /// The cache key is a content-derived `u64` hash of the tool list (length + |
| 246 | /// per-tool `name` + `description` + serialized `input_schema`). On a hit, |
| 247 | /// `PrefixFingerprint::compute` skips the per-tool JSON serialization and |
| 248 | /// the join — a workload that can be 100+ microseconds for a |
| 249 | /// 60-tool catalog. On a miss, the work runs once and only the digest is |
| 250 | /// retained (#3854); the joined catalog string is ephemeral. |
| 251 | #[derive(Debug, Default, Clone)] |
| 252 | pub struct ToolCatalogCache { |
| 253 | by_identity: HashMap<u64, CachedCatalog>, |
| 254 | insertion_order: VecDeque<u64>, |
| 255 | capacity: usize, |
| 256 | } |
| 257 | |
| 258 | /// One entry in [`ToolCatalogCache`]. Production only needs the pre-computed |
| 259 | /// SHA-256 digest of the in-order joined catalog. |
| 260 | #[derive(Debug, Clone)] |
| 261 | pub struct CachedCatalog { |
| 262 | /// SHA-256 hex digest of the newline-joined, in-order tool-catalog JSON. |
| 263 | pub sha256_hex: String, |
| 264 | } |
| 265 | |
| 266 | impl ToolCatalogCache { |
| 267 | /// Create a cache with the default capacity. |
| 268 | #[must_use] |
| 269 | pub fn new() -> Self { |
| 270 | Self::with_capacity(TOOL_CATALOG_CACHE_CAPACITY) |
| 271 | } |
| 272 | |
| 273 | /// Create a cache that holds at most `capacity` tool-set entries. |
| 274 | /// Smaller values save memory at the cost of more cache misses. |
| 275 | #[must_use] |
| 276 | pub fn with_capacity(capacity: usize) -> Self { |
| 277 | let cap = capacity.max(1); |
| 278 | Self { |
| 279 | by_identity: HashMap::with_capacity(cap), |
| 280 | insertion_order: VecDeque::with_capacity(cap), |
| 281 | capacity: cap, |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | /// Compute (or recall) the joined-and-hashed tool catalog for `tools`. |
| 286 | /// The cache is keyed on a content-derived `u64` identity so two `&[Tool]` |
| 287 | /// slices with the same payloads — in the same order — hit the same entry. |
| 288 | pub fn fingerprint_for(&mut self, tools: &[Tool]) -> CachedCatalog { |
| 289 | let identity = tool_set_identity(tools); |
| 290 | if let Some(cached) = self.by_identity.get(&identity) { |
| 291 | return cached.clone(); |
| 292 | } |
| 293 | |
| 294 | // Miss: serialize, join, hash — in wire order, never sorted. The |
| 295 | // provider cache is order-sensitive; a sorted fingerprint can say |
| 296 | // "stable" while the real prefix misses every turn (ops C1). Keep |
| 297 | // only the digest in the cache — the joined string is not needed on |
| 298 | // the hot path (#3854). |
| 299 | let serialized: Vec<String> = tools |
| 300 | .iter() |
| 301 | .filter_map(logical_tool_fingerprint_json) |
| 302 | .collect(); |
| 303 | let joined = serialized.join("\n"); |
| 304 | let entry = CachedCatalog { |
| 305 | sha256_hex: sha256_hex(joined.as_bytes()), |
| 306 | }; |
| 307 | |
| 308 | if self.by_identity.len() >= self.capacity |
| 309 | && let Some(oldest) = self.insertion_order.pop_front() |
| 310 | { |
| 311 | self.by_identity.remove(&oldest); |
| 312 | } |
| 313 | self.by_identity.insert(identity, entry.clone()); |
| 314 | self.insertion_order.push_back(identity); |
| 315 | entry |
| 316 | } |
| 317 | |
| 318 | /// Drop every cached entry. Used by tool-registry mutation paths |
| 319 | /// (e.g. plugin hot-reload, MCP attach) when the caller cannot |
| 320 | /// easily prove the tool set is unchanged. |
| 321 | pub fn invalidate(&mut self) { |
| 322 | self.by_identity.clear(); |
| 323 | self.insertion_order.clear(); |
| 324 | } |
| 325 | |
| 326 | /// Returns the number of cached entries. |
| 327 | #[must_use] |
| 328 | pub fn len(&self) -> usize { |
| 329 | self.by_identity.len() |
| 330 | } |
| 331 | |
| 332 | /// Returns `true` if the cache has no entries. |
| 333 | #[must_use] |
| 334 | pub fn is_empty(&self) -> bool { |
| 335 | self.by_identity.is_empty() |
| 336 | } |
| 337 | |
| 338 | /// Returns `(current_entries, capacity)` for observability. Surfaced via |
| 339 | /// the `/status` chip in a follow-up; tests exercise the path. |
| 340 | #[must_use] |
| 341 | pub fn stats(&self) -> (usize, usize) { |
| 342 | (self.len(), self.capacity) |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | /// Content-derived identity for a tool slice. Order-sensitive: two slices |
| 347 | /// with the same tools in different orders produce different identities. |
| 348 | /// (The downstream fingerprint itself is order-insensitive — the sort in |
| 349 | /// `fingerprint_for` takes care of that — but the cache key matches the |
| 350 | /// input order so re-registration of the same set in the same order hits.) |
| 351 | fn tool_set_identity(tools: &[Tool]) -> u64 { |
| 352 | let mut hasher = DefaultHasher::new(); |
| 353 | tools.len().hash(&mut hasher); |
| 354 | for tool in tools { |
| 355 | tool.name.hash(&mut hasher); |
| 356 | tool.description.hash(&mut hasher); |
| 357 | // `strict` participates in `logical_tool_fingerprint_json` output (it is |
| 358 | // logical catalog intent), so it MUST be part of the |
| 359 | // identity. Omitting it lets two semantically different catalogs |
| 360 | // collide and serve a stale fingerprint. |
| 361 | tool.strict.hash(&mut hasher); |
| 362 | // Walk the schema JSON directly instead of materializing it as a |
| 363 | // String. For a 60-tool catalog this saves ~25-40 KB of allocation |
| 364 | // on every cache miss. |
| 365 | hash_json_value(&tool.input_schema, &mut hasher); |
| 366 | } |
| 367 | hasher.finish() |
| 368 | } |
| 369 | |
| 370 | /// Fold a `serde_json::Value` into the hasher without allocating a |
| 371 | /// `String`. Numeric variants are hashed via their bit pattern so `1` and |
| 372 | /// `1.0` produce distinct identities (matching the JSON spec). |
| 373 | fn hash_json_value<H: Hasher>(value: &serde_json::Value, state: &mut H) { |
| 374 | match value { |
| 375 | serde_json::Value::Null => 0u8.hash(state), |
| 376 | serde_json::Value::Bool(b) => { |
| 377 | 1u8.hash(state); |
| 378 | b.hash(state); |
| 379 | } |
| 380 | serde_json::Value::Number(n) => { |
| 381 | 2u8.hash(state); |
| 382 | if let Some(i) = n.as_i64() { |
| 383 | i.hash(state); |
| 384 | } else if let Some(u) = n.as_u64() { |
| 385 | u.hash(state); |
| 386 | } else if let Some(f) = n.as_f64() { |
| 387 | f.to_bits().hash(state); |
| 388 | } |
| 389 | } |
| 390 | serde_json::Value::String(s) => { |
| 391 | 3u8.hash(state); |
| 392 | s.hash(state); |
| 393 | } |
| 394 | serde_json::Value::Array(arr) => { |
| 395 | 4u8.hash(state); |
| 396 | arr.len().hash(state); |
| 397 | for v in arr { |
| 398 | hash_json_value(v, state); |
| 399 | } |
| 400 | } |
| 401 | serde_json::Value::Object(obj) => { |
| 402 | 5u8.hash(state); |
| 403 | obj.len().hash(state); |
| 404 | // Iterate by sorted key so `{"a":1,"b":2}` and `{"b":2,"a":1}` |
| 405 | // collide — the wire format already canonicalizes via the |
| 406 | // `serde_json` Map ordering, but a defensively-sorted view |
| 407 | // future-proofs against schema serializers that emit |
| 408 | // declaration order. |
| 409 | let mut entries: Vec<(&String, &serde_json::Value)> = obj.iter().collect(); |
| 410 | entries.sort_by(|a, b| a.0.cmp(b.0)); |
| 411 | for (k, v) in entries { |
| 412 | k.hash(state); |
| 413 | hash_json_value(v, state); |
| 414 | } |
| 415 | } |
| 416 | } |
| 417 | } |
| 418 | |
| 419 | /// Process-local fallback cache used by `PrefixFingerprint::compute` |
| 420 | /// (when available). Callers that maintain their own cache (e.g. |
| 421 | /// [`PrefixStabilityManager`]) should prefer |
| 422 | /// [`PrefixFingerprint::compute_with_tool_cache`] and pass the cache in |
| 423 | /// directly, both to share state and to avoid the thread-local lookup |
| 424 | /// on the hot path. |
| 425 | impl PrefixStabilityManager { |
| 426 | /// Create a new manager and immediately pin the first fingerprint. |
| 427 | pub fn new(system_text: &str, tools: Option<&[Tool]>) -> Self { |
| 428 | let mut cache = ToolCatalogCache::new(); |
| 429 | let fp = PrefixFingerprint::compute_with_tool_cache(system_text, tools, &mut cache); |
| 430 | Self { |
| 431 | pinned: Some(fp.clone()), |
| 432 | current: Some(fp), |
| 433 | last_change: None, |
| 434 | change_count: 0, |
| 435 | check_count: 0, |
| 436 | pin_reason: Some("initial".to_string()), |
| 437 | history: VecDeque::new(), |
| 438 | last_miss_reason: None, |
| 439 | context_update_count: 0, |
| 440 | tool_catalog_cache: cache, |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | /// Create a manager in "unpinned" state — no initial fingerprint. |
| 445 | /// Call `pin()` or `check_and_update()` to establish the baseline. |
| 446 | pub fn new_unpinned() -> Self { |
| 447 | Self { |
| 448 | pinned: None, |
| 449 | current: None, |
| 450 | last_change: None, |
| 451 | change_count: 0, |
| 452 | check_count: 0, |
| 453 | pin_reason: None, |
| 454 | history: VecDeque::new(), |
| 455 | last_miss_reason: None, |
| 456 | context_update_count: 0, |
| 457 | tool_catalog_cache: ToolCatalogCache::new(), |
| 458 | } |
| 459 | } |
| 460 | |
| 461 | /// Explicitly pin a fingerprint, replacing any prior pinned state. |
| 462 | /// Returns `true` if this is the first pin, or `false` if replacing. |
| 463 | /// Note: does NOT increment `check_count` — that counter is reserved |
| 464 | /// for `check_and_update` calls so `stability_ratio()` stays accurate. |
| 465 | pub fn pin(&mut self, system_text: &str, tools: Option<&[Tool]>) -> bool { |
| 466 | self.pin_with_reason(system_text, tools, "initial") |
| 467 | } |
| 468 | |
| 469 | /// Pin under an explicit reason (`initial`, `resume`, `change:<what>`). |
| 470 | pub fn pin_with_reason( |
| 471 | &mut self, |
| 472 | system_text: &str, |
| 473 | tools: Option<&[Tool]>, |
| 474 | reason: &str, |
| 475 | ) -> bool { |
| 476 | let fp = PrefixFingerprint::compute_with_tool_cache( |
| 477 | system_text, |
| 478 | tools, |
| 479 | &mut self.tool_catalog_cache, |
| 480 | ); |
| 481 | let was_unpinned = self.pinned.is_none(); |
| 482 | self.pinned = Some(fp.clone()); |
| 483 | self.current = Some(fp); |
| 484 | self.pin_reason = Some(reason.to_string()); |
| 485 | was_unpinned |
| 486 | } |
| 487 | |
| 488 | /// Record an expected miss that is not a header change (compaction, |
| 489 | /// `/clear`, an edited turn). The pin is untouched; the reason is kept so |
| 490 | /// `/cache stats` can explain the next low hit-rate turn. |
| 491 | pub fn note_history_reset(&mut self, what: &str) { |
| 492 | let hash = self |
| 493 | .pinned |
| 494 | .as_ref() |
| 495 | .map(|fp| fp.combined_sha256.clone()) |
| 496 | .unwrap_or_default(); |
| 497 | self.push_history(PrefixHistoryEntry { |
| 498 | reason: format!("reset:{what}"), |
| 499 | repinned: false, |
| 500 | from_sha256: hash.clone(), |
| 501 | to_sha256: hash, |
| 502 | }); |
| 503 | self.last_miss_reason = Some(format!("reset:{what}")); |
| 504 | } |
| 505 | |
| 506 | /// Record that workspace drift was delivered as a `<context_update>` |
| 507 | /// history append. Not a miss: the pin and the prefix are unchanged. |
| 508 | pub fn note_context_update(&mut self) { |
| 509 | self.context_update_count = self.context_update_count.saturating_add(1); |
| 510 | let hash = self |
| 511 | .pinned |
| 512 | .as_ref() |
| 513 | .map(|fp| fp.combined_sha256.clone()) |
| 514 | .unwrap_or_default(); |
| 515 | self.push_history(PrefixHistoryEntry { |
| 516 | reason: "context_update".to_string(), |
| 517 | repinned: false, |
| 518 | from_sha256: hash.clone(), |
| 519 | to_sha256: hash, |
| 520 | }); |
| 521 | } |
| 522 | |
| 523 | /// Number of `<context_update>` snapshots appended this session. |
| 524 | pub fn context_update_count(&self) -> u64 { |
| 525 | self.context_update_count |
| 526 | } |
| 527 | |
| 528 | fn push_history(&mut self, entry: PrefixHistoryEntry) { |
| 529 | if self.history.len() >= PREFIX_HISTORY_CAP { |
| 530 | self.history.pop_front(); |
| 531 | } |
| 532 | self.history.push_back(entry); |
| 533 | } |
| 534 | |
| 535 | /// Verify the request prefix against the pin, attributing any change. |
| 536 | /// |
| 537 | /// `declared_change` names a header change the engine performed on |
| 538 | /// purpose (`model`, `mode`, `goal`, `tools:+web_fetch`, `mcp`, …). When |
| 539 | /// the prefix changed and a reason is declared, the pin moves and the |
| 540 | /// change is logged as `change:<reason>`. When it changed with no |
| 541 | /// declared reason, that is drift: it is logged as `drift:<component>` |
| 542 | /// and the pin stays put, so the same undeclared prefix keeps counting as |
| 543 | /// a miss instead of becoming the new baseline. |
| 544 | pub fn check( |
| 545 | &mut self, |
| 546 | system_text: &str, |
| 547 | tools: Option<&[Tool]>, |
| 548 | declared_change: Option<&str>, |
| 549 | ) -> PrefixCheck { |
| 550 | let fp = PrefixFingerprint::compute_with_tool_cache( |
| 551 | system_text, |
| 552 | tools, |
| 553 | &mut self.tool_catalog_cache, |
| 554 | ); |
| 555 | let old_fp = self.current.replace(fp.clone()); |
| 556 | self.check_count += 1; |
| 557 | |
| 558 | let pinned = match &self.pinned { |
| 559 | Some(p) => p.clone(), |
| 560 | None => { |
| 561 | self.pinned = Some(fp); |
| 562 | self.pin_reason = Some(declared_change.unwrap_or("initial").to_string()); |
| 563 | self.last_change = None; |
| 564 | return PrefixCheck::Stable; |
| 565 | } |
| 566 | }; |
| 567 | |
| 568 | if fp.combined_sha256 == pinned.combined_sha256 { |
| 569 | return PrefixCheck::Stable; |
| 570 | } |
| 571 | |
| 572 | let old = old_fp.unwrap_or_else(|| pinned.clone()); |
| 573 | let system_changed = fp.system_sha256 != pinned.system_sha256; |
| 574 | let tools_changed = fp.tools_sha256 != pinned.tools_sha256; |
| 575 | let change = PrefixChange { |
| 576 | old, |
| 577 | new: fp.clone(), |
| 578 | system_changed, |
| 579 | tools_changed, |
| 580 | }; |
| 581 | self.last_change = Some(change.clone()); |
| 582 | self.change_count += 1; |
| 583 | |
| 584 | match declared_change { |
| 585 | Some(reason) => { |
| 586 | let reason = format!("change:{reason}"); |
| 587 | self.push_history(PrefixHistoryEntry { |
| 588 | reason: reason.clone(), |
| 589 | repinned: true, |
| 590 | from_sha256: pinned.combined_sha256.clone(), |
| 591 | to_sha256: fp.combined_sha256.clone(), |
| 592 | }); |
| 593 | self.last_miss_reason = Some(reason.clone()); |
| 594 | self.pinned = Some(fp); |
| 595 | self.pin_reason = Some(reason.clone()); |
| 596 | PrefixCheck::Repinned { reason, change } |
| 597 | } |
| 598 | None => { |
| 599 | let reason = format!("drift:{}", change.label()); |
| 600 | self.push_history(PrefixHistoryEntry { |
| 601 | reason: reason.clone(), |
| 602 | repinned: false, |
| 603 | from_sha256: pinned.combined_sha256.clone(), |
| 604 | to_sha256: fp.combined_sha256.clone(), |
| 605 | }); |
| 606 | self.last_miss_reason = Some(reason); |
| 607 | PrefixCheck::Drift { change } |
| 608 | } |
| 609 | } |
| 610 | } |
| 611 | |
| 612 | /// Why the current pin exists. |
| 613 | pub fn pin_reason(&self) -> Option<&str> { |
| 614 | self.pin_reason.as_deref() |
| 615 | } |
| 616 | |
| 617 | /// Attributed change/drift/reset history, oldest first. |
| 618 | pub fn history(&self) -> impl Iterator<Item = &PrefixHistoryEntry> { |
| 619 | self.history.iter() |
| 620 | } |
| 621 | |
| 622 | /// Explanation of the most recent expected miss, if any. |
| 623 | pub fn last_miss_reason(&self) -> Option<&str> { |
| 624 | self.last_miss_reason.as_deref() |
| 625 | } |
| 626 | |
| 627 | /// Check whether the current prefix matches the pinned fingerprint |
| 628 | /// without a declared header change. |
| 629 | /// |
| 630 | /// - `Ok(true)` when the prefix is stable (or this was the first pin). |
| 631 | /// - `Err(change)` when the prefix drifted. The pin is **kept**: an |
| 632 | /// undeclared change never becomes the new baseline. Use [`Self::check`] |
| 633 | /// with a declared reason to move the pin on purpose. |
| 634 | pub fn check_and_update( |
| 635 | &mut self, |
| 636 | system_text: &str, |
| 637 | tools: Option<&[Tool]>, |
| 638 | ) -> Result<bool, Box<PrefixChange>> { |
| 639 | match self.check(system_text, tools, None) { |
| 640 | PrefixCheck::Stable => Ok(true), |
| 641 | PrefixCheck::Repinned { change, .. } | PrefixCheck::Drift { change } => { |
| 642 | Err(Box::new(change)) |
| 643 | } |
| 644 | } |
| 645 | } |
| 646 | |
| 647 | /// Returns the most recent prefix change, if any. |
| 648 | pub fn last_change(&self) -> Option<&PrefixChange> { |
| 649 | self.last_change.as_ref() |
| 650 | } |
| 651 | |
| 652 | /// Returns the pinned fingerprint. |
| 653 | pub fn pinned_fingerprint(&self) -> Option<&PrefixFingerprint> { |
| 654 | self.pinned.as_ref() |
| 655 | } |
| 656 | |
| 657 | /// Returns the current (most recently computed) fingerprint. |
| 658 | pub fn current_fingerprint(&self) -> Option<&PrefixFingerprint> { |
| 659 | self.current.as_ref() |
| 660 | } |
| 661 | |
| 662 | /// Returns the total number of prefix changes detected. |
| 663 | pub fn change_count(&self) -> u64 { |
| 664 | self.change_count |
| 665 | } |
| 666 | |
| 667 | /// Returns the total number of stability checks performed. |
| 668 | pub fn check_count(&self) -> u64 { |
| 669 | self.check_count |
| 670 | } |
| 671 | |
| 672 | /// Returns the prefix stability rate as a fraction (0.0 – 1.0). |
| 673 | /// 1.0 means the prefix has never changed. Returns 1.0 when no |
| 674 | /// checks have been performed (to avoid division by zero). |
| 675 | pub fn stability_ratio(&self) -> f64 { |
| 676 | if self.check_count == 0 { |
| 677 | 1.0 |
| 678 | } else { |
| 679 | let stable_checks = self.check_count - self.change_count; |
| 680 | stable_checks as f64 / self.check_count as f64 |
| 681 | } |
| 682 | } |
| 683 | |
| 684 | /// Returns a human-readable stability summary. |
| 685 | pub fn summary(&self) -> String { |
| 686 | let pct = self.stability_ratio() * 100.0; |
| 687 | let pinned_short = self |
| 688 | .pinned |
| 689 | .as_ref() |
| 690 | .map(|fp| { |
| 691 | if fp.combined_sha256.len() >= 12 { |
| 692 | &fp.combined_sha256[..12] |
| 693 | } else { |
| 694 | &fp.combined_sha256 |
| 695 | } |
| 696 | }) |
| 697 | .unwrap_or("none"); |
| 698 | |
| 699 | format!( |
| 700 | "Prefix stability: {pct:.1}% ({stable}/{total} checks stable) | fingerprint: {pinned_short} | changes: {changes}", |
| 701 | pct = pct, |
| 702 | stable = self.check_count.saturating_sub(self.change_count), |
| 703 | total = self.check_count, |
| 704 | pinned_short = pinned_short, |
| 705 | changes = self.change_count, |
| 706 | ) |
| 707 | } |
| 708 | } |
| 709 | |
| 710 | /// Serialize the logical tool fields used by this stability fingerprint. |
| 711 | /// Provider wire projection and omission are measured by the prepared request. |
| 712 | fn logical_tool_fingerprint_json(tool: &Tool) -> Option<String> { |
| 713 | let mut value = serde_json::json!({ |
| 714 | "type": "function", |
| 715 | "function": { |
| 716 | "name": tool.name, |
| 717 | "description": tool.description, |
| 718 | "parameters": tool.input_schema, |
| 719 | } |
| 720 | }); |
| 721 | if let Some(strict) = tool.strict |
| 722 | && let Some(function) = value.get_mut("function") |
| 723 | { |
| 724 | function["strict"] = serde_json::json!(strict); |
| 725 | } |
| 726 | serde_json::to_string(&value).ok() |
| 727 | } |
| 728 | |
| 729 | /// Compute the SHA-256 hex digest of a byte slice. |
| 730 | fn sha256_hex(bytes: &[u8]) -> String { |
| 731 | use sha2::{Digest, Sha256}; |
| 732 | use std::fmt::Write; |
| 733 | let mut hex = String::with_capacity(64); |
| 734 | for byte in Sha256::digest(bytes) { |
| 735 | let _ = write!(&mut hex, "{byte:02x}"); |
| 736 | } |
| 737 | hex |
| 738 | } |
| 739 | |
| 740 | /// Bounded line delta between the session context the model last saw and a |
| 741 | /// fresh composition, rendered as a `<context_update>` user-role message. |
| 742 | /// |
| 743 | /// The pinned system prompt is never rewritten; this is how workspace, |
| 744 | /// instruction, skills, memory, and goal drift reaches the model as a normal |
| 745 | /// history append. Returns `None` when the two texts are line-identical (only |
| 746 | /// whitespace/ordering noise), so no empty update is ever sent. |
| 747 | pub const CONTEXT_UPDATE_MAX_LINES: usize = 80; |
| 748 | pub const CONTEXT_UPDATE_MAX_BYTES: usize = 6_000; |
| 749 | |
| 750 | /// The fixed opening every [`context_update_message`] body starts with. |
| 751 | /// |
| 752 | /// Readers that must tell the engine's drift notices from a person's own |
| 753 | /// words recognize the envelope by it — see `is_context_update_envelope`. |
| 754 | pub const CONTEXT_UPDATE_HEADER: &str = concat!( |
| 755 | "<context_update>\n", |
| 756 | "Session context changed since it was pinned; the pinned system ", |
| 757 | "prompt is unchanged. Delta (+ added, - removed):\n", |
| 758 | ); |
| 759 | |
| 760 | /// The fixed closing every [`context_update_message`] body ends with. |
| 761 | pub const CONTEXT_UPDATE_CLOSE: &str = "</context_update>"; |
| 762 | |
| 763 | /// True when `text` is one whole `<context_update>` envelope exactly as |
| 764 | /// [`context_update_message`] renders it: the engine's fixed header, then the |
| 765 | /// delta, then the fixed close, and nothing of a person's own around it. |
| 766 | /// |
| 767 | /// The drift notice is appended to the model-visible history by the engine, |
| 768 | /// between turn records, so no reconstruction from records can reproduce it — |
| 769 | /// history alignments must skip it rather than read it as a user prompt. A |
| 770 | /// person quoting or asking about a notice carries their own words outside the |
| 771 | /// envelope, which fails either end of this check and keeps their turn whole. |
| 772 | pub fn is_context_update_envelope(text: &str) -> bool { |
| 773 | text.starts_with(CONTEXT_UPDATE_HEADER) && text.ends_with(CONTEXT_UPDATE_CLOSE) |
| 774 | } |
| 775 | |
| 776 | pub fn context_update_message(known: &str, current: &str) -> Option<String> { |
| 777 | use std::collections::HashMap; |
| 778 | let mut counts: HashMap<&str, i64> = HashMap::new(); |
| 779 | for line in known.lines() { |
| 780 | *counts.entry(line).or_insert(0) -= 1; |
| 781 | } |
| 782 | for line in current.lines() { |
| 783 | *counts.entry(line).or_insert(0) += 1; |
| 784 | } |
| 785 | let mut added: Vec<&str> = Vec::new(); |
| 786 | for line in current.lines() { |
| 787 | if let Some(count) = counts.get_mut(line) |
| 788 | && *count > 0 |
| 789 | { |
| 790 | *count -= 1; |
| 791 | if !line.trim().is_empty() { |
| 792 | added.push(line); |
| 793 | } |
| 794 | } |
| 795 | } |
| 796 | let mut removed: Vec<&str> = Vec::new(); |
| 797 | for line in known.lines() { |
| 798 | if let Some(count) = counts.get_mut(line) |
| 799 | && *count < 0 |
| 800 | { |
| 801 | *count += 1; |
| 802 | if !line.trim().is_empty() { |
| 803 | removed.push(line); |
| 804 | } |
| 805 | } |
| 806 | } |
| 807 | if added.is_empty() && removed.is_empty() { |
| 808 | return None; |
| 809 | } |
| 810 | |
| 811 | let mut out = String::from(CONTEXT_UPDATE_HEADER); |
| 812 | let mut lines_written = 0usize; |
| 813 | let mut truncated = 0usize; |
| 814 | for (sign, group) in [("+ ", &added), ("- ", &removed)] { |
| 815 | for line in group { |
| 816 | if lines_written >= CONTEXT_UPDATE_MAX_LINES |
| 817 | || out.len() + sign.len() + line.len() + 1 > CONTEXT_UPDATE_MAX_BYTES |
| 818 | { |
| 819 | truncated += 1; |
| 820 | continue; |
| 821 | } |
| 822 | out.push_str(sign); |
| 823 | out.push_str(line); |
| 824 | out.push('\n'); |
| 825 | lines_written += 1; |
| 826 | } |
| 827 | } |
| 828 | if truncated > 0 { |
| 829 | out.push_str(&format!( |
| 830 | "(+{truncated} more changed lines; re-read the files you need)\n" |
| 831 | )); |
| 832 | } |
| 833 | out.push_str(CONTEXT_UPDATE_CLOSE); |
| 834 | Some(out) |
| 835 | } |
| 836 | |
| 837 | /// Extract the system prompt text from an optional SystemPrompt, |
| 838 | /// returning an owned String. This is used for prefix fingerprinting |
| 839 | /// and avoids lifetime/leak issues with the rare SystemPrompt::Blocks case. |
| 840 | pub fn system_prompt_text(system: Option<&SystemPrompt>) -> String { |
| 841 | match system { |
| 842 | Some(SystemPrompt::Text(text)) => text.clone(), |
| 843 | Some(SystemPrompt::Blocks(blocks)) => { |
| 844 | let mut text = String::new(); |
| 845 | for block in blocks { |
| 846 | text.push_str(&block.text); |
| 847 | text.push('\n'); |
| 848 | } |
| 849 | text |
| 850 | } |
| 851 | None => String::new(), |
| 852 | } |
| 853 | } |
| 854 | |
| 855 | #[cfg(test)] |
| 856 | mod tests { |
| 857 | use super::*; |
| 858 | |
| 859 | fn make_tool(name: &str) -> Tool { |
| 860 | Tool { |
| 861 | name: name.to_string(), |
| 862 | description: String::new(), |
| 863 | input_schema: serde_json::Value::Null, |
| 864 | tool_type: None, |
| 865 | allowed_callers: None, |
| 866 | defer_loading: None, |
| 867 | input_examples: None, |
| 868 | strict: None, |
| 869 | cache_control: None, |
| 870 | } |
| 871 | } |
| 872 | |
| 873 | #[test] |
| 874 | fn same_prefix_produces_same_fingerprint() { |
| 875 | let a = PrefixFingerprint::compute("hello world", None); |
| 876 | let b = PrefixFingerprint::compute("hello world", None); |
| 877 | assert_eq!(a.combined_sha256, b.combined_sha256); |
| 878 | } |
| 879 | |
| 880 | #[test] |
| 881 | fn different_system_produces_different_fingerprint() { |
| 882 | let a = PrefixFingerprint::compute("hello", None); |
| 883 | let b = PrefixFingerprint::compute("world", None); |
| 884 | assert_ne!(a.combined_sha256, b.combined_sha256); |
| 885 | } |
| 886 | |
| 887 | #[test] |
| 888 | fn tool_order_affects_fingerprint() { |
| 889 | // The provider KV cache is order-sensitive; sorting before hashing |
| 890 | // could read a false-green while the real prefix cache missed every |
| 891 | // turn (ops C1). |
| 892 | let tools_a = vec![make_tool("read_file"), make_tool("write_file")]; |
| 893 | let tools_b = vec![make_tool("write_file"), make_tool("read_file")]; |
| 894 | let a = PrefixFingerprint::compute("system", Some(&tools_a)); |
| 895 | let b = PrefixFingerprint::compute("system", Some(&tools_b)); |
| 896 | assert_ne!(a.combined_sha256, b.combined_sha256); |
| 897 | } |
| 898 | |
| 899 | #[test] |
| 900 | fn different_tools_produce_different_fingerprint() { |
| 901 | let tools_a = vec![make_tool("read_file")]; |
| 902 | let tools_b = vec![make_tool("write_file")]; |
| 903 | let a = PrefixFingerprint::compute("system", Some(&tools_a)); |
| 904 | let b = PrefixFingerprint::compute("system", Some(&tools_b)); |
| 905 | assert_ne!(a.combined_sha256, b.combined_sha256); |
| 906 | } |
| 907 | |
| 908 | #[test] |
| 909 | fn manager_starts_stable() { |
| 910 | let mut mgr = PrefixStabilityManager::new("system prompt", None); |
| 911 | assert!(mgr.check_and_update("system prompt", None).unwrap()); |
| 912 | assert_eq!(mgr.change_count(), 0); |
| 913 | assert_eq!(mgr.check_count(), 1); |
| 914 | } |
| 915 | |
| 916 | #[test] |
| 917 | fn manager_detects_change() { |
| 918 | let mut mgr = PrefixStabilityManager::new("system prompt", None); |
| 919 | let result = mgr.check_and_update("different prompt", None); |
| 920 | assert!(result.is_err()); |
| 921 | assert_eq!(mgr.change_count(), 1); |
| 922 | let change = mgr.last_change().unwrap(); |
| 923 | assert!(change.system_changed); |
| 924 | assert!(!change.tools_changed); |
| 925 | } |
| 926 | |
| 927 | #[test] |
| 928 | fn manager_detects_tool_change() { |
| 929 | let tools_a = vec![make_tool("read_file")]; |
| 930 | let tools_b = vec![make_tool("write_file")]; |
| 931 | let mut mgr = PrefixStabilityManager::new("system", Some(&tools_a)); |
| 932 | let result = mgr.check_and_update("system", Some(&tools_b)); |
| 933 | assert!(result.is_err()); |
| 934 | let change = mgr.last_change().unwrap(); |
| 935 | assert!(!change.system_changed); |
| 936 | assert!(change.tools_changed); |
| 937 | } |
| 938 | |
| 939 | #[test] |
| 940 | fn undeclared_drift_never_moves_the_pin() { |
| 941 | let mut mgr = PrefixStabilityManager::new("old", None); |
| 942 | assert_eq!(mgr.pin_reason(), Some("initial")); |
| 943 | assert!(mgr.check_and_update("new", None).is_err()); |
| 944 | // The pin stays on "old": the same undeclared prefix is still a miss. |
| 945 | assert!(mgr.check_and_update("new", None).is_err()); |
| 946 | assert!(mgr.check_and_update("old", None).unwrap()); |
| 947 | assert_eq!(mgr.change_count(), 2); |
| 948 | assert_eq!(mgr.last_miss_reason(), Some("drift:sys")); |
| 949 | let history: Vec<_> = mgr.history().collect(); |
| 950 | assert_eq!(history.len(), 2); |
| 951 | assert!(history.iter().all(|entry| !entry.repinned)); |
| 952 | assert_eq!(mgr.pin_reason(), Some("initial")); |
| 953 | } |
| 954 | |
| 955 | #[test] |
| 956 | fn declared_header_change_repins_under_a_logged_reason() { |
| 957 | let mut mgr = PrefixStabilityManager::new("old", None); |
| 958 | match mgr.check("new", None, Some("model")) { |
| 959 | PrefixCheck::Repinned { reason, change } => { |
| 960 | assert_eq!(reason, "change:model"); |
| 961 | assert!(change.system_changed); |
| 962 | } |
| 963 | other => panic!("expected repin, got {other:?}"), |
| 964 | } |
| 965 | assert_eq!(mgr.pin_reason(), Some("change:model")); |
| 966 | assert!(matches!(mgr.check("new", None, None), PrefixCheck::Stable)); |
| 967 | assert!(matches!( |
| 968 | mgr.check("newer", None, None), |
| 969 | PrefixCheck::Drift { .. } |
| 970 | )); |
| 971 | assert_eq!(mgr.pin_reason(), Some("change:model")); |
| 972 | let reasons: Vec<&str> = mgr.history().map(|e| e.reason.as_str()).collect(); |
| 973 | assert_eq!(reasons, vec!["change:model", "drift:sys"]); |
| 974 | } |
| 975 | |
| 976 | #[test] |
| 977 | fn declared_reason_on_a_stable_prefix_is_a_noop() { |
| 978 | let mut mgr = PrefixStabilityManager::new("same", None); |
| 979 | assert!(matches!( |
| 980 | mgr.check("same", None, Some("mode")), |
| 981 | PrefixCheck::Stable |
| 982 | )); |
| 983 | assert_eq!(mgr.change_count(), 0); |
| 984 | assert_eq!(mgr.pin_reason(), Some("initial")); |
| 985 | } |
| 986 | |
| 987 | #[test] |
| 988 | fn context_update_message_reports_added_and_removed_lines_bounded() { |
| 989 | let known = "## Files\nsrc/a.rs\nsrc/b.rs\n## Instructions\nbe kind\n"; |
| 990 | let current = "## Files\nsrc/a.rs\nsrc/b.rs\nsrc/c.rs\n## Instructions\nbe precise\n"; |
| 991 | let update = context_update_message(known, current).expect("delta"); |
| 992 | assert!(update.starts_with("<context_update>")); |
| 993 | assert!(update.ends_with("</context_update>")); |
| 994 | assert!(update.contains("+ src/c.rs")); |
| 995 | assert!(update.contains("+ be precise")); |
| 996 | assert!(update.contains("- be kind")); |
| 997 | assert!(!update.contains("- src/a.rs")); |
| 998 | assert!(context_update_message(known, known).is_none()); |
| 999 | |
| 1000 | // The recognizer answers for every body the builder can render, so a |
| 1001 | // history alignment can skip the engine's notices without guessing at |
| 1002 | // their shape, while a person's words around one stay their own. |
| 1003 | assert!(is_context_update_envelope(&update)); |
| 1004 | let quoted = format!("what does this mean?\n{update}"); |
| 1005 | assert!(!is_context_update_envelope("ed)); |
| 1006 | let truncated = &update[..update.len() - CONTEXT_UPDATE_CLOSE.len()]; |
| 1007 | assert!(!is_context_update_envelope(truncated)); |
| 1008 | |
| 1009 | let mut big = String::new(); |
| 1010 | for i in 0..500 { |
| 1011 | big.push_str(&format!("line {i}\n")); |
| 1012 | } |
| 1013 | let bounded = context_update_message("", &big).expect("delta"); |
| 1014 | assert!( |
| 1015 | bounded.len() <= CONTEXT_UPDATE_MAX_BYTES + 128, |
| 1016 | "{}", |
| 1017 | bounded.len() |
| 1018 | ); |
| 1019 | assert!(bounded.contains("more changed lines")); |
| 1020 | } |
| 1021 | |
| 1022 | #[test] |
| 1023 | fn context_update_is_logged_but_is_not_a_miss() { |
| 1024 | let mut mgr = PrefixStabilityManager::new("sys", None); |
| 1025 | mgr.note_context_update(); |
| 1026 | assert_eq!(mgr.context_update_count(), 1); |
| 1027 | assert_eq!(mgr.last_miss_reason(), None); |
| 1028 | assert!(matches!(mgr.check("sys", None, None), PrefixCheck::Stable)); |
| 1029 | } |
| 1030 | |
| 1031 | #[test] |
| 1032 | fn history_reset_is_logged_without_moving_the_pin() { |
| 1033 | let mut mgr = PrefixStabilityManager::new("sys", None); |
| 1034 | mgr.note_history_reset("compaction"); |
| 1035 | assert_eq!(mgr.last_miss_reason(), Some("reset:compaction")); |
| 1036 | assert!(matches!(mgr.check("sys", None, None), PrefixCheck::Stable)); |
| 1037 | assert_eq!(mgr.history().count(), 1); |
| 1038 | } |
| 1039 | |
| 1040 | #[test] |
| 1041 | fn stability_ratio_is_one_for_no_changes() { |
| 1042 | let mut mgr = PrefixStabilityManager::new("hello", None); |
| 1043 | mgr.check_and_update("hello", None).unwrap(); |
| 1044 | mgr.check_and_update("hello", None).unwrap(); |
| 1045 | assert!((mgr.stability_ratio() - 1.0).abs() < f64::EPSILON); |
| 1046 | assert_eq!(mgr.check_count(), 2); |
| 1047 | assert_eq!(mgr.change_count(), 0); |
| 1048 | } |
| 1049 | |
| 1050 | #[test] |
| 1051 | fn stability_ratio_reflects_change_rate() { |
| 1052 | let mut mgr = PrefixStabilityManager::new("hello", None); |
| 1053 | mgr.check_and_update("hello", None).unwrap(); // check 1: stable |
| 1054 | let _ = mgr.check("world", None, Some("model")); // check 2: declared change |
| 1055 | mgr.check_and_update("world", None).unwrap(); // check 3: stable |
| 1056 | // 2 stable out of 3 checks = 0.666... |
| 1057 | // (check_count=0 at start, so 3 checks: 3 checks - 1 change = 2 stable) |
| 1058 | assert!((mgr.stability_ratio() - 2.0 / 3.0).abs() < 0.01); |
| 1059 | assert_eq!(mgr.check_count(), 3); |
| 1060 | assert_eq!(mgr.change_count(), 1); |
| 1061 | } |
| 1062 | |
| 1063 | #[test] |
| 1064 | fn empty_tools_and_none_tools_produce_same_hash() { |
| 1065 | let empty = PrefixFingerprint::compute("system", Some(&[])); |
| 1066 | let none = PrefixFingerprint::compute("system", None); |
| 1067 | // Both should produce sha256(b"") for the tool component |
| 1068 | assert_eq!(empty.tools_sha256, none.tools_sha256); |
| 1069 | } |
| 1070 | |
| 1071 | #[test] |
| 1072 | fn empty_system_produces_sha256_of_empty_string() { |
| 1073 | let fp = PrefixFingerprint::compute("", None); |
| 1074 | let expected = sha256_hex(b""); |
| 1075 | assert_eq!(fp.system_sha256, expected); |
| 1076 | } |
| 1077 | |
| 1078 | #[test] |
| 1079 | fn prefix_change_description_is_informative() { |
| 1080 | let old = PrefixFingerprint::compute("old", None); |
| 1081 | let new = PrefixFingerprint::compute("new", None); |
| 1082 | let change = PrefixChange { |
| 1083 | old, |
| 1084 | new, |
| 1085 | system_changed: true, |
| 1086 | tools_changed: false, |
| 1087 | }; |
| 1088 | assert_eq!( |
| 1089 | change.description(), |
| 1090 | "prefix cache invalidated: system prompt changed" |
| 1091 | ); |
| 1092 | assert_eq!(change.label(), "sys"); |
| 1093 | } |
| 1094 | |
| 1095 | #[test] |
| 1096 | fn new_unpinned_has_no_change_history() { |
| 1097 | let mut mgr = PrefixStabilityManager::new_unpinned(); |
| 1098 | assert!(mgr.pinned_fingerprint().is_none()); |
| 1099 | assert!(mgr.current_fingerprint().is_none()); |
| 1100 | assert!(mgr.last_change().is_none()); |
| 1101 | assert_eq!(mgr.change_count(), 0); |
| 1102 | assert_eq!(mgr.check_count(), 0); |
| 1103 | // First check should pin automatically and count as a check. |
| 1104 | assert!(mgr.check_and_update("hello", None).unwrap()); |
| 1105 | assert!(mgr.pinned_fingerprint().is_some()); |
| 1106 | assert_eq!(mgr.check_count(), 1); |
| 1107 | } |
| 1108 | |
| 1109 | #[test] |
| 1110 | fn fingerprint_detects_schema_change_not_just_name_change() { |
| 1111 | let tool_a = make_tool("my_tool"); |
| 1112 | let mut tool_a_v2 = make_tool("my_tool"); |
| 1113 | tool_a_v2.description = "updated description".to_string(); |
| 1114 | |
| 1115 | let a = PrefixFingerprint::compute("system", Some(&[tool_a])); |
| 1116 | let b = PrefixFingerprint::compute("system", Some(&[tool_a_v2])); |
| 1117 | // Same name, different description — must produce different hash. |
| 1118 | assert_ne!(a.tools_sha256, b.tools_sha256); |
| 1119 | assert_ne!(a.combined_sha256, b.combined_sha256); |
| 1120 | } |
| 1121 | |
| 1122 | #[test] |
| 1123 | fn system_prompt_text_returns_empty_for_none() { |
| 1124 | assert_eq!(system_prompt_text(None), ""); |
| 1125 | } |
| 1126 | |
| 1127 | // ── ToolCatalogCache tests ────────────────────────────────── |
| 1128 | |
| 1129 | #[test] |
| 1130 | fn tool_catalog_cache_miss_then_hit_returns_same_digest() { |
| 1131 | let mut cache = ToolCatalogCache::new(); |
| 1132 | let tools = vec![make_tool("read_file"), make_tool("write_file")]; |
| 1133 | |
| 1134 | let first = cache.fingerprint_for(&tools); |
| 1135 | assert_eq!(cache.len(), 1); |
| 1136 | |
| 1137 | let second = cache.fingerprint_for(&tools); |
| 1138 | assert_eq!(cache.len(), 1, "second call should be a cache hit"); |
| 1139 | assert_eq!(first.sha256_hex, second.sha256_hex); |
| 1140 | } |
| 1141 | |
| 1142 | #[test] |
| 1143 | fn tool_catalog_cache_different_tool_sets_dont_collide() { |
| 1144 | let mut cache = ToolCatalogCache::new(); |
| 1145 | let a = vec![make_tool("read_file")]; |
| 1146 | let b = vec![make_tool("write_file")]; |
| 1147 | |
| 1148 | let entry_a = cache.fingerprint_for(&a); |
| 1149 | let entry_b = cache.fingerprint_for(&b); |
| 1150 | assert_eq!(cache.len(), 2); |
| 1151 | assert_ne!(entry_a.sha256_hex, entry_b.sha256_hex); |
| 1152 | } |
| 1153 | |
| 1154 | #[test] |
| 1155 | fn tool_catalog_cache_fingerprint_is_order_sensitive_like_the_provider_cache() { |
| 1156 | // The identity hash includes the input order so re-registering the |
| 1157 | // same set with a different permutation produces a separate cache |
| 1158 | // entry. The digest is now order-sensitive too: the provider KV cache |
| 1159 | // is order-sensitive, so a sorted fingerprint read a false-green while |
| 1160 | // the real prefix missed every turn (ops C1). Different wire order = |
| 1161 | // different prefix = different fingerprint. |
| 1162 | let mut cache = ToolCatalogCache::new(); |
| 1163 | let a = vec![make_tool("read_file"), make_tool("write_file")]; |
| 1164 | let b = vec![make_tool("write_file"), make_tool("read_file")]; |
| 1165 | let entry_a = cache.fingerprint_for(&a); |
| 1166 | let entry_b = cache.fingerprint_for(&b); |
| 1167 | assert_ne!(entry_a.sha256_hex, entry_b.sha256_hex); |
| 1168 | assert_eq!(cache.len(), 2); |
| 1169 | // Re-requesting the original order returns the cached digest. |
| 1170 | let again = cache.fingerprint_for(&a); |
| 1171 | assert_eq!(again.sha256_hex, entry_a.sha256_hex); |
| 1172 | } |
| 1173 | |
| 1174 | #[test] |
| 1175 | fn tool_catalog_cache_detects_schema_change() { |
| 1176 | let mut cache = ToolCatalogCache::new(); |
| 1177 | let tool_v1 = make_tool("t"); |
| 1178 | let mut tool_v2 = make_tool("t"); |
| 1179 | tool_v2.description = "updated".to_string(); |
| 1180 | |
| 1181 | let entry_v1 = cache.fingerprint_for(&[tool_v1]); |
| 1182 | let entry_v2 = cache.fingerprint_for(&[tool_v2]); |
| 1183 | assert_ne!(entry_v1.sha256_hex, entry_v2.sha256_hex); |
| 1184 | assert_eq!(cache.len(), 2); |
| 1185 | } |
| 1186 | |
| 1187 | #[test] |
| 1188 | fn tool_catalog_cache_respects_capacity() { |
| 1189 | let mut cache = ToolCatalogCache::with_capacity(2); |
| 1190 | cache.fingerprint_for(&[make_tool("a")]); |
| 1191 | cache.fingerprint_for(&[make_tool("b")]); |
| 1192 | cache.fingerprint_for(&[make_tool("c")]); |
| 1193 | assert_eq!(cache.len(), 2); |
| 1194 | // The first entry was evicted; a re-query for it should miss. |
| 1195 | let re_entry = cache.fingerprint_for(&[make_tool("a")]); |
| 1196 | // After the re-query, the cache has [b, c, a] — 3 entries? No, |
| 1197 | // capacity 2 means oldest is evicted when we insert the 3rd unique. |
| 1198 | // After inserting a, the cache holds the most recent 2: {c, a}. |
| 1199 | assert_eq!(cache.len(), 2); |
| 1200 | // The returned digest should match a fresh fingerprint of the same set. |
| 1201 | let fresh = cache.fingerprint_for(&[make_tool("a")]); |
| 1202 | assert_eq!(re_entry.sha256_hex, fresh.sha256_hex); |
| 1203 | } |
| 1204 | |
| 1205 | #[test] |
| 1206 | fn tool_catalog_cache_invalidate_clears_all() { |
| 1207 | let mut cache = ToolCatalogCache::new(); |
| 1208 | cache.fingerprint_for(&[make_tool("a")]); |
| 1209 | cache.fingerprint_for(&[make_tool("b")]); |
| 1210 | cache.invalidate(); |
| 1211 | assert!(cache.is_empty()); |
| 1212 | assert_eq!(cache.len(), 0); |
| 1213 | } |
| 1214 | |
| 1215 | #[test] |
| 1216 | fn tool_catalog_cache_empty_slice_uses_zero_capacity_path() { |
| 1217 | // Empty input is fine — should produce a stable, non-empty digest. |
| 1218 | let mut cache = ToolCatalogCache::new(); |
| 1219 | let entry = cache.fingerprint_for(&[]); |
| 1220 | assert!(!entry.sha256_hex.is_empty()); |
| 1221 | let again = cache.fingerprint_for(&[]); |
| 1222 | assert_eq!(entry.sha256_hex, again.sha256_hex); |
| 1223 | } |
| 1224 | |
| 1225 | #[test] |
| 1226 | fn compute_with_tool_cache_matches_compute_uncached() { |
| 1227 | // The cached and uncached paths must produce identical fingerprints |
| 1228 | // for the same inputs — otherwise we'd silently corrupt the prefix |
| 1229 | // cache and invalidate every request. |
| 1230 | let mut cache = ToolCatalogCache::new(); |
| 1231 | let tools = vec![make_tool("alpha"), make_tool("beta")]; |
| 1232 | |
| 1233 | let cached = PrefixFingerprint::compute_with_tool_cache("sys", Some(&tools), &mut cache); |
| 1234 | let uncached = PrefixFingerprint::compute("sys", Some(&tools)); |
| 1235 | assert_eq!(cached.combined_sha256, uncached.combined_sha256); |
| 1236 | assert_eq!(cached.tools_sha256, uncached.tools_sha256); |
| 1237 | } |
| 1238 | |
| 1239 | #[test] |
| 1240 | fn manager_check_and_update_uses_cached_tool_fingerprint() { |
| 1241 | // After the first call populates the cache, subsequent calls with |
| 1242 | // the same tool list should not invalidate the prefix. |
| 1243 | let tools = vec![make_tool("t1")]; |
| 1244 | let mut mgr = PrefixStabilityManager::new("sys", Some(&tools)); |
| 1245 | assert!(mgr.check_and_update("sys", Some(&tools)).is_ok()); |
| 1246 | assert!(mgr.check_and_update("sys", Some(&tools)).is_ok()); |
| 1247 | assert_eq!(mgr.change_count(), 0); |
| 1248 | } |
| 1249 | } |
| 1250 |