1#[allow(dead_code, unused_imports)]
2use std::fs;
3use std::path::{Path, PathBuf};
4use std::time::{Duration, Instant};
5
6use anyhow::{Context, anyhow, bail};
7use serde::{Deserialize, Serialize};
8use serde_json::Value;
9
10const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_mins(5);
11
12#[derive(Debug, Clone, Serialize, Deserialize)]
14pub struct ProviderRunConfig {
15 pub run_id: String,
16 pub task_description: String,
17 pub commit_sha: String,
18 pub repo_path: PathBuf,
19 pub provider: String,
20 pub model: String,
21 pub prompt_template: String,
22 pub target_files: Vec<PathBuf>,
23 pub budget_tokens: u64,
24 pub temperature: f32,
25}
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(rename_all = "snake_case")]
30pub enum ArmType {
31 Baseline,
32 Treatment,
33}
34
35impl ArmType {
36 fn label(self) -> &'static str {
37 match self {
38 Self::Baseline => "baseline",
39 Self::Treatment => "treatment",
40 }
41 }
42}
43
44#[derive(Debug, Clone, Serialize, Deserialize)]
46pub struct ArmResult {
47 pub arm_type: ArmType,
48 pub provider: String,
51 pub model: String,
53 pub commit_sha: String,
55 pub input_tokens: u64,
56 pub cached_tokens: u64,
57 pub output_tokens: u64,
58 pub cost_micros: u64,
59 pub latency_ms: u64,
60 pub output_content: String,
61 pub proxy_observed: bool,
62 pub measurement_method: String,
63}
64
65#[derive(Debug, Clone, Serialize, Deserialize)]
67pub struct ComparisonSummary {
68 pub token_savings_ratio: f64,
69 pub cost_savings_ratio: f64,
70 pub quality_preserved: Option<bool>,
71}
72
73#[derive(Debug, Clone, Serialize, Deserialize)]
75pub struct ProviderRunResult {
76 pub run_id: String,
77 pub baseline: ArmResult,
78 pub treatment: ArmResult,
79 pub comparison: ComparisonSummary,
80}
81
82pub async fn execute_provider_run(
84 config: ProviderRunConfig,
85) -> Result<ProviderRunResult, anyhow::Error> {
86 validate_config(&config)?;
87 let (prompt, context) = load_task_material(&config)?;
88
89 let baseline_config = config.clone();
90 let baseline_prompt = prompt.clone();
91 let baseline = tokio::task::spawn_blocking(move || {
92 execute_arm(&baseline_config, ArmType::Baseline, &baseline_prompt)
93 })
94 .await
95 .context("baseline provider task failed to join")??;
96
97 let treatment_config = config.clone();
98 let treatment_prompt = prompt.clone();
99 let treatment = tokio::task::spawn_blocking(move || {
100 execute_arm(&treatment_config, ArmType::Treatment, &treatment_prompt)
101 })
102 .await
103 .context("treatment provider task failed to join")??;
104
105 let comparison = compare_arms(&baseline, &treatment);
106 let result = ProviderRunResult {
107 run_id: config.run_id.clone(),
108 baseline,
109 treatment,
110 comparison,
111 };
112
113 save_artifacts(&config, &prompt, &context, &result)?;
114 Ok(result)
115}
116
117fn validate_config(config: &ProviderRunConfig) -> anyhow::Result<()> {
118 if config.run_id.trim().is_empty() {
119 bail!("provider run id must not be empty");
120 }
121 if config.provider.trim().is_empty() {
122 bail!("provider must not be empty");
123 }
124 if config.model.trim().is_empty() {
125 bail!("model must not be empty");
126 }
127 if config.budget_tokens == 0 {
128 bail!("budget_tokens must be greater than zero");
129 }
130 if !config.temperature.is_finite() || config.temperature < 0.0 {
131 bail!("temperature must be finite and non-negative");
132 }
133 Ok(())
134}
135
136fn load_task_material(config: &ProviderRunConfig) -> anyhow::Result<(String, String)> {
137 let template_path = resolve_repo_path(&config.repo_path, Path::new(&config.prompt_template));
138 let template = fs::read_to_string(&template_path)
139 .with_context(|| format!("failed to read prompt template {}", template_path.display()))?;
140
141 let mut context_parts = Vec::with_capacity(config.target_files.len());
142 for target in &config.target_files {
143 let path = resolve_repo_path(&config.repo_path, target);
144 let content = fs::read_to_string(&path)
145 .with_context(|| format!("failed to read target file {}", path.display()))?;
146 let display_path = path
147 .strip_prefix(&config.repo_path)
148 .unwrap_or(&path)
149 .display();
150 context_parts.push(format!("===== {display_path} =====\n{content}"));
151 }
152 let context = context_parts.join("\n\n");
153 let target_files = config
154 .target_files
155 .iter()
156 .map(|path| path.display().to_string())
157 .collect::<Vec<_>>()
158 .join("\n");
159 let repo_path = config.repo_path.display().to_string();
160
161 let prompt = render_prompt(
162 &template,
163 &[
164 ("{run_id}", config.run_id.as_str()),
165 ("{task_description}", config.task_description.as_str()),
166 ("{commit_sha}", config.commit_sha.as_str()),
167 ("{repo_path}", &repo_path),
168 ("{provider}", config.provider.as_str()),
169 ("{model}", config.model.as_str()),
170 ("{target_files}", &target_files),
171 ("{context}", &context),
172 ],
173 );
174
175 Ok((prompt, context))
176}
177
178fn resolve_repo_path(repo_path: &Path, path: &Path) -> PathBuf {
179 if path.is_absolute() {
180 path.to_path_buf()
181 } else {
182 repo_path.join(path)
183 }
184}
185
186fn render_prompt(template: &str, replacements: &[(&str, &str)]) -> String {
187 let mut rendered = template.to_owned();
188 for (placeholder, value) in replacements {
189 rendered = rendered.replace(placeholder, value);
190 }
191 if !template.contains("{context}") {
192 if let Some((_, context)) = replacements.iter().find(|(key, _)| *key == "{context}") {
193 rendered.push_str("\n\n## Review context\n\n");
194 rendered.push_str(context);
195 }
196 }
197 rendered
198}
199
200fn execute_arm(
201 config: &ProviderRunConfig,
202 arm_type: ArmType,
203 prompt: &str,
204) -> anyhow::Result<ArmResult> {
205 let provider = config.provider.trim().to_ascii_lowercase();
206 let base_url = if arm_type == ArmType::Treatment {
207 proxy_base_url()
208 } else {
209 direct_base_url(&provider)
210 };
211 let url = request_url(&base_url, &provider, &config.model);
212 let payload = request_payload(config, &provider, prompt);
213 let payload = serde_json::to_vec(&payload).context("failed to encode provider request")?;
214 let api_key = provider_api_key(&provider);
215 let started = Instant::now();
216
217 let response = send_provider_request(
218 &url,
219 &provider,
220 &api_key,
221 &config.run_id,
222 arm_type,
223 &payload,
224 )
225 .with_context(|| format!("{arm_type:?} provider request failed"))?;
226 let latency_ms = elapsed_ms(started);
227 let headers = response.headers;
228 let response_body = response.body;
229 let body: Value = serde_json::from_str(&response_body)
230 .with_context(|| format!("{arm_type:?} provider returned invalid JSON: {response_body}"))?;
231
232 let output_content = extract_output_content(&body, &provider)
233 .ok_or_else(|| anyhow!("{arm_type:?} provider response contained no text content"))?;
234 let usage = usage_metrics(&body, &headers);
235 let estimated_input = estimate_tokens(prompt);
236 let estimated_output = estimate_tokens(&output_content);
237 let input_tokens = usage.input_tokens.unwrap_or(estimated_input);
238 let output_tokens = usage.output_tokens.unwrap_or(estimated_output);
239 let input_method = if usage.input_tokens.is_some() {
240 "provider_reported"
241 } else if input_tokens > 0 {
242 "estimated"
243 } else {
244 "unavailable"
245 };
246 let output_method = if usage.output_tokens.is_some() {
247 "provider_reported"
248 } else if output_tokens > 0 {
249 "estimated"
250 } else {
251 "unavailable"
252 };
253 let cached_method = if usage.cached_tokens.is_some() {
254 "provider_reported"
255 } else {
256 "unavailable"
257 };
258 let reported_cost = cost_from_headers(&headers);
259 let cost_micros = reported_cost.or_else(|| {
260 if input_tokens == 0 && output_tokens == 0 {
261 None
262 } else {
263 estimated_cost_micros(&config.model, input_tokens, output_tokens)
264 }
265 });
266 let cost_method = if reported_cost.is_some() {
267 "provider_reported"
268 } else if cost_micros.is_some() {
269 "estimated"
270 } else {
271 "unavailable"
272 };
273 let measurement_method = format!(
274 "input:{input_method},cached:{cached_method},output:{output_method},cost:{cost_method}"
275 );
276
277 Ok(ArmResult {
278 arm_type,
279 provider,
280 model: config.model.clone(),
281 commit_sha: config.commit_sha.clone(),
282 input_tokens,
283 cached_tokens: usage.cached_tokens.unwrap_or(0),
284 output_tokens,
285 cost_micros: cost_micros.unwrap_or(0),
286 latency_ms,
287 output_content,
288 proxy_observed: arm_type == ArmType::Treatment,
289 measurement_method,
290 })
291}
292
293struct ProviderResponse {
294 body: String,
295 headers: Vec<(String, String)>,
296}
297
298fn send_provider_request(
299 url: &str,
300 provider: &str,
301 api_key: &str,
302 run_id: &str,
303 arm_type: ArmType,
304 payload: &[u8],
305) -> anyhow::Result<ProviderResponse> {
306 let agent = crate::core::http_client::ureq_agent(
307 ureq::config::Config::builder()
308 .tls_config(crate::core::http_client::platform_tls_config())
309 .timeout_global(Some(request_timeout()))
310 .build(),
311 );
312 let mut request = agent
313 .post(url)
314 .header("Content-Type", "application/json")
315 .header("x-leanctx-provider-run-id", run_id)
316 .header("x-leanctx-provider-run-arm", arm_type.label());
317 if provider == "anthropic" {
318 if !api_key.is_empty() {
319 request = request.header("x-api-key", api_key);
320 }
321 request = request.header("anthropic-version", "2023-06-01");
322 } else if !api_key.is_empty() {
323 request = request.header("Authorization", &format!("Bearer {api_key}"));
324 }
325
326 let response = request
327 .send(payload)
328 .map_err(|error| anyhow!("HTTP request failed: {error}"))?;
329 let headers = response
330 .headers()
331 .iter()
332 .filter_map(|(name, value)| {
333 Some((
334 name.as_str().to_ascii_lowercase(),
335 value.to_str().ok()?.to_owned(),
336 ))
337 })
338 .collect();
339 let body = response
340 .into_body()
341 .read_to_string()
342 .map_err(|error| anyhow!("failed to read provider response: {error}"))?;
343 Ok(ProviderResponse { body, headers })
344}
345
346fn request_payload(config: &ProviderRunConfig, provider: &str, prompt: &str) -> Value {
347 if provider == "anthropic" {
348 serde_json::json!({
349 "model": config.model,
350 "max_tokens": config.budget_tokens,
351 "temperature": config.temperature,
352 "messages": [{"role": "user", "content": prompt}],
353 })
354 } else if matches!(provider, "gemini" | "google") {
355 serde_json::json!({
356 "contents": [{"role": "user", "parts": [{"text": prompt}]}],
357 "generationConfig": {
358 "maxOutputTokens": config.budget_tokens,
359 "temperature": config.temperature,
360 },
361 })
362 } else {
363 serde_json::json!({
364 "model": config.model,
365 "max_tokens": config.budget_tokens,
366 "temperature": config.temperature,
367 "messages": [{"role": "user", "content": prompt}],
368 "stream": false,
369 })
370 }
371}
372
373fn extract_output_content(body: &Value, provider: &str) -> Option<String> {
374 if provider == "anthropic" {
375 if let Some(content) = body.get("content").and_then(Value::as_array) {
376 let text = content
377 .iter()
378 .filter_map(|block| block.get("text").and_then(Value::as_str))
379 .collect::<Vec<_>>()
380 .join("");
381 if !text.is_empty() {
382 return Some(text);
383 }
384 }
385 }
386 if matches!(provider, "gemini" | "google") {
387 if let Some(text) = body
388 .get("candidates")
389 .and_then(Value::as_array)
390 .and_then(|candidates| candidates.first())
391 .and_then(|candidate| candidate.get("content"))
392 .and_then(|content| content.get("parts"))
393 .and_then(Value::as_array)
394 .map(|parts| {
395 parts
396 .iter()
397 .filter_map(|part| part.get("text").and_then(Value::as_str))
398 .collect::<Vec<_>>()
399 .join("")
400 })
401 .filter(|text| !text.is_empty())
402 {
403 return Some(text);
404 }
405 }
406 body.get("output_text")
407 .and_then(Value::as_str)
408 .or_else(|| body.get("content").and_then(Value::as_str))
409 .or_else(|| {
410 body.get("choices")
411 .and_then(Value::as_array)
412 .and_then(|choices| choices.first())
413 .and_then(|choice| choice.get("message"))
414 .and_then(|message| message.get("content"))
415 .and_then(Value::as_str)
416 })
417 .or_else(|| {
418 body.get("choices")
419 .and_then(Value::as_array)
420 .and_then(|choices| choices.first())
421 .and_then(|choice| choice.get("text"))
422 .and_then(Value::as_str)
423 })
424 .map(str::to_owned)
425 .filter(|text| !text.is_empty())
426}
427
428#[derive(Default)]
429struct UsageMetrics {
430 input_tokens: Option<u64>,
431 cached_tokens: Option<u64>,
432 output_tokens: Option<u64>,
433}
434
435fn usage_metrics(body: &Value, headers: &[(String, String)]) -> UsageMetrics {
436 let usage = body.get("usage");
437 let input_tokens = usage.and_then(|usage| {
438 first_json_u64(
439 usage,
440 &["input_tokens", "prompt_tokens", "promptTokenCount"],
441 )
442 });
443 let cached_tokens = usage.and_then(|usage| {
444 first_json_u64(
445 usage,
446 &[
447 "cache_read_input_tokens",
448 "cache_read_tokens",
449 "cached_tokens",
450 "cachedContentTokenCount",
451 ],
452 )
453 });
454 let output_tokens = usage.and_then(|usage| {
455 first_json_u64(
456 usage,
457 &["output_tokens", "completion_tokens", "candidatesTokenCount"],
458 )
459 });
460
461 UsageMetrics {
462 input_tokens: input_tokens.or_else(|| {
463 header_u64(
464 headers,
465 &[
466 "x-leanctx-input-tokens",
467 "x-leanctx-compressed-input-tokens",
468 "x-provider-input-tokens",
469 ],
470 )
471 }),
472 cached_tokens: cached_tokens.or_else(|| {
473 header_u64(
474 headers,
475 &["x-leanctx-cached-tokens", "x-provider-cached-tokens"],
476 )
477 }),
478 output_tokens: output_tokens.or_else(|| {
479 header_u64(
480 headers,
481 &["x-leanctx-output-tokens", "x-provider-output-tokens"],
482 )
483 }),
484 }
485}
486
487fn first_json_u64(value: &Value, keys: &[&str]) -> Option<u64> {
488 keys.iter()
489 .find_map(|key| value.get(*key).and_then(json_u64))
490 .or_else(|| {
491 value
492 .get("prompt_tokens_details")
493 .and_then(|details| details.get("cached_tokens"))
494 .and_then(json_u64)
495 })
496}
497
498fn json_u64(value: &Value) -> Option<u64> {
499 value.as_u64().or_else(|| {
500 value
501 .as_f64()
502 .filter(|number| number.is_finite() && *number >= 0.0)
503 .map(|number| number.round() as u64)
504 })
505}
506
507fn header_u64(headers: &[(String, String)], names: &[&str]) -> Option<u64> {
508 names.iter().find_map(|name| {
509 headers
510 .iter()
511 .find(|(header, _)| header == name)
512 .and_then(|(_, value)| value.trim().parse::<u64>().ok())
513 })
514}
515
516fn cost_from_headers(headers: &[(String, String)]) -> Option<u64> {
517 headers.iter().find_map(|(name, value)| {
518 if !name.contains("cost") {
519 return None;
520 }
521 let value = value.trim().trim_start_matches('$');
522 if name.contains("micro") {
523 return value.parse::<u64>().ok();
524 }
525 let dollars = value.parse::<f64>().ok()?;
526 if !dollars.is_finite() || dollars < 0.0 {
527 return None;
528 }
529 Some((dollars * 1_000_000.0).round() as u64)
530 })
531}
532
533fn estimate_tokens(text: &str) -> u64 {
534 if text.is_empty() {
535 return 0;
536 }
537 text.len().div_ceil(4) as u64
538}
539
540fn estimated_cost_micros(model: &str, input_tokens: u64, output_tokens: u64) -> Option<u64> {
541 let usd = crate::core::benchmark_study::llm_client::cost_for_tokens(
542 model,
543 input_tokens,
544 output_tokens,
545 );
546 if usd.is_finite() && usd >= 0.0 {
547 Some((usd * 1_000_000.0).round() as u64)
548 } else {
549 None
550 }
551}
552
553fn compare_arms(baseline: &ArmResult, treatment: &ArmResult) -> ComparisonSummary {
554 ComparisonSummary {
555 token_savings_ratio: savings_ratio(baseline.input_tokens, treatment.input_tokens),
556 cost_savings_ratio: savings_ratio(baseline.cost_micros, treatment.cost_micros),
557 quality_preserved: None,
558 }
559}
560
561fn savings_ratio(baseline: u64, treatment: u64) -> f64 {
562 if baseline == 0 {
563 0.0
564 } else {
565 (baseline as f64 - treatment as f64) / baseline as f64
566 }
567}
568
569fn elapsed_ms(started: Instant) -> u64 {
570 started.elapsed().as_millis().min(u128::from(u64::MAX)) as u64
571}
572
573fn request_timeout() -> Duration {
574 std::env::var("LEAN_CTX_PROVIDER_RUN_TIMEOUT_SECS")
575 .ok()
576 .and_then(|value| value.parse::<u64>().ok())
577 .map(Duration::from_secs)
578 .filter(|timeout| !timeout.is_zero())
579 .unwrap_or(DEFAULT_REQUEST_TIMEOUT)
580}
581
582fn direct_base_url(provider: &str) -> String {
583 let env_name = format!(
584 "LEAN_CTX_PROVIDER_RUN_{}_BASE_URL",
585 provider.to_ascii_uppercase().replace('-', "_")
586 );
587 std::env::var(&env_name)
588 .or_else(|_| std::env::var("LEAN_CTX_PROVIDER_RUN_BASE_URL"))
589 .or_else(|_| std::env::var(format!("{}_BASE_URL", provider.to_ascii_uppercase())))
590 .unwrap_or_else(|_| match provider {
591 "anthropic" => "https://api.anthropic.com".to_owned(),
592 "gemini" | "google" => "https://generativelanguage.googleapis.com".to_owned(),
593 _ => "https://api.openai.com".to_owned(),
594 })
595}
596
597fn proxy_base_url() -> String {
598 std::env::var("LEAN_CTX_PROVIDER_RUN_PROXY_URL")
599 .or_else(|_| std::env::var("LEAN_CTX_PROXY_URL"))
600 .unwrap_or_else(|_| format!("http://127.0.0.1:{}", crate::proxy_setup::default_port()))
601}
602
603fn provider_api_key(provider: &str) -> String {
604 let env_name = format!(
605 "{}_API_KEY",
606 provider.to_ascii_uppercase().replace('-', "_")
607 );
608 if let Ok(key) = std::env::var(&env_name) {
609 return key;
610 }
611 if provider == "anthropic" {
612 std::env::var("ANTHROPIC_API_KEY").unwrap_or_default()
613 } else {
614 std::env::var("OPENAI_API_KEY").unwrap_or_default()
615 }
616}
617
618fn request_url(base_url: &str, provider: &str, model: &str) -> String {
619 let base = base_url.trim_end_matches('/');
620 if matches!(provider, "gemini" | "google") {
621 format!("{base}/v1beta/models/{model}:generateContent")
622 } else if provider == "anthropic" {
623 format!("{base}/v1/messages")
624 } else {
625 format!("{base}/v1/chat/completions")
626 }
627}
628
629fn save_artifacts(
630 config: &ProviderRunConfig,
631 prompt: &str,
632 context: &str,
633 result: &ProviderRunResult,
634) -> anyhow::Result<()> {
635 let run_dir = poc_run_directory(config);
636 fs::create_dir_all(&run_dir)
637 .with_context(|| format!("failed to create POC run directory {}", run_dir.display()))?;
638 write_json(&run_dir.join("config.json"), config)?;
639 write_json(&run_dir.join("baseline.json"), &result.baseline)?;
640 write_json(&run_dir.join("treatment.json"), &result.treatment)?;
641 write_json(&run_dir.join("comparison.json"), &result.comparison)?;
642 write_json(&run_dir.join("result.json"), result)?;
643 fs::write(run_dir.join("prompt.txt"), prompt)
644 .with_context(|| format!("failed to write {}", run_dir.join("prompt.txt").display()))?;
645 fs::write(run_dir.join("context.txt"), context)
646 .with_context(|| format!("failed to write {}", run_dir.join("context.txt").display()))?;
647 fs::write(
648 run_dir.join("baseline.output.txt"),
649 &result.baseline.output_content,
650 )
651 .with_context(|| format!("failed to write baseline output in {}", run_dir.display()))?;
652 fs::write(
653 run_dir.join("treatment.output.txt"),
654 &result.treatment.output_content,
655 )
656 .with_context(|| format!("failed to write treatment output in {}", run_dir.display()))?;
657 Ok(())
658}
659
660fn write_json<T: Serialize>(path: &Path, value: &T) -> anyhow::Result<()> {
661 let json = serde_json::to_vec_pretty(value).context("failed to serialize run artifact")?;
662 fs::write(path, json).with_context(|| format!("failed to write {}", path.display()))?;
663 Ok(())
664}
665
666fn poc_run_directory(config: &ProviderRunConfig) -> PathBuf {
667 let root = std::env::var_os("LEAN_CTX_POC_RUN_DIR")
668 .or_else(|| std::env::var_os("LEAN_CTX_POC_DIR"))
669 .or_else(|| std::env::var_os("LEAN_CTX_RUN_DIR"))
670 .map(PathBuf::from)
671 .unwrap_or_else(|| config.repo_path.join(".lean-ctx").join("poc").join("runs"));
672 root.join(safe_path_component(&config.run_id))
673}
674
675fn safe_path_component(value: &str) -> String {
676 let sanitized = value
677 .chars()
678 .map(|character| {
679 if character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.') {
680 character
681 } else {
682 '_'
683 }
684 })
685 .collect::<String>();
686 if sanitized.is_empty() {
687 "run".to_owned()
688 } else {
689 sanitized
690 }
691}
692
693#[cfg(test)]
694mod tests {
695 use super::*;
696
697 #[test]
698 fn matched_ratio_reports_savings_and_regressions() {
699 assert!((savings_ratio(100, 25) - 0.75).abs() < f64::EPSILON);
700 assert!((savings_ratio(100, 125) + 0.25).abs() < f64::EPSILON);
701 assert_eq!(savings_ratio(0, 0), 0.0);
702 }
703
704 #[test]
705 fn cost_headers_accept_usd_and_micros() {
706 let headers = vec![
707 ("x-litellm-response-cost".to_owned(), "0.00042".to_owned()),
708 ("x-provider-cost-micros".to_owned(), "7".to_owned()),
709 ];
710 assert_eq!(cost_from_headers(&headers), Some(420));
711 assert_eq!(
712 cost_from_headers(&[("x-provider-cost-micros".to_owned(), "7".to_owned())]),
713 Some(7)
714 );
715 }
716
717 #[test]
718 fn prompt_context_is_added_when_template_has_no_context_slot() {
719 let rendered = render_prompt("Review this task", &[("{context}", "file body")]);
720 assert!(rendered.contains("Review context"));
721 assert!(rendered.contains("file body"));
722 }
723
724 #[test]
725 fn output_parsers_cover_provider_shapes() {
726 let anthropic = serde_json::json!({
727 "content": [{"type": "text", "text": "hello"}]
728 });
729 let openai = serde_json::json!({
730 "choices": [{"message": {"content": "world"}}]
731 });
732 assert_eq!(
733 extract_output_content(&anthropic, "anthropic").as_deref(),
734 Some("hello")
735 );
736 assert_eq!(
737 extract_output_content(&openai, "openai").as_deref(),
738 Some("world")
739 );
740 }
741}