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
34#[cfg(feature = "http-server")]
35use axum::{
36    Json,
37    http::StatusCode,
38    response::{IntoResponse, Response},
39};
40use serde::{Deserialize, Serialize};
41use serde_json::Value;
42
43#[cfg(feature = "http-server")]
44use super::admitted::{self, GatewayRefusal, Payload};
45use super::{adaptive_policy::select_policy, live_zone};
46#[cfg(feature = "http-server")]
47use crate::core::context_admission::egress::{EgressTarget, TrustedDestinationBinding};
48use crate::core::protocol::strip_trailing_savings_footer;
49use crate::core::tokens::{TokenizerFamily, count_tokens_for, detect_tokenizer};
50
51use super::compress::compress_tool_result_gateway_with_policy;
52
53#[derive(Debug, Deserialize)]
54pub struct CompressRequest {
55    pub messages: Vec<Value>,
56    /// Optional model name, echoed into `stats.model` and used to select the
57    /// tokenizer family for compression and token accounting.
58    #[serde(default)]
59    pub model: Option<String>,
60}
61
62#[derive(Debug, Serialize)]
63pub struct CompressStats {
64    pub original_tokens: usize,
65    pub compressed_tokens: usize,
66    pub saved_tokens: usize,
67    /// Percentage saved over the compressible text payloads, one decimal place.
68    pub saved_pct: f64,
69    pub tokenizer: String,
70    #[serde(skip_serializing_if = "Option::is_none")]
71    pub model: Option<String>,
72}
73
74#[derive(Debug, Serialize)]
75pub struct CompressResponse {
76    pub messages: Vec<Value>,
77    pub stats: CompressStats,
78    /// LiteLLM-guardrail telemetry aliases (#700): duplicates of
79    /// `stats.original_tokens` / `stats.compressed_tokens` under the field
80    /// names the LiteLLM headroom guardrail logs (`tokens_before` →
81    /// `tokens_after`, ratio `after/before`).
82    pub tokens_before: usize,
83    pub tokens_after: usize,
84    /// `tokens_after / tokens_before`, rounded to 2 decimals; `1.0` when the
85    /// input had no compressible text.
86    pub compression_ratio: f64,
87}
88
89#[derive(Default)]
90struct Totals {
91    original: usize,
92    compressed: usize,
93}
94
95/// Destination label of the compress API in receipts. The reply goes back to
96/// a caller that forwards it to a model this proxy never sees, so the
97/// destination's locality is unknown — not provably local: restricted
98/// content is withheld, and configured placement rules cannot be satisfied.
99#[cfg(feature = "http-server")]
100const COMPRESS_DESTINATION: &str = "compress-api";
101
102/// Axum handler. Malformed bodies are rejected by the `Json` extractor (400).
103///
104/// The reply is a delivery and the retrieval copies compression keeps are a
105/// store: the messages are admitted by the gateway first, compression only
106/// ever sees the admitted form, and the reply bytes are bound to the receipt.
107/// A refusal is answered with the typed gateway reason.
108#[cfg(feature = "http-server")]
109pub async fn handler(Json(req): Json<CompressRequest>) -> Response {
110    match admitted_compress(req).await {
111        Ok(response) => response,
112        Err(refusal) => refusal.response("OpenAI"),
113    }
114}
115
116#[cfg(feature = "http-server")]
117async fn admitted_compress(req: CompressRequest) -> Result<Response, GatewayRefusal> {
118    let CompressRequest { messages, model } = req;
119    let mut document = Value::Array(messages);
120    let original_bytes = document.to_string().len();
121    let target = EgressTarget {
122        provider: COMPRESS_DESTINATION,
123        model: model.as_deref(),
124        upstream_base: "",
125    };
126    let mut admission = admitted::admit(
127        Payload::Document(&document),
128        &target,
129        TrustedDestinationBinding::default(),
130    )?;
131    if admission.is_refused() {
132        return Err(admitted::record_refusal(admission, original_bytes, None).await);
133    }
134    if let Some(admitted_document) = admission.take_rewritten() {
135        document = admitted_document;
136    }
137    let Value::Array(messages) = document else {
138        return Err(GatewayRefusal::unavailable("egress.encode_failed"));
139    };
140    // The reader of this reply can call this proxy's routes: under protection
141    // a block is compressed only with a recovery copy bound to its lineage,
142    // and its stub names `GET /v1/references/{id}`. What stays whole for want
143    // of such a copy is named, by code only, in the reply's reason-code
144    // header; the body keeps its contract.
145    let (compressed, kept_whole) =
146        super::compress::observing(super::compress::Reader::GatewayCaller, || {
147            compress_messages(CompressRequest { messages, model })
148        });
149    let reply = serde_json::to_vec(&compressed)
150        .map_err(|_| GatewayRefusal::unavailable("egress.encode_failed"))?;
151    // The receipt of this reply states the same codes, one note per block.
152    let admission = admission.note_kept_whole(&kept_whole);
153    admitted::bind_delivery(admission, &reply, original_bytes).await?;
154    let mut response = (
155        StatusCode::OK,
156        [(axum::http::header::CONTENT_TYPE, "application/json")],
157        reply,
158    )
159        .into_response();
160    if let Some(codes) = kept_whole.codes()
161        && let Ok(value) = axum::http::HeaderValue::from_str(&codes)
162    {
163        response
164            .headers_mut()
165            .insert(admitted::REASON_CODES_HEADER, value);
166    }
167    Ok(response)
168}
169
170/// Pure, deterministic core: rewrites every text payload in `messages` and
171/// reports aggregate token savings. Same input → same output bytes (#498).
172pub fn compress_messages(req: CompressRequest) -> CompressResponse {
173    let family = req
174        .model
175        .as_deref()
176        .map(detect_tokenizer)
177        .unwrap_or_default();
178    let mut messages = req.messages;
179    let mut totals = Totals::default();
180    let last_user_content = messages
181        .iter()
182        .rev()
183        .find(|message| message.get("role").and_then(Value::as_str) == Some("user"))
184        .and_then(|message| message.get("content").and_then(Value::as_str));
185    let task_class = super::pre_optimize::classify_task(last_user_content);
186
187    let policy = super::adaptive_policy::best_policy_for(task_class);
188    let live_split = live_zone::detect_live_zone(&messages);
189    for msg in &mut messages[live_split.boundary_turn..] {
190        compress_message(msg, &mut totals, family, policy);
191    }
192    let _live_stats = live_zone::compress_live_only(&mut messages, family, select_policy("chat"));
193
194    let saved = totals.original.saturating_sub(totals.compressed);
195    let saved_pct = if totals.original > 0 {
196        ((saved as f64 / totals.original as f64) * 1000.0).round() / 10.0
197    } else {
198        0.0
199    };
200    let compression_ratio = if totals.original > 0 {
201        ((totals.compressed as f64 / totals.original as f64) * 100.0).round() / 100.0
202    } else {
203        1.0
204    };
205
206    CompressResponse {
207        messages,
208        stats: CompressStats {
209            original_tokens: totals.original,
210            compressed_tokens: totals.compressed,
211            saved_tokens: saved,
212            saved_pct,
213            tokenizer: family.to_string(),
214            model: req.model,
215        },
216        tokens_before: totals.original,
217        tokens_after: totals.compressed,
218        compression_ratio,
219    }
220}
221
222fn compress_message(
223    msg: &mut Value,
224    totals: &mut Totals,
225    family: TokenizerFamily,
226    policy: super::adaptive_policy::CompressionPolicy,
227) {
228    // OpenAI `tool`/`function` messages carry the tool name; pass it to the funnel
229    // so it can honour the #479 pass-through for lean-ctx's own `ctx_*` results.
230    let name = msg.get("name").and_then(Value::as_str).map(str::to_string);
231    if let Some(content) = msg.get_mut("content") {
232        compress_content(content, name.as_deref(), totals, family, policy);
233    }
234}
235
236fn compress_content(
237    content: &mut Value,
238    name: Option<&str>,
239    totals: &mut Totals,
240    family: TokenizerFamily,
241    policy: super::adaptive_policy::CompressionPolicy,
242) {
243    match content {
244        Value::String(s) => squeeze_in_place(s, name, totals, family, policy),
245        Value::Array(blocks) => {
246            for block in blocks.iter_mut() {
247                compress_block(block, name, totals, family, policy);
248            }
249        }
250        _ => {}
251    }
252}
253
254fn compress_block(
255    block: &mut Value,
256    name: Option<&str>,
257    totals: &mut Totals,
258    family: TokenizerFamily,
259    policy: super::adaptive_policy::CompressionPolicy,
260) {
261    let Some(obj) = block.as_object_mut() else {
262        return;
263    };
264    match obj.get("type").and_then(Value::as_str) {
265        // OpenAI + Anthropic text parts.
266        Some("text") => {
267            if let Some(Value::String(s)) = obj.get_mut("text") {
268                squeeze_in_place(s, name, totals, family, policy);
269            }
270        }
271        // Anthropic tool_result: nested string or array of content blocks — the
272        // single biggest compressible payload in an agent transcript.
273        Some("tool_result") => {
274            if let Some(inner) = obj.get_mut("content") {
275                compress_content(inner, name, totals, family, policy);
276            }
277        }
278        // image, tool_use, input_audio, document, … pass through untouched.
279        _ => {}
280    }
281}
282
283fn squeeze_in_place(
284    s: &mut String,
285    name: Option<&str>,
286    totals: &mut Totals,
287    family: TokenizerFamily,
288    policy: super::adaptive_policy::CompressionPolicy,
289) {
290    let before = count_tokens_for(s, family);
291    // Gateway audience (#702): a lossy rewrite carries the `hash=<24hex>`
292    // retrieval marker LiteLLM's CCR loop scans for; the savings footer is
293    // stripped inside the gateway funnel (stats carry the numbers instead).
294    let compressed = compress_tool_result_gateway_with_policy(s, name, family, policy);
295    let clean = strip_trailing_savings_footer(&compressed);
296    let after = count_tokens_for(clean, family);
297    totals.original += before;
298    totals.compressed += after;
299    if clean != s {
300        *s = clean.to_string();
301    }
302}
303
304#[cfg(test)]
305mod tests {
306    use super::*;
307    use serde_json::json;
308
309    /// A prose blob well over the funnel's 600-char floor: eight identical
310    /// paragraphs the prose squeeze deduplicates down to one.
311    fn dedupable_prose() -> String {
312        let para = "Rust is a multi-paradigm systems programming language that \
313                    emphasizes performance, type safety, and fearless concurrency, \
314                    achieving memory safety without a garbage collector at runtime.";
315        format!("{}\n", [para; 8].join("\n\n"))
316    }
317
318    fn run(messages: Vec<Value>, model: Option<&str>) -> CompressResponse {
319        compress_messages(CompressRequest {
320            messages,
321            model: model.map(str::to_string),
322        })
323    }
324
325    #[test]
326    fn string_content_is_compressed_and_stats_reported() {
327        let _lock = crate::core::data_dir::test_env_lock();
328        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
329        let resp = run(
330            vec![json!({"role": "user", "content": dedupable_prose()})],
331            Some("claude-sonnet-4"),
332        );
333        let out = resp.messages[0]["content"].as_str().unwrap();
334        assert_eq!(
335            out.matches("fearless concurrency").count(),
336            1,
337            "duplicate paragraphs must be deduped"
338        );
339        assert!(resp.stats.saved_tokens > 0, "stats must reflect savings");
340        assert!(resp.stats.compressed_tokens < resp.stats.original_tokens);
341        assert_eq!(resp.stats.tokenizer, "cl100k_base");
342        assert_eq!(resp.stats.model.as_deref(), Some("claude-sonnet-4"));
343    }
344
345    /// The reply of `/v1/compress` is a delivery to a destination this proxy
346    /// cannot see: a protected value is masked before compression or the
347    /// reply sees it, and restricted content is withheld in place (a notice
348    /// with its block id) instead of being handed back.
349    #[tokio::test]
350    async fn handler_admits_messages_before_compressing_or_replying() {
351        let _data = crate::core::data_dir::isolated_data_dir();
352        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
353        let key = concat!("AK", "IAIOSFODNN7EXAMPLE");
354        let request = |text: String| {
355            Json(CompressRequest {
356                messages: vec![json!({"role": "user", "content": text})],
357                model: None,
358            })
359        };
360
361        let response = handler(request(format!("deploy with {key} today"))).await;
362        assert_eq!(response.status(), StatusCode::OK);
363        let reply = axum::body::to_bytes(response.into_body(), usize::MAX)
364            .await
365            .expect("reply body");
366        let reply = String::from_utf8(reply.to_vec()).expect("JSON reply");
367        assert!(!reply.contains(key), "the reply carries the value: {reply}");
368        assert!(reply.contains("deploy with"), "{reply}");
369
370        // Restricted content is withheld in place: the reply carries the
371        // notice, never the content, and the rest of the messages.
372        let withheld = handler(request(
373            "Classification: RESTRICTED\nmerger terms for the board".to_owned(),
374        ))
375        .await;
376        assert_eq!(withheld.status(), StatusCode::OK);
377        let body = axum::body::to_bytes(withheld.into_body(), usize::MAX)
378            .await
379            .expect("reply body");
380        let body = String::from_utf8_lossy(&body);
381        assert!(!body.contains("merger terms"), "{body}");
382        assert!(body.contains("destination.remote_restricted"), "{body}");
383        assert!(body.contains("lean-ctx gateway why w-"), "{body}");
384    }
385
386    #[test]
387    fn model_selects_tokenizer_family_for_gateway_compression() {
388        let resp = run(
389            vec![json!({"role": "user", "content": dedupable_prose()})],
390            Some("claude-sonnet-4"),
391        );
392
393        assert_eq!(resp.stats.model.as_deref(), Some("claude-sonnet-4"));
394        assert_eq!(resp.stats.tokenizer, "cl100k_base");
395    }
396
397    #[test]
398    fn litellm_guardrail_fields_present_and_consistent() {
399        let _lock = crate::core::data_dir::test_env_lock();
400        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
401        // LiteLLM's headroom guardrail logs `tokens_before`/`tokens_after`/
402        // `compression_ratio` from the /v1/compress reply (#700). They must
403        // exist at the top level and agree with `stats`.
404        let resp = run(
405            vec![json!({"role": "user", "content": dedupable_prose()})],
406            None,
407        );
408        assert_eq!(resp.tokens_before, resp.stats.original_tokens);
409        assert_eq!(resp.tokens_after, resp.stats.compressed_tokens);
410        assert!(resp.compression_ratio > 0.0 && resp.compression_ratio < 1.0);
411
412        let wire = serde_json::to_value(&resp).unwrap();
413        assert!(wire["tokens_before"].is_u64());
414        assert!(wire["tokens_after"].is_u64());
415        assert!(wire["compression_ratio"].is_f64());
416
417        // No compressible text → ratio pins to 1.0, not 0/0.
418        let empty = run(vec![json!({"role": "user", "content": "hi"})], None);
419        assert_eq!(empty.compression_ratio, 1.0);
420    }
421
422    #[test]
423    fn message_bodies_stay_footer_free() {
424        let _lock = crate::core::data_dir::test_env_lock();
425        let resp = run(
426            vec![json!({"role": "user", "content": dedupable_prose()})],
427            None,
428        );
429        let out = resp.messages[0]["content"].as_str().unwrap();
430        assert!(!out.contains('\u{2500}'), "no box-drawing footer in body");
431        assert!(!out.contains("[lean-ctx:"), "no savings footer in body");
432        assert!(resp.stats.model.is_none());
433    }
434
435    /// #702: a lossy rewrite through the gateway contract must advertise its
436    /// retrieval hash in LiteLLM's regex-locked `hash=<24hex>` form, and the
437    /// hash must resolve back to the verbatim original — the wire half of the
438    /// guardrail's CCR agentic loop.
439    #[test]
440    fn lossy_rewrite_carries_litellm_retrieval_marker() {
441        let _lock = crate::core::data_dir::test_env_lock();
442        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
443        let original = dedupable_prose();
444        let resp = run(
445            vec![json!({"role": "user", "content": original.clone()})],
446            None,
447        );
448        let out = resp.messages[0]["content"].as_str().unwrap();
449
450        let litellm_regex = regex::Regex::new(r"hash=([a-f0-9]{24})").unwrap();
451        let hash = litellm_regex
452            .captures(out)
453            .unwrap_or_else(|| panic!("lossy body must carry the hash= marker: {out}"))
454            .get(1)
455            .unwrap()
456            .as_str();
457        let recovered = super::super::ccr::retrieve_litellm(hash)
458            .expect("marker hash must resolve via /v1/retrieve");
459        assert!(
460            recovered.contains("fearless concurrency"),
461            "retrieve returns the verbatim pre-compression original"
462        );
463        assert_eq!(
464            recovered.matches("fearless concurrency").count(),
465            8,
466            "all deduped paragraphs are recoverable"
467        );
468    }
469
470    #[test]
471    fn output_is_deterministic() {
472        let _lock = crate::core::data_dir::test_env_lock();
473        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
474        let msgs = vec![
475            json!({"role": "system", "content": "You are a helpful assistant."}),
476            json!({"role": "user", "content": dedupable_prose()}),
477        ];
478        let a = serde_json::to_string(&run(msgs.clone(), Some("gpt-4o"))).unwrap();
479        let b = serde_json::to_string(&run(msgs, Some("gpt-4o"))).unwrap();
480        assert_eq!(a, b, "same input must yield byte-identical output");
481    }
482
483    #[test]
484    fn short_content_is_untouched() {
485        let resp = run(vec![json!({"role": "user", "content": "hi there"})], None);
486        assert_eq!(resp.messages[0]["content"], "hi there");
487        assert_eq!(resp.stats.saved_tokens, 0);
488        assert_eq!(resp.stats.saved_pct, 0.0);
489    }
490
491    #[test]
492    fn anthropic_blocks_text_compressed_image_passthrough() {
493        let _lock = crate::core::data_dir::test_env_lock();
494        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
495        let resp = run(
496            vec![json!({
497                "role": "user",
498                "content": [
499                    {"type": "text", "text": dedupable_prose()},
500                    {"type": "image", "source": {"type": "base64", "data": "AAAA"}},
501                ],
502            })],
503            None,
504        );
505        let blocks = resp.messages[0]["content"].as_array().unwrap();
506        assert_eq!(
507            blocks[0]["text"]
508                .as_str()
509                .unwrap()
510                .matches("fearless concurrency")
511                .count(),
512            1
513        );
514        // Image block is preserved verbatim.
515        assert_eq!(blocks[1]["source"]["data"], "AAAA");
516    }
517
518    #[test]
519    fn anthropic_tool_result_block_is_compressed() {
520        let _lock = crate::core::data_dir::test_env_lock();
521        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
522        let resp = run(
523            vec![json!({
524                "role": "user",
525                "content": [{
526                    "type": "tool_result",
527                    "tool_use_id": "toolu_123",
528                    "content": dedupable_prose(),
529                }],
530            })],
531            None,
532        );
533        let block = &resp.messages[0]["content"][0];
534        assert_eq!(block["tool_use_id"], "toolu_123", "ids preserved");
535        assert_eq!(
536            block["content"]
537                .as_str()
538                .unwrap()
539                .matches("fearless concurrency")
540                .count(),
541            1
542        );
543        assert!(resp.stats.saved_tokens > 0);
544    }
545
546    #[test]
547    fn lean_ctx_tool_output_passes_through_verbatim() {
548        // A ctx_* result is already compressed at the tool boundary (#479).
549        let prose = dedupable_prose();
550        let resp = run(
551            vec![json!({"role": "tool", "name": "ctx_read", "content": prose.clone()})],
552            None,
553        );
554        assert_eq!(resp.messages[0]["content"].as_str().unwrap(), prose);
555        assert_eq!(
556            resp.stats.saved_tokens, 0,
557            "ctx_* output is not re-compressed"
558        );
559    }
560
561    #[test]
562    fn non_string_content_is_ignored() {
563        // A malformed/absent content field must not panic.
564        let resp = run(vec![json!({"role": "assistant", "tool_calls": []})], None);
565        assert_eq!(resp.stats.original_tokens, 0);
566        assert_eq!(resp.messages.len(), 1);
567    }
568
569    /// #498 regression: a full, mixed-shape conversation must serialise to
570    /// byte-identical output across repeated calls. Provider prompt caching keys
571    /// on the exact bytes, so any non-determinism (ordering, footer leakage,
572    /// counter/timestamp) would silently destroy the cache discount.
573    #[test]
574    fn determinism_regression_full_conversation_498() {
575        let _lock = crate::core::data_dir::test_env_lock();
576        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
577        let conversation = || {
578            vec![
579                json!({"role": "system", "content": "You are a helpful assistant."}),
580                json!({"role": "user", "content": dedupable_prose()}),
581                json!({
582                    "role": "user",
583                    "content": [
584                        {"type": "text", "text": dedupable_prose()},
585                        {"type": "image", "source": {"type": "base64", "data": "AAAA"}},
586                        {"type": "tool_result", "tool_use_id": "toolu_1", "content": dedupable_prose()},
587                    ],
588                }),
589                json!({"role": "tool", "name": "ctx_read", "content": dedupable_prose()}),
590            ]
591        };
592
593        let baseline =
594            serde_json::to_string(&run(conversation(), Some("claude-sonnet-4"))).unwrap();
595        for _ in 0..4 {
596            let again =
597                serde_json::to_string(&run(conversation(), Some("claude-sonnet-4"))).unwrap();
598            assert_eq!(again, baseline, "/v1/compress output must be byte-stable");
599        }
600
601        // The byte-stable bodies must also be footer-free (savings live in stats).
602        assert!(!baseline.contains("[lean-ctx:"));
603        assert!(!baseline.contains('\u{2500}'));
604    }
605
606    /// One tool result through the handler: the reply's reason codes (if
607    /// any) and the content that came back. The reply is never a refusal.
608    async fn reply_for(text: &str) -> (Option<String>, String) {
609        let response = handler(Json(CompressRequest {
610            messages: vec![json!({"role": "tool", "name": "bash", "content": text})],
611            model: None,
612        }))
613        .await;
614        assert_eq!(response.status(), StatusCode::OK);
615        assert!(
616            !response.headers().contains_key(admitted::REFUSAL_HEADER),
617            "a delivered reply is not a refusal"
618        );
619        let codes = response
620            .headers()
621            .get(admitted::REASON_CODES_HEADER)
622            .and_then(|value| value.to_str().ok())
623            .map(str::to_owned);
624        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
625            .await
626            .expect("reply body");
627        let body: Value = serde_json::from_slice(&body).expect("JSON reply");
628        let content = body["messages"][0]["content"]
629            .as_str()
630            .expect("string content")
631            .to_owned();
632        (codes, content)
633    }
634
635    /// [real register and store] Under protection `/v1/compress` follows the
636    /// rule of the forward path: a block the Engine delivered with a lineage
637    /// is compressed, with a recovery copy stored for the proxy's project and
638    /// a stub naming the route that resolves it to the exact original; a
639    /// block without a lineage comes back whole and the reply's reason-code
640    /// header says why, by code only. Before, every block came back whole
641    /// under protection and nothing said why.
642    #[tokio::test]
643    async fn protected_reply_compresses_only_with_a_bound_copy_and_names_why_not() {
644        let _data = crate::core::data_dir::isolated_data_dir();
645        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
646        let directory = tempfile::tempdir().expect("project");
647        let root = directory.path().canonicalize().expect("canonical root");
648        let config = crate::core::paths::config_dir_read_only().expect("config directory");
649        std::fs::create_dir_all(&config).expect("config directory");
650        std::fs::write(
651            config.join("config.toml"),
652            format!(
653                "[context_gateway]\nmode = \"governed\"\n\n[proxy]\nproject_root = '{}'\n",
654                root.display()
655            ),
656        )
657        .expect("gateway config");
658        let log = (1..=400)
659            .map(|i| format!("[info] processed item {i:04} ok"))
660            .collect::<Vec<_>>()
661            .join("\n");
662        let source = root.join("build.log");
663        std::fs::write(&source, &log).expect("source");
664        // The test plays the Engine: an admitted read, recorded as delivered.
665        let delivered_text = super::super::request_project::in_project(&root, || {
666            let path = source.to_str().expect("utf-8 path");
667            let admitted_text = crate::tools::ctx_read::read_file_for_tool_rooted(
668                path,
669                root.to_str().expect("utf-8 root"),
670                "ctx_read",
671            )
672            .expect("admitted read");
673            let authority = crate::core::archive::authority::ArchiveAuthority::file(
674                &root,
675                path,
676                "ctx_read",
677                &admitted_text,
678            )
679            .expect("protection is active: the read is bound");
680            assert!(crate::core::archive::delivered::record_lineage(
681                &crate::core::archive::delivered::digest(&admitted_text),
682                &crate::core::archive::delivered::Lineage::of_files(authority)
683            ));
684            admitted_text
685        });
686
687        let (codes, sent) = reply_for(&delivered_text).await;
688        assert_eq!(codes, None, "nothing stayed whole");
689        assert!(sent.len() < delivered_text.len(), "compressed: {sent}");
690        let (_, rest) = sent
691            .rsplit_once("GET /v1/references/")
692            .expect("a stub naming the route");
693        let id: String = rest.chars().take(64).collect();
694        assert!(
695            sent.ends_with(&format!(
696                "[lean-ctx CCR: full original archived — GET /v1/references/{id} on this \
697                 gateway returns it while its sources are admitted]"
698            )),
699            "{sent}"
700        );
701        assert!(!sent.contains("hash="), "not a tee marker: {sent}");
702        assert_eq!(
703            super::super::compress::resolve_recovery(&id),
704            Some(Ok(delivered_text.clone())),
705            "the id resolves to the exact original"
706        );
707        let (_, again) = reply_for(&delivered_text).await;
708        assert_eq!(again, sent, "byte-stable");
709
710        let unknown = format!("{delivered_text}\n[info] a line the Engine never delivered");
711        let (codes, whole) = reply_for(&unknown).await;
712        assert_eq!(whole, unknown, "no lineage, no copy: the original");
713        assert_eq!(codes.as_deref(), Some("recovery.unknown_lineage"));
714
715        std::fs::remove_file(&source).expect("delete the source");
716        let (codes, whole) = reply_for(&delivered_text).await;
717        assert_eq!(whole, delivered_text);
718        assert_eq!(codes.as_deref(), Some("recovery.source_no_longer_admitted"));
719    }
720
721    /// Daemon-free, o200k_base benchmark over a real on-disk corpus. Prints a
722    /// JSON report (ratio + latency) and is `#[ignore]`d so it stays out of CI.
723    /// Reproduce: `cargo test -p lean-ctx --lib \
724    /// proxy::compress_api::tests::bench_real_corpus_o200k -- --ignored --nocapture`.
725    #[test]
726    #[ignore = "benchmark; run explicitly with --ignored --nocapture"]
727    fn bench_real_corpus_o200k() {
728        use std::path::Path;
729        use std::time::Instant;
730
731        let corpus = Path::new(env!("CARGO_MANIFEST_DIR")).join("../docs/reference");
732        let mut messages = Vec::new();
733        if let Ok(entries) = std::fs::read_dir(&corpus) {
734            let mut paths: Vec<_> = entries
735                .flatten()
736                .map(|e| e.path())
737                .filter(|p| p.extension().and_then(|s| s.to_str()) == Some("md"))
738                .collect();
739            paths.sort();
740            for path in paths {
741                if let Ok(text) = std::fs::read_to_string(&path) {
742                    messages.push(json!({"role": "user", "content": text}));
743                }
744            }
745        }
746        assert!(!messages.is_empty(), "no corpus files found at {corpus:?}");
747
748        let files = messages.len();
749        let started = Instant::now();
750        let resp = run(messages, Some("gpt-4o"));
751        let latency_ms = started.elapsed().as_secs_f64() * 1000.0;
752
753        let report = json!({
754            "corpus": corpus.to_string_lossy(),
755            "files": files,
756            "tokenizer": resp.stats.tokenizer,
757            "original_tokens": resp.stats.original_tokens,
758            "compressed_tokens": resp.stats.compressed_tokens,
759            "tokens_saved": resp.stats.saved_tokens,
760            "saved_pct": resp.stats.saved_pct,
761            "latency_ms": (latency_ms * 100.0).round() / 100.0,
762        });
763        println!("{}", serde_json::to_string_pretty(&report).unwrap());
764    }
765}