use std::{
collections::{BTreeMap, HashMap},
path::{Path, PathBuf},
sync::{
Arc, Mutex,
atomic::{AtomicBool, Ordering},
},
time::Duration,
};
use clap::Parser;
use console::style;
use eyre::{Context, Result};
use indicatif::{MultiProgress, ProgressBar};
use sim_cli::{
ApiKeyArg,
args::SimRangeArgs,
engine::{
self, DrivableSession, ModificationsProvider, Outcome, SessionFailure, SessionObserver,
SlotRange, format_slot,
},
signals::{Interrupted, spawn_ctrlc_cursor_fix},
};
use simulator_api::{
AccountModifications, CreateBacktestSessionRequest, REROUTE_DATASET_RETENTION_DAYS,
RerouteAggregators, RerouteScopes, VenueTemplate, VenueTemplateReport,
session_name::SessionName,
};
use simulator_client::{
AvailableRange, BacktestClient, BacktestClientError, BundleKind, CreateSession,
backtest_ws_url,
managed::{
ManagedBacktestSession, ManagedEvent, ManagedParallelSession, ManagedSessionError,
ParallelSubSession, ReconnectCoordinator, StartSessionParams, SubscriptionDiagnostics,
},
modify_program_via_rpc, split_range,
};
use solana_address::Address;
use solana_client::nonblocking::rpc_client::RpcClient;
use tokio_util::sync::CancellationToken;
use tracing::info;
use crate::{
output::{
OutputEvent, RunDiagnostics, SessionCompletedRecord, SessionStartedRecord,
SimulationMetadata, SimulationSummary,
},
subscription::{RecordsStore, on_account_diff_notification, on_transaction_notification},
};
const MAX_PARALLEL_SESSIONS: usize = 50;
const CREATION_TIMEOUT_SECS: u16 = 900;
const DISCONNECT_TIMEOUT_SECS: u16 = 180;
const ESTIMATED_MS_PER_BLOCK: u64 = 250;
type PreloadedPrograms = Vec<(String, Vec<u8>)>;
#[derive(Clone)]
struct SessionInfra {
preloaded_programs: Arc<PreloadedPrograms>,
account_overrides: Arc<AccountModifications>,
}
impl ModificationsProvider for SessionInfra {
fn is_empty(&self) -> bool {
self.preloaded_programs.is_empty() && self.account_overrides.0.is_empty()
}
async fn build(
&self,
rpc: &RpcClient,
) -> Result<BTreeMap<Address, simulator_api::AccountData>> {
let mut mods = self.account_overrides.0.clone();
for (id, elf) in self.preloaded_programs.iter() {
let m = modify_program_via_rpc(rpc, id, elf)
.await
.map_err(|e| eyre::eyre!("building program injection for {id}: {e}"))?;
mods.extend(m);
}
Ok(mods)
}
}
#[derive(Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum SubscriptionType {
#[value(hide = true)]
Logs,
AccountDiff,
Transaction,
}
#[derive(Clone)]
struct OutputSink {
records: RecordsStore,
client_diagnostics: Arc<SubscriptionDiagnostics>,
output_tx: tokio::sync::mpsc::UnboundedSender<OutputEvent>,
}
impl SessionObserver for OutputSink {
fn on_data_event(&self, event: ManagedEvent) {
match event {
ManagedEvent::Transaction(notification) => {
on_transaction_notification(&self.records, &self.output_tx, *notification)
}
ManagedEvent::AccountDiff(notification) => {
on_account_diff_notification(&self.records, &self.output_tx, notification)
}
_ => {}
}
}
}
#[derive(clap::Args, Debug, Clone)]
pub struct RerouteArgs {
#[arg(
id = "reroute_order_flow",
long = "reroute-order-flow",
env = "SIMULATOR_REROUTE_ORDER_FLOW",
value_name = "MODE",
value_enum,
value_delimiter = ',',
num_args = 0..=1,
default_missing_value = "router",
requires_if("venue", "venue_templates")
)]
pub order_flow: Vec<RerouteMode>,
#[arg(
id = "detect_failed_l1_swaps",
value_name = "BOOL",
long = "detect-failed-l1-swaps",
env = "SIMULATOR_DETECT_FAILED_L1_SWAPS",
action = clap::ArgAction::Set,
default_value_t = false
)]
pub detect_failed_l1_swaps: bool,
#[arg(
id = "reroute_aggregators",
value_name = "REROUTE_AGGREGATORS",
long = "reroute-aggregators",
env = "SIMULATOR_REROUTE_AGGREGATORS",
default_value_t = RerouteAggregators::default()
)]
pub aggregators: RerouteAggregators,
#[arg(
id = "reroute_scopes",
value_name = "REROUTE_SCOPES",
long = "reroute-scopes",
env = "SIMULATOR_REROUTE_SCOPES",
default_value_t = RerouteScopes::default()
)]
pub scopes: RerouteScopes,
#[arg(
id = "reroute_circular_arbs",
long = "reroute-circular-arbs",
env = "SIMULATOR_REROUTE_CIRCULAR_ARBS",
requires = "reroute_order_flow"
)]
pub circular_arbs: bool,
#[arg(
id = "reroute_extra_markets",
long = "reroute-extra-markets",
env = "SIMULATOR_REROUTE_EXTRA_MARKETS",
value_name = "POOL",
value_delimiter = ',',
requires = "reroute_order_flow"
)]
pub extra_markets: Vec<Address>,
#[command(flatten)]
pub venue: VenueArgs,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum RerouteMode {
Router,
Venue,
}
impl RerouteArgs {
fn enabled(&self) -> bool {
!self.order_flow.is_empty()
}
fn selects(&self, mode: RerouteMode) -> bool {
self.order_flow.contains(&mode)
}
}
#[derive(Debug, Clone)]
pub struct VenueTemplatesFile(Vec<VenueTemplate>);
#[derive(clap::Args, Debug, Clone)]
pub struct VenueArgs {
#[arg(
id = "venue_templates",
long = "venue-templates",
value_name = "FILE",
env = "SIMULATOR_VENUE_TEMPLATES",
value_parser = venue_templates_from_file,
requires = "reroute_order_flow"
)]
pub templates: Option<VenueTemplatesFile>,
}
const RUN_EXAMPLES: &str = "\
Examples:
# Baseline run: record a program's transactions over a slot range
sim run --start-slot <START_SLOT> --end-slot <END_SLOT> --program-id <PROGRAM_ID>
# Override a program with a new program binary and collect its transactions
sim run --start-slot <START_SLOT> --end-slot <END_SLOT> \\
--program-id <PROGRAM_ID> --program-so ./target/deploy/program.so
# Split a longer range across parallel sessions
sim run --start-slot <START_SLOT> --end-slot <END_SLOT> --parallel \\
--program-id <PROGRAM_ID>
# Replace account states from a file before the range runs
sim run --start-slot <START_SLOT> --end-slot <END_SLOT> \\
--program-id <PROGRAM_ID> --account-overrides ./accounts.json
# Reroute aggregator swaps through the router
sim run --start-slot <START_SLOT> --end-slot <END_SLOT> \\
--program-id <PROGRAM_ID> --reroute-order-flow
# Reroute swaps directly to your own venue
sim run --start-slot <START_SLOT> --end-slot <END_SLOT> \\
--program-id <PROGRAM_ID> --reroute-order-flow venue \\
--venue-templates ./templates.json
# Replay recorded account state (see `sim bundle build --account-state`)
sim run --start-slot <START_SLOT> --end-slot <END_SLOT> \\
--program-id <PROGRAM_ID> --replay-account-state
# In CI: fail if any simulated outcome differs from the onchain outcome
sim run --start-slot <START_SLOT> --end-slot <END_SLOT> \\
--program-id <PROGRAM_ID> --fail-on-diff
Take <START_SLOT> and <END_SLOT> from `sim ranges`.";
#[derive(Parser, Debug, Clone)]
#[command(after_help = RUN_EXAMPLES)]
pub struct RunArgs {
#[command(flatten)]
pub api_key: ApiKeyArg,
#[command(flatten)]
pub range: SimRangeArgs,
#[arg(long, env = "SIMULATOR_PARALLEL", default_value_t = false)]
pub parallel: bool,
#[arg(long)]
pub name: Option<SessionName>,
#[arg(long, env = "SIMULATOR_FAIL_ON_DIFF", default_value_t = false)]
pub fail_on_diff: bool,
#[arg(long, env = "SIMULATOR_PROGRAM_ID")]
pub program_id: Vec<Address>,
#[arg(long, env = "SIMULATOR_PROGRAM_SO")]
pub program_so: Vec<PathBuf>,
#[arg(
long,
env = "SIMULATOR_ACCOUNT_OVERRIDES",
value_name = "FILE",
value_parser = account_overrides_from_file
)]
pub account_overrides: Option<AccountModifications>,
#[arg(long, env = "SIMULATOR_OUTPUT_FILE")]
pub output_file: Option<PathBuf>,
#[arg(long, env = "SIMULATOR_EXTRA_COMPUTE_UNITS")]
pub extra_compute_units: Option<u32>,
#[arg(long, env = "SIMULATOR_SUBSCRIPTION", requires = "program_id")]
pub subscription: Option<SubscriptionType>,
#[arg(long, default_value_t = false)]
pub verbose: bool,
#[arg(long, env = "SIMULATOR_PLAN", default_value_t = false)]
pub plan: bool,
#[command(flatten)]
pub reroute: RerouteArgs,
#[arg(
long,
env = "SIMULATOR_REPLAY_ACCOUNT_STATE",
default_value_t = false,
conflicts_with = "extra_compute_units"
)]
pub replay_account_state: bool,
}
fn venue_templates_from_file(path: &str) -> Result<VenueTemplatesFile, String> {
let raw = std::fs::read_to_string(path).map_err(|error| format!("reading {path}: {error}"))?;
simulator_client::recipes::parse_templates(path, &raw).map(VenueTemplatesFile)
}
fn account_overrides_from_file(path: &str) -> Result<AccountModifications, String> {
let raw = std::fs::read_to_string(path).map_err(|error| format!("reading {path}: {error}"))?;
let overrides: AccountModifications =
serde_json::from_str(&raw).map_err(|error| format!("parsing {path}: {error}"))?;
if overrides.0.is_empty() {
return Err(format!("{path}: names no accounts"));
}
simulator_api::decode_account_modifications(&overrides)
.map_err(|error| format!("{path}: {error}"))?;
Ok(overrides)
}
impl VenueArgs {
fn templates(&self) -> Vec<VenueTemplate> {
self.templates
.as_ref()
.map(|file| file.0.clone())
.unwrap_or_default()
}
}
impl RunArgs {
fn start_slot(&self) -> u64 {
self.range
.bounds
.start_slot
.expect("range bounds validated in validate_args")
}
fn slot_range(&self) -> Result<SlotRange> {
SlotRange::new(self.start_slot(), self.end_slot()).map_err(Into::into)
}
fn end_slot(&self) -> u64 {
self.range
.bounds
.end_slot
.expect("range bounds validated in validate_args")
}
fn with_account_overrides(&self, create: CreateSession) -> CreateSession {
match &self.account_overrides {
Some(overrides) if self.reroute.enabled() => {
let start_slot = create.start_slot;
create.add_override(start_slot, overrides.clone())
}
_ => create,
}
}
fn create_request(&self, range: SlotRange) -> Result<CreateBacktestSessionRequest> {
let create = CreateSession::builder()
.start_slot(range.start())
.end_slot(range.end())
.parallel(self.parallel)
.maybe_name(self.name.clone())
.send_summary(self.fail_on_diff || self.reroute.enabled())
.reroute_order_flow(self.reroute.enabled())
.detect_failed_l1_swaps(self.reroute.detect_failed_l1_swaps)
.reroute_aggregators(self.reroute.aggregators.clone())
.reroute_scopes(self.reroute.scopes.clone())
.reroute_circular_arbs(self.reroute.circular_arbs)
.reroute_requote(self.reroute.selects(RerouteMode::Router))
.reroute_venue_templates(self.reroute.venue.templates())
.reroute_extra_markets(self.reroute.extra_markets.iter().copied().collect())
.replay_account_state(self.replay_account_state)
.disconnect_timeout_secs(DISCONNECT_TIMEOUT_SECS)
.capacity_wait_timeout_secs(CREATION_TIMEOUT_SECS)
.maybe_extra_compute_units(self.extra_compute_units)
.build();
self.with_account_overrides(create)
.into_request()
.wrap_err("building create request")
}
}
fn validate_args(args: &RunArgs) -> Result<()> {
args.range.bounds.require()?;
if !args.program_so.is_empty() {
eyre::ensure!(
args.program_so.len() == args.program_id.len(),
"--program-so count ({}) must match --program-id count ({})",
args.program_so.len(),
args.program_id.len(),
);
}
eyre::ensure!(
args.reroute.venue.templates.is_none() || args.reroute.selects(RerouteMode::Venue),
"--venue-templates is only read under --reroute-order-flow venue",
);
eyre::ensure!(
args.reroute.extra_markets.is_empty() || args.reroute.selects(RerouteMode::Router),
"--reroute-extra-markets is only read under --reroute-order-flow router",
);
Ok(())
}
async fn split_inputs(
client: &BacktestClient,
replay_account_state: bool,
) -> Result<(Vec<AvailableRange>, BundleKind)> {
let (ranges, kind) = if replay_account_state {
(
client.available_ranges_with_account_state().await,
BundleKind::AccountState,
)
} else {
(client.available_ranges().await, BundleKind::Blocks)
};
let ranges = ranges.map_err(|e| match e {
BacktestClientError::HttpStatus { status, .. }
if matches!(
status,
reqwest::StatusCode::UNAUTHORIZED | reqwest::StatusCode::FORBIDDEN
) =>
{
api_key_rejected(status)
}
e => eyre::eyre!("failed to fetch available ranges: {e}"),
})?;
Ok((ranges, kind))
}
async fn generate_plan(client: &BacktestClient, args: &RunArgs) -> Result<()> {
let (ranges, mode) = split_inputs(client, args.replay_account_state).await?;
let sub_ranges = split_range(&ranges, args.slot_range()?, mode)
.map_err(|e| eyre::eyre!("cannot split range: {e}"))?;
if sub_ranges.len() > MAX_PARALLEL_SESSIONS {
eyre::bail!(
"unable to generate plan: requires {} sessions but max is {MAX_PARALLEL_SESSIONS}",
sub_ranges.len(),
);
}
for window in sub_ranges.windows(2) {
let (_, end) = window[0];
let (next_start, _) = window[1];
if end + 1 != next_start {
eyre::bail!(
"unable to generate plan: gap in data between slots {} and {}",
format_slot(end),
format_slot(next_start),
);
}
}
let max_slots = sub_ranges
.iter()
.map(|(start, end)| end.saturating_sub(*start) + 1)
.max()
.unwrap_or(0);
let estimated_ms = max_slots * ESTIMATED_MS_PER_BLOCK;
let estimated = if estimated_ms < 60 * 60 * 1000 {
format!("~{}m", estimated_ms / 60_000)
} else {
format!("~{:.1}h", estimated_ms as f64 / 3_600_000.0)
};
println!(
"\n{} {estimated} runtime · {} session(s)\n{} [{} → {}] · {} slots",
style(">").cyan(),
sub_ranges.len(),
style(">").cyan(),
format_slot(args.start_slot()),
format_slot(args.end_slot()),
format_slot(args.end_slot() - args.start_slot() + 1),
);
println!();
println!(
"{:<5} {:<20} {:<20} {:<15}",
"#", "Start Slot", "End Slot", "Slots"
);
println!("{}", "-".repeat(62));
for (i, (start, end)) in sub_ranges.iter().enumerate() {
let slots = end.saturating_sub(*start) + 1;
println!(
"{:<5} {:<20} {:<20} {:<15}",
i + 1,
format_slot(*start),
format_slot(*end),
format_slot(slots),
);
}
Ok(())
}
fn resolve_output_file(args: &RunArgs) -> PathBuf {
args.output_file.clone().unwrap_or_else(|| {
let suffix = if !args.program_so.is_empty() || args.account_overrides.is_some() {
"override"
} else {
"baseline"
};
PathBuf::from(format!(
"{}_{}_{}.ndjson",
args.start_slot(),
args.end_slot(),
suffix
))
})
}
fn setup_output(
output_file: &Path,
args: &RunArgs,
) -> Result<(OutputSink, tokio::task::JoinHandle<Result<()>>)> {
let output_writer = open_output_writer(output_file)?;
let (output_tx, output_rx) = tokio::sync::mpsc::unbounded_channel::<OutputEvent>();
let output_writer_handle =
spawn_output_writer(output_file.to_path_buf(), output_writer, output_rx);
let metadata = SimulationMetadata {
start_slot: args.start_slot(),
end_slot: args.end_slot(),
program_ids: args.program_id.clone(),
program_so: args
.program_so
.iter()
.map(|p| p.display().to_string())
.collect(),
ran_at_unix_secs: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0),
session_ids: Vec::new(),
};
let _ = output_tx.send(OutputEvent::Metadata(metadata));
let output = OutputSink {
records: RecordsStore::new(),
client_diagnostics: Arc::new(SubscriptionDiagnostics::default()),
output_tx,
};
Ok((output, output_writer_handle))
}
fn build_infra(args: &RunArgs) -> Result<SessionInfra> {
let preloaded_programs: Arc<PreloadedPrograms> = Arc::new(
args.program_id
.iter()
.zip(&args.program_so)
.map(|(id, path)| {
let elf = std::fs::read(path)
.with_context(|| format!("failed to read {}", path.display()))?;
Ok((id.to_string(), elf))
})
.collect::<Result<_>>()?,
);
Ok(SessionInfra {
preloaded_programs,
account_overrides: Arc::new(args.account_overrides.clone().unwrap_or_default()),
})
}
pub async fn run(args: RunArgs, url: String, cancellation: CancellationToken) -> Result<()> {
validate_args(&args)?;
let base_url = backtest_ws_url(&url);
let client = sim_cli::client::new(&base_url, &args.api_key.get());
if args.plan {
return generate_plan(&client, &args).await;
}
let output_file = resolve_output_file(&args);
let (output, output_writer_handle) = setup_output(&output_file, &args)?;
let session_ids: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
let has_deviations = Arc::new(AtomicBool::new(false));
let infra = build_infra(&args)?;
let args = Arc::new(args);
spawn_ctrlc_cursor_fix();
let mut session_failures: Vec<SessionFailure> = Vec::new();
let mut session_count = 1;
let range = args.slot_range()?;
let session_name = if args.parallel {
let progress = MultiProgress::new();
let (ranges, split_mode) = split_inputs(&client, args.replay_account_state).await?;
let sub_ranges = split_range(&ranges, range, split_mode)
.map_err(|e| eyre::eyre!("cannot split range: {e}"))?;
session_count = sub_ranges.len();
info!("splitting into {session_count} parallel session(s)");
let _ = progress.println(format!(
"{} Splitting into {session_count} parallel session(s)",
style(">").cyan(),
));
let mut bars_by_start: HashMap<u64, ProgressBar> = HashMap::new();
for &(start, end) in &sub_ranges {
let bar = if args.verbose {
ProgressBar::hidden()
} else {
let bar = ProgressBar::new(end.saturating_sub(start) + 1);
bar.set_style(engine::spinner_style(start, end));
let bar = progress.add(bar);
bar.enable_steady_tick(Duration::from_millis(100));
bar
};
bars_by_start.insert(start, bar);
}
let create = args.create_request(range)?;
let parallel = match ManagedParallelSession::start_with_params(
StartSessionParams::builder()
.url(base_url.clone())
.api_key(args.api_key.get())
.create(create)
.parent_cancel(cancellation.clone())
.subscription_diagnostics(output.client_diagnostics.clone())
.build(),
)
.await
{
Ok(p) => Some(p),
Err(ManagedSessionError::Cancelled) => None,
Err(ManagedSessionError::ApiKeyRejected(status)) => {
return Err(api_key_rejected(status));
}
Err(e @ ManagedSessionError::Create(_)) => return Err(e.into()),
Err(e) => {
return Err(eyre::Report::new(e).wrap_err("parallel session create failed"));
}
};
if let Some(parallel) = parallel {
let run_name = parallel.control_session_name().map(str::to_owned);
if let Some(name) = &run_name {
progress.suspend(|| print_session_name(name));
}
let bars_by_start = Arc::new(bars_by_start);
let drive = {
let args = args.clone();
let output = output.clone();
let session_ids = session_ids.clone();
let infra = infra.clone();
let bars = bars_by_start.clone();
let has_deviations = has_deviations.clone();
move |session: ParallelSubSession| {
let args = args.clone();
let output = output.clone();
let session_ids = session_ids.clone();
let infra = infra.clone();
let bars = bars.clone();
let has_deviations = has_deviations.clone();
async move {
drive_parallel_sub(
session,
&args,
&bars,
&output,
&session_ids,
&infra,
&has_deviations,
)
.await
}
}
};
session_failures =
engine::run_parallel_sessions(parallel, bars_by_start, None, &cancellation, drive)
.await;
run_name
} else {
for bar in bars_by_start.values() {
if !bar.is_finished() {
bar.abandon_with_message("cancelled");
}
}
None
}
} else {
let bar = if args.verbose {
ProgressBar::hidden()
} else {
let bar = ProgressBar::new(range.end().saturating_sub(range.start()) + 1);
bar.set_style(engine::spinner_style(range.start(), range.end()));
bar.set_message("starting session...");
bar.enable_steady_tick(Duration::from_millis(100));
bar
};
drive_single(
base_url,
args.api_key.get(),
&args,
&bar,
range,
&output,
&session_ids,
&infra,
&cancellation,
None,
&has_deviations,
)
.await
.inspect_err(|e| bar.abandon_with_message(format!("failed: {e:#}")))?
};
if cancellation.is_cancelled() {
let OutputSink { output_tx, .. } = output;
drop(output_tx);
let _ = output_writer_handle.await;
return Err(Interrupted.into());
}
let OutputSink {
records,
client_diagnostics,
output_tx,
} = output;
let session_ids = session_ids.lock().unwrap().clone();
let total = records.total();
let successes = records.successes();
let summary = SimulationSummary {
total_transactions: total,
successes,
failures: total.saturating_sub(successes),
session_name,
session_ids,
diagnostics: Some(RunDiagnostics {
received: records.received(),
dedup_swallowed: records.dedup_swallowed(),
malformed_dropped: records.malformed_dropped(),
reconnects: client_diagnostics.reconnects(),
}),
};
let _ = output_tx.send(OutputEvent::Summary(summary.clone()));
drop(output_tx);
output_writer_handle
.await
.context("output writer task panicked")?
.context("output writer failed")?;
render_outcome(
&session_failures,
session_count,
&summary,
&output_file,
args.replay_account_state,
)?;
if args.fail_on_diff && has_deviations.load(Ordering::SeqCst) {
return Err(eyre::eyre!(
"--fail-on-diff: simulation produced diffs against the onchain outcome"
));
}
Ok(())
}
fn render_outcome(
session_failures: &[SessionFailure],
session_count: usize,
summary: &SimulationSummary,
output_file: &Path,
state_only_replay: bool,
) -> Result<()> {
if !session_failures.is_empty() {
let mut by_reason: BTreeMap<&str, Vec<(u64, u64)>> = BTreeMap::new();
for failure in session_failures {
by_reason
.entry(failure.reason.as_str())
.or_default()
.extend(failure.range);
}
println!(
"\n{} {} of {} session(s) did not complete",
style("✖").red(),
session_failures.len(),
session_count,
);
for (reason, ranges) in &mut by_reason {
ranges.sort_unstable();
let slots = if ranges.is_empty() {
String::new()
} else {
let list = ranges
.iter()
.map(|(s, e)| format!("{s}–{e}"))
.collect::<Vec<_>>()
.join(", ");
format!(" {}", style(format!("[slots {list}]")).dim())
};
println!(" {}{}", style(reason).yellow(), slots);
}
println!(
"\n Captured {} transaction(s) from the sessions that finished",
summary.total_transactions,
);
println!(" Output file : {}", output_file.display());
return Err(eyre::eyre!(
"summary: {} of {} parallel sessions failed",
session_failures.len(),
session_count,
));
}
if summary.total_transactions == 0 && !state_only_replay {
println!(
"\n{} Simulation finished with no transactions",
style("⚠").yellow()
);
println!(" Output file : {}", output_file.display());
return Err(eyre::eyre!(
"no matching transactions found in the requested slot range"
));
}
println!("\n{} Simulation complete", style("✔").green());
println!(" Transactions : {}", summary.total_transactions);
println!(" Successes : {}", summary.successes);
println!(" Failures : {}", summary.failures);
println!(" Output file : {}", output_file.display());
Ok(())
}
fn record_session_started<S: DrivableSession>(
session: &S,
range: SlotRange,
output: &OutputSink,
session_ids: &Arc<Mutex<Vec<String>>>,
) {
let info = session.session_info();
session_ids
.lock()
.unwrap()
.push(info.session_id.to_string());
info!(
session_id = %info.session_id,
session_name = ?info.session_name,
task_id = ?info.task_id,
start = range.start(),
end = range.end(),
"session created"
);
let _ = output
.output_tx
.send(OutputEvent::SessionStarted(SessionStartedRecord {
session_id: info.session_id.to_string(),
session_name: info.session_name.clone(),
task_id: info.task_id.clone(),
start_slot: range.start(),
end_slot: range.end(),
}));
}
#[allow(clippy::too_many_arguments)]
async fn subscribe_and_drive<S: DrivableSession>(
mut session: S,
args: &RunArgs,
pb: &ProgressBar,
range: SlotRange,
advance_count: u64,
output: &OutputSink,
infra: &SessionInfra,
has_deviations: &AtomicBool,
) -> Result<Outcome> {
pb.set_message("waiting for runtime");
if !args.program_id.is_empty() {
session.subscribe_transactions(args.program_id.clone());
if matches!(args.subscription, Some(SubscriptionType::AccountDiff)) {
session.subscribe_account_diffs(args.program_id.clone());
}
}
let outcome =
engine::run_session_loop(&mut session, pb, range, advance_count, infra, output).await;
let session_id = session.session_info().session_id;
session.shutdown().await;
let Ok(Outcome::Completed {
summary: Some(summary),
..
}) = &outcome
else {
return outcome;
};
let _ = output
.output_tx
.send(OutputEvent::SessionCompleted(SessionCompletedRecord {
session_id,
start_slot: range.start(),
end_slot: range.end(),
summary: summary.clone(),
}));
if summary.has_deviations() {
pb.println(format!(
"{} Diffs detected: {}",
style("✖").red(),
summary.deviation_details("balance diffs", "log diffs"),
));
has_deviations.store(true, Ordering::SeqCst);
}
if let Some(stats) = summary.reroute_stats.as_deref() {
pb.println(format!(
"{} Reroute: {} detected → {} rerouted → {} simulated → {} succeeded | {} filtered | {} reroute-fail",
style("↻").cyan(),
stats.swaps_detected,
stats.swaps_rerouted,
stats.swaps_simulated,
stats.swaps_succeeded,
stats.swaps_filtered,
stats.requote_failures,
));
if !stats.venue_template_reports.is_empty() {
for (label, template) in &stats.venue_template_reports {
pb.println(venue_line(label, template));
}
pb.println(venue_line(
"total",
&VenueTemplateReport {
matched: stats.venue_matched,
outcomes: stats.venue_outcomes.clone(),
scored: stats.venue_scored,
bps_total: stats.venue_bps_total,
},
));
}
if let Some(uri) = &stats.dataset_uri {
pb.println(format!(
"{} Reroute tables: {uri} (published once the session shuts down, kept \
{REROUTE_DATASET_RETENTION_DAYS} days)",
style("↻").cyan(),
));
}
}
outcome
}
fn venue_line(label: &str, report: &VenueTemplateReport) -> String {
let VenueTemplateReport {
matched,
outcomes,
scored,
bps_total,
} = report;
let outcomes = match outcomes.is_empty() {
true => "(none)".to_owned(),
false => outcomes
.iter()
.map(|(outcome, n)| format!("{outcome} {n}"))
.collect::<Vec<_>>()
.join(", "),
};
let mean_bps = match *scored {
0 => "—".to_owned(),
scored => format!("{:+.1}", *bps_total as f64 / scored as f64),
};
format!(
"{} Venue probe: {label}: {matched} matched → {outcomes} | {scored} scored, {mean_bps} bps",
style("◆").magenta()
)
}
fn print_session_name(name: &str) {
eprintln!("{} Session name: {}", style(">").cyan(), style(name).bold());
}
fn api_key_rejected(status: reqwest::StatusCode) -> eyre::Report {
eyre::eyre!(
"the server rejected the API key (HTTP {status}); check SIMULATOR_API_KEY or --api-key"
)
}
#[allow(clippy::too_many_arguments)]
async fn drive_single(
base_url: String,
api_key: String,
args: &RunArgs,
pb: &ProgressBar,
range: SlotRange,
output: &OutputSink,
session_ids: &Arc<Mutex<Vec<String>>>,
infra: &SessionInfra,
parent_cancel: &CancellationToken,
reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
has_deviations: &AtomicBool,
) -> Result<Option<String>> {
let advance_count = args.range.advance_count(range.start(), range.end());
let create = args.create_request(range)?;
let session = match ManagedBacktestSession::start_with_params(
StartSessionParams::builder()
.url(base_url)
.api_key(api_key)
.create(create)
.parent_cancel(parent_cancel.clone())
.subscription_diagnostics(output.client_diagnostics.clone())
.build(),
reconnect_coordinator,
)
.await
{
Ok(s) => s,
Err(ManagedSessionError::Cancelled) => {
pb.abandon_with_message("cancelled");
return Ok(None);
}
Err(ManagedSessionError::ApiKeyRejected(status)) => return Err(api_key_rejected(status)),
Err(e @ ManagedSessionError::Create(_)) => return Err(e.into()),
Err(e) => return Err(eyre::Report::new(e).wrap_err("session create failed")),
};
let session_name = session.session_info().session_name.clone();
if let Some(name) = &session_name {
pb.suspend(|| print_session_name(name));
}
record_session_started(&session, range, output, session_ids);
let outcome = subscribe_and_drive(
session,
args,
pb,
range,
advance_count,
output,
infra,
has_deviations,
)
.await;
engine::finish_bar(pb, outcome).map(|()| session_name)
}
#[allow(clippy::too_many_arguments)]
async fn drive_parallel_sub(
session: ParallelSubSession,
args: &RunArgs,
bars: &HashMap<u64, ProgressBar>,
output: &OutputSink,
session_ids: &Arc<Mutex<Vec<String>>>,
infra: &SessionInfra,
has_deviations: &AtomicBool,
) -> std::result::Result<(), SessionFailure> {
let range = session.range();
let (start, end) = (range.start(), range.end());
let pb = bars
.get(&start)
.cloned()
.unwrap_or_else(ProgressBar::hidden);
let advance_count = args.range.advance_count(start, end);
record_session_started(&session, range, output, session_ids);
let outcome = subscribe_and_drive(
session,
args,
&pb,
range,
advance_count,
output,
infra,
has_deviations,
)
.await;
engine::finish_bar(&pb, outcome).map_err(|e| SessionFailure {
range: Some((start, end)),
reason: format!("{e:#}"),
})
}
fn open_output_writer(path: &std::path::Path) -> Result<std::fs::File> {
if let Some(parent) = path.parent()
&& !parent.as_os_str().is_empty()
&& !parent.exists()
{
std::fs::create_dir_all(parent)
.with_context(|| format!("could not create output directory '{}'", parent.display()))?;
}
std::fs::File::create(path).with_context(|| format!("could not create '{}'", path.display()))
}
fn spawn_output_writer(
path: PathBuf,
file: std::fs::File,
mut rx: tokio::sync::mpsc::UnboundedReceiver<OutputEvent>,
) -> tokio::task::JoinHandle<Result<()>> {
tokio::spawn(async move {
use std::io::Write;
let write_err = || format!("could not write to '{}'", path.display());
let mut writer = std::io::BufWriter::new(file);
while let Some(event) = rx.recv().await {
serde_json::to_writer(&mut writer, &event).with_context(write_err)?;
writer.write_all(b"\n").with_context(write_err)?;
while let Ok(event) = rx.try_recv() {
serde_json::to_writer(&mut writer, &event).with_context(write_err)?;
writer.write_all(b"\n").with_context(write_err)?;
}
writer.flush().with_context(write_err)?;
}
writer
.flush()
.with_context(|| format!("could not finalize '{}'", path.display()))?;
Ok(())
})
}
#[cfg(test)]
mod cli_tests {
use clap::{CommandFactory, error::ErrorKind};
use rstest::rstest;
use super::{CreateSession, RerouteMode, SlotRange};
#[test]
fn the_argument_wiring_names_arguments_that_exist() {
crate::Cli::command().debug_assert();
}
fn parse(extra: &[&str]) -> Result<crate::Cli, clap::Error> {
use clap::Parser;
let dir = tempfile::tempdir().expect("a temp dir");
let file = template_file(dir.path(), &[TEMPLATE]);
let overrides = overrides_file(dir.path(), &overrides_json(TOKEN_PROGRAM, false, "AAAA"));
let extra: Vec<String> = extra
.iter()
.map(|arg| match *arg {
"<FILE>" => file.clone(),
"<OVERRIDES>" => overrides.clone(),
arg => arg.to_owned(),
})
.collect();
let base = [
"sim",
"run",
"--api-key",
"k",
"--start-slot",
"1",
"--end-slot",
"2",
];
crate::Cli::try_parse_from(
base.iter()
.map(|arg| (*arg).to_owned())
.chain(extra)
.collect::<Vec<_>>(),
)
}
fn run_args(extra: &[&str]) -> super::RunArgs {
let cli = parse(extra).expect("the flags parse");
let crate::Command::Run { args, .. } = cli.command else {
panic!("the run subcommand");
};
*args
}
#[rstest]
#[case::venue_without_templates(
&["--reroute-order-flow", "venue"],
ErrorKind::MissingRequiredArgument, "--venue-templates")]
#[case::venue_alongside_router_without_templates(
&["--reroute-order-flow", "router,venue"],
ErrorKind::MissingRequiredArgument, "--venue-templates")]
#[case::templates_without_the_feature(
&["--venue-templates", "<FILE>"],
ErrorKind::MissingRequiredArgument, "--reroute-order-flow")]
#[case::an_unknown_mode(
&["--reroute-order-flow", "requote"],
ErrorKind::InvalidValue, "router")]
#[case::extra_markets_without_the_feature(
&["--reroute-extra-markets", POOL],
ErrorKind::MissingRequiredArgument, "--reroute-order-flow")]
#[case::a_pool_that_is_not_an_address(
&["--reroute-order-flow", "--reroute-extra-markets", "not-a-pool"],
ErrorKind::ValueValidation, "--reroute-extra-markets")]
#[case::a_name_with_a_space(
&["--name", "My Run"],
ErrorKind::ValueValidation, "invalid session name 'My Run'")]
fn the_parser_rejects(#[case] extra: &[&str], #[case] kind: ErrorKind, #[case] names: &str) {
let Err(error) = parse(extra) else {
panic!("expected a rejection");
};
assert_eq!(error.kind(), kind);
assert!(error.to_string().contains(names), "{error}");
}
#[test]
fn templates_without_the_venue_mode_are_refused() {
let args = run_args(&[
"--reroute-order-flow",
"router",
"--venue-templates",
"<FILE>",
]);
let error = super::validate_args(&args).expect_err("templates nothing reads");
assert!(error.to_string().contains("--venue-templates"), "{error}");
}
#[test]
fn extra_markets_outside_router_mode_are_refused() {
let error = super::validate_args(&run_args(&[
"--reroute-order-flow",
"venue",
"--venue-templates",
"<FILE>",
"--reroute-extra-markets",
POOL,
]))
.expect_err("refused");
let error = error.to_string();
assert!(
error.contains("--reroute-extra-markets")
&& error.contains("--reroute-order-flow router"),
"{error}"
);
}
#[rstest]
#[case::the_bare_flag(&["--reroute-order-flow"], &[RerouteMode::Router])]
#[case::router(&["--reroute-order-flow", "router"], &[RerouteMode::Router])]
#[case::venue(
&["--reroute-order-flow", "venue", "--venue-templates", "<FILE>"],
&[RerouteMode::Venue])]
#[case::both(
&["--reroute-order-flow", "router,venue", "--venue-templates", "<FILE>"],
&[RerouteMode::Router, RerouteMode::Venue])]
#[case::a_run_that_never_mentions_reroute(&[], &[])]
#[case::router_with_extra_markets_and_overrides(
&["--reroute-order-flow", "--reroute-extra-markets", POOL, "--account-overrides",
"<OVERRIDES>"],
&[RerouteMode::Router])]
#[case::venue_with_overrides(
&["--reroute-order-flow", "venue", "--venue-templates", "<FILE>", "--account-overrides",
"<OVERRIDES>"],
&[RerouteMode::Venue])]
#[case::overrides_without_rerouting(&["--account-overrides", "<OVERRIDES>"], &[])]
#[case::parallel_with_extra_markets_and_overrides(
&["--reroute-order-flow", "--parallel", "--reroute-extra-markets", POOL,
"--account-overrides", "<OVERRIDES>"],
&[RerouteMode::Router])]
fn the_parser_accepts(#[case] extra: &[&str], #[case] modes: &[RerouteMode]) {
let args = run_args(extra);
super::validate_args(&args).expect("a complete reroute request");
assert_eq!(args.reroute.order_flow, modes);
}
#[test]
fn the_grouped_flags_reach_their_fields() {
let args = run_args(&[
"--reroute-order-flow",
"venue",
"--detect-failed-l1-swaps",
"true",
"--reroute-aggregators",
"titan",
"--reroute-scopes",
"nested",
"--reroute-circular-arbs",
"--reroute-extra-markets",
&format!("{POOL},{OVERRIDDEN}"),
"--venue-templates",
"<FILE>",
]);
assert!(args.reroute.enabled());
assert!(!args.reroute.selects(RerouteMode::Router));
assert!(args.reroute.detect_failed_l1_swaps);
assert!(args.reroute.circular_arbs);
assert_eq!(args.reroute.scopes.to_string(), "nested");
assert_eq!(
args.reroute
.extra_markets
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>(),
[POOL, OVERRIDDEN]
);
let templates = args.reroute.venue.templates();
assert_eq!(templates.len(), 1);
assert_eq!(templates[0].label, "t");
assert_eq!(templates[0].mode, simulator_api::SwapMode::ExactIn);
}
const TEMPLATE: &str = r#"{
"label": "t",
"mode": "ExactIn",
"inputMint": "So11111111111111111111111111111111111111112",
"outputMint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
"instruction": {
"programId": "11111111111111111111111111111111",
"accounts": [
{"address": "11111111111111111111111111111111", "writable": true, "signer": true},
{"address": "11111111111111111111111111111111", "writable": true},
{"address": "11111111111111111111111111111111", "writable": true}
],
"data": {"data": "AAAAAAAAAAA=", "encoding": "base64"}
},
"amountOffset": 0,
"taker": {"user": [0], "inputTokenAccount": 1, "outputTokenAccount": 2}
}"#;
const POOL: &str = "So11111111111111111111111111111111111111112";
const OVERRIDDEN: &str = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
const TOKEN_PROGRAM: &str = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
fn overrides_json(owner: &str, executable: bool, data: &str) -> String {
format!(
r#"{{"{OVERRIDDEN}": {{"data": ["{data}", "base64"], "executable": {executable},
"lamports": 1461600, "owner": "{owner}", "rentEpoch": 0, "space": 3}}}}"#
)
}
fn overrides_file(dir: &std::path::Path, contents: &str) -> String {
let path = dir.join("overrides.json");
std::fs::write(&path, contents).expect("writing the file");
path.to_string_lossy().into_owned()
}
fn template_file(dir: &std::path::Path, templates: &[&str]) -> String {
let path = dir.join("venue.json");
std::fs::write(&path, format!("[{}]", templates.join(","))).expect("writing the file");
path.to_string_lossy().into_owned()
}
#[test]
fn an_object_shaped_spec_is_refused_naming_the_file() {
let dir = tempfile::tempdir().expect("a temp dir");
let path = dir.path().join("old-spec.json");
std::fs::write(&path, r#"{"aggregator":"router-a","venue":"venue-a"}"#)
.expect("writing the spec file");
let path = path.to_string_lossy().into_owned();
let error =
super::venue_templates_from_file(&path).expect_err("an object is not a template list");
assert!(
error.contains(&path) && error.contains("expected a sequence"),
"{error}"
);
}
#[rstest]
#[case::duplicate_labels(&[TEMPLATE, TEMPLATE], "appears more than once")]
#[case::no_templates(&[], "names no templates")]
fn a_template_list_is_screened_before_a_session_is_built(
#[case] templates: &[&str],
#[case] reason: &str,
) {
let dir = tempfile::tempdir().expect("a temp dir");
let path = template_file(dir.path(), templates);
let error = super::venue_templates_from_file(&path).expect_err("screened");
assert!(error.contains(&path) && error.contains(reason), "{error}");
}
#[rstest]
#[case::no_accounts("{}", "names no accounts")]
#[case::not_a_map("[]", "parsing")]
#[case::executable(&overrides_json(TOKEN_PROGRAM, true, "AAAA"), "executable/program")]
#[case::program_owned(
&overrides_json("BPFLoaderUpgradeab1e11111111111111111111111", false, "AAAA"),
"executable/program")]
#[case::data_that_is_not_base64(
&overrides_json(TOKEN_PROGRAM, false, "!!"),
"invalid account data")]
fn account_overrides_are_screened_before_a_session_is_built(
#[case] contents: &str,
#[case] reason: &str,
) {
let dir = tempfile::tempdir().expect("a temp dir");
let path = overrides_file(dir.path(), contents);
let error = super::account_overrides_from_file(&path).expect_err("screened");
assert!(error.contains(&path) && error.contains(reason), "{error}");
}
#[rstest]
#[case::single(&[])]
#[case::parallel(&["--parallel"])]
fn the_create_request_carries_the_name(#[case] extra: &[&str]) {
let range = SlotRange::new(7, 9).expect("a range");
let options = run_args(&[&["--name", "My-Run"], extra].concat())
.create_request(range)
.expect("a create request")
.try_into_request_options()
.expect("a valid name");
let name = options.name.map(|requested| requested.name.to_string());
assert_eq!(name.as_deref(), Some("my-run"));
assert_eq!(options.parallel, extra.contains(&"--parallel"));
}
#[test]
fn the_override_file_is_scheduled_at_the_first_slot_for_rerouting() {
let actions = |extra: &[&str]| {
let create = CreateSession::builder().start_slot(7).end_slot(9).build();
run_args(extra).with_account_overrides(create).actions
};
let [action] = actions(&["--reroute-order-flow", "--account-overrides", "<OVERRIDES>"])
.try_into()
.expect("one scheduled action");
assert!(
matches!(&action.anchor, simulator_api::ActionAnchor::BeforeSlot { slots } if slots == &[7]),
"{:?}",
action.anchor
);
assert_eq!(
action
.account_overrides
.0
.keys()
.map(ToString::to_string)
.collect::<Vec<_>>(),
[OVERRIDDEN]
);
assert!(actions(&["--reroute-order-flow"]).is_empty());
assert!(actions(&["--account-overrides", "<OVERRIDES>"]).is_empty());
}
#[test]
fn the_override_file_is_written_with_the_first_continue() {
use super::{ModificationsProvider, RpcClient};
let infra = |extra: &[&str]| super::build_infra(&run_args(extra)).expect("the infra");
assert!(infra(&[]).is_empty());
let with_overrides = infra(&["--account-overrides", "<OVERRIDES>"]);
assert!(!with_overrides.is_empty());
let runtime = tokio::runtime::Runtime::new().expect("a runtime");
let modifications = runtime
.block_on(with_overrides.build(&RpcClient::new("http://unused".to_string())))
.expect("the modifications");
assert_eq!(
modifications
.keys()
.map(ToString::to_string)
.collect::<Vec<_>>(),
[OVERRIDDEN]
);
}
#[rstest]
#[case::never_matched(0, &[], 0, 0, "0 matched → (none) | 0 scored, — bps")]
#[case::scored(3, &[("filled", 2), ("reverted_slippage", 1)], 2, 25, "3 matched → filled 2, reverted_slippage 1 | 2 scored, +12.5 bps")]
fn a_venue_line_renders_matches_outcomes_and_mean_bps(
#[case] matched: u64,
#[case] outcomes: &[(&str, u64)],
#[case] scored: u64,
#[case] bps_total: i64,
#[case] expected: &str,
) {
let report = simulator_api::VenueTemplateReport {
matched,
outcomes: outcomes
.iter()
.map(|(k, n)| ((*k).to_owned(), *n))
.collect(),
scored,
bps_total,
};
let line = console::strip_ansi_codes(&super::venue_line("t", &report)).into_owned();
assert_eq!(line, format!("◆ Venue probe: t: {expected}"));
}
}