Skip to main content

lean_ctx/core/shadow/
comparison.rs

1//! Aggregate baseline-versus-treatment comparison.
2
3use std::collections::BTreeSet;
4
5use serde::{Deserialize, Serialize};
6
7use super::{baseline::BaselineMeasurement, recommendation::TreatmentMeasurement};
8
9#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
10pub struct ShadowReport {
11    pub report_id: String,
12    pub timestamp: String,
13    pub tasks_count: u32,
14    pub tasks_accepted: u32,
15    pub baseline: AggregateMetrics,
16    pub treatment: AggregateMetrics,
17    /// Treatment minus baseline; negative values mean the treatment is lower.
18    pub delta: DeltaMetrics,
19    pub savings: SavingsMetrics,
20    pub recommendations: Vec<Recommendation>,
21}
22
23#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
24pub struct AggregateMetrics {
25    pub total_cost_micros: u64,
26    pub total_tokens: u64,
27    pub avg_cpao_micros: Option<u64>,
28    pub avg_latency_ms: u64,
29}
30
31#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
32pub struct DeltaMetrics {
33    pub cost_micros: i64,
34    pub tokens: i64,
35    pub cpao_micros: Option<i64>,
36}
37
38#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
39pub struct SavingsMetrics {
40    pub absolute_micros: u64,
41    /// Negative values indicate a cost increase instead of savings.
42    pub relative_percent: f64,
43    pub tokens_saved: u64,
44    pub quality_maintained: bool,
45}
46
47#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
48pub struct Recommendation {
49    pub category: String,
50    pub description: String,
51    pub estimated_savings_micros: u64,
52}
53
54pub fn compare(
55    baselines: &[BaselineMeasurement],
56    treatments: &[TreatmentMeasurement],
57) -> ShadowReport {
58    let baseline = aggregate(baselines.iter().map(Metric::baseline));
59    let treatment = aggregate(treatments.iter().map(Metric::treatment));
60    let cost_delta = signed_delta(treatment.total_cost_micros, baseline.total_cost_micros);
61    let token_delta = signed_delta(treatment.total_tokens, baseline.total_tokens);
62    let baseline_accepted = baselines
63        .iter()
64        .filter(|item| item.outcome_accepted)
65        .count();
66    let treatment_accepted = treatments
67        .iter()
68        .filter(|item| item.outcome_accepted)
69        .count();
70    let quality_maintained = acceptance_rate(treatment_accepted, treatments.len())
71        >= acceptance_rate(baseline_accepted, baselines.len());
72    let absolute_micros = baseline
73        .total_cost_micros
74        .saturating_sub(treatment.total_cost_micros);
75    let tokens_saved = baseline.total_tokens.saturating_sub(treatment.total_tokens);
76    let savings = SavingsMetrics {
77        absolute_micros,
78        relative_percent: percentage_savings(
79            baseline.total_cost_micros,
80            treatment.total_cost_micros,
81        ),
82        tokens_saved,
83        quality_maintained,
84    };
85    let delta = DeltaMetrics {
86        cost_micros: cost_delta,
87        tokens: token_delta,
88        cpao_micros: match (treatment.avg_cpao_micros, baseline.avg_cpao_micros) {
89            (Some(treatment), Some(baseline)) => Some(signed_delta(treatment, baseline)),
90            _ => None,
91        },
92    };
93    let recommendations =
94        recommendations(baselines, treatments, &savings, baseline.total_cost_micros);
95
96    ShadowReport {
97        report_id: format!(
98            "shadow-{}-{}-{}",
99            baseline.total_cost_micros, treatment.total_cost_micros, baseline.total_tokens
100        ),
101        timestamp: "deterministic".into(),
102        tasks_count: u32::try_from(baselines.len()).unwrap_or(u32::MAX),
103        tasks_accepted: u32::try_from(treatment_accepted).unwrap_or(u32::MAX),
104        baseline,
105        treatment,
106        delta,
107        savings,
108        recommendations,
109    }
110}
111
112/// #1905: the baseline is simulated from the same task and outcome signals as
113/// the treatment, so the acceptance comparison cannot show a quality change.
114pub const BASELINE_NOTE: &str = "Note: the baseline is simulated (uncompressed token counts, same outcome signals), not a second measured run. Cost and token deltas are estimates; the acceptance line is not a measured quality comparison.";
115
116pub fn format_report(report: &ShadowReport) -> String {
117    let recommendations = if report.recommendations.is_empty() {
118        "- No recommendation: treatment did not reduce cost without lowering outcome acceptance."
119            .into()
120    } else {
121        report
122            .recommendations
123            .iter()
124            .map(|item| {
125                format!(
126                    "- {}: {} (estimated savings: {} micros)",
127                    item.category, item.description, item.estimated_savings_micros
128                )
129            })
130            .collect::<Vec<_>>()
131            .join("\n")
132    };
133
134    format!(
135        "# Shadow Comparison Report\n\n| Metric | Baseline | Treatment | Delta |\n|---|---:|---:|---:|\n| Cost (micros) | {} | {} | {} |\n| Tokens | {} | {} | {} |\n| Avg CPAO (micros) | {} | {} | {} |\n| Avg latency (ms) | {} | {} | {} |\n\nCost savings: {} micros ({:.2}%). Token savings: {}. Outcome acceptance not below baseline: {}.\n\n{BASELINE_NOTE}\n\n## Recommendations\n{}",
136        report.baseline.total_cost_micros,
137        report.treatment.total_cost_micros,
138        format_delta(report.delta.cost_micros, "saved", "more"),
139        report.baseline.total_tokens,
140        report.treatment.total_tokens,
141        format_delta(report.delta.tokens, "saved", "more"),
142        display_cpao(report.baseline.avg_cpao_micros),
143        display_cpao(report.treatment.avg_cpao_micros),
144        display_cpao_delta(report.delta.cpao_micros),
145        report.baseline.avg_latency_ms,
146        report.treatment.avg_latency_ms,
147        format_delta(
148            signed_delta(
149                report.treatment.avg_latency_ms,
150                report.baseline.avg_latency_ms
151            ),
152            "faster",
153            "slower",
154        ),
155        report.savings.absolute_micros,
156        report.savings.relative_percent,
157        report.savings.tokens_saved,
158        if report.savings.quality_maintained {
159            "yes"
160        } else {
161            "no"
162        },
163        recommendations,
164    )
165}
166
167fn aggregate(items: impl Iterator<Item = Metric>) -> AggregateMetrics {
168    let values: Vec<_> = items.collect();
169    let accepted: Vec<_> = values.iter().filter(|item| item.accepted).collect();
170    AggregateMetrics {
171        total_cost_micros: values.iter().map(|item| item.cost).sum(),
172        total_tokens: values.iter().map(|item| item.tokens).sum(),
173        avg_cpao_micros: (!accepted.is_empty())
174            .then(|| accepted.iter().map(|item| item.cost).sum::<u64>() / accepted.len() as u64),
175        avg_latency_ms: if values.is_empty() {
176            0
177        } else {
178            values.iter().map(|item| item.duration).sum::<u64>() / values.len() as u64
179        },
180    }
181}
182
183fn recommendations(
184    baselines: &[BaselineMeasurement],
185    treatments: &[TreatmentMeasurement],
186    savings: &SavingsMetrics,
187    baseline_cost_micros: u64,
188) -> Vec<Recommendation> {
189    if savings.absolute_micros == 0 || !savings.quality_maintained {
190        return Vec::new();
191    }
192
193    let mut results = Vec::new();
194    if savings.tokens_saved > 0 {
195        results.push(Recommendation {
196            category: "Context compression".into(),
197            description: format!(
198                "Keep context compression: it removed an estimated {} tokens against the simulated baseline.",
199                savings.tokens_saved
200            ),
201            estimated_savings_micros: savings.absolute_micros,
202        });
203    }
204
205    let baseline_models = model_labels(baselines.iter().map(|item| item.model.as_str()));
206    let treatment_models = model_labels(treatments.iter().map(|item| item.model.as_str()));
207    if baseline_models != treatment_models {
208        results.push(Recommendation {
209            category: "Model routing".into(),
210            description: format!(
211                "Route comparable tasks from {} to {}; this lowered estimated cost by {:.2}% against the simulated baseline.",
212                baseline_models.join(", "),
213                treatment_models.join(", "),
214                percentage_savings(baseline_cost_micros, baseline_cost_micros - savings.absolute_micros),
215            ),
216            estimated_savings_micros: savings.absolute_micros,
217        });
218    }
219    results
220}
221
222fn model_labels<'a>(models: impl Iterator<Item = &'a str>) -> Vec<String> {
223    models
224        .into_iter()
225        .map(model_label)
226        .collect::<BTreeSet<_>>()
227        .into_iter()
228        .collect()
229}
230
231fn model_label(model: &str) -> String {
232    match model {
233        "gpt-4o" => "OpenAI GPT-4o".into(),
234        "claude-sonnet" => "Anthropic Claude Sonnet".into(),
235        _ if model.starts_with("gpt-") => format!("OpenAI {model}"),
236        _ if model.starts_with("claude-") => format!("Anthropic {model}"),
237        _ => format!("configured provider {model}"),
238    }
239}
240
241#[derive(Clone, Copy)]
242struct Metric {
243    tokens: u64,
244    cost: u64,
245    duration: u64,
246    accepted: bool,
247}
248
249impl Metric {
250    fn baseline(item: &BaselineMeasurement) -> Self {
251        Self::new(
252            item.input_tokens,
253            item.output_tokens,
254            item.total_cost_micros,
255            item.duration_ms,
256            item.outcome_accepted,
257        )
258    }
259
260    fn treatment(item: &TreatmentMeasurement) -> Self {
261        Self::new(
262            item.input_tokens,
263            item.output_tokens,
264            item.total_cost_micros,
265            item.duration_ms,
266            item.outcome_accepted,
267        )
268    }
269
270    fn new(input: u64, output: u64, cost: u64, duration: u64, accepted: bool) -> Self {
271        Self {
272            tokens: input.saturating_add(output),
273            cost,
274            duration,
275            accepted,
276        }
277    }
278}
279
280fn acceptance_rate(accepted: usize, total: usize) -> f64 {
281    if total == 0 {
282        1.0
283    } else {
284        accepted as f64 / total as f64
285    }
286}
287
288fn percentage_savings(baseline: u64, treatment: u64) -> f64 {
289    if baseline == 0 {
290        0.0
291    } else {
292        (baseline as f64 - treatment as f64) * 100.0 / baseline as f64
293    }
294}
295
296fn signed_delta(treatment: u64, baseline: u64) -> i64 {
297    let difference = i128::from(treatment) - i128::from(baseline);
298    i64::try_from(difference).unwrap_or_else(|_| {
299        if difference.is_negative() {
300            i64::MIN
301        } else {
302            i64::MAX
303        }
304    })
305}
306
307fn format_delta(delta: i64, lower_label: &str, higher_label: &str) -> String {
308    match delta.cmp(&0) {
309        std::cmp::Ordering::Less => format!("{} {lower_label}", delta.unsigned_abs()),
310        std::cmp::Ordering::Greater => format!("{} {higher_label}", delta.unsigned_abs()),
311        std::cmp::Ordering::Equal => "unchanged".into(),
312    }
313}
314
315fn display_cpao(value: Option<u64>) -> String {
316    value.map_or_else(|| "n/a".into(), |item| item.to_string())
317}
318
319fn display_cpao_delta(value: Option<i64>) -> String {
320    value.map_or_else(
321        || "n/a".into(),
322        |delta| format_delta(delta, "lower", "higher"),
323    )
324}