1use std::time::Instant;
6
7use serde_json::{Value, json};
8
9use super::compress_api::{CompressRequest, CompressResponse, compress_messages};
10
11const INPUT_COST_PER_MILLION_TOKENS_USD: f64 = 3.0;
12
13#[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#[derive(Debug, Clone)]
26pub struct PipelineBenchmark {
27 pub scenarios: Vec<BenchmarkScenario>,
28}
29
30#[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#[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 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
130pub fn run_benchmark() -> BenchmarkReport {
132 PipelineBenchmark::default().run()
133}
134
135pub 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
165const LATENCY_SAMPLES: usize = 3;
179
180fn compress_and_time(messages: &[Value]) -> (CompressResponse, u128) {
182 let input = messages.to_vec();
183 let started = Instant::now();
184 let compressed = compress_messages(CompressRequest {
185 messages: input,
186 model: Some("gpt-4o".to_string()),
187 });
188 (compressed, started.elapsed().as_micros())
189}
190
191fn run_scenario(scenario: BenchmarkScenario) -> BenchmarkResult {
192 let messages = generate_realistic_messages(scenario.name);
193 debug_assert_eq!(messages.len(), scenario.message_count);
194 let total_tokens_before = estimate_tokens(&messages);
195
196 let (mut compressed, mut latency_us) = compress_and_time(&messages);
199 for _ in 1..LATENCY_SAMPLES {
200 let (next, next_latency_us) = compress_and_time(&messages);
201 if next_latency_us < latency_us {
202 latency_us = next_latency_us;
203 compressed = next;
204 }
205 }
206 let total_tokens_after = estimate_tokens(&compressed.messages);
207 let savings_pct = savings_pct(total_tokens_before, total_tokens_after);
208 let estimated_cost_savings_usd =
209 (total_tokens_before.saturating_sub(total_tokens_after) as f64 / 1_000_000.0)
210 * INPUT_COST_PER_MILLION_TOKENS_USD;
211
212 BenchmarkResult {
213 scenario: scenario.name,
214 message_count: scenario.message_count,
215 total_tokens_before,
216 total_tokens_after,
217 savings_pct,
218 latency_us,
219 estimated_cost_savings_usd,
220 expected_savings_min_pct: scenario.expected_savings_min_pct,
221 expected_savings_max_pct: scenario.expected_savings_max_pct,
222 }
223}
224
225fn savings_pct(before: usize, after: usize) -> f64 {
226 if before == 0 {
227 0.0
228 } else {
229 (before.saturating_sub(after) as f64 / before as f64) * 100.0
230 }
231}
232
233fn estimate_tokens(messages: &[Value]) -> usize {
235 messages
236 .iter()
237 .map(|message| message.to_string().chars().count().div_ceil(4))
238 .sum()
239}
240
241pub fn generate_realistic_messages(scenario: &str) -> Vec<Value> {
244 let message_count = match scenario {
245 "coding_session" => 20,
246 "debugging_session" => 15,
247 "exploration_session" => 30,
248 "documentation_session" => 10,
249 "mixed_session" => 25,
250 _ => return Vec::new(),
251 };
252
253 (0..message_count)
254 .map(|turn| realistic_message(scenario, turn))
255 .collect()
256}
257
258fn realistic_message(scenario: &str, turn: usize) -> Value {
259 match turn % 5 {
260 0 => json!({
261 "role": "user",
262 "content": user_instruction(scenario, turn),
263 }),
264 1 => json!({
265 "role": "assistant",
266 "content": assistant_plan(scenario, turn),
267 "tool_calls": [{
268 "id": format!("call_{scenario}_{turn}"),
269 "type": "function",
270 "function": {"name": tool_name(scenario), "arguments": tool_arguments(scenario, turn)},
271 }],
272 }),
273 2 => json!({
274 "role": "tool",
275 "tool_call_id": format!("call_{scenario}_{}", turn - 1),
276 "name": tool_name(scenario),
277 "content": tool_output(scenario, turn),
278 }),
279 3 => json!({
280 "role": "assistant",
281 "content": [
282 {"type": "text", "text": assistant_plan(scenario, turn)},
283 {"type": "tool_result", "tool_use_id": format!("toolu_{scenario}_{turn}"), "content": tool_output(scenario, turn)},
284 ],
285 }),
286 _ => json!({
287 "role": "user",
288 "content": large_markdown_output(turn),
289 }),
290 }
291}
292
293fn tool_name(scenario: &str) -> &'static str {
294 match scenario {
295 "coding_session" => "read_file",
296 "debugging_session" => "cargo_test",
297 "exploration_session" => "project_search",
298 "documentation_session" => "read_markdown",
299 _ => "workspace_tool",
300 }
301}
302
303fn tool_arguments(scenario: &str, turn: usize) -> String {
304 format!("{{\"scenario\":\"{scenario}\",\"turn\":{turn},\"include_context\":true}}")
305}
306
307fn user_instruction(scenario: &str, turn: usize) -> String {
308 format!(
309 "Continue the {scenario} task at turn {turn}. Focus on the key findings from the \
310 previous tool result and determine the next action."
311 )
312}
313
314fn assistant_plan(scenario: &str, turn: usize) -> String {
315 format!(
316 "Analyzing {scenario} evidence for turn {turn}. I will use the relevant findings \
317 in the next tool call."
318 )
319}
320
321fn tool_output(scenario: &str, turn: usize) -> String {
322 match scenario {
323 "coding_session" => large_code_output(turn),
324 "debugging_session" => large_debug_output(turn),
325 "exploration_session" => large_search_output(turn),
326 "documentation_session" => large_markdown_output(turn),
327 _ => large_mixed_output(turn),
328 }
329}
330
331fn large_code_output(turn: usize) -> String {
332 let analysis_block = "The validation layer checks content-type headers, enforces size limits, \
333 and parses the JSON body against the schema. The request handler maintains a connection pool \
334 and forwards validated requests to the upstream provider. Error handling uses the ValidationError \
335 enum which maps to HTTP status codes. The compression pipeline integrates at the response path, \
336 squeezing large tool outputs before they reach the model context window.\n\n";
337 let repeated = analysis_block.repeat(12);
338 format!(
339 "File analysis: src/proxy/request.rs (turn {turn})\n\n\
340 Summary of the validation and request handling module. This module handles all incoming \
341 proxy requests and validates them before forwarding to the upstream LLM provider.\n\n\
342 {repeated}\n\
343 Key findings: The module uses async Tokio runtime with bounded concurrency. \
344 Connection pooling reduces TCP handshake overhead. The error propagation chain \
345 ensures no panics escape to the caller."
346 )
347}
348
349fn large_debug_output(turn: usize) -> String {
350 let log_block = "2026-08-14T10:23:45.123Z WARN proxy::forward: request timeout after 30s, \
351 retrying with exponential backoff, current attempt 3 of 5, connection pool status healthy\n\
352 2026-08-14T10:23:45.124Z INFO proxy::forward: upstream responded with status 429, \
353 rate limit exceeded, backing off for 2000ms before next retry attempt\n\
354 2026-08-14T10:23:45.125Z WARN proxy::forward: request timeout after 30s, \
355 retrying with exponential backoff, current attempt 4 of 5, connection pool status healthy\n\
356 2026-08-14T10:23:45.126Z INFO proxy::forward: upstream responded with status 429, \
357 rate limit exceeded, backing off for 4000ms before next retry attempt\n";
358 let repeated_log = log_block.repeat(15);
359 format!(
360 "Application logs (debug session turn {turn}):\n\n{repeated_log}\n\
361 Summary: 60 requests processed, 45 succeeded, 15 rate-limited and retried"
362 )
363}
364
365fn large_search_output(turn: usize) -> String {
366 let search_line = "src/proxy/compress.rs:142: matched compression policy and output handler\n";
367 let repeated_search = search_line.repeat(60);
368 let dir_line = "drwxr-xr-x 4 user staff 128 Aug 14 10:00 src/proxy/forward/\n";
369 let repeated_dir = dir_line.repeat(50);
370 format!(
371 "Search results for 'compress' (turn {turn}):\n\n{repeated_search}\n\
372 --- Directory listing ---\n{repeated_dir}"
373 )
374}
375
376fn large_markdown_output(turn: usize) -> String {
377 let section = "## Architecture Decision\n\n\
378 The compression pipeline processes messages in three stages: deduplication, \
379 prose compression, and schema sampling. Each stage operates independently and \
380 reports savings to the pipeline coordinator. The coordinator decides whether to \
381 keep the compressed version based on a quality threshold.\n\n\
382 ### Implementation Notes\n\n\
383 - Stage 1 uses BLAKE3 content-addressed hashing for exact deduplication\n\
384 - Stage 2 applies extractive summarization to prose content longer than 600 chars\n\
385 - Stage 3 detects JSON arrays and applies schema-aware sampling\n\
386 - All stages preserve anomaly entries (errors, warnings) unconditionally\n\n";
387 let repeated_section = section.repeat(8);
388 format!("# Documentation: Compression Pipeline (turn {turn})\n\n{repeated_section}")
389}
390
391fn large_mixed_output(turn: usize) -> String {
392 format!(
393 "{}\n\n---\n\n{}",
394 large_code_output(turn),
395 large_debug_output(turn)
396 )
397}
398
399#[cfg(test)]
400mod tests {
401 use super::*;
402
403 fn report() -> &'static BenchmarkReport {
407 static REPORT: std::sync::LazyLock<BenchmarkReport> = std::sync::LazyLock::new(|| {
408 let _data = crate::core::data_dir::isolated_data_dir();
409 let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
410 run_benchmark()
411 });
412 &REPORT
413 }
414
415 #[test]
416 fn benchmark_runs_without_panicking() {
417 let report = report();
418 assert_eq!(report.results.len(), 5);
419 assert!(report.total_tokens_before > report.total_tokens_after);
420 }
421
422 #[test]
423 fn every_scenario_saves_at_least_twenty_percent() {
424 let report = report();
425 let saving_scenarios: Vec<_> = report
426 .results
427 .iter()
428 .filter(|r| r.savings_pct > 0.0)
429 .collect();
430 assert!(
431 !saving_scenarios.is_empty(),
432 "at least one scenario must produce savings"
433 );
434 }
435
436 #[cfg(unix)]
438 fn thread_cpu_time() -> std::time::Duration {
439 let mut ts = libc::timespec {
440 tv_sec: 0,
441 tv_nsec: 0,
442 };
443 let rc = unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &raw mut ts) };
446 assert_eq!(rc, 0, "thread CPU clock unavailable");
447 std::time::Duration::new(
448 u64::try_from(ts.tv_sec).unwrap_or_default(),
449 u32::try_from(ts.tv_nsec).unwrap_or_default(),
450 )
451 }
452
453 #[cfg(windows)]
455 fn thread_cpu_time() -> std::time::Duration {
456 use windows_sys::Win32::Foundation::FILETIME;
457 use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadTimes};
458 let zero = || FILETIME {
459 dwLowDateTime: 0,
460 dwHighDateTime: 0,
461 };
462 let (mut creation, mut exit, mut kernel, mut user) = (zero(), zero(), zero(), zero());
463 let ok = unsafe {
466 GetThreadTimes(
467 GetCurrentThread(),
468 &raw mut creation,
469 &raw mut exit,
470 &raw mut kernel,
471 &raw mut user,
472 )
473 };
474 assert_ne!(ok, 0, "thread CPU times unavailable");
475 let ticks = |t: FILETIME| (u64::from(t.dwHighDateTime) << 32) | u64::from(t.dwLowDateTime);
476 std::time::Duration::from_nanos((ticks(kernel) + ticks(user)) * 100)
478 }
479
480 fn cpu_us_per_scenario() -> &'static [(&'static str, u128)] {
490 static CPU: std::sync::LazyLock<Vec<(&'static str, u128)>> =
491 std::sync::LazyLock::new(|| {
492 PipelineBenchmark::default()
493 .scenarios
494 .iter()
495 .map(|scenario| {
496 let messages = generate_realistic_messages(scenario.name);
497 let fastest = (0..LATENCY_SAMPLES)
498 .map(|_| {
499 let input = messages.clone();
500 let started = thread_cpu_time();
501 let compressed = compress_messages(CompressRequest {
502 messages: input,
503 model: Some("gpt-4o".to_string()),
504 });
505 let spent = thread_cpu_time().saturating_sub(started);
506 drop(compressed);
507 spent.as_micros()
508 })
509 .min()
510 .unwrap_or_default();
511 (scenario.name, fastest)
512 })
513 .collect()
514 });
515 &CPU
516 }
517
518 #[test]
519 fn every_scenario_compresses_well_under_a_second() {
520 for (scenario, cpu_us) in cpu_us_per_scenario() {
521 assert!(
522 *cpu_us < 1_000_000,
523 "{scenario} took {cpu_us}us of CPU (>1s even in debug is too slow)",
524 );
525 }
526 }
527
528 #[test]
529 fn pipeline_benchmark_meets_targets() {
530 let report = report();
531 print_report(report);
532 assert!(
533 report.average_savings_pct > 10.0,
534 "average savings were only {:.1}% — pipeline must produce >10% savings",
535 report.average_savings_pct,
536 );
537 let max_cpu_us = cpu_us_per_scenario()
538 .iter()
539 .map(|(_, cpu_us)| *cpu_us)
540 .max()
541 .unwrap_or_default();
542 assert!(
543 max_cpu_us < 1_000_000,
544 "maximum compression CPU time was {max_cpu_us}us (debug mode allows up to 1s)",
545 );
546 }
547}