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/// `system_compressed` latches on once the warm-prefix cost gate compressed the
78/// system prompt, so later turns keep sending that same prefix (#1912).
79#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
80struct ConvState {
81 last_touch: u64,
82 repacking: bool,
83 #[serde(default)]
84 system_compressed: bool,
85}
86
87fn store() -> &'static Mutex<HashMap<u64, ConvState>> {
88 static STORE: OnceLock<Mutex<HashMap<u64, ConvState>>> = OnceLock::new();
89 STORE.get_or_init(|| Mutex::new(HashMap::new()))
90}
91
92/// Wall-clock seconds of the last successful disk persist (throttle gate).
93fn last_persist() -> &'static AtomicU64 {
94 static LAST: AtomicU64 = AtomicU64::new(0);
95 &LAST
96}
97
98fn now_secs() -> u64 {
99 SystemTime::now()
100 .duration_since(UNIX_EPOCH)
101 .map_or(0, |d| d.as_secs())
102}
103
104fn hash_bytes(bytes: &[u8]) -> u64 {
105 let mut h = std::collections::hash_map::DefaultHasher::new();
106 bytes.hash(&mut h);
107 h.finish()
108}
109
110/// Stable per-conversation key: a hash of the first message with every
111/// `cache_control` marker stripped first. `messages[0]` is byte-stable across a
112/// conversation's turns *except* for its volatile cache breakpoint — clients move
113/// or retune the `cache_control` (`ephemeral`/`ttl`) marker as the prompt grows.
114/// Hashing the raw message would then change the key mid-conversation → a
115/// permanent "first sighting" that never repacks (#499). Stripping the marker
116/// keys on stable content only. Distinct conversations still differ (distinct
117/// opening turns); a collision can only make the recorded last-touch *more
118/// recent*, biasing toward "warm" — never a wrong "cold". `None` when there is no
119/// first message.
120pub(crate) fn conversation_key(messages: &[Value]) -> Option<u64> {
121 let mut first = messages.first()?.clone();
122 strip_cache_control(&mut first);
123 let bytes = serde_json::to_vec(&first).ok()?;
124 Some(hash_bytes(&bytes))
125}
126
127/// Content hash of the client-cached prefix `messages[0..cached]` with every
128/// volatile `cache_control` marker stripped — the stable identity of the prefix
129/// a provider would cache. Turn-to-turn equality means the cacheable prefix did
130/// not change; inequality means something (a rewrite, an edited earlier turn)
131/// busted it. `None` when `cached == 0` (nothing anchored to compare). Shared so
132/// [`crate::proxy::cache_attribution`] keys on the exact same stable bytes.
133pub(crate) fn cached_prefix_hash(messages: &[Value], cached: usize) -> Option<u64> {
134 let end = cached.min(messages.len());
135 if end == 0 {
136 return None;
137 }
138 let mut prefix: Vec<Value> = messages[..end].to_vec();
139 for msg in &mut prefix {
140 strip_cache_control(msg);
141 }
142 let bytes = serde_json::to_vec(&prefix).ok()?;
143 Some(hash_bytes(&bytes))
144}
145
146/// Recursively remove every `cache_control` field so a moving cache breakpoint
147/// can't change the conversation key. The marker always nests `type:ephemeral`
148/// and any `ttl` inside `cache_control`, so dropping that one field suffices.
149fn strip_cache_control(v: &mut Value) {
150 match v {
151 Value::Object(map) => {
152 map.remove("cache_control");
153 for val in map.values_mut() {
154 strip_cache_control(val);
155 }
156 }
157 Value::Array(arr) => {
158 for val in arr {
159 strip_cache_control(val);
160 }
161 }
162 _ => {}
163 }
164}
165
166fn parse_ttl_str(s: &str) -> Option<u64> {
167 match s.trim() {
168 "1h" => Some(HOUR_TTL_SECS),
169 "5m" => Some(DEFAULT_TTL_SECS),
170 _ => None,
171 }
172}
173
174/// Largest `cache_control.ttl` declared anywhere inside one message (message-,
175/// block-, or nested text-level), in seconds. `None` when no parseable ttl.
176fn max_ttl_in_message(msg: &Value) -> Option<u64> {
177 let mut best: Option<u64> = None;
178 collect_cc_ttl(msg, &mut best);
179 best
180}
181
182fn collect_cc_ttl(v: &Value, best: &mut Option<u64>) {
183 match v {
184 Value::Object(map) => {
185 if let Some(ttl) = map
186 .get("cache_control")
187 .and_then(|cc| cc.get("ttl"))
188 .and_then(Value::as_str)
189 .and_then(parse_ttl_str)
190 {
191 *best = Some(best.map_or(ttl, |b| b.max(ttl)));
192 }
193 for val in map.values() {
194 collect_cc_ttl(val, best);
195 }
196 }
197 Value::Array(arr) => {
198 for val in arr {
199 collect_cc_ttl(val, best);
200 }
201 }
202 _ => {}
203 }
204}
205
206/// Resolve the cache TTL (seconds) for the client-cached prefix `[0..cached)`.
207/// Returns the largest TTL any cached message requested, defaulting to the "5m"
208/// Anthropic default because a `cache_control` marker is present. `None` only
209/// when `cached == 0` (no marker) — in which case there is nothing to repack.
210pub(crate) fn resolved_ttl_secs(messages: &[Value], cached: usize) -> Option<u64> {
211 if cached == 0 {
212 return None;
213 }
214 let end = cached.min(messages.len());
215 let mut ttl = DEFAULT_TTL_SECS;
216 for msg in &messages[..end] {
217 if let Some(t) = max_ttl_in_message(msg) {
218 ttl = ttl.max(t);
219 }
220 }
221 Some(ttl)
222}
223
224fn evict_oldest(map: &mut HashMap<u64, ConvState>) {
225 if let Some(oldest_key) = map
226 .iter()
227 .min_by_key(|(_, s)| s.last_touch)
228 .map(|(k, _)| *k)
229 {
230 map.remove(&oldest_key);
231 }
232}
233
234/// Decide whether to repack the (predicted-cold) cached prefix for THIS request,
235/// recording this request as the conversation's latest touch.
236///
237/// Returns `true` when the conversation is already in the sticky repacking state
238/// (a prior turn went cold — keep the compressed prefix stable, #499) or when a
239/// fresh cold gap is detected: a client-cached prefix exists (`cached > 0`), a
240/// prior touch exists (so the idle gap is measurable), and the idle gap exceeds
241/// `TTL × SAFETY_MARGIN` and the absolute floor. The caller owns the opt-in gate;
242/// this is only ever called when the operator enabled it, so updating the
243/// last-touch baseline here is the intended side effect for the *next* request.
244pub fn repack_decision(messages: &[Value], cached: usize) -> bool {
245 let Some(key) = conversation_key(messages) else {
246 return false;
247 };
248 let now = now_secs();
249 let ttl = resolved_ttl_secs(messages, cached);
250
251 let (decision, changed) = {
252 let mut map = store()
253 .lock()
254 .unwrap_or_else(std::sync::PoisonError::into_inner);
255 let prev = map.get(&key).copied();
256 let was_first = prev.is_none();
257 let already_repacking = prev.is_some_and(|s| s.repacking);
258
259 // A fresh cold gap: a measurable idle past `TTL × margin` (and the floor)
260 // on a turn that actually carries a client-cached prefix.
261 let fresh_cold = match (prev, ttl) {
262 (Some(p), Some(t)) if cached > 0 => {
263 let idle = now.saturating_sub(p.last_touch);
264 idle > t.saturating_mul(SAFETY_MARGIN).max(COLD_FLOOR_SECS)
265 }
266 _ => false,
267 };
268
269 // Sticky latch: once cold→repacked, stay repacking. Deterministic re-
270 // compression keeps the prefix byte-stable so warm follow-ups hit the
271 // cache written at the cold turn instead of busting it (#499).
272 let repacking = already_repacking || fresh_cold;
273 map.insert(
274 key,
275 ConvState {
276 last_touch: now,
277 repacking,
278 ..prev.unwrap_or_default()
279 },
280 );
281 if map.len() > MAX_TRACKED {
282 evict_oldest(&mut map);
283 }
284
285 // Persist eagerly when the latch first engages or on a first sighting
286 // (both define a baseline that must survive an immediate restart);
287 // otherwise let the throttle decide.
288 let changed = was_first || (repacking && !already_repacking);
289 // Repack only when we are in the repacking state AND there is a cached
290 // prefix to act on this turn (a `cached == 0` turn prunes from 0 anyway).
291 (repacking && cached > 0, changed)
292 };
293
294 maybe_persist(changed, now);
295 decision
296}
297
298/// True once the warm-prefix cost gate compressed this conversation's system
299/// prompt (#1912). The latch keeps every later turn on the compressed prefix the
300/// provider cached — re-deciding per turn could flip back and bust it again.
301pub(crate) fn system_compression_latched(key: u64) -> bool {
302 store()
303 .lock()
304 .unwrap_or_else(std::sync::PoisonError::into_inner)
305 .get(&key)
306 .is_some_and(|s| s.system_compressed)
307}
308
309/// Engages the system-compression latch for a conversation and persists it
310/// eagerly, so a proxy restart cannot flip the conversation back to the
311/// uncompressed prefix.
312pub(crate) fn latch_system_compression(key: u64) {
313 let now = now_secs();
314 {
315 let mut map = store()
316 .lock()
317 .unwrap_or_else(std::sync::PoisonError::into_inner);
318 let entry = map.entry(key).or_insert(ConvState {
319 last_touch: now,
320 ..ConvState::default()
321 });
322 entry.system_compressed = true;
323 if map.len() > MAX_TRACKED {
324 evict_oldest(&mut map);
325 }
326 }
327 maybe_persist(true, now);
328}
329
330/// On-disk shape of the cross-restart baselines. `ts` is advisory (debugging);
331/// the per-conversation `last_touch` values are what prove an idle gap.
332#[derive(Debug, Default, Serialize, Deserialize)]
333struct PersistedTouch {
334 ts: u64,
335 conversations: HashMap<u64, ConvState>,
336}
337
338fn touch_path() -> Option<std::path::PathBuf> {
339 crate::core::data_dir::lean_ctx_data_dir()
340 .ok()
341 .map(|d| d.join(TOUCH_FILE))
342}
343
344/// Serializes disk read/write. Concurrent `maybe_persist` callers (and the
345/// multi-step restart test) must not interleave a stale full-map snapshot over a
346/// just-written baseline — last-writer-wins on the whole file is otherwise racy.
347fn disk_io_lock() -> &'static Mutex<()> {
348 static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
349 LOCK.get_or_init(|| Mutex::new(()))
350}
351
352/// Seeds the in-memory baselines from disk on proxy startup so an idle gap that
353/// straddles a restart is still detected. Merges by most-recent `last_touch` and
354/// OR-s the sticky `repacking` latch, so a re-seed can only bias toward "warm"
355/// (or keep a latch), never toward a wrong "cold".
356pub fn resume_from_disk() {
357 let _disk = disk_io_lock()
358 .lock()
359 .unwrap_or_else(std::sync::PoisonError::into_inner);
360 resume_from_disk_unlocked();
361}
362
363fn resume_from_disk_unlocked() {
364 let Some(path) = touch_path() else {
365 return;
366 };
367 let Ok(data) = std::fs::read_to_string(&path) else {
368 return;
369 };
370 let Ok(persisted) = serde_json::from_str::<PersistedTouch>(&data) else {
371 return;
372 };
373 let mut map = store()
374 .lock()
375 .unwrap_or_else(std::sync::PoisonError::into_inner);
376 for (key, state) in persisted.conversations {
377 let entry = map.entry(key).or_insert(state);
378 if state.last_touch > entry.last_touch {
379 entry.last_touch = state.last_touch;
380 }
381 entry.repacking |= state.repacking;
382 entry.system_compressed |= state.system_compressed;
383 }
384 while map.len() > MAX_TRACKED {
385 evict_oldest(&mut map);
386 }
387}
388
389/// Persist when forced (a baseline/latch change) or when the throttle window has
390/// elapsed. The disk write happens outside the store lock.
391fn maybe_persist(force: bool, now: u64) {
392 let last = last_persist().load(Ordering::Relaxed);
393 if !force && now.saturating_sub(last) < PERSIST_MIN_INTERVAL_SECS {
394 return;
395 }
396 last_persist().store(now, Ordering::Relaxed);
397 persist_now(now);
398}
399
400/// Atomically writes the current baselines to disk (`.tmp` + rename).
401fn persist_now(now: u64) {
402 let _disk = disk_io_lock()
403 .lock()
404 .unwrap_or_else(std::sync::PoisonError::into_inner);
405 persist_now_unlocked(now);
406}
407
408fn persist_now_unlocked(now: u64) {
409 let Some(path) = touch_path() else {
410 return;
411 };
412 let conversations = {
413 let map = store()
414 .lock()
415 .unwrap_or_else(std::sync::PoisonError::into_inner);
416 map.clone()
417 };
418 let payload = PersistedTouch {
419 ts: now,
420 conversations,
421 };
422 let Ok(json) = serde_json::to_string(&payload) else {
423 return;
424 };
425 let tmp = path.with_extension("json.tmp");
426 if std::fs::write(&tmp, json).is_ok() {
427 let _ = std::fs::rename(&tmp, &path);
428 }
429}
430
431/// Test-only: pre-seed a conversation's last-touch `secs_ago` seconds in the
432/// past so a single `repack_decision` call observes a controlled idle gap
433/// (the function overwrites last-touch with `now` on every call).
434///
435/// Tests must use a *unique* first message (hence a unique `conversation_key`)
436/// so seeding one never disturbs another running in parallel — the global store
437/// is shared, so there is deliberately no global "clear" that would race.
438#[cfg(test)]
439pub(crate) fn test_seed_last_touch(messages: &[Value], secs_ago: u64) {
440 if let Some(key) = conversation_key(messages) {
441 let when = now_secs().saturating_sub(secs_ago);
442 store()
443 .lock()
444 .unwrap_or_else(std::sync::PoisonError::into_inner)
445 .insert(
446 key,
447 ConvState {
448 last_touch: when,
449 repacking: false,
450 system_compressed: false,
451 },
452 );
453 }
454}
455
456/// Test-only: drop a single conversation's in-memory baseline (simulates a proxy
457/// restart losing RAM for that key). Single-key removal stays race-free with the
458/// other tests that share the global store.
459#[cfg(test)]
460fn test_remove(messages: &[Value]) {
461 if let Some(key) = conversation_key(messages) {
462 store()
463 .lock()
464 .unwrap_or_else(std::sync::PoisonError::into_inner)
465 .remove(&key);
466 }
467}
468
469/// Test-only: persist → drop RAM → resume under `disk_io_lock` so a concurrent
470/// `maybe_persist` cannot overwrite the file in the gap between remove and resume
471/// (the flake behind `cold_baseline_survives_restart_via_disk`).
472#[cfg(test)]
473fn test_persist_drop_and_resume(messages: &[Value]) {
474 let _disk = disk_io_lock()
475 .lock()
476 .unwrap_or_else(std::sync::PoisonError::into_inner);
477 persist_now_unlocked(now_secs());
478 test_remove(messages);
479 resume_from_disk_unlocked();
480}
481
482#[cfg(test)]
483mod tests {
484 use super::*;
485 use serde_json::json;
486
487 fn cached_body(first_text: &str, ttl: Option<&str>) -> Vec<Value> {
488 let cc = ttl.map_or_else(
489 || json!({"type": "ephemeral"}),
490 |t| json!({"type": "ephemeral", "ttl": t}),
491 );
492 vec![
493 json!({"role": "user", "content": [
494 {"type": "text", "text": first_text, "cache_control": cc}
495 ]}),
496 json!({"role": "assistant", "content": "ok"}),
497 ]
498 }
499
500 #[test]
501 fn key_is_stable_across_turns_and_distinct_per_conversation() {
502 let mut a1 = cached_body("conversation A opening", None);
503 let a2 = {
504 let mut m = a1.clone();
505 m.push(json!({"role": "user", "content": "a follow-up turn"}));
506 m
507 };
508 let b1 = cached_body("conversation B opening", None);
509
510 let ka = conversation_key(&a1).unwrap();
511 let ka2 = conversation_key(&a2).unwrap();
512 let kb = conversation_key(&b1).unwrap();
513 assert_eq!(ka, ka2, "key must be stable as the conversation grows");
514 assert_ne!(ka, kb, "distinct conversations must get distinct keys");
515
516 // Mutating messages[0] changes the key (different conversation head).
517 a1[0] = json!({"role": "user", "content": "different head"});
518 assert_ne!(conversation_key(&a1).unwrap(), ka);
519 }
520
521 #[test]
522 fn ttl_resolves_from_marker_else_default_else_none() {
523 let hour = cached_body("x", Some("1h"));
524 assert_eq!(resolved_ttl_secs(&hour, 1), Some(HOUR_TTL_SECS));
525
526 let five = cached_body("x", Some("5m"));
527 assert_eq!(resolved_ttl_secs(&five, 1), Some(DEFAULT_TTL_SECS));
528
529 // Marker present without an explicit ttl → Anthropic "5m" default.
530 let bare = cached_body("x", None);
531 assert_eq!(resolved_ttl_secs(&bare, 1), Some(DEFAULT_TTL_SECS));
532
533 // No client-cached prefix → nothing to repack.
534 assert_eq!(resolved_ttl_secs(&bare, 0), None);
535 }
536
537 use super::test_seed_last_touch as seed;
538
539 #[test]
540 fn first_sighting_only_sets_baseline() {
541 let msgs = cached_body("first-sighting conversation", None);
542 // No prior touch → never repack, but a baseline is now recorded.
543 assert!(!repack_decision(&msgs, 1));
544 // Immediately after, idle ≈ 0 → still warm.
545 assert!(!repack_decision(&msgs, 1));
546 }
547
548 #[test]
549 fn warm_prefix_is_never_repacked() {
550 let msgs = cached_body("warm conversation", Some("5m"));
551 seed(&msgs, 60); // 1 minute idle, TTL 5m → warm
552 assert!(!repack_decision(&msgs, 1));
553 }
554
555 #[test]
556 fn large_gap_triggers_repack() {
557 let msgs = cached_body("cold conversation 5m", Some("5m"));
558 seed(&msgs, 2 * 60 * 60); // 2h idle, threshold = max(600, 600) = 600
559 assert!(repack_decision(&msgs, 1));
560 }
561
562 #[test]
563 fn cached_zero_never_repacks_even_when_idle() {
564 let msgs = cached_body("idle but uncached", None);
565 seed(&msgs, 24 * 60 * 60);
566 // cached == 0: there is no client-cached prefix to repack.
567 assert!(!repack_decision(&msgs, 0));
568 }
569
570 #[test]
571 fn hour_ttl_skips_the_ambiguous_zone() {
572 let msgs = cached_body("cold conversation 1h", Some("1h"));
573 // threshold = 3600 * 2 = 7200s. Just under → still protect.
574 seed(&msgs, 7000);
575 assert!(!repack_decision(&msgs, 1));
576 // Well past → repack.
577 seed(&msgs, 8000);
578 assert!(repack_decision(&msgs, 1));
579 }
580
581 #[test]
582 fn key_ignores_cache_control_marker() {
583 // #499 (3): the same opening content with a different — or absent —
584 // cache_control marker must map to the SAME conversation key, so a moving
585 // cache breakpoint never causes a permanent first-sighting.
586 let none = cached_body("marker-invariant conversation", None);
587 let hour = cached_body("marker-invariant conversation", Some("1h"));
588 let five = cached_body("marker-invariant conversation", Some("5m"));
589 let k = conversation_key(&none).unwrap();
590 assert_eq!(k, conversation_key(&hour).unwrap());
591 assert_eq!(k, conversation_key(&five).unwrap());
592 // Different opening content still yields a different key.
593 let other = cached_body("a different opening", Some("1h"));
594 assert_ne!(k, conversation_key(&other).unwrap());
595 }
596
597 #[test]
598 fn sticky_repack_persists_into_warm_followups() {
599 // #499 (1): the N→N+1 interaction the original tests never covered.
600 let msgs = cached_body("sticky cold-then-warm conversation", Some("5m"));
601 // Turn N: a long idle gap → cold → repack fires and latches.
602 seed(&msgs, 2 * 60 * 60);
603 assert!(
604 repack_decision(&msgs, 1),
605 "a cold gap must trigger the repack"
606 );
607 // Turn N+1, seconds later (idle ≈ 0): pre-fix this fell back to protecting
608 // the prefix and re-sent the uncompressed original, busting the cache
609 // written at turn N. The latch must keep repacking so the cold-turn cache
610 // is hit.
611 assert!(
612 repack_decision(&msgs, 1),
613 "an immediate warm follow-up must stay sticky and keep repacking"
614 );
615 assert!(
616 repack_decision(&msgs, 1),
617 "stickiness persists across the rest of the session"
618 );
619 }
620
621 #[test]
622 fn cold_baseline_survives_restart_via_disk() {
623 // #499 (2): a baseline recorded before a restart must be recoverable from
624 // disk so the long gap is still detected (RAM-only loses it).
625 let _iso = crate::core::data_dir::isolated_data_dir();
626 let msgs = cached_body("restart-survival conversation", Some("5m"));
627 seed(&msgs, 3 * 60 * 60);
628 // Atomic under disk_io_lock: parallel cold_prefix tests also call
629 // maybe_persist and would otherwise wipe this key after test_remove.
630 test_persist_drop_and_resume(&msgs);
631 assert!(
632 repack_decision(&msgs, 1),
633 "a persisted cold baseline must survive a restart and still repack"
634 );
635 }
636}