Skip to main content

simulator_api/reroute_report/
probes.rs

1//! Per-template accounting of venue probes. Probes have their own table
2//! (`direct_fill_probes`) and their own wire variant (`ReplacementNotification::Venue`), so
3//! their records arrive pre-selected; nothing here checks that, and router rows fed in still
4//! render as a plausible-looking probe table.
5
6use std::collections::BTreeMap;
7
8use serde::Serialize;
9
10use super::{LegRecord, Prices, SwapMode, fmt::commas_u};
11
12/// The bucket vocabulary [`ProbeReport::from_records`] keys `outcomes` on, reconstructed from a
13/// probe's split outcome/category pair: reading `category` straight through would rebucket
14/// `unattributed`/`unsimulatable` — which carry none — as `"filled"`. Keyed on the wire strings,
15/// which the row's typed `outcome` renders to via its `#[sea_orm(string_value = ...)]`.
16pub 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/// Venue-probe counts and scores for one template.
25#[derive(Default, Clone, Serialize)]
26pub struct TemplateProbes {
27    /// `filled`, `reverted_*`, `unattributed`, `unsimulatable`, `unresolved_*` — the keys the
28    /// session metrics count, so report and log reconcile.
29    pub outcomes: BTreeMap<String, u64>,
30    /// Probes with a recorded template-vs-historical change: the count behind the `per hop`
31    /// column.
32    pub scored_vs_historical: u64,
33    /// Sum of the recorded `output_bps`, which the writer clamps; divide by
34    /// `scored_vs_historical` for the `per hop` mean.
35    pub bps_vs_historical_total: i64,
36    /// Probes where both the template and the same-state original filled — the like-for-like,
37    /// and the count behind the `vs same-state` column.
38    pub pairs_vs_same_state: u64,
39    /// Computed here, unclamped: a ratio of two same-state simulations of one hop is
40    /// structurally bounded where a market ratio would not be.
41    pub bps_vs_same_state_total: f64,
42    /// The USD notional of the probes in `scored_vs_historical`. Zero when the range priced no
43    /// mint the probes traded.
44    pub notional_usd: f64,
45    /// Those probes' bps, each weighted by its USD notional; divide by `notional_usd` for the
46    /// `per dollar` mean.
47    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 => format!(
82                "{:+.2} (${})",
83                self.weighted_bps_usd / notional,
84                commas_u(notional as u64)
85            ),
86            _ => "—".to_string(),
87        };
88        format!(
89            "| {template} | {} | {} ({pct:.1}%) | {vs_historical} | {per_dollar} | {vs_same_state} |",
90            commas_u(probes),
91            commas_u(filled),
92        )
93    }
94
95    fn outcomes_line(&self, template: &str) -> String {
96        let parts: Vec<String> = self
97            .outcomes
98            .iter()
99            .map(|(outcome, n)| format!("{outcome} {}", commas_u(*n)))
100            .collect();
101        format!("{template} outcomes: {}", parts.join(", "))
102    }
103}
104
105/// Venue-probe results by template.
106#[derive(Default, Clone, Serialize)]
107pub struct ProbeReport {
108    /// By template label; `(unnamed)` collects probes without one.
109    pub by_template: BTreeMap<String, TemplateProbes>,
110}
111
112impl ProbeReport {
113    /// Tally venue-probe records by template. `prices` values the per-dollar column; with `None`
114    /// it stays empty.
115    pub fn from_records(records: &[LegRecord], prices: Option<&Prices>) -> Self {
116        let mut report = Self::default();
117        for record in records {
118            let template = record
119                .template
120                .clone()
121                .unwrap_or_else(|| "(unnamed)".to_string());
122            let entry = report.by_template.entry(template).or_default();
123            let outcome = record
124                .error_category
125                .clone()
126                .unwrap_or_else(|| "filled".to_string());
127            *entry.outcomes.entry(outcome).or_default() += 1;
128            if let Some(bps) = record.output_bps {
129                entry.scored_vs_historical += 1;
130                entry.bps_vs_historical_total += bps;
131                let priced_mint = match record.swap_mode {
132                    SwapMode::ExactIn => &record.input_mint,
133                    SwapMode::ExactOut => &record.output_mint,
134                };
135                if let Some(usd) = prices.and_then(|p| p.usd(priced_mint, record.amount as f64)) {
136                    entry.notional_usd += usd;
137                    entry.weighted_bps_usd += usd * bps as f64;
138                }
139            }
140            if let (Some(new), Some(original)) =
141                (record.new_output_amount, record.quoted_output_amount)
142                && original > 0
143            {
144                entry.pairs_vs_same_state += 1;
145                let change = (new as f64 / original as f64 - 1.0) * 1e4;
146                entry.bps_vs_same_state_total += match record.swap_mode {
147                    SwapMode::ExactIn => change,
148                    SwapMode::ExactOut => -change,
149                };
150            }
151        }
152        report
153    }
154
155    /// Add `other` into this report, for a cross-range aggregate.
156    pub fn merge(&mut self, other: &Self) {
157        for (template, probes) in &other.by_template {
158            let entry = self.by_template.entry(template.clone()).or_default();
159            entry.notional_usd += probes.notional_usd;
160            entry.weighted_bps_usd += probes.weighted_bps_usd;
161            for (outcome, n) in &probes.outcomes {
162                *entry.outcomes.entry(outcome.clone()).or_default() += n;
163            }
164            entry.scored_vs_historical += probes.scored_vs_historical;
165            entry.bps_vs_historical_total += probes.bps_vs_historical_total;
166            entry.pairs_vs_same_state += probes.pairs_vs_same_state;
167            entry.bps_vs_same_state_total += probes.bps_vs_same_state_total;
168        }
169    }
170
171    #[allow(missing_docs)]
172    pub fn is_empty(&self) -> bool {
173        self.by_template.is_empty()
174    }
175
176    /// A Markdown section headed `name`: one table row per template, then each template's
177    /// outcome counts.
178    ///
179    /// The columns, per template. Every bps figure is positive when the template beat the
180    /// baseline: more output for ExactIn, less input charged for ExactOut.
181    /// - `probes`: every probe, whatever its outcome.
182    /// - `filled`: probes that filled, and their share of `probes`.
183    /// - `per hop (bps)`: the mean of each probe's change against the hop's onchain fill
184    ///   ([`LegRecord::output_bps`], clamped to ±[`CHANGE_CLAMP_BPS`]), every hop counting
185    ///   once. In parentheses, how many probes were scored.
186    /// - `per dollar (bps)`: the same changes, each weighted by the hop's USD notional, so large
187    ///   hops count for more. In parentheses, the total notional. `—` without prices.
188    /// - `vs same-state (bps)`: the mean change against the original swap's hop replayed on the
189    ///   same state as the probe ([`LegRecord::quoted_output_amount`]), unclamped. Unlike `per
190    ///   hop`, it excludes the state drift between the probe's simulation point and the hop's
191    ///   block, so it reads as the template's own edge. In parentheses, how many probes had both
192    ///   fills.
193    ///
194    /// A column with nothing to average shows `—`.
195    ///
196    /// [`CHANGE_CLAMP_BPS`]: crate::replacement::CHANGE_CLAMP_BPS
197    pub fn render(&self, name: &str) -> String {
198        let mut lines = vec![
199            format!("### {name}: venue probes"),
200            "| Template | probes | filled | per hop (bps) | per dollar (bps) | vs same-state (bps) |"
201                .to_string(),
202            "|---|---|---|---|---|---|".to_string(),
203        ];
204        for (template, probes) in &self.by_template {
205            lines.push(probes.row(template));
206        }
207        for (template, probes) in &self.by_template {
208            lines.push(probes.outcomes_line(template));
209        }
210        lines.push(String::new());
211        lines.join("\n")
212    }
213}
214
215#[cfg(test)]
216mod tests {
217    use rstest::rstest;
218
219    use super::*;
220    use crate::{
221        mints,
222        reroute_report::{Samples, testing::record_of},
223    };
224
225    /// Fixes SOL at $100 from the stream's own swaps, as the benchmark tests do.
226    fn prices() -> Prices {
227        let mut samples = Samples::default();
228        for n in 1..=3u64 {
229            samples.push(&LegRecord {
230                original_realized_output_amount: Some(n * 100_000_000),
231                ..record_of(mints::SOL, mints::USDC, n * 1_000_000_000, None, None, None)
232            });
233        }
234        samples.prices().expect("anchored")
235    }
236
237    /// A hop counts for the money through it, so one large good fill outweighs many tiny bad
238    /// ones — the per-hop mean says the template lost, the per-dollar mean says it won.
239    #[test]
240    fn the_per_dollar_mean_weighs_hops_by_notional() {
241        let hop = |lamports: u64, bps: i64| LegRecord {
242            template: Some("venue-a".to_string()),
243            output_bps: Some(bps),
244            ..record_of(mints::SOL, mints::USDC, lamports, None, None, None)
245        };
246        // Three hundredths of a SOL at -100 bps against one whole SOL at +10.
247        let records = [
248            hop(10_000_000, -100),
249            hop(10_000_000, -100),
250            hop(1_000_000_000, 10),
251        ];
252        let template = |prices: Option<&Prices>| {
253            ProbeReport::from_records(&records, prices).by_template["venue-a"].clone()
254        };
255
256        let weighted = template(Some(&prices()));
257        let per_hop: i64 = (-100 - 100 + 10) / 3;
258        let per_dollar = (0.01 * -100.0 + 0.01 * -100.0 + 1.0 * 10.0) / 1.02;
259        assert_eq!(weighted.bps_vs_historical_total / 3, per_hop, "per hop");
260        assert!(
261            (weighted.weighted_bps_usd / weighted.notional_usd - per_dollar).abs() < 0.01,
262            "per dollar follows the large hop, not the count"
263        );
264        // Without prices the column is simply absent rather than silently unweighted.
265        assert_eq!(template(None).notional_usd, 0.0);
266    }
267
268    fn probe(template: &str) -> LegRecord {
269        LegRecord {
270            template: Some(template.to_string()),
271            ..record_of(mints::SOL, mints::USDC, 1_000_000, None, None, None)
272        }
273    }
274
275    #[rstest]
276    #[case::success_falls_back_to_filled(None, "filled")]
277    #[case::reverted_keeps_its_category(Some("reverted_slippage".to_string()), "reverted_slippage")]
278    #[case::unattributed_keeps_its_category(Some("unattributed".to_string()), "unattributed")]
279    fn from_records_buckets_outcomes_by_error_category_else_filled(
280        #[case] error_category: Option<String>,
281        #[case] expected: &str,
282    ) {
283        let record = LegRecord {
284            error_category,
285            ..probe("venue-a")
286        };
287        let report = ProbeReport::from_records(&[record], None);
288        assert_eq!(
289            report.by_template["venue-a"].outcomes.get(expected),
290            Some(&1)
291        );
292    }
293
294    #[test]
295    fn scored_vs_historical_counts_only_rows_carrying_output_bps() {
296        let scored = LegRecord {
297            output_bps: Some(12),
298            ..probe("venue-a")
299        };
300        let unscored = probe("venue-a");
301
302        let report = ProbeReport::from_records(&[scored, unscored], None);
303        let template = &report.by_template["venue-a"];
304        assert_eq!(template.scored_vs_historical, 1);
305        assert_eq!(template.bps_vs_historical_total, 12);
306    }
307
308    #[rstest]
309    #[case::both_present_and_positive(Some(1_010_000), Some(1_000_000), 1)]
310    #[case::new_amount_missing(None, Some(1_000_000), 0)]
311    #[case::original_amount_missing(Some(1_010_000), None, 0)]
312    #[case::original_amount_zero(Some(1_010_000), Some(0), 0)]
313    fn same_state_pairs_require_both_amounts_and_a_positive_original(
314        #[case] new_output_amount: Option<u64>,
315        #[case] quoted_output_amount: Option<u64>,
316        #[case] expected_pairs: u64,
317    ) {
318        let record = LegRecord {
319            new_output_amount,
320            quoted_output_amount,
321            ..probe("venue-a")
322        };
323        let report = ProbeReport::from_records(&[record], None);
324        assert_eq!(
325            report.by_template["venue-a"].pairs_vs_same_state,
326            expected_pairs
327        );
328    }
329
330    #[test]
331    fn same_state_bps_is_the_relative_change_from_quoted_to_new() {
332        let record = LegRecord {
333            new_output_amount: Some(1_010_000),
334            quoted_output_amount: Some(1_000_000),
335            ..probe("venue-a")
336        };
337        let report = ProbeReport::from_records(&[record], None);
338        let template = &report.by_template["venue-a"];
339        assert_eq!(template.pairs_vs_same_state, 1);
340        assert!((template.bps_vs_same_state_total - 100.0).abs() < 1e-9);
341    }
342
343    #[test]
344    fn merge_carries_every_field() {
345        let a = LegRecord {
346            output_bps: Some(10),
347            new_output_amount: Some(1_010_000),
348            quoted_output_amount: Some(1_000_000),
349            ..probe("venue-a")
350        };
351        let b = LegRecord {
352            error_category: Some("reverted_slippage".to_string()),
353            output_bps: Some(20),
354            new_output_amount: Some(1_020_000),
355            quoted_output_amount: Some(1_000_000),
356            ..probe("venue-a")
357        };
358
359        let mut report = ProbeReport::from_records(&[a], None);
360        report.merge(&ProbeReport::from_records(&[b], None));
361
362        let template = &report.by_template["venue-a"];
363        assert_eq!(template.outcomes.get("filled"), Some(&1));
364        assert_eq!(template.outcomes.get("reverted_slippage"), Some(&1));
365        assert_eq!(template.scored_vs_historical, 2);
366        assert_eq!(template.bps_vs_historical_total, 30);
367        assert_eq!(template.pairs_vs_same_state, 2);
368        assert!((template.bps_vs_same_state_total - 300.0).abs() < 1e-9);
369    }
370
371    #[test]
372    fn a_record_with_no_template_lands_under_unnamed() {
373        let record = record_of(mints::SOL, mints::USDC, 1_000_000, None, None, None);
374        let report = ProbeReport::from_records(&[record], None);
375        assert!(report.by_template.contains_key("(unnamed)"));
376    }
377
378    #[test]
379    fn render_contains_the_template_row_and_outcomes_line() {
380        let filled_a = LegRecord {
381            output_bps: Some(100),
382            new_output_amount: Some(1_010_000),
383            quoted_output_amount: Some(1_000_000),
384            ..probe("venue-a")
385        };
386        let filled_b = LegRecord {
387            output_bps: Some(200),
388            new_output_amount: Some(1_020_000),
389            quoted_output_amount: Some(1_000_000),
390            ..probe("venue-a")
391        };
392        let reverted = LegRecord {
393            error_category: Some("reverted_slippage".to_string()),
394            ..probe("venue-a")
395        };
396
397        let report = ProbeReport::from_records(&[filled_a, filled_b, reverted], None);
398        let rendered = report.render("R1");
399
400        assert!(rendered.contains("### R1: venue probes"));
401        assert!(rendered.contains("| Template | probes | filled |"));
402        assert!(
403            rendered.contains(
404                "| venue-a | 3 | 2 (66.7%) | +150.00 (2 scored) | — | +150.00 (2 pairs) |"
405            )
406        );
407        assert!(rendered.contains("venue-a outcomes: filled 2, reverted_slippage 1"));
408    }
409
410    #[test]
411    fn render_shows_an_em_dash_when_a_mean_has_no_observations() {
412        let reverted = LegRecord {
413            error_category: Some("reverted_slippage".to_string()),
414            ..probe("Vertigo")
415        };
416
417        let report = ProbeReport::from_records(&[reverted], None);
418        let rendered = report.render("R2");
419
420        assert!(rendered.contains("| Vertigo | 1 | 0 (0.0%) | — | — |"));
421        assert!(rendered.contains("Vertigo outcomes: reverted_slippage 1"));
422    }
423
424    #[test]
425    fn is_empty_reflects_an_empty_template_map() {
426        assert!(ProbeReport::default().is_empty());
427        let report = ProbeReport::from_records(&[probe("venue-a")], None);
428        assert!(!report.is_empty());
429    }
430
431    /// An ExactOut probe's `amount` is the output it was sized at, so its notional is the output
432    /// mint's, not the input's: 1_000_000 base units is $1 of USDC, not 0.001 SOL at $100.
433    #[test]
434    fn an_exact_out_notional_is_priced_in_the_output_mint() {
435        let record = LegRecord {
436            swap_mode: SwapMode::ExactOut,
437            output_bps: Some(10),
438            ..probe("venue-a")
439        };
440        let report = ProbeReport::from_records(&[record], Some(&prices()));
441        let template = &report.by_template["venue-a"];
442        assert!(
443            (template.notional_usd - 1.0).abs() < 1e-9,
444            "{}",
445            template.notional_usd
446        );
447    }
448
449    #[rstest]
450    #[case::cheaper(900, 1_000.0)]
451    #[case::dearer(1_100, -1_000.0)]
452    fn an_exact_out_comparison_scores_input_saved(#[case] charged: u64, #[case] expected: f64) {
453        let record = LegRecord {
454            swap_mode: SwapMode::ExactOut,
455            new_output_amount: Some(charged),
456            quoted_output_amount: Some(1_000),
457            ..probe("t")
458        };
459        let report = ProbeReport::from_records(&[record], None);
460        assert!((report.by_template["t"].bps_vs_same_state_total - expected).abs() < 1e-9);
461    }
462}