sim-cli 0.15.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
use std::time::Duration;

use clap::Parser;
use eyre::Result;
use sim_cli::{
    ApiKeyArg,
    args::{JsonOutputArgs, KindFilter, SlotBoundsArgs},
    engine::format_slot,
};
use simulator_api::{
    AvailableRange, BundleBuildRequest, BundleBuildStatus, BundleBuildStatusResponse,
    BundleDeleteRequest, BundleKind,
};

#[derive(Parser, Debug)]
pub struct BuildBundleArgs {
    #[command(flatten)]
    pub bounds: SlotBoundsArgs,

    #[command(flatten)]
    pub api_key: ApiKeyArg,

    /// Build forward from the latest snapshot slot; requires `--bundle-size`.
    #[arg(long)]
    pub latest: bool,

    /// Slots per bundle. Omit to build the whole range as one bundle.
    #[arg(long, value_parser = clap::value_parser!(u64).range(1..))]
    pub bundle_size: Option<u64>,

    /// Also record an account-state bundle over each bundle built, which
    /// `sim run --replay-account-state` can then replay instead of executing
    /// those slots. Adds a full execution pass, so it roughly doubles the build.
    ///
    /// A session replays one bundle, so pair this with `--bundle-size` to
    /// replay the range across parallel sessions — one per bundle. List what a
    /// build produced with `sim ranges --kind account-state`.
    #[arg(long)]
    pub account_state: bool,

    /// Dedupe key: resubmitting the same key returns the existing build instead
    /// of triggering (or re-charging for) a new one.
    #[arg(long)]
    pub idempotency_key: Option<String>,

    /// Poll until the build reaches a terminal state instead of returning on submit.
    #[arg(long)]
    pub wait: bool,

    /// Seconds between status polls when `--wait` is set.
    #[arg(long, default_value_t = 15, value_parser = clap::value_parser!(u64).range(1..))]
    pub poll_secs: u64,

    #[command(flatten)]
    pub output: JsonOutputArgs,
}

pub async fn build_bundle(args: BuildBundleArgs, url: String) -> Result<()> {
    let client = sim_cli::client::new(&url, &args.api_key.get());

    let (start_slot, end_slot) = if args.latest
        && let Some(size) = args.bundle_size
    {
        let start = client.get_latest_snapshot_slot().await?.snapshot_slot + 1;
        (start, start + size)
    } else {
        args.bounds.require()?
    };

    println!("Requesting bundle build for: {start_slot}-{end_slot}...");

    let mut resp = client
        .build_bundle(&BundleBuildRequest {
            start_slot,
            end_slot,
            bundle_size: args.bundle_size,
            idempotency_key: args.idempotency_key,
            kind: if args.account_state {
                BundleKind::AccountState
            } else {
                BundleKind::Blocks
            },
        })
        .await?;
    // ETA "what's cached" inference; best-effort (empty = cold estimate).
    let ranges = if args.output.json {
        Vec::new()
    } else {
        client.available_ranges().await.unwrap_or_default()
    };
    if !args.output.json {
        println!("{}", format_status("issued", &resp, &ranges));
    }

    if args.wait {
        while matches!(resp.status, BundleBuildStatus::InProgress) {
            tokio::time::sleep(Duration::from_secs(args.poll_secs)).await;
            resp = client.get_bundle_status(&resp.request_id).await?;
            if !args.output.json {
                println!("{}", format_status("status", &resp, &ranges));
            }
        }
    }

    if args.output.json {
        println!("{}", serde_json::to_string_pretty(&resp)?);
    }
    Ok(())
}

#[derive(Parser, Debug)]
pub struct BuildStatusArgs {
    /// Request id returned by `build-bundle`.
    pub request_id: String,

    #[command(flatten)]
    pub api_key: ApiKeyArg,

    #[command(flatten)]
    pub output: JsonOutputArgs,
}

pub async fn get_status(args: BuildStatusArgs, url: String) -> Result<()> {
    let client = sim_cli::client::new(&url, &args.api_key.get());
    let resp = client.get_bundle_status(&args.request_id).await?;
    if args.output.json {
        println!("{}", serde_json::to_string_pretty(&resp)?);
    } else {
        let ranges = client.available_ranges().await.unwrap_or_default();
        println!("{}", format_status("status", &resp, &ranges));
    }
    Ok(())
}

