1use serde_json::Value;
28
29use crate::core::gain::model_pricing::ModelCost;
30use crate::core::tokens::count_tokens;
31
32pub const MIN_CACHEABLE_TOKENS: u64 = 1024;
38
39fn 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#[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#[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#[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#[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#[derive(Debug, Clone, Copy, PartialEq)]
102pub enum MutationDecision {
103 Mutate { break_even: u32 },
105 Preserve { break_even: u32 },
107}
108
109#[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#[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#[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#[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 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 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 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 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 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 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 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 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 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}