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

use clap::Parser;
use eyre::Result;
use sim_cli::{
    ApiKeyArg,
    args::{JsonOutputArgs, SlotBoundsArgs},
};
use simulator_api::{
    AvailableRange, BundleBuildRequest, BundleBuildStatus, BundleBuildStatusResponse, BundleKind,
};
use simulator_client::BacktestClient;

#[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 use the pipeline default of 50,000 slots.
    #[arg(long, value_parser = clap::value_parser!(u64).range(1..))]
    pub bundle_size: Option<u64>,

    /// Also record an account-state bundle covering exactly this range, which
    /// `sim run --replay-account-state` can then replay instead of executing
    /// the range. Adds a full execution pass, so it roughly doubles the build;
    /// incompatible with `--bundle-size`.
    ///
    /// Replay resolves the bundle by exact range, so run with the same
    /// `--start-slot`/`--end-slot` used here.
    #[arg(long, conflicts_with = "bundle_size")]
    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 = BacktestClient::builder()
        .url(url)
        .api_key(args.api_key.get())
        .build();

    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 = BacktestClient::builder()
        .url(url)
        .api_key(args.api_key.get())
        .build();
    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 = BacktestClient::builder()
        .url(url)
        .api_key(args.api_key.get())
        .build();
    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!("no bundle builds for this api key");
        return Ok(());
    }
    let ranges = client.available_ranges().await.unwrap_or_default();
    for build in &resp.builds {
        println!("{}", format_status("build", build, &ranges));
    }
    Ok(())
}

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(),
    };
    // Spelled for the reader, not the wire: `blocks` names the artifact rather
    // than what it holds, and `BundleKind::as_str` remains the stored value.
    let kind = match resp.kind {
        BundleKind::Blocks => "transactions",
        BundleKind::AccountState => "account_state",
    };
    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_conflicts_with_bundle_size() {
        // The server rejects a series for account-state; catch it locally.
        assert!(
            BuildBundleArgs::try_parse_from([
                "build-bundle",
                "--start-slot",
                "100",
                "--end-slot",
                "200",
                "--api-key",
                "test-key",
                "--account-state",
                "--bundle-size",
                "500",
            ])
            .is_err()
        );
    }

    #[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 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,
            bundle_start_slot_utc: None,
            max_bundle_end_slot: Some(end),
            max_bundle_end_slot_utc: None,
            max_bundle_size: Some(end - start + 1),
        }
    }

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