#[derive(Parser, Debug)]
pub struct BuildListArgs {
    /// Maximum builds to return, newest first.
    #[arg(long, value_parser = clap::value_parser!(u32).range(1..))]
    pub limit: Option<u32>,

    #[command(flatten)]
    pub api_key: ApiKeyArg,

    #[command(flatten)]
    pub output: JsonOutputArgs,
}

pub async fn list_builds(args: BuildListArgs, url: String) -> Result<()> {
    let client = sim_cli::client::new(&url, &args.api_key.get());
    let resp = client.list_bundle_builds(args.limit).await?;
    if args.output.json {
        println!("{}", serde_json::to_string_pretty(&resp)?);
        return Ok(());
    }
    if resp.builds.is_empty() {
        println!("\nNo builds requested at this endpoint");
    } else {
        println!("\nBuilds requested at this endpoint");
        // Only an in-progress row renders an ETA, which is all `ranges` feeds.
        let ranges = if resp
            .builds
            .iter()
            .any(|build| build.status == BundleBuildStatus::InProgress)
        {
            client.available_ranges().await.unwrap_or_default()
        } else {
            Vec::new()
        };
        for build in &resp.builds {
            println!("{}", format_status("build", build, &ranges));
        }
    }

    match resp.bundles.as_deref() {
        None => println!(
            "\nBundles you own could not be listed right now; the builds section above is unaffected"
        ),
        Some([]) => println!("\nYou own no bundles"),
        Some(bundles) => {
            println!("\nBundles you own");
            println!(
                "{:<15} {:<15} {:<15} Built (UTC)",
                "Kind", "Start Slot", "End Slot"
            );
            println!("{}", "-".repeat(60));
            for bundle in bundles {
                println!(
                    "{:<15} {:<15} {:<15} {}",
                    bundle.kind,
                    format_slot(bundle.start_slot),
                    format_slot(bundle.end_slot),
                    bundle
                        .completed_at_unix_ms
                        .and_then(format_unix_ms)
                        .unwrap_or_else(|| "-".to_string()),
                );
            }
        }
    }
    Ok(())
}

#[derive(Parser, Debug)]
pub struct BundleDeleteArgs {
    #[command(flatten)]
    pub bounds: SlotBoundsArgs,

    /// Which bundle over this range to delete.
    #[arg(long, value_enum, default_value_t = KindFilter::Transactions)]
    pub kind: KindFilter,

    #[command(flatten)]
    pub api_key: ApiKeyArg,

    /// Delete without asking for confirmation.
    #[arg(long)]
    pub yes: bool,

    #[command(flatten)]
    pub output: JsonOutputArgs,
}

pub async fn delete_bundle(args: BundleDeleteArgs, url: String) -> Result<()> {
    let (start_slot, end_slot) = args.bounds.require()?;
    let kind = BundleKind::from(args.kind);
    let client = sim_cli::client::new(&url, &args.api_key.get());

    if !args.yes {
        eprintln!(
            "Delete the {kind} bundle for slots {}..={}?",
            format_slot(start_slot),
            format_slot(end_slot)
        );
        eprintln!("A session currently reading it will fail.");
        if !confirmed()? {
            eprintln!("Left alone.");
            return Ok(());
        }
    }

    let resp = client
        .delete_bundle(&BundleDeleteRequest {
            start_slot,
            end_slot,
            kind,
        })
        .await?;

    if args.output.json {
        println!("{}", serde_json::to_string_pretty(&resp)?);
    } else {
        println!(
            "Deleted the {} bundle for slots {}..={}.",
            resp.kind,
            format_slot(resp.start_slot),
            format_slot(resp.end_slot)
        );
    }
    Ok(())
}

/// Read one line and accept only an explicit yes. A closed stdin (piped or
/// scripted without `--yes`) reads as "no" rather than proceeding unasked.
/// Prompting on stderr keeps it out of `--json` output, so `--yes` stays the
/// only way to skip the confirmation.
fn confirmed() -> Result<bool> {
    eprint!("Type 'yes' to confirm: ");
    std::io::Write::flush(&mut std::io::stderr())?;
    let mut answer = String::new();
    if std::io::BufRead::read_line(&mut std::io::stdin().lock(), &mut answer)? == 0 {
        return Ok(false);
    }
    Ok(answer.trim().eq_ignore_ascii_case("yes"))
}

fn format_unix_ms(unix_ms: i64) -> Option<String> {
    chrono::DateTime::from_timestamp_millis(unix_ms)
        .map(|time| time.format("%Y-%m-%d %H:%M:%S").to_string())
}

