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
use std::{num::NonZeroU64, time::Duration};

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

const BUILD_EXAMPLES: &str = "\
Examples:
  # Build slots 380000000-380099999 as ten 10,000-slot bundles, and wait.
  sim bundle build --start-slot 380000000 --end-slot 380099999 \\
    --bundle-size 10000 --wait

  # Also record account-state bundles, so each bundle can be replayed by its
  # own `sim run --replay-account-state` session.
  sim bundle build --start-slot 380000000 --end-slot 380099999 \\
    --bundle-size 10000 --account-state

  # Build a bundle of the slots right after the latest snapshot.
  sim bundle build --latest --bundle-size 10000

  # Follow a build submitted without --wait, or list recent builds.
  sim bundle status <job-id>
  sim bundle list --limit 10";

const DELETE_EXAMPLES: &str = "\
Examples:
  # Delete a transactions bundle, asking for confirmation first.
  sim bundle delete --start-slot 380000000 --end-slot 380009999

  # Delete the matching account-state bundle without a prompt.
  sim bundle delete --start-slot 380000000 --end-slot 380009999 \\
    --kind account-state --yes";

#[derive(Parser, Debug)]
#[command(after_help = BUILD_EXAMPLES)]
pub struct BundleBuildArgs {
    #[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)]
    pub bundle_size: Option<NonZeroU64>,

    /// 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>,

    /// Wait until the build finishes instead of returning once it is submitted.
    /// Exits with status 1 when the build fails.
    #[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,
}

/// The `size` slots right after `snapshot_slot`; the server reads `end_slot` as inclusive.
const fn latest_bounds(snapshot_slot: u64, size: NonZeroU64) -> (u64, u64) {
    let start = snapshot_slot + 1;
    (start, start + size.get() - 1)
}

pub async fn build_bundle(args: BundleBuildArgs, 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
    {
        latest_bounds(client.get_latest_snapshot_slot().await?.snapshot_slot, 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.map(NonZeroU64::get),
            idempotency_key: args.idempotency_key,
            kind: if args.account_state {
                BundleKind::AccountState
            } else {
                BundleKind::Blocks
            },
        })
        .await?;
    if !args.output.json {
        println!("{}", format_status("issued", &resp));
    }

    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));
            }
        }
    }

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

fn check_build(request_id: &str, status: BundleBuildStatus) -> Result<()> {
    match status {
        BundleBuildStatus::Completed | BundleBuildStatus::InProgress => Ok(()),
        BundleBuildStatus::Failed => Err(eyre::eyre!("bundle build {request_id} failed")),
        BundleBuildStatus::NeedsInvestigation => Err(eyre::eyre!(
            "bundle build {request_id} needs investigation: its outcome is unknown, so don't \
             assume it succeeded"
        )),
    }
}

#[derive(Parser, Debug)]
pub struct BundleStatusArgs {
    /// The job ID returned by `sim bundle build`.
    #[arg(value_name = "JOB_ID")]
    pub request_id: String,

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

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

pub async fn get_status(args: BundleStatusArgs, 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 {
        println!("{}", format_status("status", &resp));
    }
    Ok(())
}

#[derive(Parser, Debug)]
pub struct BundleListArgs {
    /// 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: BundleListArgs, 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");
        for build in &resp.builds {
            println!("{}", format_status("build", build));
        }
    }

    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,
                    bundle.start_slot,
                    bundle.end_slot,
                    bundle
                        .completed_at_unix_ms
                        .and_then(format_unix_ms)
                        .unwrap_or_else(|| "-".to_string()),
                );
            }
        }
    }
    Ok(())
}

#[derive(Parser, Debug)]
#[command(after_help = DELETE_EXAMPLES)]
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.
pub(crate) 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) -> String {
    let size = resp
        .bundle_size
        .map_or_else(|| "default".to_string(), |s| s.to_string());

    let eta = match resp.eta_secs {
        Some(0) => "finishing up".to_string(),
        Some(secs) => format_duration(secs),
        None => "-".to_string(),
    };
    let kind = resp.kind;
    format!(
        "id={}: {label}=[{}]\nslots={}..{} size={size} kind={kind} (eta {eta})",
        resp.request_id,
        resp.status.as_str(),
        resp.start_slot,
        resp.end_slot,
    )
}

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 = BundleBuildArgs::try_parse_from([
            "bundle-build",
            "--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, NonZeroU64::new(500));
        assert!(args.wait);
    }

    #[test]
    fn account_state_takes_a_bundle_size() {
        let args = BundleBuildArgs::try_parse_from([
            "bundle-build",
            "--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, NonZeroU64::new(500));
    }

    #[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!(
            BundleBuildArgs::try_parse_from([
                "bundle-build",
                "--start-slot",
                "1",
                "--end-slot",
                "2",
                "--api-key",
                "k",
                "--wait",
                "--poll-secs",
                "0",
            ])
            .is_err()
        );
    }

    #[test]
    fn latest_bounds_cover_exactly_bundle_size_slots() {
        assert_eq!(
            latest_bounds(1_000, NonZeroU64::new(500).unwrap()),
            (1_001, 1_500)
        );
        assert_eq!(latest_bounds(1_000, NonZeroU64::MIN), (1_001, 1_001));
    }

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

    fn in_progress(start: u64, end: u64, eta_secs: Option<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: 0,
            kind: BundleKind::Blocks,
            eta_secs,
        }
    }

    #[test]
    fn formats_status_with_default_size_and_the_servers_eta() {
        let line = format_status("issued", &in_progress(1, 2, Some(3_900)));
        assert!(line.contains("req-1"));
        assert!(line.contains("in_progress"));
        assert!(line.contains("size=default"));
        assert!(line.contains("eta 1h 05m"), "{line}");
    }

    #[test]
    fn a_status_without_a_server_eta_renders_without_one() {
        let line = format_status("issued", &in_progress(1, 2, None));
        assert!(line.contains("eta -"), "{line}");

        let finishing = format_status("issued", &in_progress(1, 2, Some(0)));
        assert!(finishing.contains("eta finishing up"), "{finishing}");
    }

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

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