sim-cli 0.22.0

CLI tool for running and comparing Solana simulator backtests
Documentation
//! Per-partition join and PnL diff scoring.

use std::collections::{BTreeSet, HashMap};

use solana_address::Address;
use solana_signature::Signature;

use super::model::{
    CompareTransaction, ComputeUnitEntry, ImprovementEntry, LogDiffEntry, PnlDiff, RegressionEntry,
    SolDiff, SplDiff,
};

impl PnlDiff {
    fn new(base: &CompareTransaction, exp: &CompareTransaction) -> Option<Self> {
        let base_sol: HashMap<Address, i64> = base
            .sol_changes
            .iter()
            .map(|c| (c.pubkey, c.delta()))
            .collect();
        let exp_sol: HashMap<Address, i64> = exp
            .sol_changes
            .iter()
            .map(|c| (c.pubkey, c.delta()))
            .collect();
        let sol_keys: BTreeSet<Address> = base_sol.keys().chain(exp_sol.keys()).copied().collect();
        let sol_diffs: Vec<SolDiff> = sol_keys
            .into_iter()
            .filter_map(|pk| {
                let b = base_sol.get(&pk).copied().unwrap_or(0);
                let e = exp_sol.get(&pk).copied().unwrap_or(0);
                if b == e {
                    return None;
                }
                Some(SolDiff {
                    pubkey: pk,
                    baseline_delta: b,
                    experiment_delta: e,
                })
            })
            .collect();

        let base_spl: HashMap<(Address, Address), (i64, u8)> = base
            .token_changes
            .iter()
            .map(|c| ((c.pubkey, c.mint), (c.delta(), c.decimals)))
            .collect();
        let exp_spl: HashMap<(Address, Address), (i64, u8)> = exp
            .token_changes
            .iter()
            .map(|c| ((c.pubkey, c.mint), (c.delta(), c.decimals)))
            .collect();
        let spl_keys: BTreeSet<(Address, Address)> =
            base_spl.keys().chain(exp_spl.keys()).copied().collect();
        let token_diffs: Vec<SplDiff> = spl_keys
            .into_iter()
            .filter_map(|(pk, mint)| {
                let (b, decimals) = base_spl.get(&(pk, mint)).copied().unwrap_or_else(|| {
                    exp_spl
                        .get(&(pk, mint))
                        .map(|(_, dec)| (0, *dec))
                        .unwrap_or((0, 0))
                });
                let (e, _) = exp_spl.get(&(pk, mint)).copied().unwrap_or((0, decimals));
                if b == e {
                    return None;
                }
                Some(SplDiff {
                    pubkey: pk,
                    mint,
                    symbol: String::new(),
                    decimals,
                    baseline_delta: b,
                    experiment_delta: e,
                })
            })
            .collect();

        let normalized = |base: i64, exp: i64| -> f64 {
            let diff = (exp - base).unsigned_abs() as f64;
            let base_abs = base.unsigned_abs() as f64;
            // geometric mean of absolute diff and base magnitude; weights by position size
            // so small changes on tiny positions don't dominate the ranking.
            // fall back to raw diff when base is zero (still a valid change, just no base to weight against)
            if base == 0 {
                diff
            } else {
                (diff * base_abs).sqrt()
            }
        };
        let discrepancy: f64 = sol_diffs
            .iter()
            .map(|d| normalized(d.baseline_delta, d.experiment_delta))
            .sum::<f64>()
            + token_diffs
                .iter()
                .map(|d| normalized(d.baseline_delta, d.experiment_delta))
                .sum::<f64>();

        if discrepancy == 0.0 {
            return None;
        }
        Some(PnlDiff {
            slot: base.slot,
            signature: base.signature,
            sol: sol_diffs,
            tokens: token_diffs,
            score: discrepancy,
        })
    }
}

#[derive(Default)]
pub(super) struct CompareAccumulator {
    pub(super) regressions: Vec<RegressionEntry>,
    pub(super) improvements: Vec<ImprovementEntry>,
    pub(super) log_diffs: Vec<LogDiffEntry>,
    pub(super) compute_unit_increases: Vec<ComputeUnitEntry>,
    pub(super) missing: Vec<Signature>,
    pub(super) pnl_diffs: Vec<PnlDiff>,
    pub(super) common: usize,
}