fn format_status(
    label: &str,
    resp: &BundleBuildStatusResponse,
    ranges: &[AvailableRange],
) -> String {
    let size = resp
        .bundle_size
        .map_or_else(|| "default".to_string(), |s| s.to_string());
    let eta = match resp.status {
        BundleBuildStatus::InProgress => match estimate_remaining_secs(resp, ranges, now_unix_ms())
        {
            0 => " eta finishing up".to_string(),
            secs => format!(" eta {}", format_duration(secs)),
        },
        _ => String::new(),
    };
    let kind = resp.kind;
    format!(
        "{label}: {} [{}] slots {}..={} size={size} kind={kind}{eta}",
        resp.request_id,
        resp.status.as_str(),
        resp.start_slot,
        resp.end_slot,
    )
}

// Per-phase cost model (seconds); tune as real timings firm up. ETA = phases
// still ahead − elapsed-since-submission, recomputed each poll.
const ORCHESTRATOR_SPINUP_SECS: u64 = 180;
const SNAPSHOT_DISCOVERY_SECS: u64 = 60;
const SNAPSHOT_IMPORT_SECS: u64 = 1500; // download (3m+7m) + transform (3m+12m)
const BLOCK_IMPORT_SPINUP_SECS: u64 = 180;
const BLOCK_RATE_HISTORIC: f64 = 130.0; // blk/s via jetstreamer
const BLOCK_RATE_RECENT: f64 = 45.0; // blk/s via RPC (current/prev epoch)
const BUNDLE_BUILD_SPINUP_SECS: u64 = 180;
const INTERIM_BUNDLE_SECS: u64 = 480; // 4-12m band midpoint
const FINAL_BUNDLE_SECS: u64 = 480; // 4-12m band midpoint
const SIMULATION_SECS_PER_SLOT: f64 = 0.2;
const SLOTS_PER_PARTITION: u64 = 1000;
/// `end_slot` within ~2 epochs of the latest available data is "recent" (RPC-rate).
const RECENT_WINDOW_SLOTS: u64 = 2 * 432_000;

fn estimate_remaining_secs(
    resp: &BundleBuildStatusResponse,
    ranges: &[AvailableRange],
    now_ms: u64,
) -> u64 {
    let total = estimate_total_secs(resp.start_slot, resp.end_slot, resp.kind, ranges);
    let elapsed = now_ms.saturating_sub(resp.created_at_unix_ms) / 1000;
    total.saturating_sub(elapsed)
}

fn simulation_secs(slots: u64) -> u64 {
    (slots as f64 * SIMULATION_SECS_PER_SLOT) as u64
}

fn estimate_total_secs(start: u64, end: u64, kind: BundleKind, ranges: &[AvailableRange]) -> u64 {
    let snapshot_cached = ranges.iter().any(|r| range_covers(r, start));
    let blocks_cached = ranges
        .iter()
        .any(|r| range_covers(r, start) && range_covers(r, end));

    // Snapshot import and block import run concurrently → phase-2 is the slower;
    // block import grows with the range, so a big cold range can dominate.
    let snapshot_secs = if snapshot_cached {
        0
    } else {
        SNAPSHOT_IMPORT_SECS
    };
    let block_secs = if blocks_cached {
        0
    } else {
        let rate = if is_recent(end, ranges) {
            BLOCK_RATE_RECENT
        } else {
            BLOCK_RATE_HISTORIC
        };
        BLOCK_IMPORT_SPINUP_SECS + (partition_span(start, end) as f64 / rate) as u64
    };
    let phase_two = snapshot_secs.max(block_secs);

    let gap = replay_gap(start, ranges);
    let (interim, simulation) = if gap > 0 {
        (INTERIM_BUNDLE_SECS, simulation_secs(gap))
    } else {
        (0, 0)
    };

    // Recording executes the requested range once more, after the build.
    let recording = match kind {
        BundleKind::Blocks => 0,
        BundleKind::AccountState => simulation_secs(end.saturating_sub(start) + 1),
    };

    ORCHESTRATOR_SPINUP_SECS
        + SNAPSHOT_DISCOVERY_SECS
        + phase_two
        + BUNDLE_BUILD_SPINUP_SECS
        + interim
        + simulation
        + FINAL_BUNDLE_SECS
        + recording
}

fn range_covers(r: &AvailableRange, slot: u64) -> bool {
    r.bundle_start_slot <= slot && r.max_bundle_end_slot.is_some_and(|end| slot <= end)
}

