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//!
19//! Pure functions, no globals; gated behind the opt-in `proxy.cache_policy` at
20//! the call site so a default proxy keeps today's behaviour exactly.
21
22use serde_json::Value;
23
24use crate::core::gain::model_pricing::ModelCost;
25use crate::core::tokens::count_tokens;
26
27/// Minimum cacheable prefix size, in tokens. Anthropic will not cache a prefix
28/// below this (1024 for most models; Haiku needs more), so re-seeding a smaller
29/// one can never produce a cache the provider would keep — the conservative
30/// floor below which a repack is pure churn. Chosen as the documented Anthropic
31/// minimum rather than an estimate.
32pub const MIN_CACHEABLE_TOKENS: u64 = 1024;
33
34/// Token count of an Anthropic `system` field (a string or a content-block
35/// array) — the part of the cacheable prefix that precedes every message.
36/// Serialized and BPE-counted like the messages below so both halves of the
37/// prefix use one consistent measure.
38fn system_tokens(system: Option<&Value>) -> u64 {
39    match system {
40        Some(v) if !v.is_null() => serde_json::to_string(v).map_or(0, |s| count_tokens(&s) as u64),
41        _ => 0,
42    }
43}
44
45/// Token count of the prefix the provider would actually cache: the `system`
46/// field plus the client-cached messages `messages[0..cached]`. Measured (not
47/// estimated) via the same BPE counter the rest of the proxy uses, so the gate
48/// reflects the real prefix — including the system prose a cold-prefix repack
49/// re-seeds, which is usually the bulk of it.
50#[must_use]
51pub fn prefix_tokens(system: Option<&Value>, messages: &[Value], cached: usize) -> u64 {
52    let mut total = system_tokens(system);
53    let end = cached.min(messages.len());
54    if end > 0
55        && let Ok(serialized) = serde_json::to_string(&messages[..end])
56    {
57        total += count_tokens(&serialized) as u64;
58    }
59    total
60}
61
62/// Live repack gate (pre-compression). A cold-prefix repack only pays when the
63/// cacheable prefix (system + cached messages) is large enough that the provider
64/// will actually cache the re-seeded version; below [`MIN_CACHEABLE_TOKENS`] the
65/// repack just churns the conversation's cache key. Applied as an extra
66/// AND-condition on the existing repack decision, so the policy can only make
67/// repacking *more* conservative — never trigger a rewrite that would not have
68/// happened.
69#[must_use]
70pub fn worth_repacking(system: Option<&Value>, messages: &[Value], cached: usize) -> bool {
71    prefix_tokens(system, messages, cached) >= MIN_CACHEABLE_TOKENS
72}
73
74/// Cache-write cost saved by re-seeding a compressed prefix instead of the full
75/// one, in USD. On a cold prefix the provider re-writes regardless, so the saving
76/// is the avoided write of the dropped tokens: `(before − after) × cache_write`.
77/// Clamped to `0.0` when compression did not shrink the prefix.
78#[must_use]
79pub fn repack_saving_usd(before_tokens: u64, after_tokens: u64, cost: &ModelCost) -> f64 {
80    let saved = before_tokens.saturating_sub(after_tokens);
81    saved as f64 / 1_000_000.0 * cost.cache_write_per_m
82}
83
84/// Fully priced repack decision for callers that already know the compressed
85/// size. True when the prefix is cacheable *and* re-seeding it strictly lowers
86/// the unavoidable cold re-write cost. The precondition mirrors
87/// [`worth_repacking`] so the live gate and the priced primitive never disagree.
88#[must_use]
89pub fn net_cost_decision(before_tokens: u64, after_tokens: u64, cost: &ModelCost) -> bool {
90    before_tokens >= MIN_CACHEABLE_TOKENS
91        && after_tokens < before_tokens
92        && repack_saving_usd(before_tokens, after_tokens, cost) > 0.0
93}
94
95/// Decision outcome for a frozen-region mutation.
96#[derive(Debug, Clone, Copy, PartialEq)]
97pub enum MutationDecision {
98    /// The compression saving exceeds the cache-bust cost.
99    Mutate { break_even: u32 },
100    /// The cache-bust cost exceeds the compression saving; preserve the prefix.
101    Preserve { break_even: u32 },
102}
103
104/// Generalised net-cost gate for **any** frozen-region mutation. Compares the
105/// Look up cost parameters for a model name. Falls back to Sonnet-class pricing.
106#[must_use]
107pub fn model_cost_for(model: &str) -> ModelCost {
108    let m = model.to_ascii_lowercase();
109    if m.contains("opus") {
110        ModelCost {
111            input_per_m: 15.0,
112            output_per_m: 75.0,
113            cache_write_per_m: 18.75,
114            cache_read_per_m: 1.5,
115        }
116    } else if m.contains("haiku") {
117        ModelCost {
118            input_per_m: 0.25,
119            output_per_m: 1.25,
120            cache_write_per_m: 0.30,
121            cache_read_per_m: 0.03,
122        }
123    } else {
124        ModelCost {
125            input_per_m: 3.0,
126            output_per_m: 15.0,
127            cache_write_per_m: 3.75,
128            cache_read_per_m: 0.30,
129        }
130    }
131}
132
133pub fn should_mutate_frozen(
134    before_tokens: u64,
135    after_tokens: u64,
136    estimated_reuse_count: u32,
137    cost: &ModelCost,
138) -> MutationDecision {
139    if before_tokens < MIN_CACHEABLE_TOKENS || after_tokens >= before_tokens {
140        return MutationDecision::Preserve {
141            break_even: u32::MAX,
142        };
143    }
144    let saved_tokens = before_tokens - after_tokens;
145    let bust_cost = (after_tokens as f64 / 1_000_000.0 * cost.cache_write_per_m)
146        + (before_tokens as f64 / 1_000_000.0 * cost.cache_read_per_m);
147    let per_call_saving = saved_tokens as f64 / 1_000_000.0 * cost.input_per_m;
148    if per_call_saving <= 0.0 {
149        return MutationDecision::Preserve {
150            break_even: u32::MAX,
151        };
152    }
153    let break_even = (bust_cost / per_call_saving).ceil().max(1.0) as u32;
154    if estimated_reuse_count >= break_even {
155        MutationDecision::Mutate { break_even }
156    } else {
157        MutationDecision::Preserve { break_even }
158    }
159}
160
161#[cfg(test)]
162mod tests {
163    use super::*;
164    use serde_json::json;
165
166    fn opus() -> ModelCost {
167        ModelCost {
168            input_per_m: 15.00,
169            output_per_m: 75.00,
170            cache_write_per_m: 18.75,
171            cache_read_per_m: 1.50,
172        }
173    }
174
175    #[test]
176    fn prefix_tokens_zero_when_nothing_cached() {
177        let msgs = vec![json!({"role": "user", "content": "hello"})];
178        assert_eq!(prefix_tokens(None, &msgs, 0), 0);
179    }
180
181    #[test]
182    fn prefix_tokens_counts_only_the_cached_span() {
183        let big = "lorem ipsum dolor sit amet ".repeat(50);
184        let msgs = vec![
185            json!({"role": "user", "content": big}),
186            json!({"role": "assistant", "content": "tail not counted"}),
187        ];
188        let one = prefix_tokens(None, &msgs, 1);
189        let two = prefix_tokens(None, &msgs, 2);
190        assert!(one > 0);
191        assert!(two > one, "wider cached span counts more tokens");
192    }
193
194    #[test]
195    fn prefix_tokens_includes_the_system_field() {
196        // The system prose is part of Anthropic's cacheable prefix and is what a
197        // cold repack re-seeds, so it must count toward the gate.
198        let msgs = vec![json!({"role": "user", "content": "hi"})];
199        let big_system = json!("context engineering ".repeat(400));
200        let without = prefix_tokens(None, &msgs, 1);
201        let with = prefix_tokens(Some(&big_system), &msgs, 1);
202        assert!(with > without + 500, "system prose must dominate the count");
203    }
204
205    #[test]
206    fn worth_repacking_rejects_small_prefix() {
207        let msgs = vec![json!({"role": "user", "content": "tiny"})];
208        assert!(!worth_repacking(None, &msgs, 1));
209    }
210
211    #[test]
212    fn worth_repacking_accepts_large_prefix() {
213        // Comfortably above the 1024-token cacheable floor.
214        let big = "context engineering ".repeat(1500);
215        let msgs = vec![json!({"role": "user", "content": big})];
216        assert!(worth_repacking(None, &msgs, 1));
217    }
218
219    #[test]
220    fn worth_repacking_counts_large_system_over_tiny_messages() {
221        // A small message prefix but a large system prompt still clears the gate,
222        // because the provider caches system + messages together.
223        let msgs = vec![json!({"role": "user", "content": "hi"})];
224        let big_system = json!("context engineering ".repeat(1500));
225        assert!(
226            !worth_repacking(None, &msgs, 1),
227            "tiny prefix alone is skipped"
228        );
229        assert!(
230            worth_repacking(Some(&big_system), &msgs, 1),
231            "a large system prompt makes the prefix worth re-seeding"
232        );
233    }
234
235    #[test]
236    fn net_cost_decision_rejects_subcacheable_even_if_smaller() {
237        // Below the cacheable floor: a smaller "after" still doesn't pay.
238        assert!(!net_cost_decision(500, 200, &opus()));
239    }
240
241    #[test]
242    fn net_cost_decision_rejects_when_no_shrink() {
243        assert!(!net_cost_decision(4000, 4000, &opus()));
244        assert!(!net_cost_decision(4000, 5000, &opus()));
245    }
246
247    #[test]
248    fn net_cost_decision_accepts_real_saving() {
249        assert!(net_cost_decision(4000, 2500, &opus()));
250        // Saving is the avoided write of the 1500 dropped tokens.
251        let saved = repack_saving_usd(4000, 2500, &opus());
252        assert!((saved - (1500.0 / 1_000_000.0 * 18.75)).abs() < 1e-9);
253    }
254
255    #[test]
256    fn repack_saving_is_zero_when_inflated() {
257        assert_eq!(repack_saving_usd(1000, 2000, &opus()), 0.0);
258    }
259
260    #[test]
261    fn should_mutate_frozen_accepts_with_enough_reuse() {
262        let d = should_mutate_frozen(4000, 2000, 10, &opus());
263        match d {
264            MutationDecision::Mutate { break_even } => assert!(break_even <= 10),
265            MutationDecision::Preserve { .. } => panic!("expected Mutate"),
266        }
267    }
268
269    #[test]
270    fn should_mutate_frozen_rejects_with_low_reuse() {
271        let d = should_mutate_frozen(4000, 3900, 1, &opus());
272        assert!(matches!(d, MutationDecision::Preserve { .. }));
273    }
274
275    #[test]
276    fn should_mutate_frozen_rejects_subcacheable() {
277        let d = should_mutate_frozen(500, 200, 100, &opus());
278        assert!(matches!(d, MutationDecision::Preserve { .. }));
279    }
280
281    #[test]
282    fn should_mutate_frozen_rejects_inflation() {
283        let d = should_mutate_frozen(3000, 4000, 100, &opus());
284        assert!(matches!(d, MutationDecision::Preserve { .. }));
285    }
286}