Skip to main content

lean_ctx/proxy/forward/
pipeline.rs

1use std::time::Instant;
2
3use crate::proxy::prose_patterns::remove_seen_instruction_lines;
4use axum::http::HeaderValue;
5use serde_json::Value;
6use std::collections::HashSet;
7
8use crate::{
9    core::{
10        config::PipelineConfig,
11        knowledge_router::ContextAdvice,
12        tokens::{COUNTING_FAMILY, count_tokens_for},
13    },
14    proxy::{
15        adaptive_policy::select_policy,
16        dedup::ContentAddressedDedup,
17        determinism_guard,
18        effort_routing::score_complexity,
19        live_zone::{compress_live_only, detect_live_zone},
20        pre_optimize::classify_task,
21        prose_compress::{CompressionStrategy, ProseCompressor},
22    },
23};
24
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct StageReport {
27    pub name: &'static str,
28    pub tokens_saved: u64,
29    pub duration_us: u64,
30    pub skipped: bool,
31    ran: bool,
32}
33
34#[derive(Debug, Clone)]
35pub struct PipelineReport {
36    pub stages_run: Vec<StageReport>,
37    pub total_tokens_before: u64,
38    pub total_tokens_after: u64,
39    pub total_savings_pct: f32,
40    pub(crate) effort_complexity: Option<u8>,
41}
42
43impl PipelineReport {
44    pub(crate) fn apply_effort_budget(&self, request: &mut Value) {
45        if let Some(complexity) = self.effort_complexity {
46            crate::proxy::effort_routing::apply_effort_budget(request, complexity);
47        }
48    }
49
50    pub(crate) fn apply_response_headers(&self, headers: &mut axum::http::HeaderMap) {
51        insert_header(
52            headers,
53            "x-leanctx-pipeline-stages",
54            &self.headline_stage_names(),
55        );
56        insert_header(
57            headers,
58            "x-leanctx-total-savings",
59            &format!("{:.0}%", self.total_savings_pct),
60        );
61
62        if let Some(fastest) = self.fastest_stage() {
63            insert_header(
64                headers,
65                "x-leanctx-fastest-stage",
66                &format!("{} ({}us)", fastest.name, fastest.duration_us),
67            );
68        }
69    }
70
71    fn headline_stage_names(&self) -> String {
72        ["live_zone", "dedup", "prose", "effort"]
73            .into_iter()
74            .filter(|name| {
75                self.stages_run
76                    .iter()
77                    .any(|stage| stage.name == *name && stage.ran)
78            })
79            .collect::<Vec<_>>()
80            .join(",")
81    }
82
83    fn fastest_stage(&self) -> Option<&StageReport> {
84        self.stages_run
85            .iter()
86            .filter(|stage| stage.ran && !stage.skipped)
87            .min_by_key(|stage| stage.duration_us)
88    }
89}
90
91pub struct CompressionPipeline;
92
93impl CompressionPipeline {
94    pub fn run(messages: &mut Vec<Value>, config: &PipelineConfig) -> PipelineReport {
95        Self::run_with_context_advice(messages, config, None)
96    }
97
98    /// Runs the normal pipeline while preserving message content identified by
99    /// KnowledgeRouter as source-reference context.
100    pub fn run_with_context_advice(
101        messages: &mut Vec<Value>,
102        config: &PipelineConfig,
103        context_advice: Option<&ContextAdvice>,
104    ) -> PipelineReport {
105        let original_messages = messages.clone();
106        let total_tokens_before = messages_tokens(messages);
107        let mut stages_run = Vec::with_capacity(7);
108
109        let started = Instant::now();
110        let live_zone = detect_live_zone(messages);
111        let mut live_messages = messages.split_off(live_zone.boundary_turn);
112        stages_run.push(stage_report("live_zone", true, 0, started));
113
114        let dedup_started = Instant::now();
115        let dedup_saved = if config.enable_dedup {
116            let before = messages_tokens(&live_messages);
117            let mut dedup = ContentAddressedDedup::new();
118            let _ = dedup.dedup_messages(&mut live_messages);
119            before.saturating_sub(messages_tokens(&live_messages))
120        } else {
121            0
122        };
123        stages_run.push(stage_report(
124            "dedup",
125            config.enable_dedup,
126            dedup_saved,
127            dedup_started,
128        ));
129
130        let task_class = task_class(&live_messages);
131        let policy_started = Instant::now();
132        let policy = select_policy(task_class);
133        stages_run.push(stage_report("adaptive_policy", true, 0, policy_started));
134
135        let prose_started = Instant::now();
136        let prose_saved = if config.enable_prose {
137            let before = messages_tokens(&live_messages);
138            compress_live_prose(&mut live_messages, task_class, context_advice);
139            before.saturating_sub(messages_tokens(&live_messages))
140        } else {
141            0
142        };
143        stages_run.push(stage_report(
144            "prose",
145            config.enable_prose,
146            prose_saved,
147            prose_started,
148        ));
149
150        let tool_started = Instant::now();
151        let tool_saved = if config.enable_prose {
152            let before = messages_tokens(&live_messages);
153            let _ = compress_live_only(&mut live_messages, COUNTING_FAMILY, policy);
154            before.saturating_sub(messages_tokens(&live_messages))
155        } else {
156            0
157        };
158        stages_run.push(stage_report(
159            "tool_results",
160            config.enable_prose,
161            tool_saved,
162            tool_started,
163        ));
164
165        let effort_started = Instant::now();
166        let effort_complexity = config.enable_effort.then(|| {
167            let mut all_messages = messages.clone();
168            all_messages.extend(live_messages.clone());
169            score_complexity(&all_messages)
170        });
171        stages_run.push(stage_report(
172            "effort",
173            config.enable_effort,
174            0,
175            effort_started,
176        ));
177
178        messages.append(&mut live_messages);
179
180        let determinism_started = Instant::now();
181        // #1545: this proof used to be bound to `_proof` and dropped — a
182        // live-zone disagreement with the forwarder's guard then shipped a
183        // mutated body over the wire unchecked (observed as upstream 400s and
184        // silent cache busts). Fail closed like the forwarder: an unstable
185        // proof reverts every compression stage below.
186        let proof = determinism_guard::verify_determinism(&original_messages, messages);
187        let determinism_unstable = !proof.is_stable;
188        if determinism_unstable {
189            tracing::warn!("lean-ctx pipeline determinism violation: reverting compression stages");
190        }
191        stages_run.push(stage_report(
192            "determinism_guard",
193            true,
194            0,
195            determinism_started,
196        ));
197
198        // #1789: a stage that emptied a turn must revert, however good its
199        // savings look. Checked alongside the determinism proof because neither
200        // that proof nor the savings floor below can observe this failure mode.
201        let content_destroyed = destroys_content(&original_messages, messages);
202        if content_destroyed {
203            tracing::warn!(
204                "lean-ctx pipeline: compression emptied a message that had content; \
205                 reverting compression stages"
206            );
207        }
208
209        let mut total_tokens_after = messages_tokens(messages);
210        let mut total_savings_pct = savings_pct(total_tokens_before, total_tokens_after);
211        let should_revert = determinism_unstable
212            || content_destroyed
213            || (total_tokens_before > 0 && total_savings_pct < config.min_savings_pct);
214        if should_revert {
215            *messages = original_messages;
216            total_tokens_after = total_tokens_before;
217            total_savings_pct = 0.0;
218            for stage in &mut stages_run {
219                if matches!(stage.name, "dedup" | "prose" | "tool_results") {
220                    stage.tokens_saved = 0;
221                    stage.skipped = true;
222                }
223            }
224        }
225
226        PipelineReport {
227            stages_run,
228            total_tokens_before,
229            total_tokens_after,
230            total_savings_pct,
231            effort_complexity,
232        }
233    }
234}
235
236fn stage_report(name: &'static str, ran: bool, tokens_saved: u64, started: Instant) -> StageReport {
237    StageReport {
238        name,
239        tokens_saved,
240        duration_us: duration_us(started),
241        skipped: !ran || tokens_saved == 0,
242        ran,
243    }
244}
245
246fn duration_us(started: Instant) -> u64 {
247    u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX)
248}
249
250fn messages_tokens(messages: &[Value]) -> u64 {
251    messages
252        .iter()
253        .filter_map(|message| serde_json::to_string(message).ok())
254        .map(|message| count_tokens_for(&message, COUNTING_FAMILY) as u64)
255        .sum()
256}
257
258fn savings_pct(before: u64, after: u64) -> f32 {
259    if before == 0 {
260        0.0
261    } else {
262        (before.saturating_sub(after) as f32 / before as f32) * 100.0
263    }
264}
265
266fn task_class(messages: &[Value]) -> &'static str {
267    let text = messages.iter().rev().find_map(|message| {
268        (message.get("role").and_then(Value::as_str) == Some("user"))
269            .then(|| message.get("content").and_then(Value::as_str))
270            .flatten()
271    });
272    classify_task(text)
273}
274
275fn compress_live_prose(
276    messages: &mut [Value],
277    task_class: &str,
278    context_advice: Option<&ContextAdvice>,
279) {
280    let mut seen_instruction_lines = HashSet::new();
281    for message in messages {
282        if message.get("role").and_then(Value::as_str) == Some("tool") {
283            continue;
284        }
285
286        if context_advice.is_some_and(|advice| {
287            serde_json::to_string(message)
288                .map(|serialized| advice.protects(&serialized))
289                .unwrap_or(false)
290        }) {
291            continue;
292        }
293
294        let Some(content) = message.get_mut("content") else {
295            continue;
296        };
297
298        match content {
299            Value::String(text) => compress_text(text, task_class),
300            Value::Array(blocks) => {
301                for block in blocks {
302                    let Some(block) = block.as_object_mut() else {
303                        continue;
304                    };
305                    if block.get("type").and_then(Value::as_str) == Some("text") {
306                        if let Some(Value::String(text)) = block.get_mut("text") {
307                            remove_seen_instruction_lines(text, &mut seen_instruction_lines);
308                            compress_text(text, task_class);
309                        }
310                    }
311                }
312            }
313            _ => {}
314        }
315    }
316}
317
318/// Compress one conversation turn.
319///
320/// #1789: this deliberately pins the strategy to [`CompressionStrategy::Light`]
321/// instead of letting `ProseCompressor::new` infer `Aggressive` from the
322/// presence of a task hint. `Aggressive` *drops* whole sections that carry no
323/// task/technical keyword — sound for a document, where the surviving sections
324/// still carry the content, but a chat turn is a single paragraph, so dropping
325/// its only section deletes the message. `Light` keeps every section and still
326/// applies the lossless pattern pass, which is the only squeeze a conversation
327/// turn may safely receive. Tool output keeps its section-dropping compressor
328/// in the `tool_results` stage, where whole-message deletion is impossible.
329fn compress_text(text: &mut String, task_class: &str) {
330    let result = ProseCompressor::new(Some(task_class))
331        .with_strategy(CompressionStrategy::Light)
332        .compress(text);
333    if result.compressed_tokens < result.original_tokens
334        && result.compressed.len() < text.len()
335        && !result.compressed.trim().is_empty()
336    {
337        *text = result.compressed;
338    }
339}
340
341/// All text a message carries, across both wire shapes: a plain string
342/// (`content: "…"`, OpenAI) and a block array (`content: [{type:"text",…}]`,
343/// Anthropic).
344fn message_text(message: &Value) -> String {
345    match message.get("content") {
346        Some(Value::String(text)) => text.clone(),
347        Some(Value::Array(blocks)) => blocks
348            .iter()
349            .filter_map(|block| block.get("text").and_then(Value::as_str))
350            .collect::<Vec<_>>()
351            .join(""),
352        _ => String::new(),
353    }
354}
355
356/// True when compression emptied a message that arrived with text (#1789).
357///
358/// This is a *content* invariant, deliberately separate from the determinism
359/// guard's *cache-prefix* invariant: emptying every live turn leaves the frozen
360/// prefix byte-identical, so the determinism proof stays stable while the
361/// request loses everything the model was supposed to read. Savings-based
362/// reverting cannot catch it either — deleting all content scores as a perfect
363/// ~100% saving and sails past `min_savings_pct`.
364fn destroys_content(before: &[Value], after: &[Value]) -> bool {
365    before.len() == after.len()
366        && before.iter().zip(after).any(|(before, after)| {
367            !message_text(before).trim().is_empty() && message_text(after).trim().is_empty()
368        })
369}
370
371fn insert_header(headers: &mut axum::http::HeaderMap, name: &str, value: &str) {
372    if let (Ok(name), Ok(value)) = (
373        axum::http::header::HeaderName::try_from(name),
374        HeaderValue::from_str(value),
375    ) {
376        headers.insert(name, value);
377    }
378}
379
380#[cfg(test)]
381mod tests {
382    use serde_json::json;
383
384    use super::{CompressionPipeline, PipelineConfig};
385
386    fn verbose_text() -> String {
387        (0..200)
388            .map(|index| {
389                format!(
390                    "This repeated operational detail is not needed for the current task {index}."
391                )
392            })
393            .collect::<Vec<_>>()
394            .join("\n")
395    }
396
397    #[test]
398    fn pipeline_runs_all_stages_in_order() {
399        let mut messages = vec![json!({"role": "user", "content": verbose_text()})];
400
401        let report = CompressionPipeline::run(&mut messages, &PipelineConfig::default());
402
403        assert_eq!(
404            report
405                .stages_run
406                .iter()
407                .map(|stage| stage.name)
408                .collect::<Vec<_>>(),
409            vec![
410                "live_zone",
411                "dedup",
412                "adaptive_policy",
413                "prose",
414                "tool_results",
415                "effort",
416                "determinism_guard",
417            ]
418        );
419    }
420
421    #[test]
422    fn disabled_stage_is_skipped() {
423        let mut messages = vec![json!({"role": "user", "content": verbose_text()})];
424        let config = PipelineConfig {
425            enable_dedup: false,
426            min_savings_pct: 0.0,
427            ..PipelineConfig::default()
428        };
429
430        let report = CompressionPipeline::run(&mut messages, &config);
431
432        let dedup = report
433            .stages_run
434            .iter()
435            .find(|stage| stage.name == "dedup")
436            .expect("dedup stage report");
437        assert!(dedup.skipped);
438        assert!(!dedup.ran);
439    }
440
441    // #1545: the determinism proof is enforcement now, not telemetry — a
442    // stage that rewrites content inside the client's cache_control'd prefix
443    // is reverted, so the wire body keeps the prefix byte-identical.
444    #[test]
445    fn cache_controlled_prefix_survives_pipeline_byte_identical() {
446        let repeated = verbose_text();
447        let mut messages = vec![
448            json!({"role": "user", "cache_control": {"type": "ephemeral"}, "content": &repeated}),
449            json!({"role": "assistant", "content": &repeated}),
450            json!({"role": "user", "content": "Try again"}),
451        ];
452        let before_prefix = messages[0].to_string();
453        let config = PipelineConfig {
454            min_savings_pct: 0.0,
455            ..PipelineConfig::default()
456        };
457
458        let _ = CompressionPipeline::run(&mut messages, &config);
459
460        assert_eq!(
461            messages[0].to_string(),
462            before_prefix,
463            "cache_control'd prefix must never ship mutated"
464        );
465    }
466
467    #[test]
468    fn report_accumulates_savings() {
469        let repeated = verbose_text();
470        let mut messages = vec![
471            json!({"role": "user", "content": "Fix the bug"}),
472            json!({"role": "assistant", "content": &repeated}),
473            json!({"role": "user", "content": "Try again"}),
474            json!({"role": "assistant", "content": &repeated}),
475        ];
476        let config = PipelineConfig {
477            enable_prose: false,
478            min_savings_pct: 0.0,
479            ..PipelineConfig::default()
480        };
481
482        let report = CompressionPipeline::run(&mut messages, &config);
483
484        assert!(
485            report.total_savings_pct >= 0.0,
486            "pipeline should not produce negative savings: {:.1}%",
487            report.total_savings_pct
488        );
489        let stage_total: u64 = report
490            .stages_run
491            .iter()
492            .map(|stage| stage.tokens_saved)
493            .sum();
494        assert_eq!(
495            report.total_tokens_before - report.total_tokens_after,
496            stage_total
497        );
498    }
499
500    #[test]
501    fn empty_messages_are_safe() {
502        let mut messages = Vec::new();
503
504        let report = CompressionPipeline::run(&mut messages, &PipelineConfig::default());
505
506        assert!(messages.is_empty());
507        assert_eq!(report.total_tokens_before, 0);
508        assert_eq!(report.total_tokens_after, 0);
509    }
510
511    /// #1789: the proxy emptied every non-system turn on provider routes.
512    ///
513    /// The prose stage runs `ProseCompressor` with a task hint, which selects
514    /// `CompressionStrategy::Aggressive`. That strategy drops any paragraph
515    /// without a hardcoded English technical keyword — and a chat turn *is* a
516    /// single paragraph, so dropping it deletes the whole message. The system
517    /// turn survived only because it sits in the frozen prefix.
518    #[test]
519    fn conversation_turns_never_lose_their_content() {
520        let mut messages = vec![
521            json!({"role": "system",    "content": "Tu es un assistant francais."}),
522            json!({"role": "user",      "content": "Bonjour, quelle est la capitale de la France ?"}),
523            json!({"role": "assistant", "content": "La capitale de la France est Paris."}),
524            json!({"role": "user",      "content": "Et combien d habitants environ ?"}),
525        ];
526
527        CompressionPipeline::run(&mut messages, &PipelineConfig::default());
528
529        for message in &messages {
530            let role = message["role"].as_str().unwrap_or_default();
531            let content = message["content"].as_str().unwrap_or_default();
532            assert!(
533                !content.trim().is_empty(),
534                "#1789: `{role}` turn was emptied by the compression pipeline; \
535                 upstream would receive a conversation the model cannot see"
536            );
537        }
538    }
539}