/// `[start, end]` snapped out to 1000-slot partition boundaries.
fn partition_span(start: u64, end: u64) -> u64 {
    let lo = (start / SLOTS_PER_PARTITION) * SLOTS_PER_PARTITION;
    let hi = (end / SLOTS_PER_PARTITION) * SLOTS_PER_PARTITION + (SLOTS_PER_PARTITION - 1);
    hi.saturating_sub(lo) + 1
}

fn is_recent(end: u64, ranges: &[AvailableRange]) -> bool {
    let latest = ranges
        .iter()
        .filter_map(|r| r.max_bundle_end_slot)
        .max()
        .unwrap_or(end);
    latest.saturating_sub(end) <= RECENT_WINDOW_SLOTS
}

/// Slots replayed from the nearest available boundary up to `start`; 0 when a
/// range already covers `start` or nothing anchors below it.
fn replay_gap(start: u64, ranges: &[AvailableRange]) -> u64 {
    if ranges.iter().any(|r| range_covers(r, start)) {
        return 0;
    }
    let anchor = ranges
        .iter()
        .filter_map(|r| r.max_bundle_end_slot)
        .filter(|&end| end <= start)
        .max()
        .or_else(|| {
            ranges
                .iter()
                .map(|r| r.bundle_start_slot)
                .filter(|&s| s <= start)
                .max()
        })
        .unwrap_or(start);
    start.saturating_sub(anchor)
}

fn now_unix_ms() -> u64 {
    chrono::Utc::now().timestamp_millis().max(0) as u64
}

