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};
8use std::sync::{Mutex, OnceLock};
9
10use crate::core::tokens::{TokenizerFamily, count_tokens_for};
11
12use super::adaptive_policy::CompressionPolicy;
13use super::compress::compress_tool_result_gateway_with_policy;
14
15/// A conversation split at the first message safe to rewrite.
16#[derive(Debug, Clone, PartialEq)]
17pub struct LiveZoneSplit {
18    pub frozen_messages: Vec<Value>,
19    pub live_messages: Vec<Value>,
20    pub boundary_turn: usize,
21    pub frozen_tokens_estimate: u64,
22}
23
24/// Compression accounting for a single live-zone pass.
25#[derive(Debug, Clone, Copy, Default, PartialEq)]
26pub struct LiveZoneStats {
27    pub frozen_tokens: u64,
28    pub live_tokens_before: u64,
29    pub live_tokens_after: u64,
30    pub savings_pct: f64,
31}
32
33/// An agent-selected provider-cache prefix. This state is intentionally kept
34/// in memory only: cache markers are valid for the current proxy process.
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct ExplicitFreeze {
37    pub frozen_at_turn: usize,
38    pub snapshot_hash: String,
39    pub frozen_tokens_estimate: u64,
40}
41
42static EXPLICIT_FREEZE: OnceLock<Mutex<Option<ExplicitFreeze>>> = OnceLock::new();
43static LATEST_CONTEXT: OnceLock<Mutex<Vec<Value>>> = OnceLock::new();
44
45fn explicit_freeze_state() -> &'static Mutex<Option<ExplicitFreeze>> {
46    EXPLICIT_FREEZE.get_or_init(|| Mutex::new(None))
47}
48
49fn latest_context_state() -> &'static Mutex<Vec<Value>> {
50    LATEST_CONTEXT.get_or_init(|| Mutex::new(Vec::new()))
51}
52
53/// Records the latest provider message prefix for the agent-facing live-zone
54/// tool. The data disappears with the proxy process.
55pub fn record_context(messages: &[Value]) {
56    *latest_context_state()
57        .lock()
58        .expect("live-zone context lock poisoned") = messages.to_vec();
59}
60
61pub fn latest_context() -> Vec<Value> {
62    latest_context_state()
63        .lock()
64        .expect("live-zone context lock poisoned")
65        .clone()
66}
67
68pub fn explicit_freeze() -> Option<ExplicitFreeze> {
69    explicit_freeze_state()
70        .lock()
71        .expect("live-zone freeze lock poisoned")
72        .clone()
73}
74
75pub fn set_explicit_freeze(freeze: ExplicitFreeze) {
76    *explicit_freeze_state()
77        .lock()
78        .expect("live-zone freeze lock poisoned") = Some(freeze);
79}
80
81pub fn clear_explicit_freeze() -> Option<ExplicitFreeze> {
82    explicit_freeze_state()
83        .lock()
84        .expect("live-zone freeze lock poisoned")
85        .take()
86}
87
88pub fn snapshot_hash(messages: &[Value], turns: usize) -> String {
89    let prefix = &messages[..turns.min(messages.len())];
90    let encoded = serde_json::to_vec(prefix).expect("messages must serialize");
91    blake3::hash(&encoded).to_hex().to_string()
92}
93
94pub fn estimate_context_tokens(messages: &[Value]) -> u64 {
95    serde_json::to_string(messages)
96        .map(|serialized| (serialized.len() as u64).div_ceil(4))
97        .unwrap_or_default()
98}
99
100/// Locate the prefix already eligible for provider cache reuse.
101///
102/// An Anthropic cache marker freezes every preceding turn.  Absent a marker, retain the
103/// preceding conversation and expose only the final three messages for mutation. System
104/// messages are always frozen, so a system message that appears later advances the boundary.
105pub fn detect_live_zone(messages: &[Value]) -> LiveZoneSplit {
106    record_context(messages);
107    if let Some(freeze) = explicit_freeze() {
108        let boundary = freeze.frozen_at_turn.min(messages.len());
109        if snapshot_hash(messages, boundary) == freeze.snapshot_hash {
110            let frozen_messages = messages[..boundary].to_vec();
111            let live_messages = messages[boundary..].to_vec();
112            return LiveZoneSplit {
113                frozen_messages,
114                live_messages,
115                boundary_turn: boundary,
116                frozen_tokens_estimate: freeze.frozen_tokens_estimate,
117            };
118        }
119    }
120    let marked_boundary = messages
121        .iter()
122        .enumerate()
123        .filter(|(_, message)| has_cache_control(message))
124        .map(|(index, _)| index + 1)
125        .max();
126    let fallback_boundary = messages.len().saturating_sub(3);
127    let mut boundary_turn = marked_boundary.unwrap_or(fallback_boundary);
128
129    // System prompts must never become a live rewrite target.
130    if let Some(last_system) = messages
131        .iter()
132        .enumerate()
133        .filter(|(_, message)| role(message) == Some("system"))
134        .map(|(index, _)| index)
135        .max()
136    {
137        boundary_turn = boundary_turn.max(last_system + 1);
138    }
139    boundary_turn = boundary_turn.min(messages.len());
140
141    let frozen_messages = messages[..boundary_turn].to_vec();
142    let live_messages = messages[boundary_turn..].to_vec();
143    let frozen_tokens_estimate = messages_tokens(&frozen_messages, TokenizerFamily::default());
144    LiveZoneSplit {
145        frozen_messages,
146        live_messages,
147        boundary_turn,
148        frozen_tokens_estimate,
149    }
150}
151
152/// Compress only the non-cached suffix in place.
153///
154/// This function reconstructs the original slice order without assigning to the frozen prefix.
155pub fn compress_live_only(
156    messages: &mut [Value],
157    family: TokenizerFamily,
158    policy: CompressionPolicy,
159) -> LiveZoneStats {
160    let split = detect_live_zone(messages);
161    let mut stats = LiveZoneStats {
162        frozen_tokens: messages_tokens(&split.frozen_messages, family),
163        live_tokens_before: messages_tokens(&split.live_messages, family),
164        ..LiveZoneStats::default()
165    };
166
167    for message in &mut messages[split.boundary_turn..] {
168        compress_message(message, family, policy);
169    }
170
171    stats.live_tokens_after = messages_tokens(&messages[split.boundary_turn..], family);
172    stats.savings_pct = percentage_saved(stats.live_tokens_before, stats.live_tokens_after);
173    stats
174}
175
176/// Add one Anthropic cache breakpoint at the frozen/live boundary.
177///
178/// Existing client cache markers are retained. The marker is attached to an existing text
179/// block so it does not alter provider message ordering.
180pub fn add_cache_markers(messages: &mut [Value]) {
181    let boundary = detect_live_zone(messages).boundary_turn;
182    let idx = if boundary > 0 && boundary <= messages.len() {
183        boundary - 1
184    } else {
185        messages.len().saturating_sub(1)
186    };
187    let Some(message) = messages.get_mut(idx) else {
188        return;
189    };
190
191    if has_cache_control(message) {
192        return;
193    }
194
195    let Some(object) = message.as_object_mut() else {
196        return;
197    };
198    match object.get_mut("content") {
199        Some(Value::Array(blocks)) => {
200            if let Some(block) = blocks.last_mut().and_then(Value::as_object_mut) {
201                block.insert("cache_control".into(), ephemeral());
202            }
203        }
204        Some(Value::String(text)) => {
205            let text = std::mem::take(text);
206            object.insert(
207                "content".into(),
208                Value::Array(vec![json!({
209                    "type": "text",
210                    "text": text,
211                    "cache_control": ephemeral(),
212                })]),
213            );
214        }
215        _ => {}
216    }
217}
218
219fn compress_message(message: &mut Value, family: TokenizerFamily, policy: CompressionPolicy) {
220    let tool_name = message
221        .get("name")
222        .and_then(Value::as_str)
223        .map(str::to_owned);
224    if let Some(content) = message.get_mut("content") {
225        compress_content(content, tool_name.as_deref(), family, policy);
226    }
227}
228
229fn compress_content(
230    content: &mut Value,
231    tool_name: Option<&str>,
232    family: TokenizerFamily,
233    policy: CompressionPolicy,
234) {
235    match content {
236        Value::String(text) => compress_text(text, tool_name, family, policy),
237        Value::Array(blocks) => {
238            for block in blocks {
239                let Some(object) = block.as_object_mut() else {
240                    continue;
241                };
242                let name = object
243                    .get("name")
244                    .and_then(Value::as_str)
245                    .map(str::to_owned);
246                let block_type = object
247                    .get("type")
248                    .and_then(Value::as_str)
249                    .map(str::to_owned);
250                match block_type.as_deref() {
251                    Some("text") => {
252                        if let Some(Value::String(text)) = object.get_mut("text") {
253                            compress_text(text, name.as_deref(), family, policy);
254                        }
255                    }
256                    Some("tool_result") => {
257                        if let Some(inner) = object.get_mut("content") {
258                            compress_content(inner, name.as_deref(), family, policy);
259                        }
260                    }
261                    _ => {}
262                }
263            }
264        }
265        _ => {}
266    }
267}
268
269fn compress_text(
270    text: &mut String,
271    tool_name: Option<&str>,
272    family: TokenizerFamily,
273    policy: CompressionPolicy,
274) {
275    let compressed = compress_tool_result_gateway_with_policy(text, tool_name, family, policy);
276    if compressed.len() < text.len() {
277        *text = compressed;
278    }
279}
280
281fn messages_tokens(messages: &[Value], family: TokenizerFamily) -> u64 {
282    messages
283        .iter()
284        .map(|message| count_tokens_for(&message.to_string(), family) as u64)
285        .sum()
286}
287
288fn percentage_saved(before: u64, after: u64) -> f64 {
289    if before == 0 {
290        0.0
291    } else {
292        ((before.saturating_sub(after)) as f64 / before as f64) * 100.0
293    }
294}
295
296fn role(message: &Value) -> Option<&str> {
297    message.get("role").and_then(Value::as_str)
298}
299
300fn has_cache_control(message: &Value) -> bool {
301    message.get("cache_control").is_some()
302        || message
303            .get("content")
304            .and_then(Value::as_array)
305            .is_some_and(|blocks| {
306                blocks
307                    .iter()
308                    .any(|block| block.get("cache_control").is_some())
309            })
310}
311
312fn ephemeral() -> Value {
313    json!({"type": "ephemeral"})
314}
315
316#[cfg(test)]
317mod tests {
318    use serde_json::json;
319
320    use super::*;
321
322    fn policy() -> CompressionPolicy {
323        super::super::adaptive_policy::select_policy("chat")
324    }
325
326    fn verbose_text() -> String {
327        (0..80)
328            .map(|index| format!("log line {index}: repeated operational detail for compression"))
329            .collect::<Vec<_>>()
330            .join("\n")
331    }
332
333    #[test]
334    fn system_messages_always_frozen() {
335        let messages = vec![
336            json!({"role": "user", "content": "old"}),
337            json!({"role": "system", "content": "do not alter"}),
338            json!({"role": "user", "content": "new"}),
339        ];
340        let split = detect_live_zone(&messages);
341        assert_eq!(split.boundary_turn, 2);
342        assert_eq!(split.frozen_messages[1], messages[1]);
343    }
344
345    #[test]
346    fn cache_control_freezes_preceding_messages() {
347        let messages = vec![
348            json!({"role": "user", "content": "old"}),
349            json!({"role": "assistant", "content": [{"type":"text", "text":"cached", "cache_control":{"type":"ephemeral"}}]}),
350            json!({"role": "user", "content": "new"}),
351        ];
352        let split = detect_live_zone(&messages);
353        assert_eq!(split.boundary_turn, 2);
354        assert_eq!(split.frozen_messages, messages[..2]);
355        assert_eq!(split.live_messages, messages[2..]);
356    }
357
358    #[test]
359    fn live_messages_are_compressed() {
360        let mut messages = vec![
361            json!({"role": "user", "content": "old"}),
362            json!({"role": "assistant", "content": "cached"}),
363            json!({"role": "user", "content": "old too"}),
364            json!({"role": "tool", "name": "bash", "content": verbose_text()}),
365        ];
366        let before = messages[3].clone();
367        let stats = compress_live_only(&mut messages, TokenizerFamily::default(), policy());
368        assert!(stats.live_tokens_after < stats.live_tokens_before);
369        assert_ne!(messages[3], before);
370    }
371
372    #[test]
373    fn frozen_messages_remain_byte_identical() {
374        let mut messages = vec![
375            json!({"role": "system", "content": "stable system"}),
376            json!({"role": "user", "content": [{"type":"text", "text":"cached", "cache_control":{"type":"ephemeral"}}]}),
377            json!({"role": "assistant", "content": "answer"}),
378            json!({"role": "tool", "name": "bash", "content": verbose_text()}),
379        ];
380        let frozen = messages[..2]
381            .iter()
382            .map(Value::to_string)
383            .collect::<Vec<_>>();
384        compress_live_only(&mut messages, TokenizerFamily::default(), policy());
385        assert_eq!(
386            frozen,
387            messages[..2]
388                .iter()
389                .map(Value::to_string)
390                .collect::<Vec<_>>(),
391        );
392    }
393
394    #[test]
395    fn stats_report_frozen_and_live_token_counts() {
396        let mut messages = vec![
397            json!({"role": "system", "content": "stable"}),
398            json!({"role": "user", "content": "old"}),
399            json!({"role": "assistant", "content": "answer"}),
400            json!({"role": "tool", "name": "bash", "content": verbose_text()}),
401        ];
402        let stats = compress_live_only(&mut messages, TokenizerFamily::default(), policy());
403        assert!(stats.frozen_tokens > 0);
404        assert!(stats.live_tokens_before >= stats.live_tokens_after);
405        assert!(stats.savings_pct >= 0.0);
406    }
407
408    #[test]
409    fn cache_marker_is_added_at_boundary() {
410        let mut messages = vec![
411            json!({"role": "user", "content": "old"}),
412            json!({"role": "assistant", "content": "answer"}),
413            json!({"role": "user", "content": "new"}),
414            json!({"role": "user", "content": "latest"}),
415        ];
416        add_cache_markers(&mut messages);
417        assert!(has_cache_control(&messages[0]));
418    }
419}