Skip to main content

lean_ctx/proxy/
cold_prefix.rs

1//! Big-gap cold-prefix repack prediction (#480).
2//!
3//! The proxy is deliberately cache-safe: it never rewrites the client-cached
4//! prefix (`history_prune::cached_prefix_len`), so provider prompt caches keep
5//! hitting and cheap cache reads (~0.1x) never turn into full-price writes
6//! (~1.25x) — the #448 invariant.
7//!
8//! That protection has one blind spot. Provider prompt caches EXPIRE after a TTL
9//! of inactivity. After a long idle gap (the agent asked a question, the user
10//! replies hours later) the cached prefix is already gone; the provider will
11//! re-WRITE the whole prefix on the next request regardless. Staying in
12//! "never touch the cached prefix" mode then writes the *uncompressed* prefix at
13//! full price and re-seeds a fat cache for the rest of the session.
14//!
15//! This module makes a PRE-SEND prediction — purely from elapsed idle time vs
16//! the provider's cache TTL — of whether the prefix is already cold. The trigger
17//! must be a clock, not response feedback: hit/miss is only known *after* the
18//! request that already (re-)cached the prefix, and by the next request the
19//! cache is warm again, so feedback would bust the fresh cache.
20//!
21//! Safety is paramount because the cost of a wrong "cold" guess is asymmetric (a
22//! cache write is ~12x a cache read). We therefore:
23//!   * act only when the caller opted in (`repacks_cold_prefix()`),
24//!   * act only on a measured idle gap well past expiry (`TTL × SAFETY_MARGIN`,
25//!     with an absolute floor), skipping the ambiguous near-TTL zone entirely,
26//!   * never act without a prior touch (the first sighting only sets a baseline),
27//!   * and bias every ambiguity toward "warm" (do nothing).
28//!
29//! State persists across restarts (`{data_dir}/cold_prefix_touch.json`, atomic
30//! write, throttled) so an idle gap that straddles a daemon recycle is still
31//! detected — a stale on-disk timestamp is exactly what proves the gap and can
32//! only ever bias toward "warm" if lost (#499). A missing/corrupt file simply
33//! disables the optimization until a fresh baseline is recorded — a safe
34//! degradation that can never wrongly trigger.
35//!
36//! Once a conversation is judged cold and repacked, the decision is *sticky*:
37//! every later turn keeps applying the same deterministic prefix compression, so
38//! the warm follow-ups that resume active use hit the compressed prefix written
39//! at the cold turn instead of re-sending the uncompressed original and busting
40//! the freshly-seeded cache (#499). Deterministic re-compression is prefix-
41//! stable, so the latch stays cache-safe for the rest of the session.
42
43use std::collections::HashMap;
44use std::hash::{Hash, Hasher};
45use std::sync::atomic::{AtomicU64, Ordering};
46use std::sync::{Mutex, OnceLock};
47use std::time::{SystemTime, UNIX_EPOCH};
48
49use serde::{Deserialize, Serialize};
50use serde_json::Value;
51
52/// Multiplier applied to the resolved TTL before a prefix is declared cold. The
53/// provider cache is a sliding inactivity window, so `idle > TTL` already implies
54/// expiry; `× 2` keeps a safety buffer against clock skew and provider nuance.
55const SAFETY_MARGIN: u64 = 2;
56/// Absolute minimum idle (seconds) before any repack, regardless of a short
57/// per-request TTL — never repack on a gap under 10 minutes.
58const COLD_FLOOR_SECS: u64 = 600;
59/// Anthropic default cache TTL when a `cache_control` marker carries no explicit
60/// `ttl` (the API default is "5m").
61const DEFAULT_TTL_SECS: u64 = 300;
62/// Anthropic extended cache TTL (`"ttl":"1h"`).
63const HOUR_TTL_SECS: u64 = 3600;
64/// Hard cap on tracked conversations so a long-lived proxy can't grow the
65/// last-touch map without bound; the oldest entry is evicted past this.
66const MAX_TRACKED: usize = 4096;
67/// Minimum seconds between disk persists. The on-disk baseline only needs to be
68/// "fresh enough" to prove a multi-minute gap, so throttling keeps the hot path
69/// off the disk on every request without weakening the long-gap guarantee.
70const PERSIST_MIN_INTERVAL_SECS: u64 = 30;
71/// Cross-restart baseline store, in the shared data dir.
72const TOUCH_FILE: &str = "cold_prefix_touch.json";
73
74/// Per-conversation tracking state. `last_touch` is the Unix-seconds timestamp of
75/// the most recent request; `repacking` latches on once a cold gap triggered a
76/// repack, so subsequent turns stay cache-stable on the compressed prefix (#499).
77#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
78struct ConvState {
79    last_touch: u64,
80    repacking: bool,
81}
82
83fn store() -> &'static Mutex<HashMap<u64, ConvState>> {
84    static STORE: OnceLock<Mutex<HashMap<u64, ConvState>>> = OnceLock::new();
85    STORE.get_or_init(|| Mutex::new(HashMap::new()))
86}
87
88/// Wall-clock seconds of the last successful disk persist (throttle gate).
89fn last_persist() -> &'static AtomicU64 {
90    static LAST: AtomicU64 = AtomicU64::new(0);
91    &LAST
92}
93
94fn now_secs() -> u64 {
95    SystemTime::now()
96        .duration_since(UNIX_EPOCH)
97        .map_or(0, |d| d.as_secs())
98}
99
100fn hash_bytes(bytes: &[u8]) -> u64 {
101    let mut h = std::collections::hash_map::DefaultHasher::new();
102    bytes.hash(&mut h);
103    h.finish()
104}
105
106/// Stable per-conversation key: a hash of the first message with every
107/// `cache_control` marker stripped first. `messages[0]` is byte-stable across a
108/// conversation's turns *except* for its volatile cache breakpoint — clients move
109/// or retune the `cache_control` (`ephemeral`/`ttl`) marker as the prompt grows.
110/// Hashing the raw message would then change the key mid-conversation → a
111/// permanent "first sighting" that never repacks (#499). Stripping the marker
112/// keys on stable content only. Distinct conversations still differ (distinct
113/// opening turns); a collision can only make the recorded last-touch *more
114/// recent*, biasing toward "warm" — never a wrong "cold". `None` when there is no
115/// first message.
116fn conversation_key(messages: &[Value]) -> Option<u64> {
117    let mut first = messages.first()?.clone();
118    strip_cache_control(&mut first);
119    let bytes = serde_json::to_vec(&first).ok()?;
120    Some(hash_bytes(&bytes))
121}
122
123/// Recursively remove every `cache_control` field so a moving cache breakpoint
124/// can't change the conversation key. The marker always nests `type:ephemeral`
125/// and any `ttl` inside `cache_control`, so dropping that one field suffices.
126fn strip_cache_control(v: &mut Value) {
127    match v {
128        Value::Object(map) => {
129            map.remove("cache_control");
130            for val in map.values_mut() {
131                strip_cache_control(val);
132            }
133        }
134        Value::Array(arr) => {
135            for val in arr {
136                strip_cache_control(val);
137            }
138        }
139        _ => {}
140    }
141}
142
143fn parse_ttl_str(s: &str) -> Option<u64> {
144    match s.trim() {
145        "1h" => Some(HOUR_TTL_SECS),
146        "5m" => Some(DEFAULT_TTL_SECS),
147        _ => None,
148    }
149}
150
151/// Largest `cache_control.ttl` declared anywhere inside one message (message-,
152/// block-, or nested text-level), in seconds. `None` when no parseable ttl.
153fn max_ttl_in_message(msg: &Value) -> Option<u64> {
154    let mut best: Option<u64> = None;
155    collect_cc_ttl(msg, &mut best);
156    best
157}
158
159fn collect_cc_ttl(v: &Value, best: &mut Option<u64>) {
160    match v {
161        Value::Object(map) => {
162            if let Some(ttl) = map
163                .get("cache_control")
164                .and_then(|cc| cc.get("ttl"))
165                .and_then(Value::as_str)
166                .and_then(parse_ttl_str)
167            {
168                *best = Some(best.map_or(ttl, |b| b.max(ttl)));
169            }
170            for val in map.values() {
171                collect_cc_ttl(val, best);
172            }
173        }
174        Value::Array(arr) => {
175            for val in arr {
176                collect_cc_ttl(val, best);
177            }
178        }
179        _ => {}
180    }
181}
182
183/// Resolve the cache TTL (seconds) for the client-cached prefix `[0..cached)`.
184/// Returns the largest TTL any cached message requested, defaulting to the "5m"
185/// Anthropic default because a `cache_control` marker is present. `None` only
186/// when `cached == 0` (no marker) — in which case there is nothing to repack.
187fn resolved_ttl_secs(messages: &[Value], cached: usize) -> Option<u64> {
188    if cached == 0 {
189        return None;
190    }
191    let end = cached.min(messages.len());
192    let mut ttl = DEFAULT_TTL_SECS;
193    for msg in &messages[..end] {
194        if let Some(t) = max_ttl_in_message(msg) {
195            ttl = ttl.max(t);
196        }
197    }
198    Some(ttl)
199}
200
201fn evict_oldest(map: &mut HashMap<u64, ConvState>) {
202    if let Some(oldest_key) = map
203        .iter()
204        .min_by_key(|(_, s)| s.last_touch)
205        .map(|(k, _)| *k)
206    {
207        map.remove(&oldest_key);
208    }
209}
210
211/// Decide whether to repack the (predicted-cold) cached prefix for THIS request,
212/// recording this request as the conversation's latest touch.
213///
214/// Returns `true` when the conversation is already in the sticky repacking state
215/// (a prior turn went cold — keep the compressed prefix stable, #499) or when a
216/// fresh cold gap is detected: a client-cached prefix exists (`cached > 0`), a
217/// prior touch exists (so the idle gap is measurable), and the idle gap exceeds
218/// `TTL × SAFETY_MARGIN` and the absolute floor. The caller owns the opt-in gate;
219/// this is only ever called when the operator enabled it, so updating the
220/// last-touch baseline here is the intended side effect for the *next* request.
221pub fn repack_decision(messages: &[Value], cached: usize) -> bool {
222    let Some(key) = conversation_key(messages) else {
223        return false;
224    };
225    let now = now_secs();
226    let ttl = resolved_ttl_secs(messages, cached);
227
228    let (decision, changed) = {
229        let mut map = store()
230            .lock()
231            .unwrap_or_else(std::sync::PoisonError::into_inner);
232        let prev = map.get(&key).copied();
233        let was_first = prev.is_none();
234        let already_repacking = prev.is_some_and(|s| s.repacking);
235
236        // A fresh cold gap: a measurable idle past `TTL × margin` (and the floor)
237        // on a turn that actually carries a client-cached prefix.
238        let fresh_cold = match (prev, ttl) {
239            (Some(p), Some(t)) if cached > 0 => {
240                let idle = now.saturating_sub(p.last_touch);
241                idle > t.saturating_mul(SAFETY_MARGIN).max(COLD_FLOOR_SECS)
242            }
243            _ => false,
244        };
245
246        // Sticky latch: once cold→repacked, stay repacking. Deterministic re-
247        // compression keeps the prefix byte-stable so warm follow-ups hit the
248        // cache written at the cold turn instead of busting it (#499).
249        let repacking = already_repacking || fresh_cold;
250        map.insert(
251            key,
252            ConvState {
253                last_touch: now,
254                repacking,
255            },
256        );
257        if map.len() > MAX_TRACKED {
258            evict_oldest(&mut map);
259        }
260
261        // Persist eagerly when the latch first engages or on a first sighting
262        // (both define a baseline that must survive an immediate restart);
263        // otherwise let the throttle decide.
264        let changed = was_first || (repacking && !already_repacking);
265        // Repack only when we are in the repacking state AND there is a cached
266        // prefix to act on this turn (a `cached == 0` turn prunes from 0 anyway).
267        (repacking && cached > 0, changed)
268    };
269
270    maybe_persist(changed, now);
271    decision
272}
273
274/// On-disk shape of the cross-restart baselines. `ts` is advisory (debugging);
275/// the per-conversation `last_touch` values are what prove an idle gap.
276#[derive(Debug, Default, Serialize, Deserialize)]
277struct PersistedTouch {
278    ts: u64,
279    conversations: HashMap<u64, ConvState>,
280}
281
282fn touch_path() -> Option<std::path::PathBuf> {
283    crate::core::data_dir::lean_ctx_data_dir()
284        .ok()
285        .map(|d| d.join(TOUCH_FILE))
286}
287
288/// Seeds the in-memory baselines from disk on proxy startup so an idle gap that
289/// straddles a restart is still detected. Merges by most-recent `last_touch` and
290/// OR-s the sticky `repacking` latch, so a re-seed can only bias toward "warm"
291/// (or keep a latch), never toward a wrong "cold".
292pub fn resume_from_disk() {
293    let Some(path) = touch_path() else {
294        return;
295    };
296    let Ok(data) = std::fs::read_to_string(&path) else {
297        return;
298    };
299    let Ok(persisted) = serde_json::from_str::<PersistedTouch>(&data) else {
300        return;
301    };
302    let mut map = store()
303        .lock()
304        .unwrap_or_else(std::sync::PoisonError::into_inner);
305    for (key, state) in persisted.conversations {
306        let entry = map.entry(key).or_insert(state);
307        if state.last_touch > entry.last_touch {
308            entry.last_touch = state.last_touch;
309        }
310        entry.repacking |= state.repacking;
311    }
312    while map.len() > MAX_TRACKED {
313        evict_oldest(&mut map);
314    }
315}
316
317/// Persist when forced (a baseline/latch change) or when the throttle window has
318/// elapsed. The disk write happens outside the store lock.
319fn maybe_persist(force: bool, now: u64) {
320    let last = last_persist().load(Ordering::Relaxed);
321    if !force && now.saturating_sub(last) < PERSIST_MIN_INTERVAL_SECS {
322        return;
323    }
324    last_persist().store(now, Ordering::Relaxed);
325    persist_now(now);
326}
327
328/// Atomically writes the current baselines to disk (`.tmp` + rename).
329fn persist_now(now: u64) {
330    let Some(path) = touch_path() else {
331        return;
332    };
333    let conversations = {
334        let map = store()
335            .lock()
336            .unwrap_or_else(std::sync::PoisonError::into_inner);
337        map.clone()
338    };
339    let payload = PersistedTouch {
340        ts: now,
341        conversations,
342    };
343    let Ok(json) = serde_json::to_string(&payload) else {
344        return;
345    };
346    let tmp = path.with_extension("json.tmp");
347    if std::fs::write(&tmp, json).is_ok() {
348        let _ = std::fs::rename(&tmp, &path);
349    }
350}
351
352/// Test-only: pre-seed a conversation's last-touch `secs_ago` seconds in the
353/// past so a single `repack_decision` call observes a controlled idle gap
354/// (the function overwrites last-touch with `now` on every call).
355///
356/// Tests must use a *unique* first message (hence a unique `conversation_key`)
357/// so seeding one never disturbs another running in parallel — the global store
358/// is shared, so there is deliberately no global "clear" that would race.
359#[cfg(test)]
360pub(crate) fn test_seed_last_touch(messages: &[Value], secs_ago: u64) {
361    if let Some(key) = conversation_key(messages) {
362        let when = now_secs().saturating_sub(secs_ago);
363        store()
364            .lock()
365            .unwrap_or_else(std::sync::PoisonError::into_inner)
366            .insert(
367                key,
368                ConvState {
369                    last_touch: when,
370                    repacking: false,
371                },
372            );
373    }
374}
375
376/// Test-only: drop a single conversation's in-memory baseline (simulates a proxy
377/// restart losing RAM for that key). Single-key removal stays race-free with the
378/// other tests that share the global store.
379#[cfg(test)]
380fn test_remove(messages: &[Value]) {
381    if let Some(key) = conversation_key(messages) {
382        store()
383            .lock()
384            .unwrap_or_else(std::sync::PoisonError::into_inner)
385            .remove(&key);
386    }
387}
388
389#[cfg(test)]
390mod tests {
391    use super::*;
392    use serde_json::json;
393
394    fn cached_body(first_text: &str, ttl: Option<&str>) -> Vec<Value> {
395        let cc = ttl.map_or_else(
396            || json!({"type": "ephemeral"}),
397            |t| json!({"type": "ephemeral", "ttl": t}),
398        );
399        vec![
400            json!({"role": "user", "content": [
401                {"type": "text", "text": first_text, "cache_control": cc}
402            ]}),
403            json!({"role": "assistant", "content": "ok"}),
404        ]
405    }
406
407    #[test]
408    fn key_is_stable_across_turns_and_distinct_per_conversation() {
409        let mut a1 = cached_body("conversation A opening", None);
410        let a2 = {
411            let mut m = a1.clone();
412            m.push(json!({"role": "user", "content": "a follow-up turn"}));
413            m
414        };
415        let b1 = cached_body("conversation B opening", None);
416
417        let ka = conversation_key(&a1).unwrap();
418        let ka2 = conversation_key(&a2).unwrap();
419        let kb = conversation_key(&b1).unwrap();
420        assert_eq!(ka, ka2, "key must be stable as the conversation grows");
421        assert_ne!(ka, kb, "distinct conversations must get distinct keys");
422
423        // Mutating messages[0] changes the key (different conversation head).
424        a1[0] = json!({"role": "user", "content": "different head"});
425        assert_ne!(conversation_key(&a1).unwrap(), ka);
426    }
427
428    #[test]
429    fn ttl_resolves_from_marker_else_default_else_none() {
430        let hour = cached_body("x", Some("1h"));
431        assert_eq!(resolved_ttl_secs(&hour, 1), Some(HOUR_TTL_SECS));
432
433        let five = cached_body("x", Some("5m"));
434        assert_eq!(resolved_ttl_secs(&five, 1), Some(DEFAULT_TTL_SECS));
435
436        // Marker present without an explicit ttl → Anthropic "5m" default.
437        let bare = cached_body("x", None);
438        assert_eq!(resolved_ttl_secs(&bare, 1), Some(DEFAULT_TTL_SECS));
439
440        // No client-cached prefix → nothing to repack.
441        assert_eq!(resolved_ttl_secs(&bare, 0), None);
442    }
443
444    use super::test_seed_last_touch as seed;
445
446    #[test]
447    fn first_sighting_only_sets_baseline() {
448        let msgs = cached_body("first-sighting conversation", None);
449        // No prior touch → never repack, but a baseline is now recorded.
450        assert!(!repack_decision(&msgs, 1));
451        // Immediately after, idle ≈ 0 → still warm.
452        assert!(!repack_decision(&msgs, 1));
453    }
454
455    #[test]
456    fn warm_prefix_is_never_repacked() {
457        let msgs = cached_body("warm conversation", Some("5m"));
458        seed(&msgs, 60); // 1 minute idle, TTL 5m → warm
459        assert!(!repack_decision(&msgs, 1));
460    }
461
462    #[test]
463    fn large_gap_triggers_repack() {
464        let msgs = cached_body("cold conversation 5m", Some("5m"));
465        seed(&msgs, 2 * 60 * 60); // 2h idle, threshold = max(600, 600) = 600
466        assert!(repack_decision(&msgs, 1));
467    }
468
469    #[test]
470    fn cached_zero_never_repacks_even_when_idle() {
471        let msgs = cached_body("idle but uncached", None);
472        seed(&msgs, 24 * 60 * 60);
473        // cached == 0: there is no client-cached prefix to repack.
474        assert!(!repack_decision(&msgs, 0));
475    }
476
477    #[test]
478    fn hour_ttl_skips_the_ambiguous_zone() {
479        let msgs = cached_body("cold conversation 1h", Some("1h"));
480        // threshold = 3600 * 2 = 7200s. Just under → still protect.
481        seed(&msgs, 7000);
482        assert!(!repack_decision(&msgs, 1));
483        // Well past → repack.
484        seed(&msgs, 8000);
485        assert!(repack_decision(&msgs, 1));
486    }
487
488    #[test]
489    fn key_ignores_cache_control_marker() {
490        // #499 (3): the same opening content with a different — or absent —
491        // cache_control marker must map to the SAME conversation key, so a moving
492        // cache breakpoint never causes a permanent first-sighting.
493        let none = cached_body("marker-invariant conversation", None);
494        let hour = cached_body("marker-invariant conversation", Some("1h"));
495        let five = cached_body("marker-invariant conversation", Some("5m"));
496        let k = conversation_key(&none).unwrap();
497        assert_eq!(k, conversation_key(&hour).unwrap());
498        assert_eq!(k, conversation_key(&five).unwrap());
499        // Different opening content still yields a different key.
500        let other = cached_body("a different opening", Some("1h"));
501        assert_ne!(k, conversation_key(&other).unwrap());
502    }
503
504    #[test]
505    fn sticky_repack_persists_into_warm_followups() {
506        // #499 (1): the N→N+1 interaction the original tests never covered.
507        let msgs = cached_body("sticky cold-then-warm conversation", Some("5m"));
508        // Turn N: a long idle gap → cold → repack fires and latches.
509        seed(&msgs, 2 * 60 * 60);
510        assert!(
511            repack_decision(&msgs, 1),
512            "a cold gap must trigger the repack"
513        );
514        // Turn N+1, seconds later (idle ≈ 0): pre-fix this fell back to protecting
515        // the prefix and re-sent the uncompressed original, busting the cache
516        // written at turn N. The latch must keep repacking so the cold-turn cache
517        // is hit.
518        assert!(
519            repack_decision(&msgs, 1),
520            "an immediate warm follow-up must stay sticky and keep repacking"
521        );
522        assert!(
523            repack_decision(&msgs, 1),
524            "stickiness persists across the rest of the session"
525        );
526    }
527
528    #[test]
529    fn cold_baseline_survives_restart_via_disk() {
530        // #499 (2): a baseline recorded before a restart must be recoverable from
531        // disk so the long gap is still detected (RAM-only loses it).
532        let _iso = crate::core::data_dir::isolated_data_dir();
533        let msgs = cached_body("restart-survival conversation", Some("5m"));
534        seed(&msgs, 3 * 60 * 60);
535        persist_now(now_secs());
536        // Simulate a proxy restart: the in-memory baseline is gone.
537        test_remove(&msgs);
538        // resume_from_disk restores it; the persisted cold gap still triggers.
539        resume_from_disk();
540        assert!(
541            repack_decision(&msgs, 1),
542            "a persisted cold baseline must survive a restart and still repack"
543        );
544    }
545}