Skip to main content

simulator_api/reroute_report/
benchmark.rs

1//! The reroute benchmark: how each rerouted route did against the historical one, as win/loss
2//! counts, volume-weighted bps, and the venues both sides routed through.
3//!
4//! The caller selects the records — landed reroutes whose original also landed, with both
5//! realized amounts present and the two mints distinct. [`collect`] adds only what needs every
6//! record to decide: a signature seen twice is an ambiguous pairing and drops wholesale.
7//! ExactOut legs are measured input-side (`amount` is output-token-denominated and outputs tie by
8//! construction, so a win is paying less major input), which leaves a non-major-input ExactOut leg
9//! unpriceable — those are skipped.
10//!
11//! Two deliberate differences from the pre-typed-plan reader, both forced by the typing. Hop
12//! amounts arrive as strings, so a float-typed string like `"1.5e3"` truncates to an integer
13//! instead of voiding the plan — the JSON number/string distinction died with the DOM parse;
14//! genuinely unparseable text still voids. And an explicit `"inAmount": null` used to void the
15//! whole plan where an absent key merely contributed zero — an `Option<String>` cannot tell the
16//! two apart, so both now contribute zero.
17
18use std::{
19    cmp::Ordering,
20    collections::{BTreeMap, HashMap, HashSet, hash_map::Entry},
21};
22
23use serde::Serialize;
24use solana_address::Address;
25
26use super::{
27    fmt::{commas_u, median},
28    prices::Prices,
29    record::{LegRecord, SwapMode},
30};
31use crate::{mints, route_plan::RoutePlan};
32
33/// Venues under this USD exposure on both sides are dust, hidden from the table.
34pub const VENUE_DUST_USD: f64 = 1e4;
35/// Legs whose change exceeds this many bps either way are treated as pricing artifacts, not
36/// routing outcomes, and skipped.
37pub const OUTLIER_BPS: f64 = 2000.0;
38
39/// What [`collect`] dropped.
40#[derive(Default, Debug)]
41pub struct LoadStats {
42    /// Signatures dropped because they had more than one row (multi-swap transactions).
43    pub dropped_multi_row: usize,
44}
45
46/// Row order is preserved so float accumulation stays deterministic across runs. A signature seen
47/// more than once is an ambiguous multi-swap transaction — pairing is by signature — so its rows
48/// drop wholesale, and a skipped ExactOut row never claims a signature it could make ambiguous.
49pub fn collect(rows: Vec<LegRecord>) -> (Vec<LegRecord>, LoadStats) {
50    let mut kept: Vec<LegRecord> = Vec::new();
51    let mut first_row: HashMap<String, usize> = HashMap::new();
52    let mut dropped: HashSet<usize> = HashSet::new();
53    for row in rows {
54        if row.swap_mode == SwapMode::ExactOut && !mints::is_major(&row.input_mint) {
55            continue;
56        }
57        match first_row.entry(row.original_signature.clone()) {
58            Entry::Vacant(slot) => {
59                slot.insert(kept.len());
60                kept.push(row);
61            }
62            Entry::Occupied(slot) => {
63                dropped.insert(*slot.get());
64            }
65        }
66    }
67    let stats = LoadStats {
68        dropped_multi_row: dropped.len(),
69    };
70    (
71        kept.into_iter()
72            .enumerate()
73            .filter(|(index, _)| !dropped.contains(index))
74            .map(|(_, row)| row)
75            .collect(),
76        stats,
77    )
78}
79
80/// Total `inAmount` for `mint` across the plan's hops. Amounts are strings on the wire; an integer
81/// parse is preferred and a float truncates, matching how numeric JSON amounts were read before
82/// plans were typed. A string that parses as neither voids the plan.
83fn plan_input(plan: &RoutePlan, mint: &Address) -> Option<i64> {
84    let mint = mint.to_string();
85    let mut total = 0i64;
86    for hop in plan.hops() {
87        if hop.input_mint() != Some(mint.as_str()) {
88            continue;
89        }
90        // An absent inAmount contributes zero; a present one that reads as no number at all voids
91        // the whole plan.
92        total += match hop.swap_info.in_amount.as_deref() {
93            None => 0,
94            Some(amount) => amount.parse::<i64>().ok().or_else(|| {
95                #[expect(
96                    clippy::cast_possible_truncation,
97                    reason = "wire float amounts intentionally truncate to i64"
98                )]
99                amount.parse::<f64>().ok().map(|float| float as i64)
100            })?,
101        };
102    }
103    (total > 0).then_some(total)
104}
105
106/// `[(label, weight)]`; sequential hops each carry the full amount, splits weighted by percent.
107/// Unlabeled hops keep their weight under `None` so dropped flow stays visible.
108fn venue_weights(plan: &RoutePlan) -> Vec<(Option<&str>, f64)> {
109    plan.hops()
110        .iter()
111        .map(|hop| (hop.label(), hop.percent as f64 / 100.0))
112        .collect()
113}
114
115/// One measured leg: how the rerouted route compared and what it was worth.
116pub struct Measurement {
117    /// `Greater` when the reroute beat the original swap, `Equal` on a tie, `Less` when it lost.
118    pub outcome: Ordering,
119    /// The original swap's value, in USD.
120    pub l1_usd: f64,
121    /// The reroute's value on the same basis, in USD.
122    pub rerouted_usd: f64,
123}
124
125/// ExactIn compares delivered output (buys valued at spend); ExactOut compares major input paid
126/// for the identical output. `None` = unpriceable or a |bps| > [`OUTLIER_BPS`] dollar-outlier.
127pub fn measure(record: &LegRecord, prices: &Prices) -> Option<Measurement> {
128    match record.swap_mode {
129        SwapMode::ExactOut => measure_exact_out(record, prices),
130        SwapMode::ExactIn => measure_exact_in(record, prices),
131    }
132}
133
134fn measure_exact_out(record: &LegRecord, prices: &Prices) -> Option<Measurement> {
135    let mint = &record.input_mint;
136    let rerouted = plan_input(record.route_plan.as_ref()?, mint)?;
137    let l1 = plan_input(record.original_route_plan.as_ref()?, mint)?;
138    let l1_usd = prices.usd(mint, l1 as f64)?;
139    // Same output either way, so credit the input saved: l1 + (l1 - rerouted).
140    let rerouted_usd = prices.usd(mint, (2 * l1 - rerouted) as f64)?;
141    if l1_usd <= 0.0 || (rerouted_usd / l1_usd - 1.0).abs() * 1e4 > OUTLIER_BPS {
142        return None;
143    }
144    Some(Measurement {
145        outcome: l1.cmp(&rerouted),
146        l1_usd,
147        rerouted_usd,
148    })
149}
150
151fn measure_exact_in(record: &LegRecord, prices: &Prices) -> Option<Measurement> {
152    let rerouted = record.realized_output_amount.unwrap_or(0);
153    let l1 = record.original_realized_output_amount.unwrap_or(0);
154    let bps = (rerouted as f64 / l1 as f64 - 1.0) * 1e4;
155    let scaled = |usd: f64| usd * (1.0 + bps / 1e4);
156    // Majors first, so a leg with a priced side is valued on that side rather than through the
157    // exotic map the last two arms fall back to.
158    let (l1_usd, rerouted_usd) = if mints::is_major(&record.output_mint) {
159        (
160            prices.usd(&record.output_mint, l1 as f64),
161            prices.usd(&record.output_mint, rerouted as f64),
162        )
163    } else if mints::is_major(&record.input_mint) {
164        let spend = prices.usd(&record.input_mint, record.amount as f64);
165        (spend, spend.map(scaled))
166    } else if let Some(l1_usd) = prices.usd(&record.output_mint, l1 as f64) {
167        (
168            Some(l1_usd),
169            prices.usd(&record.output_mint, rerouted as f64),
170        )
171    } else {
172        let spend = prices.usd(&record.input_mint, record.amount as f64)?;
173        (Some(spend), Some(scaled(spend)))
174    };
175    let (l1_usd, rerouted_usd) = (l1_usd?, rerouted_usd?);
176    if l1_usd <= 0.0 || bps.abs() > OUTLIER_BPS {
177        return None;
178    }
179    Some(Measurement {
180        outcome: rerouted.cmp(&l1),
181        l1_usd,
182        rerouted_usd,
183    })
184}
185
186/// USD totals for one side of the majors/exotic split.
187#[derive(Default, Clone, Serialize)]
188pub struct SideTotals {
189    /// The original swaps' volume.
190    pub vol: f64,
191    /// Reroute minus original; positive means the reroutes did better.
192    pub net: f64,
193}
194
195/// One venue's USD volume, each leg split across its route's venues by `percent`.
196#[derive(Default, Clone, Serialize)]
197pub struct VenueTotals {
198    /// Volume the reroutes sent through it.
199    pub rerouted: f64,
200    /// Volume the original swaps sent through it.
201    pub l1: f64,
202    /// The reroutes' net gain, attributed by the venue's share of each reroute.
203    pub net: f64,
204}
205
206/// How the reroutes did against the original swaps, for one range or a cross-range aggregate.
207/// Dollar figures are USD; volumes are the original swaps' value.
208#[derive(Default, Clone, Serialize)]
209pub struct RangeReport {
210    /// Measured legs.
211    pub n: u64,
212    /// Legs where the reroute did better.
213    pub better: u64,
214    /// Legs where the reroute tied.
215    pub same: u64,
216    /// Legs where the reroute did worse.
217    pub worse: u64,
218    /// Volume across measured legs.
219    pub vol: f64,
220    /// Reroute minus original across measured legs; positive means the reroutes did better.
221    pub net: f64,
222    /// Volume of the legs in [`Self::better`].
223    pub vol_better: f64,
224    /// Volume of the legs in [`Self::same`].
225    pub vol_same: f64,
226    /// Volume of the legs in [`Self::worse`].
227    pub vol_worse: f64,
228    /// Each measured leg's change, in bps.
229    pub bps: Vec<f64>,
230    /// Legs between two majors.
231    pub majors: SideTotals,
232    /// Legs with at least one non-major mint.
233    pub exotic: SideTotals,
234    /// By venue label; `(unlabeled)` collects hops without one.
235    pub venues: BTreeMap<String, VenueTotals>,
236}
237
238impl RangeReport {
239    /// [`measure`] each record and total the results; records it cannot measure are skipped.
240    pub fn from_records(records: &[LegRecord], prices: &Prices) -> Self {
241        let mut report = Self::default();
242        for record in records {
243            if let Some(measurement) = measure(record, prices) {
244                report.record(record, &measurement);
245            }
246        }
247        report
248    }
249
250    fn record(&mut self, leg: &LegRecord, measurement: &Measurement) {
251        let delta = measurement.rerouted_usd - measurement.l1_usd;
252        self.n += 1;
253        let (count, vol) = match measurement.outcome {
254            Ordering::Greater => (&mut self.better, &mut self.vol_better),
255            Ordering::Equal => (&mut self.same, &mut self.vol_same),
256            Ordering::Less => (&mut self.worse, &mut self.vol_worse),
257        };
258        *count += 1;
259        *vol += measurement.l1_usd;
260        self.vol += measurement.l1_usd;
261        self.net += delta;
262        if measurement.l1_usd > 0.0 {
263            self.bps.push(delta / measurement.l1_usd * 1e4);
264        }
265        let side = if mints::trades_only_majors(&leg.input_mint, &leg.output_mint) {
266            &mut self.majors
267        } else {
268            &mut self.exotic
269        };
270        side.vol += measurement.l1_usd;
271        side.net += delta;
272        self.attribute_venues(leg, measurement.l1_usd, delta);
273    }
274
275    /// Split the leg's USD across its route's venues, per-leg-normalized so every leg contributes
276    /// its USD exactly once, for both the rerouted route and L1's landed one.
277    fn attribute_venues(&mut self, leg: &LegRecord, l1_usd: f64, delta: f64) {
278        for (rerouted, plan) in [(true, &leg.route_plan), (false, &leg.original_route_plan)] {
279            let Some(plan) = plan else {
280                continue;
281            };
282            let weights = venue_weights(plan);
283            let total: f64 = weights.iter().map(|(_, weight)| weight).sum();
284            let total = if total == 0.0 { 1.0 } else { total };
285            for (label, weight) in weights {
286                let label = label.unwrap_or("(unlabeled)");
287                let entry = self.venues.entry(label.to_string()).or_default();
288                let share = weight / total;
289                if rerouted {
290                    entry.rerouted += l1_usd * share;
291                    entry.net += delta * share;
292                } else {
293                    entry.l1 += l1_usd * share;
294                }
295            }
296        }
297    }
298
299    /// Add `other` into this report, for a cross-range aggregate.
300    pub fn merge(&mut self, other: &Self) {
301        self.n += other.n;
302        self.better += other.better;
303        self.same += other.same;
304        self.worse += other.worse;
305        self.vol += other.vol;
306        self.net += other.net;
307        self.vol_better += other.vol_better;
308        self.vol_same += other.vol_same;
309        self.vol_worse += other.vol_worse;
310        self.bps.extend_from_slice(&other.bps);
311        self.majors.vol += other.majors.vol;
312        self.majors.net += other.majors.net;
313        self.exotic.vol += other.exotic.vol;
314        self.exotic.net += other.exotic.net;
315        for (venue, totals) in &other.venues {
316            let entry = self.venues.entry(venue.clone()).or_default();
317            entry.rerouted += totals.rerouted;
318            entry.l1 += totals.l1;
319            entry.net += totals.net;
320        }
321    }
322
323    /// The volume-weighted change in bps, `net / vol * 10_000`; 0 when nothing was measured.
324    pub fn vw_bps(&self) -> f64 {
325        if self.vol == 0.0 {
326            0.0
327        } else {
328            self.net / self.vol * 1e4
329        }
330    }
331
332    /// A Markdown section headed `name`: the summary lines, then the venue table without venues
333    /// under [`VENUE_DUST_USD`] on both sides.
334    pub fn render(&self, name: &str) -> String {
335        if self.vol == 0.0 {
336            return format!("### {name}: no measurable legs\n");
337        }
338        let mut lines = self.summary_lines(name);
339        lines.push(String::new());
340        lines.extend(self.venue_table());
341        lines.push(String::new());
342        lines.join("\n")
343    }
344
345    fn summary_lines(&self, name: &str) -> Vec<String> {
346        let mut bps = self.bps.clone();
347        let (q1_at, q3_at) = (bps.len() / 4, 3 * bps.len() / 4);
348        let med = median(&mut bps);
349        let mut lines = vec![
350            format!("### {name}"),
351            format!(
352                "vw vs historical: **{:+.2} bps** (net {}$ on ${})",
353                self.vw_bps(),
354                commas_signed(self.net),
355                commas(self.vol)
356            ),
357            format!(
358                "b/s/w: {} / {} / {}  (by volume {:.1} / {:.1} / {:.1}%)",
359                commas_u(self.better),
360                commas_u(self.same),
361                commas_u(self.worse),
362                self.vol_better / self.vol * 100.0,
363                self.vol_same / self.vol * 100.0,
364                self.vol_worse / self.vol * 100.0
365            ),
366            format!(
367                "per-leg bps: median {med:+.2}, IQR [{:+.2}, {:+.2}]",
368                bps[q1_at], bps[q3_at]
369            ),
370        ];
371        for (label, side) in [
372            ("majors<->majors", &self.majors),
373            ("exotic-involved", &self.exotic),
374        ] {
375            if side.vol > 0.0 {
376                lines.push(format!(
377                    "{label}: {:+.2} bps (net {}$ on ${})",
378                    side.net / side.vol * 1e4,
379                    commas_signed(side.net),
380                    commas(side.vol)
381                ));
382            }
383        }
384        lines
385    }
386
387    fn venue_table(&self) -> Vec<String> {
388        let mut lines = vec![
389            "| Venue | rerouted share | historical share | vw bps (rerouted legs) |".to_string(),
390            "|---|---|---|---|".to_string(),
391        ];
392        let total_rerouted: f64 = self
393            .venues
394            .values()
395            .map(|e| e.rerouted)
396            .sum::<f64>()
397            .max(1.0);
398        let total_l1: f64 = self.venues.values().map(|e| e.l1).sum::<f64>().max(1.0);
399        let mut ranked: Vec<_> = self.venues.iter().collect();
400        ranked.sort_by(|a, b| b.1.rerouted.total_cmp(&a.1.rerouted));
401        for (venue, e) in ranked {
402            if e.rerouted < VENUE_DUST_USD && e.l1 < VENUE_DUST_USD {
403                continue;
404            }
405            let vw = if e.rerouted == 0.0 {
406                0.0
407            } else {
408                e.net / e.rerouted * 1e4
409            };
410            lines.push(format!(
411                "| {venue} | {:.1}% | {:.1}% | {vw:+.2} |",
412                e.rerouted / total_rerouted * 100.0,
413                e.l1 / total_l1 * 100.0
414            ));
415        }
416        lines
417    }
418}
419
420fn commas(x: f64) -> String {
421    #[expect(
422        clippy::cast_possible_truncation,
423        clippy::cast_sign_loss,
424        reason = "non-negative rounded USD display value"
425    )]
426    commas_u(x.round().abs() as u64)
427}
428
429fn commas_signed(x: f64) -> String {
430    format!("{}{}", if x < 0.0 { "-" } else { "+" }, commas(x))
431}
432
433#[cfg(test)]
434mod tests {
435    use rstest::rstest;
436
437    use super::*;
438    use crate::{
439        reroute_report::{
440            Samples,
441            testing::{hop, plan, record_of},
442        },
443        route_plan::RouteHop,
444    };
445
446    #[rstest]
447    #[case::rounds_up("+1,235", 1_234.6)]
448    #[case::negative("-1,235", -1_234.6)]
449    fn signed_commas_carry_the_sign(#[case] expected: &str, #[case] x: f64) {
450        assert_eq!(commas_signed(x), expected);
451    }
452
453    fn hop_of(input_mint: &Address, in_amount: u64) -> RouteHop {
454        hop(
455            None,
456            "Venue",
457            &input_mint.to_string(),
458            &mints::USDT.to_string(),
459            in_amount,
460        )
461    }
462
463    /// The wire carries amounts as text, which a fixture with a `u64` cannot express.
464    fn amount_hop(in_amount: Option<&str>) -> RouteHop {
465        let mut hop = hop_of(&mints::USDC, 0);
466        hop.swap_info.in_amount = in_amount.map(str::to_string);
467        hop
468    }
469
470    #[rstest]
471    #[case::integer_amount(Some("1000"), Some(1_000))]
472    #[case::float_amount_truncates(Some("1000.9"), Some(1_000))]
473    #[case::float_string_truncates(Some("1.5e3"), Some(1_500))]
474    #[case::unparseable_voids_the_plan(Some("abc"), None)]
475    #[case::an_absent_amount_alone_sums_to_nothing(None, None)]
476    fn plan_input_reads_integer_and_float_amounts(
477        #[case] amount: Option<&str>,
478        #[case] expected: Option<i64>,
479    ) {
480        let plan = plan(vec![amount_hop(amount)]).expect("a plan");
481        assert_eq!(plan_input(&plan, &mints::USDC), expected);
482    }
483
484    #[test]
485    fn plan_input_sums_only_the_asked_mints_hops() {
486        let plan = plan(vec![
487            hop_of(&mints::USDC, 300),
488            hop_of(&Address::default(), 999),
489            hop_of(&mints::USDC, 700),
490        ])
491        .expect("a plan");
492        assert_eq!(plan_input(&plan, &mints::USDC), Some(1_000));
493
494        // Deserialization bypasses `RoutePlan::new`, so a plan off the wire can still be empty.
495        let empty: RoutePlan = serde_json::from_str("[]").expect("an empty plan");
496        assert_eq!(plan_input(&empty, &mints::USDC), None);
497    }
498
499    #[test]
500    fn an_absent_amount_contributes_zero_without_voiding() {
501        let plan = plan(vec![amount_hop(None), hop_of(&mints::USDC, 700)]).expect("a plan");
502        assert_eq!(plan_input(&plan, &mints::USDC), Some(700));
503    }
504
505    /// Fixes SOL at $100 from the stream's own swaps; the stable legs below price off decimals
506    /// alone, so nothing else needs deriving.
507    fn prices() -> Prices {
508        let mut samples = Samples::default();
509        for n in 1..=3u64 {
510            samples.push(&LegRecord {
511                original_realized_output_amount: Some(n * 100_000_000),
512                ..record_of(mints::SOL, mints::USDC, n * 1_000_000_000, None, None, None)
513            });
514        }
515        samples.prices().expect("anchored")
516    }
517
518    fn stable_record(mode: SwapMode, rerouted: u64, l1: u64) -> LegRecord {
519        LegRecord {
520            swap_mode: mode,
521            realized_output_amount: Some(rerouted),
522            original_realized_output_amount: Some(l1),
523            route_plan: plan(vec![hop_of(&mints::USDC, rerouted)]),
524            original_route_plan: plan(vec![hop_of(&mints::USDC, l1)]),
525            ..record_of(mints::USDC, mints::USDT, 1_000_000, None, None, None)
526        }
527    }
528
529    #[test]
530    fn exact_out_credits_the_input_saved() {
531        let m = measure(
532            &stable_record(SwapMode::ExactOut, 999_000, 1_000_000),
533            &prices(),
534        )
535        .expect("measurable");
536        assert_eq!(m.outcome, Ordering::Greater);
537        assert!((m.l1_usd - 1.0).abs() < 1e-9);
538        assert!((m.rerouted_usd - 1.001).abs() < 1e-9);
539    }
540
541    #[rstest]
542    #[case::win(1_010_000, 1_000_000, Some(Ordering::Greater))]
543    #[case::tie(1_000_000, 1_000_000, Some(Ordering::Equal))]
544    #[case::exactly_at_the_outlier_bound_stays(1_200_000, 1_000_000, Some(Ordering::Greater))]
545    #[case::past_the_outlier_bound_drops(1_210_000, 1_000_000, None)]
546    fn exact_in_measures_major_output_with_the_outlier_gate(
547        #[case] rerouted: u64,
548        #[case] l1: u64,
549        #[case] expected: Option<Ordering>,
550    ) {
551        let m = measure(&stable_record(SwapMode::ExactIn, rerouted, l1), &prices());
552        assert_eq!(m.map(|m| m.outcome), expected);
553    }
554
555    /// Pairing is by signature, so a signature seen twice is ambiguous and drops wholesale.
556    #[test]
557    fn collect_drops_multi_row_signatures_wholesale() {
558        let mut a = stable_record(SwapMode::ExactIn, 1_000_000, 999_000);
559        a.original_signature = "sigA".to_string();
560        let mut a2 = a.clone();
561        a2.amount = 2_000_000;
562        let mut b = stable_record(SwapMode::ExactIn, 1_000_000, 999_000);
563        b.original_signature = "sigB".to_string();
564
565        let (kept, stats) = collect(vec![a, a2, b]);
566        assert_eq!(kept.len(), 1);
567        assert_eq!(kept[0].original_signature, "sigB");
568        assert_eq!(stats.dropped_multi_row, 1);
569    }
570
571    /// An ExactOut leg is measured on its input, so a non-major input has no price to measure
572    /// against — and dropping it before the signature bookkeeping keeps it from making a
573    /// measurable row ambiguous.
574    #[test]
575    fn collect_skips_exact_out_legs_it_cannot_price() {
576        let exotic = LegRecord {
577            input_mint: Address::default(),
578            ..stable_record(SwapMode::ExactOut, 1_000_000, 999_000)
579        };
580        let major = stable_record(SwapMode::ExactOut, 1_000_000, 999_000);
581
582        let (kept, stats) = collect(vec![exotic, major]);
583        assert_eq!(kept.len(), 1);
584        assert_eq!(kept[0].input_mint, mints::USDC);
585        assert_eq!(stats.dropped_multi_row, 0, "a skipped row is not a pairing");
586    }
587}