Skip to main content

lean_ctx/proxy/
cache_policy.rs

1//! Net-cost policy for cache-busting rewrites (#986, cache-economics).
2//!
3//! The cold-prefix repack (#480) re-seeds a leaner prompt cache when the proxy
4//! predicts the client-cached prefix has already gone cold (idle past the TTL).
5//! Because the entry is *already* expired, the provider re-writes the prefix on
6//! the next turn no matter what — so compressing that unavoidable re-write is
7//! free savings, **except** for prefixes too small to be cached at all. Repacking
8//! one of those only churns the conversation's cache identity for no benefit.
9//!
10//! This module is the pricing brain that decides when a repack pays:
11//!
12//! - [`worth_repacking`] — the live gate applied in `anthropic.rs`. It runs
13//!   *before* compression, so it can only weigh the measurable precondition: is
14//!   the cacheable prefix even large enough to be worth re-seeding?
15//! - [`net_cost_decision`] / [`repack_saving_usd`] — the fully priced primitive
16//!   (before/after token counts × `ModelCost`) for callers that already know
17//!   the compressed size (tests today, cache-edit batching later).
18//! - [`system_mutation_decision`] — the warm-prefix gate for compressing the
19//!   `system` prompt while a message prefix is cached (#1912): it prices the
20//!   bust of the whole prefix against the per-turn cache-read saving, with the
21//!   conversation's own turn count as the reuse estimate and current prices
22//!   from the shared table ([`model_cost_for`]).
23//!
24//! Pure functions, no globals; gated behind the opt-in `proxy.cache_policy` at
25//! the call site so a default proxy keeps today's behaviour exactly.
26
27use serde_json::Value;
28
29use crate::core::gain::model_pricing::ModelCost;
30use crate::core::tokens::count_tokens;
31
32/// Minimum cacheable prefix size, in tokens. Anthropic will not cache a prefix
33/// below this (1024 for most models; Haiku needs more), so re-seeding a smaller
34/// one can never produce a cache the provider would keep — the conservative
35/// floor below which a repack is pure churn. Chosen as the documented Anthropic
36/// minimum rather than an estimate.
37pub const MIN_CACHEABLE_TOKENS: u64 = 1024;
38
39/// Token count of an Anthropic `system` field (a string or a content-block
40/// array) — the part of the cacheable prefix that precedes every message.
41/// Serialized and BPE-counted like the messages below so both halves of the
42/// prefix use one consistent measure.
43fn system_tokens(system: Option<&Value>) -> u64 {
44    match system {
45        Some(v) if !v.is_null() => serde_json::to_string(v).map_or(0, |s| count_tokens(&s) as u64),
46        _ => 0,
47    }
48}
49
50/// Token count of the prefix the provider would actually cache: the `system`
51/// field plus the client-cached messages `messages[0..cached]`. Measured (not
52/// estimated) via the same BPE counter the rest of the proxy uses, so the gate
53/// reflects the real prefix — including the system prose a cold-prefix repack
54/// re-seeds, which is usually the bulk of it.
55#[must_use]
56pub fn prefix_tokens(system: Option<&Value>, messages: &[Value], cached: usize) -> u64 {
57    let mut total = system_tokens(system);
58    let end = cached.min(messages.len());
59    if end > 0
60        && let Ok(serialized) = serde_json::to_string(&messages[..end])
61    {
62        total += count_tokens(&serialized) as u64;
63    }
64    total
65}
66
67/// Live repack gate (pre-compression). A cold-prefix repack only pays when the
68/// cacheable prefix (system + cached messages) is large enough that the provider
69/// will actually cache the re-seeded version; below [`MIN_CACHEABLE_TOKENS`] the
70/// repack just churns the conversation's cache key. Applied as an extra
71/// AND-condition on the existing repack decision, so the policy can only make
72/// repacking *more* conservative — never trigger a rewrite that would not have
73/// happened.
74#[must_use]
75pub fn worth_repacking(system: Option<&Value>, messages: &[Value], cached: usize) -> bool {
76    prefix_tokens(system, messages, cached) >= MIN_CACHEABLE_TOKENS
77}
78
79/// Cache-write cost saved by re-seeding a compressed prefix instead of the full
80/// one, in USD. On a cold prefix the provider re-writes regardless, so the saving
81/// is the avoided write of the dropped tokens: `(before − after) × cache_write`.
82/// Clamped to `0.0` when compression did not shrink the prefix.
83#[must_use]
84pub fn repack_saving_usd(before_tokens: u64, after_tokens: u64, cost: &ModelCost) -> f64 {
85    let saved = before_tokens.saturating_sub(after_tokens);
86    saved as f64 / 1_000_000.0 * cost.cache_write_per_m
87}
88
89/// Fully priced repack decision for callers that already know the compressed
90/// size. True when the prefix is cacheable *and* re-seeding it strictly lowers
91/// the unavoidable cold re-write cost. The precondition mirrors
92/// [`worth_repacking`] so the live gate and the priced primitive never disagree.
93#[must_use]
94pub fn net_cost_decision(before_tokens: u64, after_tokens: u64, cost: &ModelCost) -> bool {
95    before_tokens >= MIN_CACHEABLE_TOKENS
96        && after_tokens < before_tokens
97        && repack_saving_usd(before_tokens, after_tokens, cost) > 0.0
98}
99
100/// Decision outcome for a frozen-region mutation.
101#[derive(Debug, Clone, Copy, PartialEq)]
102pub enum MutationDecision {
103    /// The compression saving exceeds the cache-bust cost.
104    Mutate { break_even: u32 },
105    /// The cache-bust cost exceeds the compression saving; preserve the prefix.
106    Preserve { break_even: u32 },
107}
108
109/// Cost parameters for a model name, from the shared pricing table (embedded
110/// prices, `[cost.prices]` overrides, live list) so the gate never prices a
111/// request with stale per-family constants (#1912).
112#[must_use]
113pub fn model_cost_for(model: &str) -> ModelCost {
114    crate::core::gain::model_pricing::ModelPricing::load()
115        .quote(Some(model))
116        .cost
117}
118
119/// Generalised net-cost gate for **any** frozen-region mutation. A frozen
120/// region is served from the prompt cache, so:
121///
122/// - the one-off bust is the mutation turn's re-write of the shrunk prefix in
123///   place of the cache read it would otherwise have been
124///   (`after × cache_write − before × cache_read`, never negative);
125/// - the per-call saving afterwards is the dropped tokens at the *cache-read*
126///   price (they would have been cache reads, not fresh input).
127///
128/// Mutates only when the expected reuse count reaches the break-even point.
129#[must_use]
130pub fn should_mutate_frozen(
131    before_tokens: u64,
132    after_tokens: u64,
133    estimated_reuse_count: u32,
134    cost: &ModelCost,
135) -> MutationDecision {
136    if before_tokens < MIN_CACHEABLE_TOKENS || after_tokens >= before_tokens {
137        return MutationDecision::Preserve {
138            break_even: u32::MAX,
139        };
140    }
141    let saved_tokens = before_tokens - after_tokens;
142    let bust_cost = (after_tokens as f64 / 1_000_000.0 * cost.cache_write_per_m
143        - before_tokens as f64 / 1_000_000.0 * cost.cache_read_per_m)
144        .max(0.0);
145    let per_call_saving = saved_tokens as f64 / 1_000_000.0 * cost.cache_read_per_m;
146    if per_call_saving <= 0.0 {
147        return MutationDecision::Preserve {
148            break_even: u32::MAX,
149        };
150    }
151    let break_even = (bust_cost / per_call_saving).ceil().max(1.0) as u32;
152    if estimated_reuse_count >= break_even {
153        MutationDecision::Mutate { break_even }
154    } else {
155        MutationDecision::Preserve { break_even }
156    }
157}
158
159/// Expected future reuses of a cached prefix, read from the conversation
160/// itself: every prior assistant turn is a request that already re-sent the
161/// prefix. A pure function of the request, so the gate below decides the same
162/// way on every replay of the same turn (#498) — unlike a process-wide rate.
163#[must_use]
164pub fn observed_prefix_reuse(messages: &[Value]) -> u32 {
165    let turns = messages
166        .iter()
167        .filter(|m| m.get("role").and_then(Value::as_str) == Some("assistant"))
168        .count();
169    u32::try_from(turns).unwrap_or(u32::MAX)
170}
171
172/// Priced gate for compressing the `system` prompt while the client caches a
173/// message prefix (#1912). The system block sits in front of every cached
174/// message, so rewriting it busts the *whole* prefix: the bust is priced on
175/// `prefix_before` (system + cached messages, see [`prefix_tokens`]) and the
176/// saving on the measured shrink of the system block alone.
177#[must_use]
178pub fn system_mutation_decision(
179    prefix_before: u64,
180    system_before: &Value,
181    system_after: &Value,
182    reuse: u32,
183    cost: &ModelCost,
184) -> MutationDecision {
185    let saved =
186        system_tokens(Some(system_before)).saturating_sub(system_tokens(Some(system_after)));
187    should_mutate_frozen(
188        prefix_before,
189        prefix_before.saturating_sub(saved),
190        reuse,
191        cost,
192    )
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198    use serde_json::json;
199
200    fn opus() -> ModelCost {
201        ModelCost {
202            input_per_m: 5.00,
203            output_per_m: 25.00,
204            cache_write_per_m: 6.25,
205            cache_read_per_m: 0.50,
206        }
207    }
208
209    #[test]
210    fn prefix_tokens_zero_when_nothing_cached() {
211        let msgs = vec![json!({"role": "user", "content": "hello"})];
212        assert_eq!(prefix_tokens(None, &msgs, 0), 0);
213    }
214
215    #[test]
216    fn prefix_tokens_counts_only_the_cached_span() {
217        let big = "lorem ipsum dolor sit amet ".repeat(50);
218        let msgs = vec![
219            json!({"role": "user", "content": big}),
220            json!({"role": "assistant", "content": "tail not counted"}),
221        ];
222        let one = prefix_tokens(None, &msgs, 1);
223        let two = prefix_tokens(None, &msgs, 2);
224        assert!(one > 0);
225        assert!(two > one, "wider cached span counts more tokens");
226    }
227
228    #[test]
229    fn prefix_tokens_includes_the_system_field() {
230        // The system prose is part of Anthropic's cacheable prefix and is what a
231        // cold repack re-seeds, so it must count toward the gate.
232        let msgs = vec![json!({"role": "user", "content": "hi"})];
233        let big_system = json!("context engineering ".repeat(400));
234        let without = prefix_tokens(None, &msgs, 1);
235        let with = prefix_tokens(Some(&big_system), &msgs, 1);
236        assert!(with > without + 500, "system prose must dominate the count");
237    }
238
239    #[test]
240    fn worth_repacking_rejects_small_prefix() {
241        let msgs = vec![json!({"role": "user", "content": "tiny"})];
242        assert!(!worth_repacking(None, &msgs, 1));
243    }
244
245    #[test]
246    fn worth_repacking_accepts_large_prefix() {
247        // Comfortably above the 1024-token cacheable floor.
248        let big = "context engineering ".repeat(1500);
249        let msgs = vec![json!({"role": "user", "content": big})];
250        assert!(worth_repacking(None, &msgs, 1));
251    }
252
253    #[test]
254    fn worth_repacking_counts_large_system_over_tiny_messages() {
255        // A small message prefix but a large system prompt still clears the gate,
256        // because the provider caches system + messages together.
257        let msgs = vec![json!({"role": "user", "content": "hi"})];
258        let big_system = json!("context engineering ".repeat(1500));
259        assert!(
260            !worth_repacking(None, &msgs, 1),
261            "tiny prefix alone is skipped"
262        );
263        assert!(
264            worth_repacking(Some(&big_system), &msgs, 1),
265            "a large system prompt makes the prefix worth re-seeding"
266        );
267    }
268
269    #[test]
270    fn net_cost_decision_rejects_subcacheable_even_if_smaller() {
271        // Below the cacheable floor: a smaller "after" still doesn't pay.
272        assert!(!net_cost_decision(500, 200, &opus()));
273    }
274
275    #[test]
276    fn net_cost_decision_rejects_when_no_shrink() {
277        assert!(!net_cost_decision(4000, 4000, &opus()));
278        assert!(!net_cost_decision(4000, 5000, &opus()));
279    }
280
281    #[test]
282    fn net_cost_decision_accepts_real_saving() {
283        assert!(net_cost_decision(4000, 2500, &opus()));
284        // Saving is the avoided write of the 1500 dropped tokens.
285        let saved = repack_saving_usd(4000, 2500, &opus());
286        assert!((saved - (1500.0 / 1_000_000.0 * 6.25)).abs() < 1e-9);
287    }
288
289    #[test]
290    fn repack_saving_is_zero_when_inflated() {
291        assert_eq!(repack_saving_usd(1000, 2000, &opus()), 0.0);
292    }
293
294    #[test]
295    fn should_mutate_frozen_accepts_with_enough_reuse() {
296        // bust = 2000×6.25 − 4000×0.50 = 10 500; saving/call = 2000×0.50 = 1 000
297        // (per-million units) → break-even after 11 reuses.
298        let d = should_mutate_frozen(4000, 2000, 20, &opus());
299        assert_eq!(d, MutationDecision::Mutate { break_even: 11 });
300        assert_eq!(
301            should_mutate_frozen(4000, 2000, 10, &opus()),
302            MutationDecision::Preserve { break_even: 11 }
303        );
304    }
305
306    #[test]
307    fn should_mutate_frozen_prices_savings_as_cache_reads() {
308        // Without a cache discount there is nothing to bust: mutate at once.
309        let flat = ModelCost {
310            input_per_m: 2.0,
311            output_per_m: 8.0,
312            cache_write_per_m: 2.0,
313            cache_read_per_m: 2.0,
314        };
315        assert_eq!(
316            should_mutate_frozen(4000, 2000, 1, &flat),
317            MutationDecision::Mutate { break_even: 1 }
318        );
319    }
320
321    #[test]
322    fn observed_reuse_counts_prior_assistant_turns() {
323        let msgs = vec![
324            json!({"role": "user", "content": "a"}),
325            json!({"role": "assistant", "content": "b"}),
326            json!({"role": "user", "content": "c"}),
327            json!({"role": "assistant", "content": "d"}),
328            json!({"role": "user", "content": "e"}),
329        ];
330        assert_eq!(observed_prefix_reuse(&msgs), 2);
331        assert_eq!(observed_prefix_reuse(&[]), 0);
332    }
333
334    #[test]
335    fn system_gate_prices_the_whole_prefix() {
336        let before = json!("context engineering ".repeat(1500));
337        let after = json!("context engineering ".repeat(300));
338        let prefix = system_tokens(Some(&before));
339        // Same shrink, but a large cached message tail behind the system block
340        // makes the bust dearer — the break-even must move out.
341        let small = system_mutation_decision(prefix, &before, &after, 1000, &opus());
342        let large = system_mutation_decision(prefix * 10, &before, &after, 1000, &opus());
343        let be = |d: MutationDecision| match d {
344            MutationDecision::Mutate { break_even } | MutationDecision::Preserve { break_even } => {
345                break_even
346            }
347        };
348        assert!(be(large) > be(small), "{small:?} vs {large:?}");
349        assert!(matches!(
350            system_mutation_decision(prefix, &before, &before, 1000, &opus()),
351            MutationDecision::Preserve { .. }
352        ));
353    }
354
355    #[test]
356    fn should_mutate_frozen_rejects_with_low_reuse() {
357        let d = should_mutate_frozen(4000, 3900, 1, &opus());
358        assert!(matches!(d, MutationDecision::Preserve { .. }));
359    }
360
361    #[test]
362    fn should_mutate_frozen_rejects_subcacheable() {
363        let d = should_mutate_frozen(500, 200, 100, &opus());
364        assert!(matches!(d, MutationDecision::Preserve { .. }));
365    }
366
367    #[test]
368    fn should_mutate_frozen_rejects_inflation() {
369        let d = should_mutate_frozen(3000, 4000, 100, &opus());
370        assert!(matches!(d, MutationDecision::Preserve { .. }));
371    }
372
373    #[test]
374    fn model_cost_uses_current_pricing_table() {
375        // #1912: the gate used to price every Opus at the retired $15/$75 and
376        // every Haiku at $0.25 — now it reads the shared, current table.
377        let opus = model_cost_for("claude-opus-4-5");
378        assert!((opus.input_per_m - 5.0).abs() < 1e-9, "{opus:?}");
379        assert!((opus.cache_write_per_m - 6.25).abs() < 1e-9, "{opus:?}");
380        let haiku = model_cost_for("claude-haiku-4-5");
381        assert!((haiku.input_per_m - 1.0).abs() < 1e-9, "{haiku:?}");
382    }
383}