fn format_duration(secs: u64) -> String {
    let (hours, minutes) = (secs / 3600, (secs % 3600) / 60);
    if hours > 0 {
        format!("~{hours}h{minutes:02}m")
    } else {
        format!("~{minutes}m")
    }
}

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

    use super::*;

    #[test]
    fn parses_range_and_flags() {
        let args = BuildBundleArgs::try_parse_from([
            "build-bundle",
            "--start-slot",
            "100",
            "--end-slot",
            "200",
            "--api-key",
            "test-key",
            "--bundle-size",
            "500",
            "--wait",
        ])
        .unwrap();
        assert_eq!(
            (args.bounds.start_slot, args.bounds.end_slot),
            (Some(100), Some(200))
        );
        assert_eq!(args.bundle_size, Some(500));
        assert!(args.wait);
    }

    #[test]
    fn account_state_takes_a_bundle_size() {
        let args = BuildBundleArgs::try_parse_from([
            "build-bundle",
            "--start-slot",
            "100",
            "--end-slot",
            "200",
            "--api-key",
            "test-key",
            "--account-state",
            "--bundle-size",
            "500",
        ])
        .expect("account-state builds accept a bundle size");
        assert!(args.account_state);
        assert_eq!(args.bundle_size, Some(500));
    }

    #[test]
    fn recording_pass_is_added_to_the_eta_for_account_state() {
        // Without it a full-width account-state build reads as hung for hours.
        let (start, end) = (100, 50_099);
        let blocks = estimate_total_secs(start, end, BundleKind::Blocks, &[]);
        let account_state = estimate_total_secs(start, end, BundleKind::AccountState, &[]);
        assert_eq!(account_state - blocks, simulation_secs(end - start + 1));
        assert!(account_state > blocks);
    }

    #[test]
    fn bundle_delete_defaults_to_the_transactions_bundle() {
        let args = BundleDeleteArgs::try_parse_from([
            "bundle-delete",
            "--start-slot",
            "100",
            "--end-slot",
            "200",
            "--api-key",
            "k",
        ])
        .unwrap();
        assert_eq!(args.kind, KindFilter::Transactions);
        assert!(!args.yes);
    }

    #[test]
    fn bundle_delete_takes_a_kind_and_a_confirmation_bypass() {
        let args = BundleDeleteArgs::try_parse_from([
            "bundle-delete",
            "--start-slot",
            "100",
            "--end-slot",
            "200",
            "--api-key",
            "k",
            "--kind",
            "account-state",
            "--yes",
        ])
        .unwrap();
        assert_eq!(
            (args.bounds.start_slot, args.bounds.end_slot),
            (Some(100), Some(200))
        );
        assert_eq!(args.kind, KindFilter::AccountState);
        assert!(args.yes);
    }

    #[test]
    fn build_times_render_as_utc_and_tolerate_a_bad_value() {
        assert_eq!(
            format_unix_ms(1_700_000_000_000).as_deref(),
            Some("2023-11-14 22:13:20")
        );
        assert_eq!(format_unix_ms(i64::MAX), None);
    }

    #[test]
    fn poll_secs_rejects_zero() {
        assert!(
            BuildBundleArgs::try_parse_from([
                "build-bundle",
                "--start-slot",
                "1",
                "--end-slot",
                "2",
                "--api-key",
                "k",
                "--wait",
                "--poll-secs",
                "0",
            ])
            .is_err()
        );
    }

    #[test]
    fn bundle_size_rejects_zero() {
        assert!(
            BuildBundleArgs::try_parse_from([
                "build-bundle",
                "--start-slot",
                "1",
                "--end-slot",
                "2",
                "--api-key",
                "k",
                "--bundle-size",
                "0",
            ])
            .is_err()
        );
    }

    fn range(start: u64, end: u64) -> AvailableRange {
        AvailableRange {
            bundle_start_slot: start,
            max_bundle_end_slot: Some(end),
            max_bundle_size: Some(end - start + 1),
            ..Default::default()
        }
    }

    fn in_progress(start: u64, end: u64, created_at_unix_ms: u64) -> BundleBuildStatusResponse {
        BundleBuildStatusResponse {
            request_id: "req-1".to_string(),
            start_slot: start,
            end_slot: end,
            bundle_size: None,
            status: BundleBuildStatus::InProgress,
            created_at_unix_ms,
            kind: BundleKind::Blocks,
        }
    }

    #[test]
    fn formats_status_with_default_size() {
        let resp = in_progress(1, 2, now_unix_ms());
        let line = format_status("issued", &resp, &[]);
        assert!(line.contains("req-1"));
        assert!(line.contains("in_progress"));
        assert!(line.contains("size=default"));
        assert!(line.contains(" eta "));
    }

    #[test]
    fn formats_status_naming_either_kind() {
        let blocks = format_status("issued", &in_progress(1, 2, now_unix_ms()), &[]);
        assert!(blocks.contains("kind=transactions"), "{blocks}");

        let mut resp = in_progress(1, 2, now_unix_ms());
        resp.kind = BundleKind::AccountState;
        let account_state = format_status("issued", &resp, &[]);
        assert!(
            account_state.contains("kind=account_state"),
            "{account_state}"
        );
    }

    #[test]
    fn cached_range_is_cheaper_than_cold() {
        let covered = [range(0, 2_000_000)];
        let warm = estimate_total_secs(1_000_000, 1_100_000, BundleKind::Blocks, &covered);
        let cold = estimate_total_secs(1_000_000, 1_100_000, BundleKind::Blocks, &[]);
        assert!(warm < cold, "warm {warm} should be < cold {cold}");
    }

    #[test]
    fn block_import_dominates_for_big_cold_range() {
        let (start, end) = (1_000_000, 3_000_000); // 2M slots, uncovered
        // With no ranges the build counts as recent (slow 45 blk/s), so the block
        // path far exceeds the snapshot import — phase-2 must take the block path.
        let block_path = BLOCK_IMPORT_SPINUP_SECS
            + (partition_span(start, end) as f64 / BLOCK_RATE_RECENT) as u64;
        assert!(block_path > SNAPSHOT_IMPORT_SECS);
        assert!(estimate_total_secs(start, end, BundleKind::Blocks, &[]) >= block_path);
    }

    #[test]
    fn countdown_decreases_and_floors_at_zero() {
        let t0 = 1_000_000_000_000;
        let resp = in_progress(1_000_000, 1_100_000, t0);
        let r0 = estimate_remaining_secs(&resp, &[], t0);
        let r1 = estimate_remaining_secs(&resp, &[], t0 + 60_000);
        assert!(r1 < r0 && r1 + 60 == r0);
        assert_eq!(estimate_remaining_secs(&resp, &[], t0 + 10_000_000_000), 0);
    }

    #[test]
    fn recent_is_pricier_than_historic() {
        // A high "latest" marker that covers neither build window.
        let latest = [range(20_000_000, 21_000_000)];
        let recent = estimate_total_secs(21_200_000, 21_300_000, BundleKind::Blocks, &latest); // near latest -> 45 blk/s
        let historic = estimate_total_secs(1_000_000, 1_100_000, BundleKind::Blocks, &latest); // far below -> 130 blk/s
        assert!(recent > historic);
    }
}