mod diff;
mod model;
mod render;
mod spill;
mod symbols;
use std::path::{Path, PathBuf};
use clap::{Parser, Subcommand};
use diff::CompareAccumulator;
use eyre::{Context, Result};
use model::CompareReport;
use rayon::iter::{IndexedParallelIterator, IntoParallelRefIterator, ParallelIterator};
use render::{print_json, print_text};
use spill::{load_side, partition_count, read_partition};
use symbols::resolve_token_symbols;
const MAX_PARALLEL_PARTITION_JOINS: usize = 8;
const DEFAULT_COMPUTE_UNITS_THRESHOLD_PCT: f64 = 10.0;
const COMPARE_EXAMPLES: &str = "\
Examples:
# Run the same range with the onchain program and with a new program
# binary, then compare.
sim run --start-slot <slot> --end-slot <slot> --program-id <program> \\
--output-file baseline.ndjson
sim run --start-slot <slot> --end-slot <slot> --program-id <program> \\
--program-so ./program.so --output-file experiment.ndjson
sim compare baseline.ndjson experiment.ndjson
# Only the transactions that went from success to failure, as JSON.
sim compare --json baseline.ndjson experiment.ndjson regressions
# In CI: exit with status 1 if the new program binary turned any successful
# transaction into a failure, or the experiment is missing any transaction.
sim compare baseline.ndjson experiment.ndjson regressions --fail-on-diff
# In CI: exit with status 1 if any transaction's compute units rose by more
# than 5%.
sim compare baseline.ndjson experiment.ndjson compute-units --fail-on-diff \\
--compute-units-threshold 5
Both files must come from finished runs (with a `summary` line), hold every
transaction their summary counts, and share at least one transaction;
otherwise compare exits with status 1.
Token symbols are looked up on Solana mainnet's public RPC; a token whose
lookup fails is shown as TOK.";
#[derive(Subcommand, Debug)]
pub enum CompareSection {
Regressions,
Improvements,
Logs,
ComputeUnits,
Balances,
}
#[derive(Parser, Debug)]
#[command(after_help = COMPARE_EXAMPLES)]
pub struct CompareArgs {
pub baseline: PathBuf,
pub experiment: PathBuf,
#[command(subcommand)]
pub section: Option<CompareSection>,
#[arg(long, global = true)]
pub json: bool,
#[arg(long, global = true)]
pub fail_on_diff: bool,
#[arg(
long,
global = true,
value_name = "PERCENT",
default_value_t = DEFAULT_COMPUTE_UNITS_THRESHOLD_PCT,
value_parser = parse_threshold_pct
)]
pub compute_units_threshold: f64,
}
fn parse_threshold_pct(value: &str) -> Result<f64, String> {
let pct = value.parse::<f64>().map_err(|e| e.to_string())?;
if pct.is_finite() && pct >= 0.0 {
Ok(pct)
} else {
Err("expected a non-negative percent".to_owned())
}
}
pub async fn compare(args: CompareArgs) -> Result<()> {
let partitions = partition_count(&args.baseline, &args.experiment)?;
let report = {
let (baseline, experiment) = (args.baseline.clone(), args.experiment.clone());
let threshold = args.compute_units_threshold;
tokio::task::spawn_blocking(move || compute(&baseline, &experiment, partitions, threshold))
.await
.context("compute task panicked")??
};
let has_diff = report.has_diff(args.section.as_ref());
let missing = report.missing.len();
let symbols = resolve_token_symbols(&report.pnl_diffs).await;
if args.json {
print_json(&args, report, &symbols)?;
} else {
print_text(&args, &report, &symbols);
}
if args.fail_on_diff && has_diff {
if missing > 0 {
return Err(eyre::eyre!(
"--fail-on-diff: {missing} baseline transaction(s) are missing from the experiment"
));
}
return Err(eyre::eyre!(
"--fail-on-diff: the experiment differs from the baseline"
));
}
Ok(())
}
fn compute(
baseline: &Path,
experiment: &Path,
partitions: usize,
compute_units_threshold_pct: f64,
) -> Result<CompareReport> {
let spill_dir = tempfile::tempdir().context("failed to create spill directory")?;
let (base_side, exp_side) = std::thread::scope(|s| {
let base = s.spawn(|| load_side(baseline, partitions, spill_dir.path(), "baseline"));
let exp = load_side(experiment, partitions, spill_dir.path(), "experiment");
let Ok(base) = base.join() else {
return Err(eyre::eyre!("baseline load thread panicked"));
};
Ok::<_, eyre::Report>((base?, exp?))
})?;
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(MAX_PARALLEL_PARTITION_JOINS.min(base_side.partitions.len()))
.build()
.context("failed to build partition join pool")?;
let partition_accs: Vec<Result<CompareAccumulator>> = pool.install(|| {
base_side
.partitions
.par_iter()
.zip(exp_side.partitions.par_iter())
.map(|(base_part, exp_part)| {
let mut acc = CompareAccumulator::default();
acc.join_partition(
read_partition(base_part)?,
&read_partition(exp_part)?,
compute_units_threshold_pct,
);
Ok(acc)
})
.collect()
});
let mut acc = CompareAccumulator::default();
for partition_acc in partition_accs {
acc.merge(partition_acc?);
}
let CompareAccumulator {
mut regressions,
mut improvements,
mut log_diffs,
mut compute_unit_increases,
mut missing,
mut pnl_diffs,
common,
} = acc;
if common == 0 {
return Err(eyre::eyre!(
"{} and {} share no transactions, so there is nothing to compare. Check that both \
runs cover the same slots with the same --program-id",
baseline.display(),
experiment.display()
));
}
regressions.sort_by(|a, b| (a.slot, &a.signature).cmp(&(b.slot, &b.signature)));
improvements.sort_by(|a, b| (a.slot, &a.signature).cmp(&(b.slot, &b.signature)));
log_diffs.sort_by(|a, b| (a.slot, &a.signature).cmp(&(b.slot, &b.signature)));
compute_unit_increases.sort_by(|a, b| {
b.increase()
.cmp(&a.increase())
.then_with(|| (a.slot, &a.signature).cmp(&(b.slot, &b.signature)))
});
missing.sort();
pnl_diffs.sort_by(|a, b| {
b.score
.total_cmp(&a.score)
.then_with(|| (a.slot, &a.signature).cmp(&(b.slot, &b.signature)))
});
Ok(CompareReport {
baseline_transactions: base_side.total_transactions,
experiment_transactions: exp_side.total_transactions,
common,
regressions,
improvements,
log_diffs,
compute_unit_increases,
missing,
pnl_diffs,
})
}
#[cfg(test)]
mod tests {
use rstest::rstest;
use solana_address::Address;
use solana_signature::Signature;
use super::{
model::{ComputeUnitEntry, LogDiffEntry, RegressionEntry},
render::format_pct_change,
spill::TARGET_PARTITION_BYTES,
*,
};
use crate::output::{
OutputEvent, SimulationMetadata, SimulationSummary, SolChange, TokenChange, Transaction,
};
fn sig(label: &str) -> Signature {
let mut bytes = [0_u8; 64];
let src = label.as_bytes();
bytes[..src.len()].copy_from_slice(src);
Signature::from(bytes)
}
fn addr(label: &str) -> Address {
let mut bytes = [0_u8; 32];
let src = label.as_bytes();
bytes[..src.len()].copy_from_slice(src);
Address::from(bytes)
}
fn tx(slot: u64, signature: &str, success: bool, logs: usize, sol_delta: i64) -> Transaction {
Transaction {
slot,
timestamp: None,
signature: sig(signature),
success,
error: (!success).then(|| format!("err-{signature}")),
compute_units: Some(1_000),
logs: (0..logs).map(|i| format!("log {i}")).collect(),
sol_changes: vec![SolChange {
pubkey: addr(signature),
pre_lamports: 1_000_000,
post_lamports: u64::try_from(1_000_000_i64 + sol_delta).unwrap(),
}],
token_changes: Vec::new(),
account_diffs: Vec::new(),
}
}
fn write_ndjson(dir: &Path, name: &str, txs: &[Transaction]) -> PathBuf {
write_ndjson_with_total(dir, name, txs, txs.len())
}
fn write_ndjson_with_total(
dir: &Path,
name: &str,
txs: &[Transaction],
total_transactions: usize,
) -> PathBuf {
let path = dir.join(name);
let mut lines = vec![
serde_json::to_string(&OutputEvent::Metadata(SimulationMetadata {
start_slot: 1,
end_slot: 100,
program_ids: Vec::new(),
program_so: Vec::new(),
ran_at_unix_secs: 0,
session_ids: Vec::new(),
}))
.unwrap(),
];
for tx in txs {
lines.push(serde_json::to_string(&OutputEvent::Tx(tx.clone())).unwrap());
}
lines.push(
serde_json::to_string(&OutputEvent::Summary(SimulationSummary {
total_transactions,
successes: txs.iter().filter(|t| t.success).count(),
failures: txs.iter().filter(|t| !t.success).count(),
session_name: None,
session_ids: Vec::new(),
diagnostics: None,
}))
.unwrap(),
);
std::fs::write(&path, lines.join("\n")).unwrap();
path
}
fn fixture() -> (Vec<Transaction>, Vec<Transaction>) {
let baseline = vec![
tx(1, "sig-regressed", true, 5, 10),
tx(2, "sig-improved", false, 5, 10),
tx(3, "sig-logs", true, 5, 10),
tx(4, "sig-missing", true, 5, 10),
tx(5, "sig-pnl-small", true, 5, 10),
tx(6, "sig-pnl-big", true, 5, 10),
tx(7, "sig-same", true, 5, 10),
];
let experiment = vec![
tx(1, "sig-regressed", false, 5, 10),
tx(2, "sig-improved", true, 5, 10),
tx(3, "sig-logs", true, 9, 10),
tx(5, "sig-pnl-small", true, 5, 11),
tx(6, "sig-pnl-big", true, 5, 5_000),
tx(7, "sig-same", true, 5, 10),
tx(8, "sig-extra-in-experiment", true, 5, 10),
];
(baseline, experiment)
}
fn compare_files(
baseline: &Path,
experiment: &Path,
partitions: usize,
) -> Result<CompareReport> {
compute(
baseline,
experiment,
partitions,
DEFAULT_COMPUTE_UNITS_THRESHOLD_PCT,
)
}
fn report_value(report: &CompareReport) -> serde_json::Value {
serde_json::to_value(report).unwrap()
}
#[test]
fn compare_sections_match_expectations() {
let dir = tempfile::tempdir().unwrap();
let (baseline, experiment) = fixture();
let base_path = write_ndjson(dir.path(), "base.ndjson", &baseline);
let exp_path = write_ndjson(dir.path(), "exp.ndjson", &experiment);
let report = compare_files(&base_path, &exp_path, 1).unwrap();
assert_eq!(report.baseline_transactions, 7);
assert_eq!(report.experiment_transactions, 7);
assert_eq!(report.common, 6);
assert_eq!(
report
.regressions
.iter()
.map(|r| r.signature)
.collect::<Vec<_>>(),
[sig("sig-regressed")]
);
assert_eq!(
report.regressions[0].error.as_deref(),
Some("err-sig-regressed")
);
assert_eq!(
report
.improvements
.iter()
.map(|i| i.signature)
.collect::<Vec<_>>(),
[sig("sig-improved")]
);
assert_eq!(
report
.log_diffs
.iter()
.map(|l| (l.signature, l.baseline_log_count, l.experiment_log_count))
.collect::<Vec<_>>(),
[(sig("sig-logs"), 5, 9)]
);
assert_eq!(report.missing, [sig("sig-missing")]);
assert_eq!(
report
.pnl_diffs
.iter()
.map(|p| p.signature)
.collect::<Vec<_>>(),
[sig("sig-pnl-big"), sig("sig-pnl-small")]
);
}
#[test]
fn report_is_invariant_under_partition_count() {
let dir = tempfile::tempdir().unwrap();
let (mut baseline, mut experiment) = fixture();
for i in 0..200 {
baseline.push(tx(10 + i, &format!("sig-bulk-{i}"), true, 3, 10));
let delta = if i % 3 == 0 { 999 } else { 10 };
experiment.push(tx(10 + i, &format!("sig-bulk-{i}"), true, 3, delta));
}
let base_path = write_ndjson(dir.path(), "base.ndjson", &baseline);
let exp_path = write_ndjson(dir.path(), "exp.ndjson", &experiment);
let in_memory = compare_files(&base_path, &exp_path, 1).unwrap();
let partitioned = compare_files(&base_path, &exp_path, 7).unwrap();
assert_eq!(report_value(&in_memory), report_value(&partitioned));
}
#[test]
fn missing_metadata_envelope_is_rejected() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("no-meta.ndjson");
let line = serde_json::to_string(&OutputEvent::Tx(tx(1, "sig", true, 1, 10))).unwrap();
std::fs::write(&path, line).unwrap();
let other = write_ndjson(dir.path(), "ok.ndjson", &fixture().0);
let err = compare_files(&path, &other, 1).map(|_| ()).unwrap_err();
assert!(
err.to_string()
.contains("missing the leading `metadata` envelope")
);
}
#[test]
fn empty_file_is_rejected() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("empty.ndjson");
std::fs::write(&path, "").unwrap();
let other = write_ndjson(dir.path(), "ok.ndjson", &fixture().0);
let err = compare_files(&path, &other, 1).map(|_| ()).unwrap_err();
assert!(
err.to_string()
.contains("missing the leading `metadata` envelope")
);
}
#[test]
fn files_sharing_no_transactions_are_rejected() {
let dir = tempfile::tempdir().unwrap();
let base_path = write_ndjson(dir.path(), "base.ndjson", &fixture().0);
let exp_path = write_ndjson(dir.path(), "exp.ndjson", &[]);
let err = compare_files(&base_path, &exp_path, 1)
.map(|_| ())
.unwrap_err();
assert!(err.to_string().contains("share no transactions"));
}
#[test]
fn file_without_summary_line_is_rejected() {
let dir = tempfile::tempdir().unwrap();
let (baseline, experiment) = fixture();
let base_path = write_ndjson(dir.path(), "base.ndjson", &baseline);
let exp_path = write_ndjson(dir.path(), "exp.ndjson", &experiment);
let content = std::fs::read_to_string(&exp_path).unwrap();
let (without_summary, _) = content.rsplit_once('\n').unwrap();
std::fs::write(&exp_path, without_summary).unwrap();
let err = compare_files(&base_path, &exp_path, 1)
.map(|_| ())
.unwrap_err();
assert!(err.to_string().contains("has no `summary` line"));
}
#[rstest]
#[case::short_baseline(true, 1)]
#[case::short_experiment(false, 1)]
#[case::extra_baseline_lines(true, -1)]
fn file_whose_summary_miscounts_its_transactions_is_rejected(
#[case] baseline_is_off: bool,
#[case] summary_minus_lines: isize,
) {
let dir = tempfile::tempdir().unwrap();
let (baseline, experiment) = fixture();
let off_path = |name: &str, txs: &[Transaction]| {
let total = txs.len().checked_add_signed(summary_minus_lines).unwrap();
write_ndjson_with_total(dir.path(), name, txs, total)
};
let (base_path, exp_path) = if baseline_is_off {
(
off_path("base.ndjson", &baseline),
write_ndjson(dir.path(), "exp.ndjson", &experiment),
)
} else {
(
write_ndjson(dir.path(), "base.ndjson", &baseline),
off_path("exp.ndjson", &experiment),
)
};
let err = compare_files(&base_path, &exp_path, 1)
.map(|_| ())
.unwrap_err();
assert!(err.to_string().contains("the file is incomplete"));
}
#[test]
fn compute_unit_increases_past_the_threshold_are_reported() {
let dir = tempfile::tempdir().unwrap();
let with_units = |signature: &str, units: u64| {
let mut t = tx(1, signature, true, 5, 10);
t.compute_units = Some(units);
t
};
let mut unrecorded = with_units("sig-cu-unrecorded", 1_000);
unrecorded.compute_units = None;
let baseline = [with_units("sig-cu-big", 1_000), unrecorded.clone()];
let experiment = [with_units("sig-cu-big", 9_000), unrecorded];
let base_path = write_ndjson(dir.path(), "base.ndjson", &baseline);
let exp_path = write_ndjson(dir.path(), "exp.ndjson", &experiment);
let report = compare_files(&base_path, &exp_path, 1).unwrap();
assert_eq!(
report
.compute_unit_increases
.iter()
.map(|e| (
e.signature,
e.baseline_compute_units,
e.experiment_compute_units
))
.collect::<Vec<_>>(),
[(sig("sig-cu-big"), 1_000, 9_000)]
);
}
#[rstest]
#[case::flags_after_the_section(&[
"regressions", "--fail-on-diff", "--json", "--compute-units-threshold", "5",
])]
#[case::flags_before_the_section(&[
"--fail-on-diff", "--json", "--compute-units-threshold", "5", "regressions",
])]
fn global_flags_parse_on_either_side_of_the_section(#[case] tail: &[&str]) {
let argv = ["compare", "base.ndjson", "exp.ndjson"]
.iter()
.chain(tail)
.copied();
let args = CompareArgs::try_parse_from(argv).unwrap();
assert!(args.fail_on_diff && args.json);
assert_eq!(args.compute_units_threshold, 5.0);
assert!(matches!(args.section, Some(CompareSection::Regressions)));
}
#[rstest]
#[case::negative("-1")]
#[case::not_a_number("NaN")]
#[case::infinite("inf")]
#[case::not_numeric("ten")]
fn invalid_compute_units_threshold_is_rejected(#[case] value: &str) {
let flag = format!("--compute-units-threshold={value}");
let argv = ["compare", "base.ndjson", "exp.ndjson", flag.as_str()];
assert!(CompareArgs::try_parse_from(argv).is_err());
}
#[test]
fn duplicate_signatures_keep_the_last_record() {
let dir = tempfile::tempdir().unwrap();
let baseline = vec![
tx(2, "sig-dup", true, 5, 10),
tx(1, "sig-dup", false, 5, 10),
];
let experiment = vec![tx(2, "sig-dup", false, 5, 10)];
let base_path = write_ndjson(dir.path(), "base.ndjson", &baseline);
let exp_path = write_ndjson(dir.path(), "exp.ndjson", &experiment);
let report = compare_files(&base_path, &exp_path, 1).unwrap();
assert_eq!(report.common, 1);
assert_eq!(
report
.regressions
.iter()
.map(|r| (r.slot, r.signature))
.collect::<Vec<_>>(),
[(2, sig("sig-dup"))]
);
}
#[test]
fn token_changes_produce_ranked_spl_diffs() {
let dir = tempfile::tempdir().unwrap();
let with_tokens = |amount: u64| {
let mut t = tx(1, "sig-tokens", true, 5, 10);
t.token_changes = vec![TokenChange {
pubkey: addr("token-account"),
mint: addr("mint-a"),
owner: Some(addr("owner")),
pre_amount: 100,
post_amount: amount,
decimals: 6,
}];
t
};
let base_path = write_ndjson(dir.path(), "base.ndjson", &[with_tokens(150)]);
let exp_path = write_ndjson(dir.path(), "exp.ndjson", &[with_tokens(300)]);
let report = compare_files(&base_path, &exp_path, 1).unwrap();
assert_eq!(report.pnl_diffs.len(), 1);
let diff = &report.pnl_diffs[0];
assert!(diff.sol.is_empty());
assert_eq!(diff.tokens.len(), 1);
let spl = &diff.tokens[0];
assert_eq!(spl.mint, addr("mint-a"));
assert_eq!(spl.decimals, 6);
assert_eq!(spl.baseline_delta, 50);
assert_eq!(spl.experiment_delta, 200);
}
fn report(
regressions: usize,
log_diffs: usize,
compute_unit_increases: usize,
missing: usize,
) -> CompareReport {
CompareReport {
baseline_transactions: 0,
experiment_transactions: 0,
common: 0,
regressions: (0..regressions)
.map(|_| RegressionEntry {
slot: 1,
signature: sig("sig-regressed"),
error: None,
})
.collect(),
improvements: Vec::new(),
log_diffs: (0..log_diffs)
.map(|_| LogDiffEntry {
slot: 1,
signature: sig("sig-logs"),
baseline_log_count: 1,
experiment_log_count: 2,
})
.collect(),
compute_unit_increases: (0..compute_unit_increases)
.map(|_| ComputeUnitEntry {
slot: 1,
signature: sig("sig-cu"),
baseline_compute_units: 1_000,
experiment_compute_units: 9_000,
})
.collect(),
missing: vec![sig("sig-missing"); missing],
pnl_diffs: Vec::new(),
}
}
#[rstest]
#[case::no_diff(report(0, 0, 0, 0), None, false)]
#[case::no_diff_in_section(report(0, 0, 0, 0), Some(CompareSection::Regressions), false)]
#[case::diff_in_selected_section(report(1, 0, 0, 0), Some(CompareSection::Regressions), true)]
#[case::diff_only_in_unselected_section(
report(0, 1, 1, 0),
Some(CompareSection::Regressions),
false
)]
#[case::missing_counts_without_section(report(0, 0, 0, 1), None, true)]
#[case::missing_counts_in_any_section(
report(0, 0, 0, 1),
Some(CompareSection::Regressions),
true
)]
#[case::diff_in_any_section(report(0, 1, 0, 0), None, true)]
#[case::compute_units_in_selected_section(
report(0, 0, 1, 0),
Some(CompareSection::ComputeUnits),
true
)]
#[case::compute_units_without_section(report(0, 0, 1, 0), None, true)]
fn fail_on_diff_counts_the_selected_section_and_missing(
#[case] report: CompareReport,
#[case] section: Option<CompareSection>,
#[case] expected: bool,
) {
assert_eq!(report.has_diff(section.as_ref()), expected);
}
#[test]
fn pct_change_handles_zero_baseline() {
assert_eq!(format_pct_change(0, 500), "new");
assert_eq!(format_pct_change(200, 300), "+50.0000%");
assert_eq!(format_pct_change(-200, -300), "-50.0000%");
}
#[test]
fn spill_threshold_starts_just_past_one_partition() {
let dir = tempfile::tempdir().unwrap();
let small = dir.path().join("small");
let big = dir.path().join("big");
std::fs::write(&small, vec![0_u8; 1024]).unwrap();
std::fs::write(
&big,
vec![0_u8; usize::try_from(TARGET_PARTITION_BYTES + 1).unwrap()],
)
.unwrap();
assert_eq!(partition_count(&small, &small).unwrap(), 1);
assert_eq!(partition_count(&small, &big).unwrap(), 2);
}
}