/// Whether `experiment` compute units exceed `baseline` by more than
/// `threshold_pct` percent. Any rise from zero counts.
fn compute_units_rose(baseline: u64, experiment: u64, threshold_pct: f64) -> bool {
    experiment as f64 > baseline as f64 * (1.0 + threshold_pct / 100.0)
}

impl CompareAccumulator {
    /// Fold another partition's accumulator into this one. Ordering across
    /// partitions is irrelevant: the caller sorts every section afterwards.
    pub(super) fn merge(&mut self, other: Self) {
        self.regressions.extend(other.regressions);
        self.improvements.extend(other.improvements);
        self.log_diffs.extend(other.log_diffs);
        self.compute_unit_increases
            .extend(other.compute_unit_increases);
        self.missing.extend(other.missing);
        self.pnl_diffs.extend(other.pnl_diffs);
        self.common += other.common;
    }

    /// Join two signature-keyed partition maps (already deduped by
    /// `read_partition`); every section is sorted afterwards, so map
    /// iteration order is irrelevant. A transaction successful on both sides
    /// whose compute units rose by more than `compute_units_threshold_pct`
    /// percent is a compute-unit increase.
    pub(super) fn join_partition(
        &mut self,
        base_map: HashMap<Signature, CompareTransaction>,
        exp_map: HashMap<Signature, CompareTransaction>,
        compute_units_threshold_pct: f64,
    ) {
        for (sig, base_tx) in base_map {
            let Some(exp_tx) = exp_map.get(&sig) else {
                self.missing.push(sig);
                continue;
            };
            self.common += 1;
            if base_tx.success
                && exp_tx.success
                && let Some(diff) = PnlDiff::new(&base_tx, exp_tx)
            {
                self.pnl_diffs.push(diff);
            }
            if base_tx.success
                && exp_tx.success
                && let (Some(baseline_units), Some(experiment_units)) =
                    (base_tx.compute_units, exp_tx.compute_units)
                && compute_units_rose(
                    baseline_units,
                    experiment_units,
                    compute_units_threshold_pct,
                )
            {
                self.compute_unit_increases.push(ComputeUnitEntry {
                    slot: base_tx.slot,
                    signature: base_tx.signature,
                    baseline_compute_units: baseline_units,
                    experiment_compute_units: experiment_units,
                });
            }
            match (base_tx.success, exp_tx.success) {
                (true, false) => self.regressions.push(RegressionEntry {
                    slot: base_tx.slot,
                    signature: base_tx.signature,
                    error: exp_tx.error.clone(),
                }),
                (false, true) => self.improvements.push(ImprovementEntry {
                    slot: base_tx.slot,
                    signature: base_tx.signature,
                    was: base_tx.error,
                }),
                _ => {
                    if base_tx.log_count != exp_tx.log_count {
                        self.log_diffs.push(LogDiffEntry {
                            slot: base_tx.slot,
                            signature: base_tx.signature,
                            baseline_log_count: base_tx.log_count,
                            experiment_log_count: exp_tx.log_count,
                        });
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use rstest::rstest;

    use super::compute_units_rose;

    #[rstest]
    #[case::unchanged(1_000, 1_000, 10.0, false)]
    #[case::drop(1_000, 500, 10.0, false)]
    #[case::rise_at_threshold(1_000, 1_100, 10.0, false)]
    #[case::rise_past_threshold(1_000, 1_101, 10.0, true)]
    #[case::any_rise_at_zero_threshold(1_000, 1_001, 0.0, true)]
    #[case::rise_from_zero(0, 1, 10.0, true)]
    fn compute_units_rise_counts_only_past_the_threshold(
        #[case] baseline: u64,
        #[case] experiment: u64,
        #[case] threshold_pct: f64,
        #[case] expected: bool,
    ) {
        assert_eq!(
            compute_units_rose(baseline, experiment, threshold_pct),
            expected
        );
    }
}