1use serde::{Deserialize, Serialize};
5
6use super::{baseline::BaselineMeasurement, recommendation::TreatmentMeasurement};
7
8pub const SAME_HOST_MODEL_SEMANTICS: &str = "same-host-model/v2";
10pub const LEGACY_SEMANTICS: &str = "legacy-reference-model";
14
15fn legacy_semantics() -> String {
16 LEGACY_SEMANTICS.into()
17}
18
19#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
20pub struct ShadowReport {
21 #[serde(default = "legacy_semantics")]
22 pub semantics: String,
23 pub report_id: String,
24 pub timestamp: String,
25 pub tasks_count: u32,
26 pub tasks_accepted: u32,
27 pub baseline: AggregateMetrics,
28 pub treatment: AggregateMetrics,
29 pub delta: DeltaMetrics,
31 pub savings: SavingsMetrics,
32 pub recommendations: Vec<Recommendation>,
33}
34
35#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
36pub struct AggregateMetrics {
37 pub total_cost_micros: u64,
38 pub total_tokens: u64,
39 pub avg_cpao_micros: Option<u64>,
40 pub avg_latency_ms: u64,
41}
42
43#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
44pub struct DeltaMetrics {
45 pub cost_micros: i64,
46 pub tokens: i64,
47 pub cpao_micros: Option<i64>,
48}
49
50#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
51pub struct SavingsMetrics {
52 pub absolute_micros: u64,
53 pub relative_percent: f64,
55 pub tokens_saved: u64,
56 pub quality_maintained: bool,
57}
58
59#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
60pub struct Recommendation {
61 pub category: String,
62 pub description: String,
63 pub estimated_savings_micros: u64,
64}
65
66pub fn compare(
67 baselines: &[BaselineMeasurement],
68 treatments: &[TreatmentMeasurement],
69) -> ShadowReport {
70 let baseline = aggregate(baselines.iter().map(Metric::baseline));
71 let treatment = aggregate(treatments.iter().map(Metric::treatment));
72 let cost_delta = signed_delta(treatment.total_cost_micros, baseline.total_cost_micros);
73 let token_delta = signed_delta(treatment.total_tokens, baseline.total_tokens);
74 let baseline_accepted = baselines
75 .iter()
76 .filter(|item| item.outcome_accepted)
77 .count();
78 let treatment_accepted = treatments
79 .iter()
80 .filter(|item| item.outcome_accepted)
81 .count();
82 let quality_maintained = acceptance_rate(treatment_accepted, treatments.len())
83 >= acceptance_rate(baseline_accepted, baselines.len());
84 let absolute_micros = baseline
85 .total_cost_micros
86 .saturating_sub(treatment.total_cost_micros);
87 let tokens_saved = baseline.total_tokens.saturating_sub(treatment.total_tokens);
88 let savings = SavingsMetrics {
89 absolute_micros,
90 relative_percent: percentage_savings(
91 baseline.total_cost_micros,
92 treatment.total_cost_micros,
93 ),
94 tokens_saved,
95 quality_maintained,
96 };
97 let delta = DeltaMetrics {
98 cost_micros: cost_delta,
99 tokens: token_delta,
100 cpao_micros: match (treatment.avg_cpao_micros, baseline.avg_cpao_micros) {
101 (Some(treatment), Some(baseline)) => Some(signed_delta(treatment, baseline)),
102 _ => None,
103 },
104 };
105 let recommendations = recommendations(baselines, treatments, &savings);
106
107 ShadowReport {
108 semantics: SAME_HOST_MODEL_SEMANTICS.into(),
109 report_id: format!(
110 "shadow-{}-{}-{}",
111 baseline.total_cost_micros, treatment.total_cost_micros, baseline.total_tokens
112 ),
113 timestamp: "deterministic".into(),
114 tasks_count: u32::try_from(baselines.len()).unwrap_or(u32::MAX),
115 tasks_accepted: u32::try_from(treatment_accepted).unwrap_or(u32::MAX),
116 baseline,
117 treatment,
118 delta,
119 savings,
120 recommendations,
121 }
122}
123
124pub 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.";
127
128impl ShadowReport {
129 pub fn is_legacy(&self) -> bool {
131 self.semantics != SAME_HOST_MODEL_SEMANTICS
132 }
133}
134
135pub const LEGACY_NOTE: &str = "Legacy record: written before reports compared each task with its own host model. Its baseline may be priced with a different reference model, so its cost difference is not a context saving and its recommendations are not current guidance. Kept for history only.";
136
137pub fn format_report(report: &ShadowReport) -> String {
138 if report.is_legacy() {
139 return format!(
142 "# Shadow Comparison Report (legacy record)\n\n{LEGACY_NOTE}\n\nRecorded tasks: {}. Tokens: baseline {}, treatment {}.\n\n{BASELINE_NOTE}\n\n## Recommendations\n- Withheld: recommendations of legacy records are not current guidance.",
143 report.tasks_count, report.baseline.total_tokens, report.treatment.total_tokens,
144 );
145 }
146 let recommendations = if report.recommendations.is_empty() {
147 "- No recommendation: treatment did not reduce cost without lowering outcome acceptance."
148 .into()
149 } else {
150 report
151 .recommendations
152 .iter()
153 .map(|item| {
154 format!(
155 "- {}: {} (estimated savings: {} micros)",
156 item.category, item.description, item.estimated_savings_micros
157 )
158 })
159 .collect::<Vec<_>>()
160 .join("\n")
161 };
162
163 format!(
164 "# 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{}",
165 report.baseline.total_cost_micros,
166 report.treatment.total_cost_micros,
167 format_delta(report.delta.cost_micros, "saved", "more"),
168 report.baseline.total_tokens,
169 report.treatment.total_tokens,
170 format_delta(report.delta.tokens, "saved", "more"),
171 display_cpao(report.baseline.avg_cpao_micros),
172 display_cpao(report.treatment.avg_cpao_micros),
173 display_cpao_delta(report.delta.cpao_micros),
174 report.baseline.avg_latency_ms,
175 report.treatment.avg_latency_ms,
176 format_delta(
177 signed_delta(
178 report.treatment.avg_latency_ms,
179 report.baseline.avg_latency_ms
180 ),
181 "faster",
182 "slower",
183 ),
184 report.savings.absolute_micros,
185 report.savings.relative_percent,
186 report.savings.tokens_saved,
187 if report.savings.quality_maintained {
188 "yes"
189 } else {
190 "no"
191 },
192 recommendations,
193 )
194}
195
196fn aggregate(items: impl Iterator<Item = Metric>) -> AggregateMetrics {
197 let values: Vec<_> = items.collect();
198 let accepted: Vec<_> = values.iter().filter(|item| item.accepted).collect();
199 AggregateMetrics {
200 total_cost_micros: values.iter().map(|item| item.cost).sum(),
201 total_tokens: values.iter().map(|item| item.tokens).sum(),
202 avg_cpao_micros: (!accepted.is_empty())
203 .then(|| accepted.iter().map(|item| item.cost).sum::<u64>() / accepted.len() as u64),
204 avg_latency_ms: if values.is_empty() {
205 0
206 } else {
207 values.iter().map(|item| item.duration).sum::<u64>() / values.len() as u64
208 },
209 }
210}
211
212fn recommendations(
216 baselines: &[BaselineMeasurement],
217 treatments: &[TreatmentMeasurement],
218 savings: &SavingsMetrics,
219) -> Vec<Recommendation> {
220 let same_models = baselines.len() == treatments.len()
221 && baselines
222 .iter()
223 .zip(treatments)
224 .all(|(baseline, treatment)| baseline.model == treatment.model);
225 if !same_models
226 || savings.absolute_micros == 0
227 || savings.tokens_saved == 0
228 || !savings.quality_maintained
229 {
230 return Vec::new();
231 }
232 vec![Recommendation {
233 category: "Context compression".into(),
234 description: format!(
235 "Keep context compression: it removed an estimated {} tokens against the simulated baseline.",
236 savings.tokens_saved
237 ),
238 estimated_savings_micros: savings.absolute_micros,
239 }]
240}
241
242#[derive(Clone, Copy)]
243struct Metric {
244 tokens: u64,
245 cost: u64,
246 duration: u64,
247 accepted: bool,
248}
249
250impl Metric {
251 fn baseline(item: &BaselineMeasurement) -> Self {
252 Self::new(
253 item.input_tokens,
254 item.output_tokens,
255 item.total_cost_micros,
256 item.duration_ms,
257 item.outcome_accepted,
258 )
259 }
260
261 fn treatment(item: &TreatmentMeasurement) -> Self {
262 Self::new(
263 item.input_tokens,
264 item.output_tokens,
265 item.total_cost_micros,
266 item.duration_ms,
267 item.outcome_accepted,
268 )
269 }
270
271 fn new(input: u64, output: u64, cost: u64, duration: u64, accepted: bool) -> Self {
272 Self {
273 tokens: input.saturating_add(output),
274 cost,
275 duration,
276 accepted,
277 }
278 }
279}
280
281fn acceptance_rate(accepted: usize, total: usize) -> f64 {
282 if total == 0 {
283 1.0
284 } else {
285 accepted as f64 / total as f64
286 }
287}
288
289fn percentage_savings(baseline: u64, treatment: u64) -> f64 {
290 if baseline == 0 {
291 0.0
292 } else {
293 (baseline as f64 - treatment as f64) * 100.0 / baseline as f64
294 }
295}
296
297fn signed_delta(treatment: u64, baseline: u64) -> i64 {
298 let difference = i128::from(treatment) - i128::from(baseline);
299 i64::try_from(difference).unwrap_or_else(|_| {
300 if difference.is_negative() {
301 i64::MIN
302 } else {
303 i64::MAX
304 }
305 })
306}
307
308fn format_delta(delta: i64, lower_label: &str, higher_label: &str) -> String {
309 match delta.cmp(&0) {
310 std::cmp::Ordering::Less => format!("{} {lower_label}", delta.unsigned_abs()),
311 std::cmp::Ordering::Greater => format!("{} {higher_label}", delta.unsigned_abs()),
312 std::cmp::Ordering::Equal => "unchanged".into(),
313 }
314}
315
316fn display_cpao(value: Option<u64>) -> String {
317 value.map_or_else(|| "n/a".into(), |item| item.to_string())
318}
319
320fn display_cpao_delta(value: Option<i64>) -> String {
321 value.map_or_else(
322 || "n/a".into(),
323 |delta| format_delta(delta, "lower", "higher"),
324 )
325}