Skip to main content

lean_ctx/proxy/
compress_api.rs

1//! `POST /v1/compress` — deterministic messages-in / messages-out compression.
2//!
3//! Drop-in parity with library-style `compress(messages, model)` gateways: the
4//! caller sends a chat-style `messages` array, the proxy rewrites every text
5//! payload through the same deterministic funnel used on the wire
6//! ([`super::compress::compress_tool_result_gateway`]), and returns the
7//! rewritten messages plus a structured token-savings summary. A lossy rewrite
8//! embeds a `hash=<24hex>` retrieval marker (#702) that LiteLLM's headroom
9//! guardrail resolves through `GET /v1/retrieve/{hash}` — the CCR agentic loop
10//! (BerriAI/litellm#31681) works against lean-ctx unchanged.
11//!
12//! ## Contract
13//! Request:  `{ "messages": [ … ], "model": "…"? }`
14//! Response: `{ "messages": [ … ], "stats": { … } }`
15//!
16//! Both OpenAI (`content: "string"`) and Anthropic (`content: [ {type:"text"…},
17//! {type:"tool_result"…} ]`) message shapes are accepted. Only text payloads are
18//! compressed; images, `tool_use` blocks, ids and every other field pass through
19//! untouched. lean-ctx's own `ctx_*` tool results are left verbatim (#479).
20//!
21//! ## Gateway compatibility (#700)
22//! The response also carries `tokens_before` / `tokens_after` /
23//! `compression_ratio` at the top level — the field names LiteLLM's
24//! prompt-compression guardrail reads for its per-request savings log. That
25//! makes lean-ctx a drop-in `api_base` for `guardrail: headroom` deployments:
26//! LiteLLM only requires `messages` in the reply and treats the token fields
27//! as optional telemetry.
28//!
29//! ## Determinism (#498)
30//! Output is a pure function of `(messages, model)`. Compression runs footer-free
31//! — savings are reported in `stats`, never injected into message bodies — so the
32//! result stays byte-stable for provider prompt caching.
33
34use axum::{Json, http::StatusCode, response::IntoResponse};
35use serde::{Deserialize, Serialize};
36use serde_json::Value;
37
38use super::{adaptive_policy::select_policy, live_zone};
39use crate::core::protocol::strip_trailing_savings_footer;
40use crate::core::tokens::{TokenizerFamily, count_tokens_for, detect_tokenizer};
41
42use super::compress::compress_tool_result_gateway_with_policy;
43
44#[derive(Debug, Deserialize)]
45pub struct CompressRequest {
46    pub messages: Vec<Value>,
47    /// Optional model name, echoed into `stats.model` and used to select the
48    /// tokenizer family for compression and token accounting.
49    #[serde(default)]
50    pub model: Option<String>,
51}
52
53#[derive(Debug, Serialize)]
54pub struct CompressStats {
55    pub original_tokens: usize,
56    pub compressed_tokens: usize,
57    pub saved_tokens: usize,
58    /// Percentage saved over the compressible text payloads, one decimal place.
59    pub saved_pct: f64,
60    pub tokenizer: String,
61    #[serde(skip_serializing_if = "Option::is_none")]
62    pub model: Option<String>,
63}
64
65#[derive(Debug, Serialize)]
66pub struct CompressResponse {
67    pub messages: Vec<Value>,
68    pub stats: CompressStats,
69    /// LiteLLM-guardrail telemetry aliases (#700): duplicates of
70    /// `stats.original_tokens` / `stats.compressed_tokens` under the field
71    /// names the LiteLLM headroom guardrail logs (`tokens_before` →
72    /// `tokens_after`, ratio `after/before`).
73    pub tokens_before: usize,
74    pub tokens_after: usize,
75    /// `tokens_after / tokens_before`, rounded to 2 decimals; `1.0` when the
76    /// input had no compressible text.
77    pub compression_ratio: f64,
78}
79
80#[derive(Default)]
81struct Totals {
82    original: usize,
83    compressed: usize,
84}
85
86/// Axum handler. Malformed bodies are rejected by the `Json` extractor (400).
87pub async fn handler(Json(req): Json<CompressRequest>) -> impl IntoResponse {
88    (StatusCode::OK, Json(compress_messages(req)))
89}
90
91/// Pure, deterministic core: rewrites every text payload in `messages` and
92/// reports aggregate token savings. Same input → same output bytes (#498).
93pub fn compress_messages(req: CompressRequest) -> CompressResponse {
94    let family = req
95        .model
96        .as_deref()
97        .map(detect_tokenizer)
98        .unwrap_or_default();
99    let mut messages = req.messages;
100    let mut totals = Totals::default();
101    let last_user_content = messages
102        .iter()
103        .rev()
104        .find(|message| message.get("role").and_then(Value::as_str) == Some("user"))
105        .and_then(|message| message.get("content").and_then(Value::as_str));
106    let task_class = super::pre_optimize::classify_task(last_user_content);
107
108    let policy = super::adaptive_policy::best_policy_for(task_class);
109    let live_split = live_zone::detect_live_zone(&messages);
110    for msg in &mut messages[live_split.boundary_turn..] {
111        compress_message(msg, &mut totals, family, policy);
112    }
113    let _live_stats = live_zone::compress_live_only(&mut messages, family, select_policy("chat"));
114
115    let saved = totals.original.saturating_sub(totals.compressed);
116    let saved_pct = if totals.original > 0 {
117        ((saved as f64 / totals.original as f64) * 1000.0).round() / 10.0
118    } else {
119        0.0
120    };
121    let compression_ratio = if totals.original > 0 {
122        ((totals.compressed as f64 / totals.original as f64) * 100.0).round() / 100.0
123    } else {
124        1.0
125    };
126
127    CompressResponse {
128        messages,
129        stats: CompressStats {
130            original_tokens: totals.original,
131            compressed_tokens: totals.compressed,
132            saved_tokens: saved,
133            saved_pct,
134            tokenizer: family.to_string(),
135            model: req.model,
136        },
137        tokens_before: totals.original,
138        tokens_after: totals.compressed,
139        compression_ratio,
140    }
141}
142
143fn compress_message(
144    msg: &mut Value,
145    totals: &mut Totals,
146    family: TokenizerFamily,
147    policy: super::adaptive_policy::CompressionPolicy,
148) {
149    // OpenAI `tool`/`function` messages carry the tool name; pass it to the funnel
150    // so it can honour the #479 pass-through for lean-ctx's own `ctx_*` results.
151    let name = msg.get("name").and_then(Value::as_str).map(str::to_string);
152    if let Some(content) = msg.get_mut("content") {
153        compress_content(content, name.as_deref(), totals, family, policy);
154    }
155}
156
157fn compress_content(
158    content: &mut Value,
159    name: Option<&str>,
160    totals: &mut Totals,
161    family: TokenizerFamily,
162    policy: super::adaptive_policy::CompressionPolicy,
163) {
164    match content {
165        Value::String(s) => squeeze_in_place(s, name, totals, family, policy),
166        Value::Array(blocks) => {
167            for block in blocks.iter_mut() {
168                compress_block(block, name, totals, family, policy);
169            }
170        }
171        _ => {}
172    }
173}
174
175fn compress_block(
176    block: &mut Value,
177    name: Option<&str>,
178    totals: &mut Totals,
179    family: TokenizerFamily,
180    policy: super::adaptive_policy::CompressionPolicy,
181) {
182    let Some(obj) = block.as_object_mut() else {
183        return;
184    };
185    match obj.get("type").and_then(Value::as_str) {
186        // OpenAI + Anthropic text parts.
187        Some("text") => {
188            if let Some(Value::String(s)) = obj.get_mut("text") {
189                squeeze_in_place(s, name, totals, family, policy);
190            }
191        }
192        // Anthropic tool_result: nested string or array of content blocks — the
193        // single biggest compressible payload in an agent transcript.
194        Some("tool_result") => {
195            if let Some(inner) = obj.get_mut("content") {
196                compress_content(inner, name, totals, family, policy);
197            }
198        }
199        // image, tool_use, input_audio, document, … pass through untouched.
200        _ => {}
201    }
202}
203
204fn squeeze_in_place(
205    s: &mut String,
206    name: Option<&str>,
207    totals: &mut Totals,
208    family: TokenizerFamily,
209    policy: super::adaptive_policy::CompressionPolicy,
210) {
211    let before = count_tokens_for(s, family);
212    // Gateway audience (#702): a lossy rewrite carries the `hash=<24hex>`
213    // retrieval marker LiteLLM's CCR loop scans for; the savings footer is
214    // stripped inside the gateway funnel (stats carry the numbers instead).
215    let compressed = compress_tool_result_gateway_with_policy(s, name, family, policy);
216    let clean = strip_trailing_savings_footer(&compressed);
217    let after = count_tokens_for(clean, family);
218    totals.original += before;
219    totals.compressed += after;
220    if clean != s {
221        *s = clean.to_string();
222    }
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228    use serde_json::json;
229
230    /// A prose blob well over the funnel's 600-char floor: eight identical
231    /// paragraphs the prose squeeze deduplicates down to one.
232    fn dedupable_prose() -> String {
233        let para = "Rust is a multi-paradigm systems programming language that \
234                    emphasizes performance, type safety, and fearless concurrency, \
235                    achieving memory safety without a garbage collector at runtime.";
236        format!("{}\n", [para; 8].join("\n\n"))
237    }
238
239    fn run(messages: Vec<Value>, model: Option<&str>) -> CompressResponse {
240        compress_messages(CompressRequest {
241            messages,
242            model: model.map(str::to_string),
243        })
244    }
245
246    #[test]
247    fn string_content_is_compressed_and_stats_reported() {
248        let _lock = crate::core::data_dir::test_env_lock();
249        let resp = run(
250            vec![json!({"role": "user", "content": dedupable_prose()})],
251            Some("claude-sonnet-4"),
252        );
253        let out = resp.messages[0]["content"].as_str().unwrap();
254        assert_eq!(
255            out.matches("fearless concurrency").count(),
256            1,
257            "duplicate paragraphs must be deduped"
258        );
259        assert!(resp.stats.saved_tokens > 0, "stats must reflect savings");
260        assert!(resp.stats.compressed_tokens < resp.stats.original_tokens);
261        assert_eq!(resp.stats.tokenizer, "cl100k_base");
262        assert_eq!(resp.stats.model.as_deref(), Some("claude-sonnet-4"));
263    }
264
265    #[test]
266    fn model_selects_tokenizer_family_for_gateway_compression() {
267        let resp = run(
268            vec![json!({"role": "user", "content": dedupable_prose()})],
269            Some("claude-sonnet-4"),
270        );
271
272        assert_eq!(resp.stats.model.as_deref(), Some("claude-sonnet-4"));
273        assert_eq!(resp.stats.tokenizer, "cl100k_base");
274    }
275
276    #[test]
277    fn litellm_guardrail_fields_present_and_consistent() {
278        let _lock = crate::core::data_dir::test_env_lock();
279        // LiteLLM's headroom guardrail logs `tokens_before`/`tokens_after`/
280        // `compression_ratio` from the /v1/compress reply (#700). They must
281        // exist at the top level and agree with `stats`.
282        let resp = run(
283            vec![json!({"role": "user", "content": dedupable_prose()})],
284            None,
285        );
286        assert_eq!(resp.tokens_before, resp.stats.original_tokens);
287        assert_eq!(resp.tokens_after, resp.stats.compressed_tokens);
288        assert!(resp.compression_ratio > 0.0 && resp.compression_ratio < 1.0);
289
290        let wire = serde_json::to_value(&resp).unwrap();
291        assert!(wire["tokens_before"].is_u64());
292        assert!(wire["tokens_after"].is_u64());
293        assert!(wire["compression_ratio"].is_f64());
294
295        // No compressible text → ratio pins to 1.0, not 0/0.
296        let empty = run(vec![json!({"role": "user", "content": "hi"})], None);
297        assert_eq!(empty.compression_ratio, 1.0);
298    }
299
300    #[test]
301    fn message_bodies_stay_footer_free() {
302        let _lock = crate::core::data_dir::test_env_lock();
303        let resp = run(
304            vec![json!({"role": "user", "content": dedupable_prose()})],
305            None,
306        );
307        let out = resp.messages[0]["content"].as_str().unwrap();
308        assert!(!out.contains('\u{2500}'), "no box-drawing footer in body");
309        assert!(!out.contains("[lean-ctx:"), "no savings footer in body");
310        assert!(resp.stats.model.is_none());
311    }
312
313    /// #702: a lossy rewrite through the gateway contract must advertise its
314    /// retrieval hash in LiteLLM's regex-locked `hash=<24hex>` form, and the
315    /// hash must resolve back to the verbatim original — the wire half of the
316    /// guardrail's CCR agentic loop.
317    #[test]
318    fn lossy_rewrite_carries_litellm_retrieval_marker() {
319        let _lock = crate::core::data_dir::test_env_lock();
320        let original = dedupable_prose();
321        let resp = run(
322            vec![json!({"role": "user", "content": original.clone()})],
323            None,
324        );
325        let out = resp.messages[0]["content"].as_str().unwrap();
326
327        let litellm_regex = regex::Regex::new(r"hash=([a-f0-9]{24})").unwrap();
328        let hash = litellm_regex
329            .captures(out)
330            .unwrap_or_else(|| panic!("lossy body must carry the hash= marker: {out}"))
331            .get(1)
332            .unwrap()
333            .as_str();
334        let recovered = super::super::ccr::retrieve_litellm(hash)
335            .expect("marker hash must resolve via /v1/retrieve");
336        assert!(
337            recovered.contains("fearless concurrency"),
338            "retrieve returns the verbatim pre-compression original"
339        );
340        assert_eq!(
341            recovered.matches("fearless concurrency").count(),
342            8,
343            "all deduped paragraphs are recoverable"
344        );
345    }
346
347    #[test]
348    fn output_is_deterministic() {
349        let _lock = crate::core::data_dir::test_env_lock();
350        let msgs = vec![
351            json!({"role": "system", "content": "You are a helpful assistant."}),
352            json!({"role": "user", "content": dedupable_prose()}),
353        ];
354        let a = serde_json::to_string(&run(msgs.clone(), Some("gpt-4o"))).unwrap();
355        let b = serde_json::to_string(&run(msgs, Some("gpt-4o"))).unwrap();
356        assert_eq!(a, b, "same input must yield byte-identical output");
357    }
358
359    #[test]
360    fn short_content_is_untouched() {
361        let resp = run(vec![json!({"role": "user", "content": "hi there"})], None);
362        assert_eq!(resp.messages[0]["content"], "hi there");
363        assert_eq!(resp.stats.saved_tokens, 0);
364        assert_eq!(resp.stats.saved_pct, 0.0);
365    }
366
367    #[test]
368    fn anthropic_blocks_text_compressed_image_passthrough() {
369        let _lock = crate::core::data_dir::test_env_lock();
370        let resp = run(
371            vec![json!({
372                "role": "user",
373                "content": [
374                    {"type": "text", "text": dedupable_prose()},
375                    {"type": "image", "source": {"type": "base64", "data": "AAAA"}},
376                ],
377            })],
378            None,
379        );
380        let blocks = resp.messages[0]["content"].as_array().unwrap();
381        assert_eq!(
382            blocks[0]["text"]
383                .as_str()
384                .unwrap()
385                .matches("fearless concurrency")
386                .count(),
387            1
388        );
389        // Image block is preserved verbatim.
390        assert_eq!(blocks[1]["source"]["data"], "AAAA");
391    }
392
393    #[test]
394    fn anthropic_tool_result_block_is_compressed() {
395        let _lock = crate::core::data_dir::test_env_lock();
396        let resp = run(
397            vec![json!({
398                "role": "user",
399                "content": [{
400                    "type": "tool_result",
401                    "tool_use_id": "toolu_123",
402                    "content": dedupable_prose(),
403                }],
404            })],
405            None,
406        );
407        let block = &resp.messages[0]["content"][0];
408        assert_eq!(block["tool_use_id"], "toolu_123", "ids preserved");
409        assert_eq!(
410            block["content"]
411                .as_str()
412                .unwrap()
413                .matches("fearless concurrency")
414                .count(),
415            1
416        );
417        assert!(resp.stats.saved_tokens > 0);
418    }
419
420    #[test]
421    fn lean_ctx_tool_output_passes_through_verbatim() {
422        // A ctx_* result is already compressed at the tool boundary (#479).
423        let prose = dedupable_prose();
424        let resp = run(
425            vec![json!({"role": "tool", "name": "ctx_read", "content": prose.clone()})],
426            None,
427        );
428        assert_eq!(resp.messages[0]["content"].as_str().unwrap(), prose);
429        assert_eq!(
430            resp.stats.saved_tokens, 0,
431            "ctx_* output is not re-compressed"
432        );
433    }
434
435    #[test]
436    fn non_string_content_is_ignored() {
437        // A malformed/absent content field must not panic.
438        let resp = run(vec![json!({"role": "assistant", "tool_calls": []})], None);
439        assert_eq!(resp.stats.original_tokens, 0);
440        assert_eq!(resp.messages.len(), 1);
441    }
442
443    /// #498 regression: a full, mixed-shape conversation must serialise to
444    /// byte-identical output across repeated calls. Provider prompt caching keys
445    /// on the exact bytes, so any non-determinism (ordering, footer leakage,
446    /// counter/timestamp) would silently destroy the cache discount.
447    #[test]
448    fn determinism_regression_full_conversation_498() {
449        let _lock = crate::core::data_dir::test_env_lock();
450        let conversation = || {
451            vec![
452                json!({"role": "system", "content": "You are a helpful assistant."}),
453                json!({"role": "user", "content": dedupable_prose()}),
454                json!({
455                    "role": "user",
456                    "content": [
457                        {"type": "text", "text": dedupable_prose()},
458                        {"type": "image", "source": {"type": "base64", "data": "AAAA"}},
459                        {"type": "tool_result", "tool_use_id": "toolu_1", "content": dedupable_prose()},
460                    ],
461                }),
462                json!({"role": "tool", "name": "ctx_read", "content": dedupable_prose()}),
463            ]
464        };
465
466        let baseline =
467            serde_json::to_string(&run(conversation(), Some("claude-sonnet-4"))).unwrap();
468        for _ in 0..4 {
469            let again =
470                serde_json::to_string(&run(conversation(), Some("claude-sonnet-4"))).unwrap();
471            assert_eq!(again, baseline, "/v1/compress output must be byte-stable");
472        }
473
474        // The byte-stable bodies must also be footer-free (savings live in stats).
475        assert!(!baseline.contains("[lean-ctx:"));
476        assert!(!baseline.contains('\u{2500}'));
477    }
478
479    /// Daemon-free, o200k_base benchmark over a real on-disk corpus. Prints a
480    /// JSON report (ratio + latency) and is `#[ignore]`d so it stays out of CI.
481    /// Reproduce: `cargo test -p lean-ctx --lib \
482    /// proxy::compress_api::tests::bench_real_corpus_o200k -- --ignored --nocapture`.
483    #[test]
484    #[ignore = "benchmark; run explicitly with --ignored --nocapture"]
485    fn bench_real_corpus_o200k() {
486        use std::path::Path;
487        use std::time::Instant;
488
489        let corpus = Path::new(env!("CARGO_MANIFEST_DIR")).join("../docs/reference");
490        let mut messages = Vec::new();
491        if let Ok(entries) = std::fs::read_dir(&corpus) {
492            let mut paths: Vec<_> = entries
493                .flatten()
494                .map(|e| e.path())
495                .filter(|p| p.extension().and_then(|s| s.to_str()) == Some("md"))
496                .collect();
497            paths.sort();
498            for path in paths {
499                if let Ok(text) = std::fs::read_to_string(&path) {
500                    messages.push(json!({"role": "user", "content": text}));
501                }
502            }
503        }
504        assert!(!messages.is_empty(), "no corpus files found at {corpus:?}");
505
506        let files = messages.len();
507        let started = Instant::now();
508        let resp = run(messages, Some("gpt-4o"));
509        let latency_ms = started.elapsed().as_secs_f64() * 1000.0;
510
511        let report = json!({
512            "corpus": corpus.to_string_lossy(),
513            "files": files,
514            "tokenizer": resp.stats.tokenizer,
515            "original_tokens": resp.stats.original_tokens,
516            "compressed_tokens": resp.stats.compressed_tokens,
517            "tokens_saved": resp.stats.saved_tokens,
518            "saved_pct": resp.stats.saved_pct,
519            "latency_ms": (latency_ms * 100.0).round() / 100.0,
520        });
521        println!("{}", serde_json::to_string_pretty(&report).unwrap());
522    }
523}