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