1use std::collections::BTreeMap;
7
8use serde::Serialize;
9
10use super::{LegRecord, Prices, SwapMode, fmt::commas_u};
11
12pub fn bucket(outcome: &str, category: Option<&str>) -> Option<String> {
17 match outcome {
18 "filled" => None,
19 "reverted" | "unresolved" => Some(format!("{outcome}_{}", category.unwrap_or_default())),
20 other => Some(other.to_string()),
21 }
22}
23
24#[derive(Default, Clone, Serialize)]
26pub struct TemplateProbes {
27 pub outcomes: BTreeMap<String, u64>,
30 pub scored_vs_historical: u64,
33 pub bps_vs_historical_total: i64,
36 pub pairs_vs_same_state: u64,
39 pub bps_vs_same_state_total: f64,
42 pub notional_usd: f64,
45 pub weighted_bps_usd: f64,
48}
49
50impl TemplateProbes {
51 fn probes(&self) -> u64 {
52 self.outcomes.values().sum()
53 }
54
55 fn filled(&self) -> u64 {
56 self.outcomes.get("filled").copied().unwrap_or(0)
57 }
58
59 fn mean(total: f64, count: u64, unit: &str) -> String {
60 match count {
61 0 => "—".to_string(),
62 n => format!("{:+.2} ({} {unit})", total / n as f64, commas_u(n)),
63 }
64 }
65
66 fn row(&self, template: &str) -> String {
67 let probes = self.probes();
68 let filled = self.filled();
69 let pct = filled as f64 / probes as f64 * 100.0;
70 let vs_historical = Self::mean(
71 self.bps_vs_historical_total as f64,
72 self.scored_vs_historical,
73 "scored",
74 );
75 let vs_same_state = Self::mean(
76 self.bps_vs_same_state_total,
77 self.pairs_vs_same_state,
78 "pairs",
79 );
80 let per_dollar = match self.notional_usd {
81 notional if notional > 0.0 => {
82 #[expect(
83 clippy::cast_possible_truncation,
84 clippy::cast_sign_loss,
85 reason = "guarded positive USD notional truncated to whole dollars for display"
86 )]
87 let dollars = notional as u64;
88 format!(
89 "{:+.2} (${})",
90 self.weighted_bps_usd / notional,
91 commas_u(dollars)
92 )
93 }
94 _ => "—".to_string(),
95 };
96 format!(
97 "| {template} | {} | {} ({pct:.1}%) | {vs_historical} | {per_dollar} | {vs_same_state} |",
98 commas_u(probes),
99 commas_u(filled),
100 )
101 }
102
103 fn outcomes_line(&self, template: &str) -> String {
104 let parts: Vec<String> = self
105 .outcomes
106 .iter()
107 .map(|(outcome, n)| format!("{outcome} {}", commas_u(*n)))
108 .collect();
109 format!("{template} outcomes: {}", parts.join(", "))
110 }
111}
112
113#[derive(Default, Clone, Serialize)]
115pub struct ProbeReport {
116 pub by_template: BTreeMap<String, TemplateProbes>,
118}
119
120impl ProbeReport {
121 pub fn from_records(records: &[LegRecord], prices: Option<&Prices>) -> Self {
124 let mut report = Self::default();
125 for record in records {
126 let template = record
127 .template
128 .clone()
129 .unwrap_or_else(|| "(unnamed)".to_string());
130 let entry = report.by_template.entry(template).or_default();
131 let outcome = record
132 .error_category
133 .clone()
134 .unwrap_or_else(|| "filled".to_string());
135 *entry.outcomes.entry(outcome).or_default() += 1;
136 if let Some(bps) = record.output_bps {
137 entry.scored_vs_historical += 1;
138 entry.bps_vs_historical_total += bps;
139 let priced_mint = match record.swap_mode {
140 SwapMode::ExactIn => &record.input_mint,
141 SwapMode::ExactOut => &record.output_mint,
142 };
143 if let Some(usd) = prices.and_then(|p| p.usd(priced_mint, record.amount as f64)) {
144 entry.notional_usd += usd;
145 entry.weighted_bps_usd += usd * bps as f64;
146 }
147 }
148 if let (Some(new), Some(original)) =
149 (record.new_output_amount, record.quoted_output_amount)
150 && original > 0
151 {
152 entry.pairs_vs_same_state += 1;
153 let change = (new as f64 / original as f64 - 1.0) * 1e4;
154 entry.bps_vs_same_state_total += match record.swap_mode {
155 SwapMode::ExactIn => change,
156 SwapMode::ExactOut => -change,
157 };
158 }
159 }
160 report
161 }
162
163 pub fn merge(&mut self, other: &Self) {
165 for (template, probes) in &other.by_template {
166 let entry = self.by_template.entry(template.clone()).or_default();
167 entry.notional_usd += probes.notional_usd;
168 entry.weighted_bps_usd += probes.weighted_bps_usd;
169 for (outcome, n) in &probes.outcomes {
170 *entry.outcomes.entry(outcome.clone()).or_default() += n;
171 }
172 entry.scored_vs_historical += probes.scored_vs_historical;
173 entry.bps_vs_historical_total += probes.bps_vs_historical_total;
174 entry.pairs_vs_same_state += probes.pairs_vs_same_state;
175 entry.bps_vs_same_state_total += probes.bps_vs_same_state_total;
176 }
177 }
178
179 #[expect(missing_docs, reason = "self-explanatory")]
180 pub fn is_empty(&self) -> bool {
181 self.by_template.is_empty()
182 }
183
184 pub fn render(&self, name: &str) -> String {
206 let mut lines = vec![
207 format!("### {name}: venue probes"),
208 "| Template | probes | filled | per hop (bps) | per dollar (bps) | vs same-state (bps) |"
209 .to_string(),
210 "|---|---|---|---|---|---|".to_string(),
211 ];
212 for (template, probes) in &self.by_template {
213 lines.push(probes.row(template));
214 }
215 for (template, probes) in &self.by_template {
216 lines.push(probes.outcomes_line(template));
217 }
218 lines.push(String::new());
219 lines.join("\n")
220 }
221}
222
223#[cfg(test)]
224mod tests {
225 use rstest::rstest;
226
227 use super::*;
228 use crate::{
229 mints,
230 reroute_report::{Samples, testing::record_of},
231 };
232
233 fn prices() -> Prices {
235 let mut samples = Samples::default();
236 for n in 1..=3u64 {
237 samples.push(&LegRecord {
238 original_realized_output_amount: Some(n * 100_000_000),
239 ..record_of(mints::SOL, mints::USDC, n * 1_000_000_000, None, None, None)
240 });
241 }
242 samples.prices().expect("anchored")
243 }
244
245 #[test]
248 fn the_per_dollar_mean_weighs_hops_by_notional() {
249 let hop = |lamports: u64, bps: i64| LegRecord {
250 template: Some("venue-a".to_string()),
251 output_bps: Some(bps),
252 ..record_of(mints::SOL, mints::USDC, lamports, None, None, None)
253 };
254 let records = [
256 hop(10_000_000, -100),
257 hop(10_000_000, -100),
258 hop(1_000_000_000, 10),
259 ];
260 let template = |prices: Option<&Prices>| {
261 ProbeReport::from_records(&records, prices).by_template["venue-a"].clone()
262 };
263
264 let weighted = template(Some(&prices()));
265 let per_hop: i64 = (-100 - 100 + 10) / 3;
266 let per_dollar = (0.01 * -100.0 + 0.01 * -100.0 + 1.0 * 10.0) / 1.02;
267 assert_eq!(weighted.bps_vs_historical_total / 3, per_hop, "per hop");
268 assert!(
269 (weighted.weighted_bps_usd / weighted.notional_usd - per_dollar).abs() < 0.01,
270 "per dollar follows the large hop, not the count"
271 );
272 assert_eq!(template(None).notional_usd, 0.0);
274 }
275
276 fn probe(template: &str) -> LegRecord {
277 LegRecord {
278 template: Some(template.to_string()),
279 ..record_of(mints::SOL, mints::USDC, 1_000_000, None, None, None)
280 }
281 }
282
283 #[rstest]
284 #[case::success_falls_back_to_filled(None, "filled")]
285 #[case::reverted_keeps_its_category(Some("reverted_slippage".to_string()), "reverted_slippage")]
286 #[case::unattributed_keeps_its_category(Some("unattributed".to_string()), "unattributed")]
287 fn from_records_buckets_outcomes_by_error_category_else_filled(
288 #[case] error_category: Option<String>,
289 #[case] expected: &str,
290 ) {
291 let record = LegRecord {
292 error_category,
293 ..probe("venue-a")
294 };
295 let report = ProbeReport::from_records(&[record], None);
296 assert_eq!(
297 report.by_template["venue-a"].outcomes.get(expected),
298 Some(&1)
299 );
300 }
301
302 #[test]
303 fn scored_vs_historical_counts_only_rows_carrying_output_bps() {
304 let scored = LegRecord {
305 output_bps: Some(12),
306 ..probe("venue-a")
307 };
308 let unscored = probe("venue-a");
309
310 let report = ProbeReport::from_records(&[scored, unscored], None);
311 let template = &report.by_template["venue-a"];
312 assert_eq!(template.scored_vs_historical, 1);
313 assert_eq!(template.bps_vs_historical_total, 12);
314 }
315
316 #[rstest]
317 #[case::both_present_and_positive(Some(1_010_000), Some(1_000_000), 1)]
318 #[case::new_amount_missing(None, Some(1_000_000), 0)]
319 #[case::original_amount_missing(Some(1_010_000), None, 0)]
320 #[case::original_amount_zero(Some(1_010_000), Some(0), 0)]
321 fn same_state_pairs_require_both_amounts_and_a_positive_original(
322 #[case] new_output_amount: Option<u64>,
323 #[case] quoted_output_amount: Option<u64>,
324 #[case] expected_pairs: u64,
325 ) {
326 let record = LegRecord {
327 new_output_amount,
328 quoted_output_amount,
329 ..probe("venue-a")
330 };
331 let report = ProbeReport::from_records(&[record], None);
332 assert_eq!(
333 report.by_template["venue-a"].pairs_vs_same_state,
334 expected_pairs
335 );
336 }
337
338 #[test]
339 fn same_state_bps_is_the_relative_change_from_quoted_to_new() {
340 let record = LegRecord {
341 new_output_amount: Some(1_010_000),
342 quoted_output_amount: Some(1_000_000),
343 ..probe("venue-a")
344 };
345 let report = ProbeReport::from_records(&[record], None);
346 let template = &report.by_template["venue-a"];
347 assert_eq!(template.pairs_vs_same_state, 1);
348 assert!((template.bps_vs_same_state_total - 100.0).abs() < 1e-9);
349 }
350
351 #[test]
352 fn merge_carries_every_field() {
353 let a = LegRecord {
354 output_bps: Some(10),
355 new_output_amount: Some(1_010_000),
356 quoted_output_amount: Some(1_000_000),
357 ..probe("venue-a")
358 };
359 let b = LegRecord {
360 error_category: Some("reverted_slippage".to_string()),
361 output_bps: Some(20),
362 new_output_amount: Some(1_020_000),
363 quoted_output_amount: Some(1_000_000),
364 ..probe("venue-a")
365 };
366
367 let mut report = ProbeReport::from_records(&[a], None);
368 report.merge(&ProbeReport::from_records(&[b], None));
369
370 let template = &report.by_template["venue-a"];
371 assert_eq!(template.outcomes.get("filled"), Some(&1));
372 assert_eq!(template.outcomes.get("reverted_slippage"), Some(&1));
373 assert_eq!(template.scored_vs_historical, 2);
374 assert_eq!(template.bps_vs_historical_total, 30);
375 assert_eq!(template.pairs_vs_same_state, 2);
376 assert!((template.bps_vs_same_state_total - 300.0).abs() < 1e-9);
377 }
378
379 #[test]
380 fn a_record_with_no_template_lands_under_unnamed() {
381 let record = record_of(mints::SOL, mints::USDC, 1_000_000, None, None, None);
382 let report = ProbeReport::from_records(&[record], None);
383 assert!(report.by_template.contains_key("(unnamed)"));
384 }
385
386 #[test]
387 fn render_contains_the_template_row_and_outcomes_line() {
388 let filled_a = LegRecord {
389 output_bps: Some(100),
390 new_output_amount: Some(1_010_000),
391 quoted_output_amount: Some(1_000_000),
392 ..probe("venue-a")
393 };
394 let filled_b = LegRecord {
395 output_bps: Some(200),
396 new_output_amount: Some(1_020_000),
397 quoted_output_amount: Some(1_000_000),
398 ..probe("venue-a")
399 };
400 let reverted = LegRecord {
401 error_category: Some("reverted_slippage".to_string()),
402 ..probe("venue-a")
403 };
404
405 let report = ProbeReport::from_records(&[filled_a, filled_b, reverted], None);
406 let rendered = report.render("R1");
407
408 assert!(rendered.contains("### R1: venue probes"));
409 assert!(rendered.contains("| Template | probes | filled |"));
410 assert!(
411 rendered.contains(
412 "| venue-a | 3 | 2 (66.7%) | +150.00 (2 scored) | — | +150.00 (2 pairs) |"
413 )
414 );
415 assert!(rendered.contains("venue-a outcomes: filled 2, reverted_slippage 1"));
416 }
417
418 #[test]
419 fn render_shows_an_em_dash_when_a_mean_has_no_observations() {
420 let reverted = LegRecord {
421 error_category: Some("reverted_slippage".to_string()),
422 ..probe("Vertigo")
423 };
424
425 let report = ProbeReport::from_records(&[reverted], None);
426 let rendered = report.render("R2");
427
428 assert!(rendered.contains("| Vertigo | 1 | 0 (0.0%) | — | — |"));
429 assert!(rendered.contains("Vertigo outcomes: reverted_slippage 1"));
430 }
431
432 #[test]
433 fn is_empty_reflects_an_empty_template_map() {
434 assert!(ProbeReport::default().is_empty());
435 let report = ProbeReport::from_records(&[probe("venue-a")], None);
436 assert!(!report.is_empty());
437 }
438
439 #[test]
442 fn an_exact_out_notional_is_priced_in_the_output_mint() {
443 let record = LegRecord {
444 swap_mode: SwapMode::ExactOut,
445 output_bps: Some(10),
446 ..probe("venue-a")
447 };
448 let report = ProbeReport::from_records(&[record], Some(&prices()));
449 let template = &report.by_template["venue-a"];
450 assert!(
451 (template.notional_usd - 1.0).abs() < 1e-9,
452 "{}",
453 template.notional_usd
454 );
455 }
456
457 #[rstest]
458 #[case::cheaper(900, 1_000.0)]
459 #[case::dearer(1_100, -1_000.0)]
460 fn an_exact_out_comparison_scores_input_saved(#[case] charged: u64, #[case] expected: f64) {
461 let record = LegRecord {
462 swap_mode: SwapMode::ExactOut,
463 new_output_amount: Some(charged),
464 quoted_output_amount: Some(1_000),
465 ..probe("t")
466 };
467 let report = ProbeReport::from_records(&[record], None);
468 assert!((report.by_template["t"].bps_vs_same_state_total - expected).abs() < 1e-9);
469 }
470}