Skip to main content

lean_ctx/proxy/
live_zone.rs

1//! Live-zone-aware request compression preserves provider-cached prefixes.
2//!
3//! The detector deliberately works on message values rather than serialized request bytes:
4//! frozen messages are moved through the pipeline unchanged, while only the live suffix may
5//! be rewritten.
6
7use serde_json::{Value, json};
8
9use crate::core::tokens::{TokenizerFamily, count_tokens_for};
10
11use super::adaptive_policy::CompressionPolicy;
12use super::compress::compress_tool_result_gateway_with_policy;
13
14/// A conversation split at the first message safe to rewrite.
15#[derive(Debug, Clone, PartialEq)]
16pub struct LiveZoneSplit {
17    pub frozen_messages: Vec<Value>,
18    pub live_messages: Vec<Value>,
19    pub boundary_turn: usize,
20    pub frozen_tokens_estimate: u64,
21}
22
23/// Compression accounting for a single live-zone pass.
24#[derive(Debug, Clone, Copy, Default, PartialEq)]
25pub struct LiveZoneStats {
26    pub frozen_tokens: u64,
27    pub live_tokens_before: u64,
28    pub live_tokens_after: u64,
29    pub savings_pct: f64,
30}
31
32/// Locate the prefix already eligible for provider cache reuse.
33///
34/// An Anthropic cache marker freezes every preceding turn.  Absent a marker, retain the
35/// preceding conversation and expose only the final three messages for mutation. System
36/// messages are always frozen, so a system message that appears later advances the boundary.
37pub fn detect_live_zone(messages: &[Value]) -> LiveZoneSplit {
38    let marked_boundary = messages
39        .iter()
40        .enumerate()
41        .filter(|(_, message)| has_cache_control(message))
42        .map(|(index, _)| index + 1)
43        .max();
44    let fallback_boundary = messages.len().saturating_sub(3);
45    let mut boundary_turn = marked_boundary.unwrap_or(fallback_boundary);
46
47    // System prompts must never become a live rewrite target.
48    if let Some(last_system) = messages
49        .iter()
50        .enumerate()
51        .filter(|(_, message)| role(message) == Some("system"))
52        .map(|(index, _)| index)
53        .max()
54    {
55        boundary_turn = boundary_turn.max(last_system + 1);
56    }
57    boundary_turn = boundary_turn.min(messages.len());
58
59    let frozen_messages = messages[..boundary_turn].to_vec();
60    let live_messages = messages[boundary_turn..].to_vec();
61    let frozen_tokens_estimate = messages_tokens(&frozen_messages, TokenizerFamily::default());
62    LiveZoneSplit {
63        frozen_messages,
64        live_messages,
65        boundary_turn,
66        frozen_tokens_estimate,
67    }
68}
69
70/// Compress only the non-cached suffix in place.
71///
72/// This function reconstructs the original slice order without assigning to the frozen prefix.
73pub fn compress_live_only(
74    messages: &mut [Value],
75    family: TokenizerFamily,
76    policy: CompressionPolicy,
77) -> LiveZoneStats {
78    let split = detect_live_zone(messages);
79    let mut stats = LiveZoneStats {
80        frozen_tokens: messages_tokens(&split.frozen_messages, family),
81        live_tokens_before: messages_tokens(&split.live_messages, family),
82        ..LiveZoneStats::default()
83    };
84
85    for message in &mut messages[split.boundary_turn..] {
86        compress_message(message, family, policy);
87    }
88
89    stats.live_tokens_after = messages_tokens(&messages[split.boundary_turn..], family);
90    stats.savings_pct = percentage_saved(stats.live_tokens_before, stats.live_tokens_after);
91    stats
92}
93
94/// Add one Anthropic cache breakpoint at the frozen/live boundary.
95///
96/// Existing client cache markers are retained. The marker is attached to an existing text
97/// block so it does not alter provider message ordering.
98pub fn add_cache_markers(messages: &mut [Value]) {
99    let boundary = detect_live_zone(messages).boundary_turn;
100    let idx = if boundary > 0 && boundary <= messages.len() {
101        boundary - 1
102    } else {
103        messages.len().saturating_sub(1)
104    };
105    let Some(message) = messages.get_mut(idx) else {
106        return;
107    };
108
109    if has_cache_control(message) {
110        return;
111    }
112
113    let Some(object) = message.as_object_mut() else {
114        return;
115    };
116    match object.get_mut("content") {
117        Some(Value::Array(blocks)) => {
118            if let Some(block) = blocks.last_mut().and_then(Value::as_object_mut) {
119                block.insert("cache_control".into(), ephemeral());
120            }
121        }
122        Some(Value::String(text)) => {
123            let text = std::mem::take(text);
124            object.insert(
125                "content".into(),
126                Value::Array(vec![json!({
127                    "type": "text",
128                    "text": text,
129                    "cache_control": ephemeral(),
130                })]),
131            );
132        }
133        _ => {}
134    }
135}
136
137fn compress_message(message: &mut Value, family: TokenizerFamily, policy: CompressionPolicy) {
138    let tool_name = message
139        .get("name")
140        .and_then(Value::as_str)
141        .map(str::to_owned);
142    if let Some(content) = message.get_mut("content") {
143        compress_content(content, tool_name.as_deref(), family, policy);
144    }
145}
146
147fn compress_content(
148    content: &mut Value,
149    tool_name: Option<&str>,
150    family: TokenizerFamily,
151    policy: CompressionPolicy,
152) {
153    match content {
154        Value::String(text) => compress_text(text, tool_name, family, policy),
155        Value::Array(blocks) => {
156            for block in blocks {
157                let Some(object) = block.as_object_mut() else {
158                    continue;
159                };
160                let name = object
161                    .get("name")
162                    .and_then(Value::as_str)
163                    .map(str::to_owned);
164                let block_type = object
165                    .get("type")
166                    .and_then(Value::as_str)
167                    .map(str::to_owned);
168                match block_type.as_deref() {
169                    Some("text") => {
170                        if let Some(Value::String(text)) = object.get_mut("text") {
171                            compress_text(text, name.as_deref(), family, policy);
172                        }
173                    }
174                    Some("tool_result") => {
175                        if let Some(inner) = object.get_mut("content") {
176                            compress_content(inner, name.as_deref(), family, policy);
177                        }
178                    }
179                    _ => {}
180                }
181            }
182        }
183        _ => {}
184    }
185}
186
187fn compress_text(
188    text: &mut String,
189    tool_name: Option<&str>,
190    family: TokenizerFamily,
191    policy: CompressionPolicy,
192) {
193    let compressed = compress_tool_result_gateway_with_policy(text, tool_name, family, policy);
194    if compressed.len() < text.len() {
195        *text = compressed;
196    }
197}
198
199fn messages_tokens(messages: &[Value], family: TokenizerFamily) -> u64 {
200    messages
201        .iter()
202        .map(|message| count_tokens_for(&message.to_string(), family) as u64)
203        .sum()
204}
205
206fn percentage_saved(before: u64, after: u64) -> f64 {
207    if before == 0 {
208        0.0
209    } else {
210        ((before.saturating_sub(after)) as f64 / before as f64) * 100.0
211    }
212}
213
214fn role(message: &Value) -> Option<&str> {
215    message.get("role").and_then(Value::as_str)
216}
217
218fn has_cache_control(message: &Value) -> bool {
219    message.get("cache_control").is_some()
220        || message
221            .get("content")
222            .and_then(Value::as_array)
223            .is_some_and(|blocks| {
224                blocks
225                    .iter()
226                    .any(|block| block.get("cache_control").is_some())
227            })
228}
229
230fn ephemeral() -> Value {
231    json!({"type": "ephemeral"})
232}
233
234#[cfg(test)]
235mod tests {
236    use serde_json::json;
237
238    use super::*;
239
240    fn policy() -> CompressionPolicy {
241        super::super::adaptive_policy::select_policy("chat")
242    }
243
244    fn verbose_text() -> String {
245        (0..80)
246            .map(|index| format!("log line {index}: repeated operational detail for compression"))
247            .collect::<Vec<_>>()
248            .join("\n")
249    }
250
251    #[test]
252    fn system_messages_always_frozen() {
253        let messages = vec![
254            json!({"role": "user", "content": "old"}),
255            json!({"role": "system", "content": "do not alter"}),
256            json!({"role": "user", "content": "new"}),
257        ];
258        let split = detect_live_zone(&messages);
259        assert_eq!(split.boundary_turn, 2);
260        assert_eq!(split.frozen_messages[1], messages[1]);
261    }
262
263    #[test]
264    fn cache_control_freezes_preceding_messages() {
265        let messages = vec![
266            json!({"role": "user", "content": "old"}),
267            json!({"role": "assistant", "content": [{"type":"text", "text":"cached", "cache_control":{"type":"ephemeral"}}]}),
268            json!({"role": "user", "content": "new"}),
269        ];
270        let split = detect_live_zone(&messages);
271        assert_eq!(split.boundary_turn, 2);
272        assert_eq!(split.frozen_messages, messages[..2]);
273        assert_eq!(split.live_messages, messages[2..]);
274    }
275
276    #[test]
277    fn live_messages_are_compressed() {
278        let _data = crate::core::data_dir::isolated_data_dir();
279        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
280        let mut messages = vec![
281            json!({"role": "user", "content": "old"}),
282            json!({"role": "assistant", "content": "cached"}),
283            json!({"role": "user", "content": "old too"}),
284            json!({"role": "tool", "name": "bash", "content": verbose_text()}),
285        ];
286        let before = messages[3].clone();
287        let stats = compress_live_only(&mut messages, TokenizerFamily::default(), policy());
288        assert!(stats.live_tokens_after < stats.live_tokens_before);
289        assert_ne!(messages[3], before);
290    }
291
292    #[test]
293    fn frozen_messages_remain_byte_identical() {
294        let mut messages = vec![
295            json!({"role": "system", "content": "stable system"}),
296            json!({"role": "user", "content": [{"type":"text", "text":"cached", "cache_control":{"type":"ephemeral"}}]}),
297            json!({"role": "assistant", "content": "answer"}),
298            json!({"role": "tool", "name": "bash", "content": verbose_text()}),
299        ];
300        let frozen = messages[..2]
301            .iter()
302            .map(Value::to_string)
303            .collect::<Vec<_>>();
304        compress_live_only(&mut messages, TokenizerFamily::default(), policy());
305        assert_eq!(
306            frozen,
307            messages[..2]
308                .iter()
309                .map(Value::to_string)
310                .collect::<Vec<_>>(),
311        );
312    }
313
314    #[test]
315    fn stats_report_frozen_and_live_token_counts() {
316        let mut messages = vec![
317            json!({"role": "system", "content": "stable"}),
318            json!({"role": "user", "content": "old"}),
319            json!({"role": "assistant", "content": "answer"}),
320            json!({"role": "tool", "name": "bash", "content": verbose_text()}),
321        ];
322        let stats = compress_live_only(&mut messages, TokenizerFamily::default(), policy());
323        assert!(stats.frozen_tokens > 0);
324        assert!(stats.live_tokens_before >= stats.live_tokens_after);
325        assert!(stats.savings_pct >= 0.0);
326    }
327
328    #[test]
329    fn cache_marker_is_added_at_boundary() {
330        let mut messages = vec![
331            json!({"role": "user", "content": "old"}),
332            json!({"role": "assistant", "content": "answer"}),
333            json!({"role": "user", "content": "new"}),
334            json!({"role": "user", "content": "latest"}),
335        ];
336        add_cache_markers(&mut messages);
337        assert!(has_cache_control(&messages[0]));
338    }
339}