sim-cli 0.23.0

CLI tool for running and comparing Solana simulator backtests
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
//! `sim compare`: diff two simulation output files (baseline vs experiment).
//!
//! The pipeline is `spill` (hash-partition both sides to disk) → `diff` (join
//! partition pairs and score PnL discrepancies) → `symbols` (best-effort token
//! tickers) → `render` (JSON or console). Shared types live in `model`.

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;

/// Upper bound on partition pairs joined concurrently, which also bounds join
/// memory to roughly `2 × TARGET_PARTITION_BYTES` of records per slot.
const MAX_PARALLEL_PARTITION_JOINS: usize = 8;

/// Default for `--compute-units-threshold`, in percent.
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 {
    /// Only show regressed transactions (success → failure)
    Regressions,
    /// Only show improved transactions (failure → success)
    Improvements,
    /// Only show transactions with the same status but a different number of
    /// log lines
    Logs,
    /// Only show transactions successful in both runs whose compute units rose
    /// by more than --compute-units-threshold percent, largest increase first
    ComputeUnits,
    /// Only show successful transactions whose PnL differs, largest difference
    /// first
    Balances,
}

#[derive(Parser, Debug)]
#[command(after_help = COMPARE_EXAMPLES)]
pub struct CompareArgs {
    /// Output file of the baseline run (`sim run --output-file`)
    pub baseline: PathBuf,
    /// Output file of the experiment run to check against the baseline, e.g. one with
    /// `--program-so` or `--account-overrides`
    pub experiment: PathBuf,
    #[command(subcommand)]
    pub section: Option<CompareSection>,
    /// Output results as JSON instead of human-readable text
    #[arg(long, global = true)]
    pub json: bool,
    /// Exit with status 1 if the selected section has any entry, or, without a
    /// section, if any section does. Transactions missing from the experiment
    /// always count. Results are still printed first.
    #[arg(long, global = true)]
    pub fail_on_diff: bool,
    /// Count a transaction in the `compute-units` section when its compute
    /// units rose by more than this percent
    #[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,
}

/// Parse `--compute-units-threshold`: a finite, non-negative percent.
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)?;
    // The whole load/join pipeline is blocking file I/O + CPU; run it off the
    // async workers so signal handling stays responsive during large compares.
    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
            .expect("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")?;

    // The two sides spill to disjoint files, so load them concurrently; on
    // dual errors the baseline's surfaces first.
    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 base = base.join().expect("baseline load thread panicked");
        Ok::<_, eyre::Report>((base?, exp?))
    })?;

    // Partition pairs join independently and deserialization dominates, so
    // read + join each pair in parallel and fold the per-partition results.
    // Errors surface in partition order, matching the sequential path.
    // A dedicated pool caps in-flight pairs: each one holds up to two
    // partitions' records in memory, so an unbounded fan-out on a many-core
    // machine would defeat the spill bound on join memory.
    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,
    };

    /// Deterministic label -> value mapping, so the fixtures keep readable
    /// names while the typed fields hold real base58.
    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: (1_000_000_i64 + sol_delta) as u64,
            }],
            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())
    }

    /// As [`write_ndjson`], with a `summary` line counting `total_transactions`.
    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();
        // Out of slot order: the highest (slot, signature) record must win.
        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; (TARGET_PARTITION_BYTES + 1) as usize]).unwrap();

        assert_eq!(partition_count(&small, &small).unwrap(), 1);
        assert_eq!(partition_count(&small, &big).unwrap(), 2);
    }
}