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::spawn_ctrlc_cursor_fix,
};
use simulator_api::{DirectFillParams, MintPair, RerouteAggregators, SwapAggregator};
use simulator_client::{
AvailableRange, BacktestClient, 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 solana_rpc_client::{http_sender::HttpSender, rpc_client::RpcClientConfig};
use tokio_util::sync::CancellationToken;
use tracing::info;
use crate::{
output::{
OutputEvent, RunDiagnostics, 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;
const HTTP_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
const HTTP_POOL_IDLE_TIMEOUT: Duration = Duration::from_secs(30);
type PreloadedPrograms = Vec<(String, Vec<u8>)>;
#[derive(Clone)]
struct SessionInfra {
preloaded_programs: Arc<PreloadedPrograms>,
http_client: reqwest::Client,
}
fn make_rpc_client(rpc_endpoint: &str, http_client: &reqwest::Client) -> RpcClient {
let sender = HttpSender::new_with_client(rpc_endpoint, http_client.clone());
RpcClient::new_sender(sender, RpcClientConfig::default())
}
impl ModificationsProvider for SessionInfra {
fn is_empty(&self) -> bool {
self.preloaded_programs.is_empty()
}
async fn build(
&self,
rpc_endpoint: &str,
) -> Result<BTreeMap<Address, simulator_api::AccountData>> {
if self.preloaded_programs.is_empty() {
return Ok(BTreeMap::new());
}
let rpc = make_rpc_client(rpc_endpoint, &self.http_client);
let mut mods = BTreeMap::new();
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 {
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",
default_value_t = false
)]
pub order_flow: bool,
#[arg(
id = "detect_failed_l1_swaps",
value_name = "DETECT_FAILED_L1_SWAPS",
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_requote",
value_name = "REROUTE_REQUOTE",
long = "reroute-requote",
env = "SIMULATOR_REROUTE_REQUOTE",
default_value_t = true,
action = clap::ArgAction::Set,
requires = "reroute_order_flow"
)]
pub requote: bool,
#[arg(
id = "reroute_circular_arbs",
long = "reroute-circular-arbs",
env = "SIMULATOR_REROUTE_CIRCULAR_ARBS",
requires = "reroute_order_flow"
)]
pub circular_arbs: bool,
#[command(flatten)]
pub direct_fill: DirectFillArgs,
}
#[derive(clap::Args, Debug, Clone)]
pub struct DirectFillArgs {
#[arg(
id = "direct_fill_aggregator",
value_name = "DIRECT_FILL_AGGREGATOR",
long = "direct-fill-aggregator",
env = "SIMULATOR_DIRECT_FILL_AGGREGATOR",
requires = "direct_fill_venue"
)]
pub aggregator: Option<SwapAggregator>,
#[arg(
id = "direct_fill_venue",
value_name = "DIRECT_FILL_VENUE",
long = "direct-fill-venue",
env = "SIMULATOR_DIRECT_FILL_VENUE",
requires = "direct_fill_aggregator",
// A book with no pair admits no hop, so the census would silently read zero.
requires = "direct_fill_pair",
// With neither a re-quote nor a venue the reroute session does nothing.
required_if_eq("reroute_requote", "false")
)]
pub venue: Option<String>,
#[arg(
id = "direct_fill_pair",
value_name = "DIRECT_FILL_PAIR",
long = "direct-fill-pair",
env = "SIMULATOR_DIRECT_FILL_PAIR",
requires = "direct_fill_aggregator"
)]
pub pair: Option<MintPair>,
#[arg(
id = "direct_fill_slippage_bps",
value_name = "DIRECT_FILL_SLIPPAGE_BPS",
long = "direct-fill-slippage-bps",
env = "SIMULATOR_DIRECT_FILL_SLIPPAGE_BPS",
default_value_t = 50,
// A tolerance at a whole unit bounds nothing, so the range stops below it.
value_parser = clap::value_parser!(u16).range(..10_000),
requires = "direct_fill_aggregator"
)]
pub slippage_bps: u16,
}
#[derive(Parser, Debug, Clone)]
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, 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_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,
}
impl DirectFillArgs {
fn params(&self) -> Option<DirectFillParams> {
Some(DirectFillParams {
aggregator: self.aggregator?,
venue: self.venue.clone()?,
pair: self.pair?,
slippage_bps: self.slippage_bps,
})
}
}
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 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(),
);
}
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)
};
Ok((
ranges.map_err(|e| eyre::eyre!("failed to fetch available ranges: {e}"))?,
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() {
"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<_>>()?,
);
let http_client = reqwest::Client::builder()
.timeout(HTTP_REQUEST_TIMEOUT)
.pool_idle_timeout(HTTP_POOL_IDLE_TIMEOUT)
.hickory_dns(true)
.build()
.context("failed to build shared HTTP client")?;
Ok(SessionInfra {
preloaded_programs,
http_client,
})
}
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 default_filter = if args.verbose { "info" } else { "warn" };
tracing_subscriber::fmt()
.with_writer(std::io::stderr)
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(default_filter)),
)
.init();
let mut session_failures: Vec<SessionFailure> = Vec::new();
let mut session_count = 1;
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, args.slot_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 = CreateSession::builder()
.start_slot(args.start_slot())
.end_slot(args.end_slot())
.parallel(true)
.send_summary(args.fail_on_diff || args.reroute.order_flow)
.reroute_order_flow(args.reroute.order_flow)
.detect_failed_l1_swaps(args.reroute.detect_failed_l1_swaps)
.reroute_aggregators(args.reroute.aggregators.clone())
.reroute_circular_arbs(args.reroute.circular_arbs)
.reroute_requote(args.reroute.requote)
.maybe_reroute_direct_fill(args.reroute.direct_fill.params().map(Box::new))
.replay_account_state(args.replay_account_state)
.disconnect_timeout_secs(DISCONNECT_TIMEOUT_SECS)
.capacity_wait_timeout_secs(CREATION_TIMEOUT_SECS)
.maybe_extra_compute_units(args.extra_compute_units)
.build()
.into_request()
.map_err(|e| eyre::eyre!("building parallel create request: {e}"))?;
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(e) => return Err(eyre::eyre!("parallel session create failed: {e}")),
};
if let Some(parallel) = parallel {
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;
} else {
for bar in bars_by_start.values() {
if !bar.is_finished() {
bar.abandon_with_message("cancelled");
}
}
}
} else {
let range = args.slot_range()?;
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() {
eprintln!("\n{} Cancelled by user", style("!").yellow());
let OutputSink { output_tx, .. } = output;
drop(output_tx);
let _ = output_writer_handle.await;
return Ok(());
}
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_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 on-chain 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 {} sub-range(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 sub-ranges that finished",
summary.total_transactions,
);
println!(" Output file : {}", output_file.display());
return Err(eyre::eyre!(
"summary: {} of {} parallel sub-ranges 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,
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(),
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;
session.shutdown().await;
if let Ok(Outcome::Completed {
summary: Some(summary),
..
}) = &outcome
&& 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 Ok(Outcome::Completed {
summary: Some(summary),
..
}) = &outcome
&& let Some(stats) = summary.reroute_stats.as_deref()
{
pb.println(format!(
"{} Reroute: {} detected → {} rerouted → {} simulated → {} succeeded | {} filtered | {} requote-fail",
style("↻").cyan(),
stats.swaps_detected,
stats.swaps_rerouted,
stats.swaps_simulated,
stats.swaps_succeeded,
stats.swaps_filtered,
stats.requote_failures,
));
if stats.direct_fill_matched > 0 {
pb.println(format!(
"{} Direct fill: {} hops matched → {} built | {}",
style("◆").magenta(),
stats.direct_fill_matched,
stats.direct_fill_built,
stats
.direct_fill_rejections
.iter()
.map(|(reason, count)| format!("{reason} {count}"))
.collect::<Vec<_>>()
.join(", "),
));
}
}
outcome
}
#[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<()> {
let advance_count = args.range.advance_count(range.start(), range.end());
let create = CreateSession::builder()
.start_slot(range.start())
.end_slot(range.end())
.send_summary(args.fail_on_diff || args.reroute.order_flow)
.reroute_order_flow(args.reroute.order_flow)
.detect_failed_l1_swaps(args.reroute.detect_failed_l1_swaps)
.reroute_aggregators(args.reroute.aggregators.clone())
.reroute_circular_arbs(args.reroute.circular_arbs)
.reroute_requote(args.reroute.requote)
.maybe_reroute_direct_fill(args.reroute.direct_fill.params().map(Box::new))
.replay_account_state(args.replay_account_state)
.disconnect_timeout_secs(DISCONNECT_TIMEOUT_SECS)
.capacity_wait_timeout_secs(CREATION_TIMEOUT_SECS)
.maybe_extra_compute_units(args.extra_compute_units)
.build()
.into_request()
.map_err(|e| eyre::eyre!("building create request: {e}"))?;
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(());
}
Err(e) => return Err(eyre::eyre!("session create failed: {e}")),
};
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)
}
#[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 (start, end) = session.range();
let range = SlotRange::new_unchecked(start, 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;
const PAIR: &str = "So11111111111111111111111111111111111111112,\
EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
#[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 base = [
"sim",
"run",
"--api-key",
"k",
"--start-slot",
"1",
"--end-slot",
"2",
];
crate::Cli::try_parse_from(base.iter().chain(extra).copied())
}
#[rstest]
#[case::a_venue_with_no_pair(
&["--direct-fill-aggregator", "titan", "--direct-fill-venue", "Tempest"],
ErrorKind::MissingRequiredArgument, "--direct-fill-pair")]
#[case::a_pair_with_no_venue(
&["--direct-fill-pair", PAIR],
ErrorKind::MissingRequiredArgument, "--direct-fill-aggregator")]
#[case::a_tolerance_of_a_whole_unit(
&["--direct-fill-aggregator", "titan", "--direct-fill-venue", "Tempest",
"--direct-fill-pair", PAIR, "--direct-fill-slippage-bps", "10000"],
ErrorKind::ValueValidation, "--direct-fill-slippage-bps")]
#[case::nothing_left_to_ask(
&["--reroute-order-flow", "--reroute-requote", "false"],
ErrorKind::MissingRequiredArgument, "--direct-fill-venue")]
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}");
}
#[rstest]
#[case::a_complete_direct_fill(&[
"--reroute-order-flow", "--reroute-requote", "false",
"--direct-fill-aggregator", "titan", "--direct-fill-venue", "Tempest",
"--direct-fill-pair", PAIR,
])]
#[case::a_run_that_never_mentions_reroute(&[])]
fn the_parser_accepts(#[case] extra: &[&str]) {
assert!(
parse(extra).is_ok(),
"{:?}",
parse(extra).err().map(|e| e.to_string())
);
}
#[test]
fn grouping_the_knobs_left_the_flag_surface_alone() {
use clap::Parser;
let cli = crate::Cli::try_parse_from([
"sim",
"run",
"--api-key",
"k",
"--start-slot",
"1",
"--end-slot",
"2",
"--reroute-order-flow",
"--detect-failed-l1-swaps",
"true",
"--reroute-aggregators",
"titan",
"--reroute-requote",
"false",
"--reroute-circular-arbs",
"--direct-fill-aggregator",
"titan",
"--direct-fill-venue",
"Tempest",
"--direct-fill-pair",
PAIR,
"--direct-fill-slippage-bps",
"25",
])
.expect("the grouped flags parse under the names they had when loose");
let crate::Command::Run(args) = cli.command else {
panic!("the run subcommand");
};
assert!(args.reroute.order_flow);
assert!(args.reroute.detect_failed_l1_swaps);
assert!(args.reroute.circular_arbs);
assert!(!args.reroute.requote, "--reroute-requote takes a value");
let fill = args
.reroute
.direct_fill
.params()
.expect("the aggregator and venue name a direct fill");
assert_eq!(fill.venue, "Tempest");
assert_eq!(fill.slippage_bps, 25);
}
#[test]
fn requoting_stays_on_unless_a_run_turns_it_off() {
use clap::Parser;
let cli = crate::Cli::try_parse_from([
"sim",
"run",
"--api-key",
"k",
"--start-slot",
"1",
"--end-slot",
"2",
])
.expect("a run that never mentions reroute still parses");
let crate::Command::Run(args) = cli.command else {
panic!("the run subcommand");
};
assert!(args.reroute.requote);
assert!(!args.reroute.order_flow, "and asks for nothing on its own");
}
}