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
95                .parse::<i64>()
96                .ok()
97                .or_else(|| amount.parse::<f64>().ok().map(|float| float as i64))?,
98        };
99    }
100    (total > 0).then_some(total)
101}
102
103/// `[(label, weight)]`; sequential hops each carry the full amount, splits weighted by percent.
104/// Unlabeled hops keep their weight under `None` so dropped flow stays visible.
105fn venue_weights(plan: &RoutePlan) -> Vec<(Option<&str>, f64)> {
106    plan.hops()
107        .iter()
108        .map(|hop| (hop.label(), hop.percent as f64 / 100.0))
109        .collect()
110}
111
112/// One measured leg: how the rerouted route compared and what it was worth.
113pub struct Measurement {
114    /// `Greater` when the reroute beat the original swap, `Equal` on a tie, `Less` when it lost.
115    pub outcome: Ordering,
116    /// The original swap's value, in USD.
117    pub l1_usd: f64,
118    /// The reroute's value on the same basis, in USD.
119    pub rerouted_usd: f64,
120}
121
122/// ExactIn compares delivered output (buys valued at spend); ExactOut compares major input paid
123/// for the identical output. `None` = unpriceable or a |bps| > [`OUTLIER_BPS`] dollar-outlier.
124pub fn measure(record: &LegRecord, prices: &Prices) -> Option<Measurement> {
125    match record.swap_mode {
126        SwapMode::ExactOut => measure_exact_out(record, prices),
127        SwapMode::ExactIn => measure_exact_in(record, prices),
128    }
129}
130
131fn measure_exact_out(record: &LegRecord, prices: &Prices) -> Option<Measurement> {
132    let mint = &record.input_mint;
133    let rerouted = plan_input(record.route_plan.as_ref()?, mint)?;
134    let l1 = plan_input(record.original_route_plan.as_ref()?, mint)?;
135    let l1_usd = prices.usd(mint, l1 as f64)?;
136    // Same output either way, so credit the input saved: l1 + (l1 - rerouted).
137    let rerouted_usd = prices.usd(mint, (2 * l1 - rerouted) as f64)?;
138    if l1_usd <= 0.0 || (rerouted_usd / l1_usd - 1.0).abs() * 1e4 > OUTLIER_BPS {
139        return None;
140    }
141    Some(Measurement {
142        outcome: l1.cmp(&rerouted),
143        l1_usd,
144        rerouted_usd,
145    })
146}
147
148fn measure_exact_in(record: &LegRecord, prices: &Prices) -> Option<Measurement> {
149    let rerouted = record.realized_output_amount.unwrap_or(0) as i64;
150    let l1 = record.original_realized_output_amount.unwrap_or(0) as i64;
151    let bps = (rerouted as f64 / l1 as f64 - 1.0) * 1e4;
152    let scaled = |usd: f64| usd * (1.0 + bps / 1e4);
153    // Majors first, so a leg with a priced side is valued on that side rather than through the
154    // exotic map the last two arms fall back to.
155    let (l1_usd, rerouted_usd) = if mints::is_major(&record.output_mint) {
156        (
157            prices.usd(&record.output_mint, l1 as f64),
158            prices.usd(&record.output_mint, rerouted as f64),
159        )
160    } else if mints::is_major(&record.input_mint) {
161        let spend = prices.usd(&record.input_mint, record.amount as f64);
162        (spend, spend.map(scaled))
163    } else if let Some(l1_usd) = prices.usd(&record.output_mint, l1 as f64) {
164        (
165            Some(l1_usd),
166            prices.usd(&record.output_mint, rerouted as f64),
167        )
168    } else {
169        let spend = prices.usd(&record.input_mint, record.amount as f64)?;
170        (Some(spend), Some(scaled(spend)))
171    };
172    let (l1_usd, rerouted_usd) = (l1_usd?, rerouted_usd?);
173    if l1_usd <= 0.0 || bps.abs() > OUTLIER_BPS {
174        return None;
175    }
176    Some(Measurement {
177        outcome: rerouted.cmp(&l1),
178        l1_usd,
179        rerouted_usd,
180    })
181}
182
183/// USD totals for one side of the majors/exotic split.
184#[derive(Default, Clone, Serialize)]
185pub struct SideTotals {
186    /// The original swaps' volume.
187    pub vol: f64,
188    /// Reroute minus original; positive means the reroutes did better.
189    pub net: f64,
190}
191
192/// One venue's USD volume, each leg split across its route's venues by `percent`.
193#[derive(Default, Clone, Serialize)]
194pub struct VenueTotals {
195    /// Volume the reroutes sent through it.
196    pub rerouted: f64,
197    /// Volume the original swaps sent through it.
198    pub l1: f64,
199    /// The reroutes' net gain, attributed by the venue's share of each reroute.
200    pub net: f64,
201}
202
203/// How the reroutes did against the original swaps, for one range or a cross-range aggregate.
204/// Dollar figures are USD; volumes are the original swaps' value.
205#[derive(Default, Clone, Serialize)]
206pub struct RangeReport {
207    /// Measured legs.
208    pub n: u64,
209    /// Legs where the reroute did better.
210    pub better: u64,
211    /// Legs where the reroute tied.
212    pub same: u64,
213    /// Legs where the reroute did worse.
214    pub worse: u64,
215    /// Volume across measured legs.
216    pub vol: f64,
217    /// Reroute minus original across measured legs; positive means the reroutes did better.
218    pub net: f64,
219    /// Volume of the legs in [`Self::better`].
220    pub vol_better: f64,
221    /// Volume of the legs in [`Self::same`].
222    pub vol_same: f64,
223    /// Volume of the legs in [`Self::worse`].
224    pub vol_worse: f64,
225    /// Each measured leg's change, in bps.
226    pub bps: Vec<f64>,
227    /// Legs between two majors.
228    pub majors: SideTotals,
229    /// Legs with at least one non-major mint.
230    pub exotic: SideTotals,
231    /// By venue label; `(unlabeled)` collects hops without one.
232    pub venues: BTreeMap<String, VenueTotals>,
233}
234
235impl RangeReport {
236    /// [`measure`] each record and total the results; records it cannot measure are skipped.
237    pub fn from_records(records: &[LegRecord], prices: &Prices) -> Self {
238        let mut report = Self::default();
239        for record in records {
240            if let Some(measurement) = measure(record, prices) {
241                report.record(record, &measurement);
242            }
243        }
244        report
245    }
246
247    fn record(&mut self, leg: &LegRecord, measurement: &Measurement) {
248        let delta = measurement.rerouted_usd - measurement.l1_usd;
249        self.n += 1;
250        let (count, vol) = match measurement.outcome {
251            Ordering::Greater => (&mut self.better, &mut self.vol_better),
252            Ordering::Equal => (&mut self.same, &mut self.vol_same),
253            Ordering::Less => (&mut self.worse, &mut self.vol_worse),
254        };
255        *count += 1;
256        *vol += measurement.l1_usd;
257        self.vol += measurement.l1_usd;
258        self.net += delta;
259        if measurement.l1_usd > 0.0 {
260            self.bps.push(delta / measurement.l1_usd * 1e4);
261        }
262        let side = if mints::trades_only_majors(&leg.input_mint, &leg.output_mint) {
263            &mut self.majors
264        } else {
265            &mut self.exotic
266        };
267        side.vol += measurement.l1_usd;
268        side.net += delta;
269        self.attribute_venues(leg, measurement.l1_usd, delta);
270    }
271
272    /// Split the leg's USD across its route's venues, per-leg-normalized so every leg contributes
273    /// its USD exactly once, for both the rerouted route and L1's landed one.
274    fn attribute_venues(&mut self, leg: &LegRecord, l1_usd: f64, delta: f64) {
275        for (rerouted, plan) in [(true, &leg.route_plan), (false, &leg.original_route_plan)] {
276            let Some(plan) = plan else {
277                continue;
278            };
279            let weights = venue_weights(plan);
280            let total: f64 = weights.iter().map(|(_, weight)| weight).sum();
281            let total = if total == 0.0 { 1.0 } else { total };
282            for (label, weight) in weights {
283                let label = label.unwrap_or("(unlabeled)");
284                let entry = self.venues.entry(label.to_string()).or_default();
285                let share = weight / total;
286                if rerouted {
287                    entry.rerouted += l1_usd * share;
288                    entry.net += delta * share;
289                } else {
290                    entry.l1 += l1_usd * share;
291                }
292            }
293        }
294    }
295
296    /// Add `other` into this report, for a cross-range aggregate.
297    pub fn merge(&mut self, other: &Self) {
298        self.n += other.n;
299        self.better += other.better;
300        self.same += other.same;
301        self.worse += other.worse;
302        self.vol += other.vol;
303        self.net += other.net;
304        self.vol_better += other.vol_better;
305        self.vol_same += other.vol_same;
306        self.vol_worse += other.vol_worse;
307        self.bps.extend_from_slice(&other.bps);
308        self.majors.vol += other.majors.vol;
309        self.majors.net += other.majors.net;
310        self.exotic.vol += other.exotic.vol;
311        self.exotic.net += other.exotic.net;
312        for (venue, totals) in &other.venues {
313            let entry = self.venues.entry(venue.clone()).or_default();
314            entry.rerouted += totals.rerouted;
315            entry.l1 += totals.l1;
316            entry.net += totals.net;
317        }
318    }
319
320    /// The volume-weighted change in bps, `net / vol * 10_000`; 0 when nothing was measured.
321    pub fn vw_bps(&self) -> f64 {
322        if self.vol == 0.0 {
323            0.0
324        } else {
325            self.net / self.vol * 1e4
326        }
327    }
328
329    /// A Markdown section headed `name`: the summary lines, then the venue table without venues
330    /// under [`VENUE_DUST_USD`] on both sides.
331    pub fn render(&self, name: &str) -> String {
332        if self.vol == 0.0 {
333            return format!("### {name}: no measurable legs\n");
334        }
335        let mut lines = self.summary_lines(name);
336        lines.push(String::new());
337        lines.extend(self.venue_table());
338        lines.push(String::new());
339        lines.join("\n")
340    }
341
342    fn summary_lines(&self, name: &str) -> Vec<String> {
343        let mut bps = self.bps.clone();
344        let (q1_at, q3_at) = (bps.len() / 4, 3 * bps.len() / 4);
345        let med = median(&mut bps);
346        let mut lines = vec![
347            format!("### {name}"),
348            format!(
349                "vw vs historical: **{:+.2} bps** (net {}$ on ${})",
350                self.vw_bps(),
351                commas_signed(self.net),
352                commas(self.vol)
353            ),
354            format!(
355                "b/s/w: {} / {} / {}  (by volume {:.1} / {:.1} / {:.1}%)",
356                commas_u(self.better),
357                commas_u(self.same),
358                commas_u(self.worse),
359                self.vol_better / self.vol * 100.0,
360                self.vol_same / self.vol * 100.0,
361                self.vol_worse / self.vol * 100.0
362            ),
363            format!(
364                "per-leg bps: median {med:+.2}, IQR [{:+.2}, {:+.2}]",
365                bps[q1_at], bps[q3_at]
366            ),
367        ];
368        for (label, side) in [
369            ("majors<->majors", &self.majors),
370            ("exotic-involved", &self.exotic),
371        ] {
372            if side.vol > 0.0 {
373                lines.push(format!(
374                    "{label}: {:+.2} bps (net {}$ on ${})",
375                    side.net / side.vol * 1e4,
376                    commas_signed(side.net),
377                    commas(side.vol)
378                ));
379            }
380        }
381        lines
382    }
383
384    fn venue_table(&self) -> Vec<String> {
385        let mut lines = vec![
386            "| Venue | rerouted share | historical share | vw bps (rerouted legs) |".to_string(),
387            "|---|---|---|---|".to_string(),
388        ];
389        let total_rerouted: f64 = self
390            .venues
391            .values()
392            .map(|e| e.rerouted)
393            .sum::<f64>()
394            .max(1.0);
395        let total_l1: f64 = self.venues.values().map(|e| e.l1).sum::<f64>().max(1.0);
396        let mut ranked: Vec<_> = self.venues.iter().collect();
397        ranked.sort_by(|a, b| b.1.rerouted.total_cmp(&a.1.rerouted));
398        for (venue, e) in ranked {
399            if e.rerouted < VENUE_DUST_USD && e.l1 < VENUE_DUST_USD {
400                continue;
401            }
402            let vw = if e.rerouted == 0.0 {
403                0.0
404            } else {
405                e.net / e.rerouted * 1e4
406            };
407            lines.push(format!(
408                "| {venue} | {:.1}% | {:.1}% | {vw:+.2} |",
409                e.rerouted / total_rerouted * 100.0,
410                e.l1 / total_l1 * 100.0
411            ));
412        }
413        lines
414    }
415}
416
417fn commas(x: f64) -> String {
418    commas_u(x.round().abs() as u64)
419}
420
421fn commas_signed(x: f64) -> String {
422    format!("{}{}", if x < 0.0 { "-" } else { "+" }, commas(x))
423}
424
425#[cfg(test)]
426mod tests {
427    use rstest::rstest;
428
429    use super::*;
430    use crate::{
431        reroute_report::{
432            Samples,
433            testing::{hop, plan, record_of},
434        },
435        route_plan::RouteHop,
436    };
437
438    #[rstest]
439    #[case::rounds_up("+1,235", 1_234.6)]
440    #[case::negative("-1,235", -1_234.6)]
441    fn signed_commas_carry_the_sign(#[case] expected: &str, #[case] x: f64) {
442        assert_eq!(commas_signed(x), expected);
443    }
444
445    fn hop_of(input_mint: &Address, in_amount: u64) -> RouteHop {
446        hop(
447            None,
448            "Venue",
449            &input_mint.to_string(),
450            &mints::USDT.to_string(),
451            in_amount,
452        )
453    }
454
455    /// The wire carries amounts as text, which a fixture with a `u64` cannot express.
456    fn amount_hop(in_amount: Option<&str>) -> RouteHop {
457        let mut hop = hop_of(&mints::USDC, 0);
458        hop.swap_info.in_amount = in_amount.map(str::to_string);
459        hop
460    }
461
462    #[rstest]
463    #[case::integer_amount(Some("1000"), Some(1_000))]
464    #[case::float_amount_truncates(Some("1000.9"), Some(1_000))]
465    #[case::float_string_truncates(Some("1.5e3"), Some(1_500))]
466    #[case::unparseable_voids_the_plan(Some("abc"), None)]
467    #[case::an_absent_amount_alone_sums_to_nothing(None, None)]
468    fn plan_input_reads_integer_and_float_amounts(
469        #[case] amount: Option<&str>,
470        #[case] expected: Option<i64>,
471    ) {
472        let plan = plan(vec![amount_hop(amount)]).expect("a plan");
473        assert_eq!(plan_input(&plan, &mints::USDC), expected);
474    }
475
476    #[test]
477    fn plan_input_sums_only_the_asked_mints_hops() {
478        let plan = plan(vec![
479            hop_of(&mints::USDC, 300),
480            hop_of(&Address::default(), 999),
481            hop_of(&mints::USDC, 700),
482        ])
483        .expect("a plan");
484        assert_eq!(plan_input(&plan, &mints::USDC), Some(1_000));
485
486        // Deserialization bypasses `RoutePlan::new`, so a plan off the wire can still be empty.
487        let empty: RoutePlan = serde_json::from_str("[]").expect("an empty plan");
488        assert_eq!(plan_input(&empty, &mints::USDC), None);
489    }
490
491    #[test]
492    fn an_absent_amount_contributes_zero_without_voiding() {
493        let plan = plan(vec![amount_hop(None), hop_of(&mints::USDC, 700)]).expect("a plan");
494        assert_eq!(plan_input(&plan, &mints::USDC), Some(700));
495    }
496
497    /// Fixes SOL at $100 from the stream's own swaps; the stable legs below price off decimals
498    /// alone, so nothing else needs deriving.
499    fn prices() -> Prices {
500        let mut samples = Samples::default();
501        for n in 1..=3u64 {
502            samples.push(&LegRecord {
503                original_realized_output_amount: Some(n * 100_000_000),
504                ..record_of(mints::SOL, mints::USDC, n * 1_000_000_000, None, None, None)
505            });
506        }
507        samples.prices().expect("anchored")
508    }
509
510    fn stable_record(mode: SwapMode, rerouted: u64, l1: u64) -> LegRecord {
511        LegRecord {
512            swap_mode: mode,
513            realized_output_amount: Some(rerouted),
514            original_realized_output_amount: Some(l1),
515            route_plan: plan(vec![hop_of(&mints::USDC, rerouted)]),
516            original_route_plan: plan(vec![hop_of(&mints::USDC, l1)]),
517            ..record_of(mints::USDC, mints::USDT, 1_000_000, None, None, None)
518        }
519    }
520
521    #[test]
522    fn exact_out_credits_the_input_saved() {
523        let m = measure(
524            &stable_record(SwapMode::ExactOut, 999_000, 1_000_000),
525            &prices(),
526        )
527        .expect("measurable");
528        assert_eq!(m.outcome, Ordering::Greater);
529        assert!((m.l1_usd - 1.0).abs() < 1e-9);
530        assert!((m.rerouted_usd - 1.001).abs() < 1e-9);
531    }
532
533    #[rstest]
534    #[case::win(1_010_000, 1_000_000, Some(Ordering::Greater))]
535    #[case::tie(1_000_000, 1_000_000, Some(Ordering::Equal))]
536    #[case::exactly_at_the_outlier_bound_stays(1_200_000, 1_000_000, Some(Ordering::Greater))]
537    #[case::past_the_outlier_bound_drops(1_210_000, 1_000_000, None)]
538    fn exact_in_measures_major_output_with_the_outlier_gate(
539        #[case] rerouted: u64,
540        #[case] l1: u64,
541        #[case] expected: Option<Ordering>,
542    ) {
543        let m = measure(&stable_record(SwapMode::ExactIn, rerouted, l1), &prices());
544        assert_eq!(m.map(|m| m.outcome), expected);
545    }
546
547    /// Pairing is by signature, so a signature seen twice is ambiguous and drops wholesale.
548    #[test]
549    fn collect_drops_multi_row_signatures_wholesale() {
550        let mut a = stable_record(SwapMode::ExactIn, 1_000_000, 999_000);
551        a.original_signature = "sigA".to_string();
552        let mut a2 = a.clone();
553        a2.amount = 2_000_000;
554        let mut b = stable_record(SwapMode::ExactIn, 1_000_000, 999_000);
555        b.original_signature = "sigB".to_string();
556
557        let (kept, stats) = collect(vec![a, a2, b]);
558        assert_eq!(kept.len(), 1);
559        assert_eq!(kept[0].original_signature, "sigB");
560        assert_eq!(stats.dropped_multi_row, 1);
561    }
562
563    /// An ExactOut leg is measured on its input, so a non-major input has no price to measure
564    /// against — and dropping it before the signature bookkeeping keeps it from making a
565    /// measurable row ambiguous.
566    #[test]
567    fn collect_skips_exact_out_legs_it_cannot_price() {
568        let exotic = LegRecord {
569            input_mint: Address::default(),
570            ..stable_record(SwapMode::ExactOut, 1_000_000, 999_000)
571        };
572        let major = stable_record(SwapMode::ExactOut, 1_000_000, 999_000);
573
574        let (kept, stats) = collect(vec![exotic, major]);
575        assert_eq!(kept.len(), 1);
576        assert_eq!(kept[0].input_mint, mints::USDC);
577        assert_eq!(stats.dropped_multi_row, 0, "a skipped row is not a pairing");
578    }
579}