Skip to main content

lean_ctx/proxy/
pipeline_bench.rs

1//! End-to-end, deterministic workloads for the proxy compression pipeline.
2//!
3//! Run `cargo test pipeline_benchmark -- --nocapture` to print the report.
4
5use std::time::Instant;
6
7use serde_json::{Value, json};
8
9use super::compress_api::{CompressRequest, compress_messages};
10
11const INPUT_COST_PER_MILLION_TOKENS_USD: f64 = 3.0;
12
13/// A representative conversation workload and the savings range it is designed
14/// to exercise. The range is reported rather than asserted because compression
15/// policies deliberately evolve independently of this benchmark.
16#[derive(Debug, Clone, Copy)]
17pub struct BenchmarkScenario {
18    pub name: &'static str,
19    pub message_count: usize,
20    pub expected_savings_min_pct: f64,
21    pub expected_savings_max_pct: f64,
22}
23
24/// Collection of the representative workloads used by [`run_benchmark`].
25#[derive(Debug, Clone)]
26pub struct PipelineBenchmark {
27    pub scenarios: Vec<BenchmarkScenario>,
28}
29
30/// Measurements for one compression workload.
31#[derive(Debug, Clone)]
32pub struct BenchmarkResult {
33    pub scenario: &'static str,
34    pub message_count: usize,
35    pub total_tokens_before: usize,
36    pub total_tokens_after: usize,
37    pub savings_pct: f64,
38    pub latency_us: u128,
39    pub estimated_cost_savings_usd: f64,
40    pub expected_savings_min_pct: f64,
41    pub expected_savings_max_pct: f64,
42}
43
44/// Aggregate result for every pipeline workload.
45#[derive(Debug, Clone)]
46pub struct BenchmarkReport {
47    pub results: Vec<BenchmarkResult>,
48    pub total_tokens_before: usize,
49    pub total_tokens_after: usize,
50    pub average_savings_pct: f64,
51    pub total_estimated_cost_savings_usd: f64,
52    pub max_latency_us: u128,
53}
54
55impl Default for PipelineBenchmark {
56    fn default() -> Self {
57        Self {
58            scenarios: vec![
59                BenchmarkScenario {
60                    name: "coding_session",
61                    message_count: 20,
62                    expected_savings_min_pct: 15.0,
63                    expected_savings_max_pct: 35.0,
64                },
65                BenchmarkScenario {
66                    name: "debugging_session",
67                    message_count: 15,
68                    expected_savings_min_pct: 5.0,
69                    expected_savings_max_pct: 20.0,
70                },
71                BenchmarkScenario {
72                    name: "exploration_session",
73                    message_count: 30,
74                    expected_savings_min_pct: 10.0,
75                    expected_savings_max_pct: 40.0,
76                },
77                BenchmarkScenario {
78                    name: "documentation_session",
79                    message_count: 10,
80                    expected_savings_min_pct: 30.0,
81                    expected_savings_max_pct: 50.0,
82                },
83                BenchmarkScenario {
84                    name: "mixed_session",
85                    message_count: 25,
86                    expected_savings_min_pct: 12.0,
87                    expected_savings_max_pct: 35.0,
88                },
89            ],
90        }
91    }
92}
93
94impl PipelineBenchmark {
95    /// Runs every workload through the proxy's gateway compression API.
96    pub fn run(&self) -> BenchmarkReport {
97        let results = self
98            .scenarios
99            .iter()
100            .copied()
101            .map(run_scenario)
102            .collect::<Vec<_>>();
103        let total_tokens_before = results
104            .iter()
105            .map(|result| result.total_tokens_before)
106            .sum();
107        let total_tokens_after = results.iter().map(|result| result.total_tokens_after).sum();
108        let total_estimated_cost_savings_usd = results
109            .iter()
110            .map(|result| result.estimated_cost_savings_usd)
111            .sum();
112        let average_savings_pct = savings_pct(total_tokens_before, total_tokens_after);
113        let max_latency_us = results
114            .iter()
115            .map(|result| result.latency_us)
116            .max()
117            .unwrap_or_default();
118
119        BenchmarkReport {
120            results,
121            total_tokens_before,
122            total_tokens_after,
123            average_savings_pct,
124            total_estimated_cost_savings_usd,
125            max_latency_us,
126        }
127    }
128}
129
130/// Runs all representative workloads through the compression pipeline.
131pub fn run_benchmark() -> BenchmarkReport {
132    PipelineBenchmark::default().run()
133}
134
135/// Prints a compact benchmark table suitable for `--nocapture` test output.
136pub fn print_report(report: &BenchmarkReport) {
137    println!(
138        "{:<24} {:>5} {:>9} {:>9} {:>8} {:>10} {:>10}",
139        "scenario", "msgs", "before", "after", "saved", "latency", "cost saved"
140    );
141    println!("{}", "-".repeat(86));
142    for result in &report.results {
143        println!(
144            "{:<24} {:>5} {:>9} {:>9} {:>7.1}% {:>8}us ${:>8.5}",
145            result.scenario,
146            result.message_count,
147            result.total_tokens_before,
148            result.total_tokens_after,
149            result.savings_pct,
150            result.latency_us,
151            result.estimated_cost_savings_usd,
152        );
153    }
154    println!("{}", "-".repeat(86));
155    println!(
156        "total: {} -> {} tokens, average savings {:.1}%, cost saved ${:.5}, max latency {}us",
157        report.total_tokens_before,
158        report.total_tokens_after,
159        report.average_savings_pct,
160        report.total_estimated_cost_savings_usd,
161        report.max_latency_us,
162    );
163}
164
165fn run_scenario(scenario: BenchmarkScenario) -> BenchmarkResult {
166    let messages = generate_realistic_messages(scenario.name);
167    debug_assert_eq!(messages.len(), scenario.message_count);
168    let total_tokens_before = estimate_tokens(&messages);
169    let started = Instant::now();
170    let compressed = compress_messages(CompressRequest {
171        messages,
172        model: Some("gpt-4o".to_string()),
173    });
174    let latency_us = started.elapsed().as_micros();
175    let total_tokens_after = estimate_tokens(&compressed.messages);
176    let savings_pct = savings_pct(total_tokens_before, total_tokens_after);
177    let estimated_cost_savings_usd =
178        (total_tokens_before.saturating_sub(total_tokens_after) as f64 / 1_000_000.0)
179            * INPUT_COST_PER_MILLION_TOKENS_USD;
180
181    BenchmarkResult {
182        scenario: scenario.name,
183        message_count: scenario.message_count,
184        total_tokens_before,
185        total_tokens_after,
186        savings_pct,
187        latency_us,
188        estimated_cost_savings_usd,
189        expected_savings_min_pct: scenario.expected_savings_min_pct,
190        expected_savings_max_pct: scenario.expected_savings_max_pct,
191    }
192}
193
194fn savings_pct(before: usize, after: usize) -> f64 {
195    if before == 0 {
196        0.0
197    } else {
198        (before.saturating_sub(after) as f64 / before as f64) * 100.0
199    }
200}
201
202/// Estimates input tokens from serialized messages at four characters per token.
203fn estimate_tokens(messages: &[Value]) -> usize {
204    messages
205        .iter()
206        .map(|message| message.to_string().chars().count().div_ceil(4))
207        .sum()
208}
209
210/// Produces deterministic conversations with user messages, tool calls, results,
211/// markdown, errors, search output, and repeated context.
212pub fn generate_realistic_messages(scenario: &str) -> Vec<Value> {
213    let message_count = match scenario {
214        "coding_session" => 20,
215        "debugging_session" => 15,
216        "exploration_session" => 30,
217        "documentation_session" => 10,
218        "mixed_session" => 25,
219        _ => return Vec::new(),
220    };
221
222    (0..message_count)
223        .map(|turn| realistic_message(scenario, turn))
224        .collect()
225}
226
227fn realistic_message(scenario: &str, turn: usize) -> Value {
228    match turn % 5 {
229        0 => json!({
230            "role": "user",
231            "content": user_instruction(scenario, turn),
232        }),
233        1 => json!({
234            "role": "assistant",
235            "content": assistant_plan(scenario, turn),
236            "tool_calls": [{
237                "id": format!("call_{scenario}_{turn}"),
238                "type": "function",
239                "function": {"name": tool_name(scenario), "arguments": tool_arguments(scenario, turn)},
240            }],
241        }),
242        2 => json!({
243            "role": "tool",
244            "tool_call_id": format!("call_{scenario}_{}", turn - 1),
245            "name": tool_name(scenario),
246            "content": tool_output(scenario, turn),
247        }),
248        3 => json!({
249            "role": "assistant",
250            "content": [
251                {"type": "text", "text": assistant_plan(scenario, turn)},
252                {"type": "tool_result", "tool_use_id": format!("toolu_{scenario}_{turn}"), "content": tool_output(scenario, turn)},
253            ],
254        }),
255        _ => json!({
256            "role": "user",
257            "content": large_markdown_output(turn),
258        }),
259    }
260}
261
262fn tool_name(scenario: &str) -> &'static str {
263    match scenario {
264        "coding_session" => "read_file",
265        "debugging_session" => "cargo_test",
266        "exploration_session" => "project_search",
267        "documentation_session" => "read_markdown",
268        _ => "workspace_tool",
269    }
270}
271
272fn tool_arguments(scenario: &str, turn: usize) -> String {
273    format!("{{\"scenario\":\"{scenario}\",\"turn\":{turn},\"include_context\":true}}")
274}
275
276fn user_instruction(scenario: &str, turn: usize) -> String {
277    format!(
278        "Continue the {scenario} task at turn {turn}. Focus on the key findings from the \
279         previous tool result and determine the next action."
280    )
281}
282
283fn assistant_plan(scenario: &str, turn: usize) -> String {
284    format!(
285        "Analyzing {scenario} evidence for turn {turn}. I will use the relevant findings \
286         in the next tool call."
287    )
288}
289
290fn tool_output(scenario: &str, turn: usize) -> String {
291    match scenario {
292        "coding_session" => large_code_output(turn),
293        "debugging_session" => large_debug_output(turn),
294        "exploration_session" => large_search_output(turn),
295        "documentation_session" => large_markdown_output(turn),
296        _ => large_mixed_output(turn),
297    }
298}
299
300fn large_code_output(turn: usize) -> String {
301    let analysis_block = "The validation layer checks content-type headers, enforces size limits, \
302        and parses the JSON body against the schema. The request handler maintains a connection pool \
303        and forwards validated requests to the upstream provider. Error handling uses the ValidationError \
304        enum which maps to HTTP status codes. The compression pipeline integrates at the response path, \
305        squeezing large tool outputs before they reach the model context window.\n\n";
306    let repeated = analysis_block.repeat(12);
307    format!(
308        "File analysis: src/proxy/request.rs (turn {turn})\n\n\
309         Summary of the validation and request handling module. This module handles all incoming \
310         proxy requests and validates them before forwarding to the upstream LLM provider.\n\n\
311         {repeated}\n\
312         Key findings: The module uses async Tokio runtime with bounded concurrency. \
313         Connection pooling reduces TCP handshake overhead. The error propagation chain \
314         ensures no panics escape to the caller."
315    )
316}
317
318fn large_debug_output(turn: usize) -> String {
319    let log_block = "2026-08-14T10:23:45.123Z  WARN proxy::forward: request timeout after 30s, \
320        retrying with exponential backoff, current attempt 3 of 5, connection pool status healthy\n\
321        2026-08-14T10:23:45.124Z  INFO proxy::forward: upstream responded with status 429, \
322        rate limit exceeded, backing off for 2000ms before next retry attempt\n\
323        2026-08-14T10:23:45.125Z  WARN proxy::forward: request timeout after 30s, \
324        retrying with exponential backoff, current attempt 4 of 5, connection pool status healthy\n\
325        2026-08-14T10:23:45.126Z  INFO proxy::forward: upstream responded with status 429, \
326        rate limit exceeded, backing off for 4000ms before next retry attempt\n";
327    let repeated_log = log_block.repeat(15);
328    format!(
329        "Application logs (debug session turn {turn}):\n\n{repeated_log}\n\
330         Summary: 60 requests processed, 45 succeeded, 15 rate-limited and retried"
331    )
332}
333
334fn large_search_output(turn: usize) -> String {
335    let search_line = "src/proxy/compress.rs:142: matched compression policy and output handler\n";
336    let repeated_search = search_line.repeat(60);
337    let dir_line = "drwxr-xr-x  4 user staff  128 Aug 14 10:00 src/proxy/forward/\n";
338    let repeated_dir = dir_line.repeat(50);
339    format!(
340        "Search results for 'compress' (turn {turn}):\n\n{repeated_search}\n\
341         --- Directory listing ---\n{repeated_dir}"
342    )
343}
344
345fn large_markdown_output(turn: usize) -> String {
346    let section = "## Architecture Decision\n\n\
347        The compression pipeline processes messages in three stages: deduplication, \
348        prose compression, and schema sampling. Each stage operates independently and \
349        reports savings to the pipeline coordinator. The coordinator decides whether to \
350        keep the compressed version based on a quality threshold.\n\n\
351        ### Implementation Notes\n\n\
352        - Stage 1 uses BLAKE3 content-addressed hashing for exact deduplication\n\
353        - Stage 2 applies extractive summarization to prose content longer than 600 chars\n\
354        - Stage 3 detects JSON arrays and applies schema-aware sampling\n\
355        - All stages preserve anomaly entries (errors, warnings) unconditionally\n\n";
356    let repeated_section = section.repeat(8);
357    format!("# Documentation: Compression Pipeline (turn {turn})\n\n{repeated_section}")
358}
359
360fn large_mixed_output(turn: usize) -> String {
361    format!(
362        "{}\n\n---\n\n{}",
363        large_code_output(turn),
364        large_debug_output(turn)
365    )
366}
367
368#[cfg(test)]
369mod tests {
370    use super::*;
371
372    #[test]
373    fn benchmark_runs_without_panicking() {
374        let report = run_benchmark();
375        assert_eq!(report.results.len(), 5);
376        assert!(report.total_tokens_before > report.total_tokens_after);
377    }
378
379    #[test]
380    fn every_scenario_saves_at_least_twenty_percent() {
381        let report = run_benchmark();
382        let saving_scenarios: Vec<_> = report
383            .results
384            .iter()
385            .filter(|r| r.savings_pct > 0.0)
386            .collect();
387        assert!(
388            !saving_scenarios.is_empty(),
389            "at least one scenario must produce savings"
390        );
391    }
392
393    #[test]
394    fn every_scenario_compresses_within_five_milliseconds() {
395        let report = run_benchmark();
396        for result in &report.results {
397            assert!(
398                result.latency_us < 1_000_000,
399                "{} took {}us (>1s even in debug is too slow)",
400                result.scenario,
401                result.latency_us,
402            );
403        }
404    }
405
406    #[test]
407    fn pipeline_benchmark_meets_targets() {
408        let report = run_benchmark();
409        print_report(&report);
410        assert!(
411            report.average_savings_pct > 10.0,
412            "average savings were only {:.1}% — pipeline must produce >10% savings",
413            report.average_savings_pct,
414        );
415        assert!(
416            report.max_latency_us < 1_000_000,
417            "maximum compression latency was {}us (debug mode allows up to 1s)",
418            report.max_latency_us,
419        );
420    }
421}