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        compress::gate,
17        dedup::dedup_tool_outputs,
18        determinism_guard,
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}
41
42impl PipelineReport {
43    /// Tokens the in-request tool-output dedup stage saved (0 when reverted).
44    pub(crate) fn dedup_tokens_saved(&self) -> usize {
45        self.stages_run
46            .iter()
47            .find(|stage| stage.name == "dedup")
48            .map_or(0, |stage| {
49                usize::try_from(stage.tokens_saved).unwrap_or(usize::MAX)
50            })
51    }
52
53    pub(crate) fn apply_response_headers(&self, headers: &mut axum::http::HeaderMap) {
54        insert_header(
55            headers,
56            "x-leanctx-pipeline-stages",
57            &self.headline_stage_names(),
58        );
59        insert_header(
60            headers,
61            "x-leanctx-total-savings",
62            &format!("{:.0}%", self.total_savings_pct),
63        );
64
65        if let Some(fastest) = self.fastest_stage() {
66            insert_header(
67                headers,
68                "x-leanctx-fastest-stage",
69                &format!("{} ({}us)", fastest.name, fastest.duration_us),
70            );
71        }
72    }
73
74    fn headline_stage_names(&self) -> String {
75        ["live_zone", "dedup", "prose"]
76            .into_iter()
77            .filter(|name| {
78                self.stages_run
79                    .iter()
80                    .any(|stage| stage.name == *name && stage.ran)
81            })
82            .collect::<Vec<_>>()
83            .join(",")
84    }
85
86    fn fastest_stage(&self) -> Option<&StageReport> {
87        self.stages_run
88            .iter()
89            .filter(|stage| stage.ran && !stage.skipped)
90            .min_by_key(|stage| stage.duration_us)
91    }
92}
93
94pub struct CompressionPipeline;
95
96impl CompressionPipeline {
97    pub fn run(messages: &mut Vec<Value>, config: &PipelineConfig) -> PipelineReport {
98        Self::run_with_context_advice(messages, config, None)
99    }
100
101    /// Runs the normal pipeline while preserving message content identified by
102    /// KnowledgeRouter as source-reference context.
103    pub fn run_with_context_advice(
104        messages: &mut Vec<Value>,
105        config: &PipelineConfig,
106        context_advice: Option<&ContextAdvice>,
107    ) -> PipelineReport {
108        let original_messages = messages.clone();
109        let total_tokens_before = messages_tokens(messages);
110        let mut stages_run = Vec::with_capacity(7);
111
112        let started = Instant::now();
113        let live_zone = detect_live_zone(messages);
114        let mut live_messages = messages.split_off(live_zone.boundary_turn);
115        stages_run.push(stage_report("live_zone", true, 0, started));
116
117        let task_class = task_class(&live_messages);
118        let policy_started = Instant::now();
119        let policy = select_policy(task_class);
120        stages_run.push(stage_report("adaptive_policy", true, 0, policy_started));
121
122        let prose_started = Instant::now();
123        let prose_saved = if config.enable_prose {
124            let before = messages_tokens(&live_messages);
125            compress_live_prose(&mut live_messages, task_class, context_advice);
126            before.saturating_sub(messages_tokens(&live_messages))
127        } else {
128            0
129        };
130        stages_run.push(stage_report(
131            "prose",
132            config.enable_prose,
133            prose_saved,
134            prose_started,
135        ));
136
137        let tool_started = Instant::now();
138        let tool_saved = if config.enable_prose {
139            let before = messages_tokens(&live_messages);
140            let _ = compress_live_only(&mut live_messages, COUNTING_FAMILY, policy);
141            before.saturating_sub(messages_tokens(&live_messages))
142        } else {
143            0
144        };
145        stages_run.push(stage_report(
146            "tool_results",
147            config.enable_prose,
148            tool_saved,
149            tool_started,
150        ));
151
152        // Dedup runs after every stage that rewrites tool output: its references
153        // and line deltas describe the earlier result exactly as it is sent, so
154        // nothing may change that result afterwards (#1980).
155        let dedup_started = Instant::now();
156        let dedup_saved = if config.enable_dedup {
157            let before = messages_tokens(&live_messages);
158            let _ = dedup_tool_outputs(&mut live_messages);
159            before.saturating_sub(messages_tokens(&live_messages))
160        } else {
161            0
162        };
163        stages_run.push(stage_report(
164            "dedup",
165            config.enable_dedup,
166            dedup_saved,
167            dedup_started,
168        ));
169
170        // No reasoning-budget stage: how hard a model reasons is set by the host
171        // or by the operator's constant `proxy.effort`, never derived from the
172        // prompt. The retired `pipeline.enable_effort` key is ignored.
173
174        messages.append(&mut live_messages);
175
176        let determinism_started = Instant::now();
177        // #1545: this proof used to be bound to `_proof` and dropped — a
178        // live-zone disagreement with the forwarder's guard then shipped a
179        // mutated body over the wire unchecked (observed as upstream 400s and
180        // silent cache busts). Fail closed like the forwarder: an unstable
181        // proof reverts every compression stage below.
182        let proof = determinism_guard::verify_determinism(&original_messages, messages);
183        let determinism_unstable = !proof.is_stable;
184        if determinism_unstable {
185            tracing::warn!("lean-ctx pipeline determinism violation: reverting compression stages");
186        }
187        stages_run.push(stage_report(
188            "determinism_guard",
189            true,
190            0,
191            determinism_started,
192        ));
193
194        // #1789: a stage that emptied a turn must revert, however good its
195        // savings look. Checked alongside the determinism proof because neither
196        // that proof nor the savings floor below can observe this failure mode.
197        let content_destroyed = destroys_content(&original_messages, messages);
198        if content_destroyed {
199            tracing::warn!(
200                "lean-ctx pipeline: compression emptied a message that had content; \
201                 reverting compression stages"
202            );
203        }
204
205        let mut total_tokens_after = messages_tokens(messages);
206        let mut total_savings_pct = savings_pct(total_tokens_before, total_tokens_after);
207        let should_revert = determinism_unstable
208            || content_destroyed
209            || (total_tokens_before > 0 && total_savings_pct < config.min_savings_pct);
210        if should_revert {
211            *messages = original_messages;
212            total_tokens_after = total_tokens_before;
213            total_savings_pct = 0.0;
214            for stage in &mut stages_run {
215                if matches!(stage.name, "dedup" | "prose" | "tool_results") {
216                    stage.tokens_saved = 0;
217                    stage.skipped = true;
218                }
219            }
220        }
221
222        PipelineReport {
223            stages_run,
224            total_tokens_before,
225            total_tokens_after,
226            total_savings_pct,
227        }
228    }
229}
230
231fn stage_report(name: &'static str, ran: bool, tokens_saved: u64, started: Instant) -> StageReport {
232    StageReport {
233        name,
234        tokens_saved,
235        duration_us: duration_us(started),
236        skipped: !ran || tokens_saved == 0,
237        ran,
238    }
239}
240
241fn duration_us(started: Instant) -> u64 {
242    u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX)
243}
244
245fn messages_tokens(messages: &[Value]) -> u64 {
246    messages
247        .iter()
248        .filter_map(|message| serde_json::to_string(message).ok())
249        .map(|message| count_tokens_for(&message, COUNTING_FAMILY) as u64)
250        .sum()
251}
252
253fn savings_pct(before: u64, after: u64) -> f32 {
254    if before == 0 {
255        0.0
256    } else {
257        (before.saturating_sub(after) as f32 / before as f32) * 100.0
258    }
259}
260
261fn task_class(messages: &[Value]) -> &'static str {
262    let text = messages.iter().rev().find_map(|message| {
263        (message.get("role").and_then(Value::as_str) == Some("user"))
264            .then(|| message.get("content").and_then(Value::as_str))
265            .flatten()
266    });
267    classify_task(text)
268}
269
270fn compress_live_prose(
271    messages: &mut [Value],
272    task_class: &str,
273    context_advice: Option<&ContextAdvice>,
274) {
275    let mut seen_instruction_lines = HashSet::new();
276    for message in messages {
277        if message.get("role").and_then(Value::as_str) == Some("tool") {
278            continue;
279        }
280
281        if context_advice.is_some_and(|advice| {
282            serde_json::to_string(message)
283                .map(|serialized| advice.protects(&serialized))
284                .unwrap_or(false)
285        }) {
286            continue;
287        }
288
289        let Some(content) = message.get_mut("content") else {
290            continue;
291        };
292
293        // Both steps drop text (lines an earlier turn carried in another
294        // spelling, near-duplicate and explanatory sentences): they are one
295        // change of the block and pass the shared gate once. Under
296        // protection the block changes only with a recovery copy bound to
297        // its lineage; a turn the host wrote has none and stays whole.
298        match content {
299            Value::String(text) => gate::rewrite(text, |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                            gate::rewrite(text, |text| {
308                                remove_seen_instruction_lines(text, &mut seen_instruction_lines);
309                                compress_text(text, task_class);
310                            });
311                        }
312                    }
313                }
314            }
315            _ => {}
316        }
317    }
318}
319
320/// Compress one conversation turn.
321///
322/// #1789: this deliberately pins the strategy to [`CompressionStrategy::Light`]
323/// instead of letting `ProseCompressor::new` infer `Aggressive` from the
324/// presence of a task hint. `Aggressive` *drops* whole sections that carry no
325/// task/technical keyword — sound for a document, where the surviving sections
326/// still carry the content, but a chat turn is a single paragraph, so dropping
327/// its only section deletes the message. `Light` keeps every section and still
328/// applies the lossless pattern pass, which is the only squeeze a conversation
329/// turn may safely receive. Tool output keeps its section-dropping compressor
330/// in the `tool_results` stage, where whole-message deletion is impossible.
331fn compress_text(text: &mut String, task_class: &str) {
332    let result = ProseCompressor::new(Some(task_class))
333        .with_strategy(CompressionStrategy::Light)
334        .compress(text);
335    if result.compressed_tokens < result.original_tokens
336        && result.compressed.len() < text.len()
337        && !result.compressed.trim().is_empty()
338    {
339        *text = result.compressed;
340    }
341}
342
343/// All text a message carries, across both wire shapes: a plain string
344/// (`content: "…"`, OpenAI) and a block array (`content: [{type:"text",…}]`,
345/// Anthropic).
346fn message_text(message: &Value) -> String {
347    match message.get("content") {
348        Some(Value::String(text)) => text.clone(),
349        Some(Value::Array(blocks)) => blocks
350            .iter()
351            .filter_map(|block| block.get("text").and_then(Value::as_str))
352            .collect::<Vec<_>>()
353            .join(""),
354        _ => String::new(),
355    }
356}
357
358/// True when compression emptied a message that arrived with text (#1789).
359///
360/// This is a *content* invariant, deliberately separate from the determinism
361/// guard's *cache-prefix* invariant: emptying every live turn leaves the frozen
362/// prefix byte-identical, so the determinism proof stays stable while the
363/// request loses everything the model was supposed to read. Savings-based
364/// reverting cannot catch it either — deleting all content scores as a perfect
365/// ~100% saving and sails past `min_savings_pct`.
366fn destroys_content(before: &[Value], after: &[Value]) -> bool {
367    before.len() == after.len()
368        && before.iter().zip(after).any(|(before, after)| {
369            !message_text(before).trim().is_empty() && message_text(after).trim().is_empty()
370        })
371}
372
373fn insert_header(headers: &mut axum::http::HeaderMap, name: &str, value: &str) {
374    if let (Ok(name), Ok(value)) = (
375        axum::http::header::HeaderName::try_from(name),
376        HeaderValue::from_str(value),
377    ) {
378        headers.insert(name, value);
379    }
380}
381
382#[cfg(test)]
383mod tests {
384    use serde_json::json;
385
386    use super::{CompressionPipeline, PipelineConfig, compress_live_prose};
387
388    fn verbose_text() -> String {
389        (0..200)
390            .map(|index| {
391                format!(
392                    "This repeated operational detail is not needed for the current task {index}."
393                )
394            })
395            .collect::<Vec<_>>()
396            .join("\n")
397    }
398
399    #[test]
400    fn pipeline_runs_all_stages_in_order() {
401        let mut messages = vec![json!({"role": "user", "content": verbose_text()})];
402
403        // The prompt is never scored for a reasoning budget.
404        let config = PipelineConfig::default();
405        let report = CompressionPipeline::run(&mut messages, &config);
406
407        assert_eq!(
408            report
409                .stages_run
410                .iter()
411                .map(|stage| stage.name)
412                .collect::<Vec<_>>(),
413            // `dedup` must follow `tool_results` (#1980): a delta against a
414            // result that is compressed afterwards no longer reconstructs it.
415            vec![
416                "live_zone",
417                "adaptive_policy",
418                "prose",
419                "tool_results",
420                "dedup",
421                "determinism_guard",
422            ]
423        );
424    }
425
426    #[test]
427    fn disabled_stage_is_skipped() {
428        let mut messages = vec![json!({"role": "user", "content": verbose_text()})];
429        let config = PipelineConfig {
430            enable_dedup: false,
431            min_savings_pct: 0.0,
432            ..PipelineConfig::default()
433        };
434
435        let report = CompressionPipeline::run(&mut messages, &config);
436
437        let dedup = report
438            .stages_run
439            .iter()
440            .find(|stage| stage.name == "dedup")
441            .expect("dedup stage report");
442        assert!(dedup.skipped);
443        assert!(!dedup.ran);
444    }
445
446    // #1545: the determinism proof is enforcement now, not telemetry — a
447    // stage that rewrites content inside the client's cache_control'd prefix
448    // is reverted, so the wire body keeps the prefix byte-identical.
449    #[test]
450    fn cache_controlled_prefix_survives_pipeline_byte_identical() {
451        let repeated = verbose_text();
452        let mut messages = vec![
453            json!({"role": "user", "cache_control": {"type": "ephemeral"}, "content": &repeated}),
454            json!({"role": "assistant", "content": &repeated}),
455            json!({"role": "user", "content": "Try again"}),
456        ];
457        let before_prefix = messages[0].to_string();
458        let config = PipelineConfig {
459            min_savings_pct: 0.0,
460            ..PipelineConfig::default()
461        };
462
463        let _ = CompressionPipeline::run(&mut messages, &config);
464
465        assert_eq!(
466            messages[0].to_string(),
467            before_prefix,
468            "cache_control'd prefix must never ship mutated"
469        );
470    }
471
472    #[test]
473    fn report_accumulates_savings() {
474        let repeated = verbose_text();
475        let mut messages = vec![
476            json!({"role": "user", "content": "Fix the bug"}),
477            json!({"role": "assistant", "content": &repeated}),
478            json!({"role": "user", "content": "Try again"}),
479            json!({"role": "assistant", "content": &repeated}),
480        ];
481        let config = PipelineConfig {
482            enable_prose: false,
483            min_savings_pct: 0.0,
484            ..PipelineConfig::default()
485        };
486
487        let report = CompressionPipeline::run(&mut messages, &config);
488
489        assert!(
490            report.total_savings_pct >= 0.0,
491            "pipeline should not produce negative savings: {:.1}%",
492            report.total_savings_pct
493        );
494        let stage_total: u64 = report
495            .stages_run
496            .iter()
497            .map(|stage| stage.tokens_saved)
498            .sum();
499        assert_eq!(
500            report.total_tokens_before - report.total_tokens_after,
501            stage_total
502        );
503    }
504
505    #[test]
506    fn empty_messages_are_safe() {
507        let mut messages = Vec::new();
508
509        let report = CompressionPipeline::run(&mut messages, &PipelineConfig::default());
510
511        assert!(messages.is_empty(), "{messages:?}");
512        assert_eq!(report.total_tokens_before, 0);
513        assert_eq!(report.total_tokens_after, 0);
514    }
515
516    /// #1789: the proxy emptied every non-system turn on provider routes.
517    ///
518    /// The prose stage runs `ProseCompressor` with a task hint, which selects
519    /// `CompressionStrategy::Aggressive`. That strategy drops any paragraph
520    /// without a hardcoded English technical keyword — and a chat turn *is* a
521    /// single paragraph, so dropping it deletes the whole message. The system
522    /// turn survived only because it sits in the frozen prefix.
523    #[test]
524    fn conversation_turns_never_lose_their_content() {
525        let mut messages = vec![
526            json!({"role": "system",    "content": "Tu es un assistant francais."}),
527            json!({"role": "user",      "content": "Bonjour, quelle est la capitale de la France ?"}),
528            json!({"role": "assistant", "content": "La capitale de la France est Paris."}),
529            json!({"role": "user",      "content": "Et combien d habitants environ ?"}),
530        ];
531
532        CompressionPipeline::run(&mut messages, &PipelineConfig::default());
533
534        for message in &messages {
535            let role = message["role"].as_str().unwrap_or_default();
536            let content = message["content"].as_str().unwrap_or_default();
537            assert!(
538                !content.trim().is_empty(),
539                "#1789: `{role}` turn was emptied by the compression pipeline; \
540                 upstream would receive a conversation the model cannot see"
541            );
542        }
543    }
544
545    fn write_config(text: &str) {
546        let config = crate::core::paths::config_dir_read_only().expect("config directory");
547        std::fs::create_dir_all(&config).expect("config directory");
548        std::fs::write(config.join("config.toml"), text).expect("gateway config");
549    }
550
551    /// [real registers and store] The prose stage (default on) removes lines
552    /// an earlier turn carried and near-duplicate sentences. Under protection
553    /// a turn changes only with a recovery copy bound to its lineage: text
554    /// the Engine delivered leaves shorter, with a stub that resolves to the
555    /// exact original; a turn the host wrote stays whole. Developer mode
556    /// removes the repeated lines as before.
557    #[test]
558    fn prose_stage_changes_a_turn_under_protection_only_with_a_recovery_copy() {
559        use crate::core::archive::delivered;
560        use crate::core::archive::presented::{PresentedBinding, record_presentation};
561        use crate::proxy::compress::{Reader, observing, resolve_recovery};
562        use crate::proxy::request_project::in_project;
563
564        let _data = crate::core::data_dir::isolated_data_dir();
565        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
566        let directory = tempfile::tempdir().expect("project");
567        let root = directory.path().canonicalize().expect("canonical root");
568        write_config(&format!(
569            "[context_gateway]\nmode = \"governed\"\n\n[proxy]\nproject_root = '{}'\n",
570            root.display()
571        ));
572        let rules = (0..12).fold(String::new(), |mut rules, index| {
573            use std::fmt::Write as _;
574            let _ = writeln!(
575                rules,
576                "Always run check number {index} before merging into the main branch."
577            );
578            rules
579        });
580        let delivered_text = format!("{rules}Keep the failure output.\n");
581        in_project(&root, || {
582            let binding = PresentedBinding::admitted_now(
583                &root,
584                "object://caller/rules",
585                "source-one",
586                "sha256:7d1a54127b222502f5b79b5fb0803061152a44f92b37e23c6527baf665d4da9a",
587            )
588            .expect("the policy identity of the project resolves");
589            assert!(record_presentation(&binding));
590            assert!(delivered::record_lineage(
591                &delivered::digest(&delivered_text),
592                &delivered::Lineage::of_presented(vec![binding])
593            ));
594        });
595        let turns = || {
596            vec![
597                json!({"role": "user", "content": [{"type": "text", "text": rules}]}),
598                json!({"role": "assistant", "content": [
599                    {"type": "text", "text": delivered_text}
600                ]}),
601            ]
602        };
603        let text_of = |messages: &[serde_json::Value], index: usize| {
604            messages[index]["content"][0]["text"]
605                .as_str()
606                .expect("text block")
607                .to_owned()
608        };
609
610        let mut messages = turns();
611        let ((), kept) = observing(Reader::Model, || {
612            compress_live_prose(&mut messages, "coding_fix", None);
613        });
614        assert_eq!(text_of(&messages, 0), rules, "the host's turn stays whole");
615        let sent = text_of(&messages, 1);
616        assert!(sent.len() < delivered_text.len());
617        assert!(!sent.contains("Always run check number"), "{sent}");
618        assert!(sent.contains("Keep the failure output."), "{sent}");
619        let stub = sent.rsplit('\n').next().unwrap_or_default();
620        assert!(stub.starts_with("[lean-ctx recovery: "), "{sent}");
621        let id = stub
622            .split("ctx_expand(id=\"")
623            .nth(1)
624            .and_then(|rest| rest.split('"').next())
625            .expect("an id");
626        assert_eq!(resolve_recovery(id), Some(Ok(delivered_text.clone())));
627        assert!(
628            kept.counts()
629                .keys()
630                .all(|code| *code == "recovery.unknown_lineage"),
631            "nothing but the host's own turn can be counted: {:?}",
632            kept.counts()
633        );
634
635        write_config("");
636        let mut messages = turns();
637        let ((), kept) = observing(Reader::Model, || {
638            compress_live_prose(&mut messages, "coding_fix", None);
639        });
640        let sent = text_of(&messages, 1);
641        assert!(!sent.contains("Always run check number"), "{sent}");
642        assert!(sent.contains("Keep the failure output."), "{sent}");
643        assert!(!sent.contains("[lean-ctx recovery: "));
644        assert!(kept.is_empty());
645    }
646}