simulator_client/managed/session.rs
1use std::{
2 collections::VecDeque,
3 sync::{Arc, OnceLock},
4 time::Duration,
5};
6
7use futures::FutureExt;
8use simulator_api::{
9 BacktestError, BacktestStatus, ContinueParams, ContinueToParams, CreateBacktestSessionRequest,
10 CreateBacktestSessionRequestV1, DiscoveryBatchEvent, PausedEvent, SessionSummary,
11};
12use solana_address::Address;
13use solana_client::nonblocking::rpc_client::RpcClient;
14use solana_commitment_config::CommitmentConfig;
15use solana_transaction_status::EncodedConfirmedTransactionWithStatusMeta;
16use thiserror::Error;
17use tokio::sync::{mpsc, watch};
18use tokio_util::sync::CancellationToken;
19
20use super::{
21 ConnectionStatus, ControlEvent, ControlHandle, DEFAULT_DISCONNECT_TIMEOUT_SECS,
22 ReconnectCoordinator, SessionInfo, StartSessionParams, SubscriptionDiagnostics,
23 SubscriptionHandle, SubscriptionNotification, spawn_account_diff_subscription_manager,
24 spawn_action_subscription_manager, spawn_control_manager,
25 spawn_diagnostic_subscription_manager, spawn_replacement_subscription_manager,
26 spawn_transaction_subscription_manager,
27};
28use crate::subscriptions::{
29 AccountDiffNotification, ActionResultNotification, DiagnosticNotification,
30 ReplacementNotification,
31};
32
33/// Why `start` could not create a managed session; carried by [`ManagedSessionError::Create`].
34#[derive(Debug, Error)]
35pub enum CreateError {
36 /// The server refused the create request. Retry later when
37 /// [`BacktestError::is_retryable`] is true, as for insufficient capacity
38 /// ([`BacktestError::Internal`]). Otherwise fix what the error names.
39 #[error("server rejected the request: {0}")]
40 Rejected(BacktestError),
41
42 /// The server could not be reached, or the connection dropped before the session existed,
43 /// past the retry budget. Retry later.
44 #[error("{0}")]
45 Connection(String),
46
47 /// The server's reply does not fit this client, such as a parallel create without
48 /// per-session ranges. Stop: upgrade `simulator-client`.
49 #[error("{0}")]
50 Protocol(String),
51}
52
53impl CreateError {
54 /// Whether calling `start` again later, with the same request, may succeed.
55 pub fn is_retryable(&self) -> bool {
56 match self {
57 Self::Rejected(err) => err.is_retryable(),
58 Self::Connection(_) => true,
59 Self::Protocol(_) => false,
60 }
61 }
62}
63
64/// Why a managed session call failed.
65///
66/// The managed layer has already retried what it could, so none of these is worth retrying on
67/// the same session: each variant says what to do instead. [`Self::is_retryable`] says whether
68/// a new session may succeed.
69#[derive(Debug, Error)]
70pub enum ManagedSessionError {
71 /// `start` could not create the session. Match on [`CreateError`] for why, or call
72 /// [`CreateError::is_retryable`].
73 #[error("session create failed: {0}")]
74 Create(CreateError),
75
76 /// The session control channel is closed, so the session is over. `next_event` returns this
77 /// after `Completed` has been delivered, once the connection has failed past the retry
78 /// budget, and (on a [`ManagedBacktestSession`]) after a terminal [`ManagedEvent::Error`].
79 /// Stop driving the session.
80 #[error("control channel closed")]
81 ControlClosed,
82
83 /// The session control channel gave up before a continue could be sent: the retry budget ran
84 /// out, the server ended the session, or reattaching was rejected. Start a new session.
85 #[error("control failed: {0}")]
86 ControlFailed(String),
87
88 /// A subscription gave up, so its notifications are incomplete. `send_continue` returns this
89 /// when a subscription ran out of retries; `next_event` returns it in place of `Completed`
90 /// when a subscription stopped delivering before its stream ended. Rerun the session if you
91 /// need every notification.
92 #[error("subscription failed: {0}")]
93 SubscriptionFailed(String),
94
95 /// The session was cancelled: [`StartSessionParams::parent_cancel`] fired or, for a
96 /// [`ParallelSubSession`](super::ParallelSubSession), its run was shut down. Stop.
97 #[error("cancelled")]
98 Cancelled,
99
100 /// The server refused the API key when the session control channel connected (HTTP 401 or
101 /// 403). Never retried: fix the key.
102 #[error("API key rejected: HTTP {0}")]
103 ApiKeyRejected(http::StatusCode),
104
105 /// The session control channel closed while a continue was being handed to it: the session
106 /// has ended. Call `next_event` to see why, or stop.
107 #[error("control closed while sending continue: {0}")]
108 ContinueSend(String),
109
110 /// The server reported an error. Returned by [`ManagedBacktestSession::wait_until_ready`] and
111 /// [`ManagedBacktestSession::run_to_completion`] on any [`ManagedEvent::Error`], terminal or
112 /// not. Fix what it names and start a new session.
113 #[error("server error: {0}")]
114 Remote(BacktestError),
115
116 /// The session sent `Completed` before its first `ReadyForContinue`. Returned by
117 /// [`ManagedBacktestSession::wait_until_ready`].
118 #[error("session completed before it was ready to continue")]
119 CompletedBeforeReady,
120}
121
122impl ManagedSessionError {
123 /// Whether starting a new session with the same request, after a backoff, may succeed.
124 ///
125 /// - `Create`: as [`CreateError::is_retryable`].
126 /// - `Remote`: as [`BacktestError::is_retryable`].
127 /// - `ControlFailed`, `SubscriptionFailed`: true; a connection ran out of retries.
128 /// - `ControlClosed`, `ContinueSend`, `Cancelled`, `ApiKeyRejected`, `CompletedBeforeReady`:
129 /// false.
130 pub fn is_retryable(&self) -> bool {
131 match self {
132 Self::Create(err) => err.is_retryable(),
133 Self::Remote(err) => err.is_retryable(),
134 Self::ControlFailed(_) | Self::SubscriptionFailed(_) => true,
135 Self::ControlClosed
136 | Self::ContinueSend(_)
137 | Self::Cancelled
138 | Self::ApiKeyRejected(_)
139 | Self::CompletedBeforeReady => false,
140 }
141 }
142}
143
144/// An event from a managed session, returned by `next_event`.
145///
146/// One stream carries both the session control channel's events and the notifications of every
147/// `subscribe_*` call.
148///
149/// # Order
150///
151/// - Control events arrive in the order the server sent them, starting with `Status` updates
152/// while the session starts.
153/// - Each subscription's notifications arrive in order. Across subscriptions, and between
154/// notifications and control events, there is no order: a `Transaction` can arrive after the
155/// `Slot` or `ReadyForContinue` that follows it.
156/// - Every notification arrives before `Completed`: on `Completed`, the session waits for each
157/// subscription to finish its stream.
158/// - After `Completed`, `next_event` returns [`ManagedSessionError::ControlClosed`].
159/// - If a subscription stops delivering before its stream ends, `next_event` returns the
160/// notifications it has, then [`ManagedSessionError::SubscriptionFailed`] in place of
161/// `Completed`.
162/// - After a reconnect, a subscription sends the last slot it delivered again. Dedupe
163/// transactions by signature, and account diffs by (signature, account, slot).
164#[derive(Debug)]
165pub enum ManagedEvent {
166 /// The session is waiting for your next [`ManagedBacktestSession::send_continue`] or
167 /// [`ManagedBacktestSession::send_continue_to`]. Read and change state through the session's
168 /// RPC endpoint now.
169 ReadyForContinue,
170 /// The session stopped where a `send_continue_to` asked. Read state now, but do not answer
171 /// it: a `ReadyForContinue` always follows, and that is the event to answer.
172 Paused(PausedEvent),
173 /// An upcoming batch matches a discovery filter from the create request. Send
174 /// `send_continue_to(slot, batch_index)` to pause just before it executes.
175 DiscoveryBatch(DiscoveryBatchEvent),
176 /// The slot that just executed. A skipped slot has no block and sends none.
177 Slot(u64),
178 /// A progress update, while the session starts and during each continue.
179 Status(BacktestStatus),
180 /// The session replayed its last slot. Every notification has arrived before this; the next
181 /// `next_event` returns [`ManagedSessionError::ControlClosed`].
182 Completed {
183 /// `None` unless the session was created with `send_summary`.
184 summary: Option<SessionSummary>,
185 },
186 /// The server reported an error. When [`BacktestError::is_terminal`] is true the session is
187 /// over: stop driving it. Otherwise it keeps running. Per-transaction `SimulationError`s
188 /// never arrive here; they are logged.
189 Error(BacktestError),
190 /// From [`ManagedBacktestSession::subscribe_transactions`]: a transaction in the shape
191 /// `getTransaction` returns. Program logs are in `meta.log_messages`.
192 Transaction(Box<EncodedConfirmedTransactionWithStatusMeta>),
193 /// From [`ManagedBacktestSession::subscribe_account_diffs`]: one changed account.
194 AccountDiff(AccountDiffNotification),
195 /// From [`ManagedBacktestSession::subscribe_actions`]: the result of one pre-scheduled
196 /// action.
197 ActionResult(ActionResultNotification),
198 /// From [`ManagedBacktestSession::subscribe_diagnostics`]: one diagnostic probe sample.
199 Diagnostic(DiagnosticNotification),
200 /// From [`ManagedBacktestSession::subscribe_replacements`]: one reroute result for an
201 /// original swap.
202 Replacement(Box<ReplacementNotification>),
203}
204
205/// Idle backstop for the completion drain: if no trailing notification arrives
206/// for this long after `Completed`, assume the data plane is stalled and stop
207/// waiting. Bounds the gap *between* notifications, not total drain time, so a
208/// slow-but-flowing stream (large backlog over a slow link) is never truncated.
209const DEFAULT_COMPLETION_DRAIN_TIMEOUT: Duration = Duration::from_secs(60);
210
211/// Result of [`ManagedBacktestSession::drain_until_subscriptions_complete`].
212pub(super) enum DrainOutcome {
213 /// Every subscription delivered its terminal (channels closed), or the
214 /// session was cancelled. The drained events are complete up to the stop.
215 Complete(Vec<ManagedEvent>),
216 /// The idle backstop fired with subscriptions still open — trailing
217 /// notifications never arrived, so the run is incomplete. Carries whatever
218 /// was drained before the stall.
219 Stalled(Vec<ManagedEvent>),
220}
221
222/// A session that reconnects on its own.
223///
224/// 1. [`Self::start`] it.
225/// 2. Call `subscribe_*` for the notifications you need.
226/// 3. Drive it: read [`Self::next_event`], and answer each [`ManagedEvent::ReadyForContinue`]
227/// with one [`Self::send_continue`] or [`Self::send_continue_to`]. Never answer
228/// [`ManagedEvent::Paused`]: a `ReadyForContinue` follows it, and answering both sends two
229/// continues. [`Self::run_to_completion`] runs this loop for you.
230/// 4. [`Self::shutdown`] it. Dropping it instead cancels the session without waiting for its
231/// tasks to stop.
232///
233/// See the [module docs](crate::managed) for what happens when a connection drops.
234pub struct ManagedBacktestSession {
235 session_info: SessionInfo,
236 /// Built on first [`Self::rpc`] call, so sessions that never read state skip the HTTP client.
237 rpc: OnceLock<RpcClient>,
238 control: Option<ControlHandle>,
239 subscriptions: Vec<SubscriptionHandle>,
240 session_cancel: CancellationToken,
241 /// Notifications drained on `Completed`, followed by `Completed`; served in
242 /// order by `next_event`. `None` until completion.
243 post_completion: Option<VecDeque<ManagedEvent>>,
244 /// Surfaced after `post_completion` drains: set when the completion drain
245 /// stalled (idle backstop fired with subscriptions still open), so a
246 /// silently-truncated run fails loudly instead of reporting `Completed`.
247 post_completion_error: Option<ManagedSessionError>,
248 completion_drain_timeout: Duration,
249 /// Shared across a parallel batch so this session's subscription reconnects
250 /// step aside for still-streaming siblings. `None` for a standalone session.
251 reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
252 subscription_diagnostics: Arc<SubscriptionDiagnostics>,
253}
254
255impl ManagedBacktestSession {
256 /// Create a session and return once the server has created it.
257 ///
258 /// `url` may be a bare host (see [`StartSessionParams::url`]). Build `create` with
259 /// [`crate::CreateSession`] and `into_request`. Use [`Self::start_with_params`] for extra
260 /// headers or your own cancellation token.
261 ///
262 /// # Errors
263 ///
264 /// - [`ManagedSessionError::ApiKeyRejected`] if the server refuses the API key.
265 /// - [`ManagedSessionError::Create`] if the server rejects the create request, or the
266 /// connection fails past the retry budget.
267 pub async fn start(
268 url: String,
269 api_key: String,
270 create: CreateBacktestSessionRequest,
271 ) -> Result<Self, ManagedSessionError> {
272 Self::start_with_params(
273 StartSessionParams::builder()
274 .url(url)
275 .api_key(api_key)
276 .create(create)
277 .build(),
278 None,
279 )
280 .await
281 }
282
283 /// Like [`Self::start`], from explicit [`StartSessionParams`]. Pass `None` for
284 /// `reconnect_coordinator`; it is internal plumbing for parallel runs.
285 ///
286 /// A create that leaves `disconnect_timeout_secs` unset gets
287 /// [`DEFAULT_DISCONNECT_TIMEOUT_SECS`], so the server keeps the session while the client
288 /// reconnects.
289 ///
290 /// # Errors
291 ///
292 /// As [`Self::start`], plus [`ManagedSessionError::Cancelled`] if
293 /// [`StartSessionParams::parent_cancel`] fires first.
294 pub async fn start_with_params(
295 params: StartSessionParams,
296 reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
297 ) -> Result<Self, ManagedSessionError> {
298 let StartSessionParams {
299 url,
300 api_key,
301 extra_headers,
302 mut create,
303 parent_cancel,
304 subscription_diagnostics,
305 } = params;
306 set_default_disconnect_timeout(&mut create);
307 let session_cancel = parent_cancel.child_token();
308 let mut control =
309 spawn_control_manager(url, api_key, extra_headers, create, session_cancel.clone());
310
311 let session_info = tokio::select! {
312 biased;
313 _ = parent_cancel.cancelled() => {
314 session_cancel.cancel();
315 control.join().await;
316 return Err(ManagedSessionError::Cancelled);
317 }
318 result = control.wait_for_session() => result?,
319 };
320
321 Ok(Self {
322 session_info,
323 rpc: OnceLock::new(),
324 control: Some(control),
325 subscriptions: Vec::new(),
326 session_cancel,
327 post_completion: None,
328 post_completion_error: None,
329 completion_drain_timeout: DEFAULT_COMPLETION_DRAIN_TIMEOUT,
330 reconnect_coordinator,
331 subscription_diagnostics,
332 })
333 }
334
335 /// Metadata reported by the server when the session was created.
336 pub fn session_info(&self) -> &SessionInfo {
337 &self.session_info
338 }
339
340 /// RPC client (`confirmed` commitment) for the session's chain state at its current slot;
341 /// serves from the first `ReadyForContinue` until `Completed`, and 502s after.
342 pub fn rpc(&self) -> &RpcClient {
343 self.rpc.get_or_init(|| {
344 RpcClient::new_with_commitment(
345 self.session_info.rpc_endpoint.clone(),
346 CommitmentConfig::confirmed(),
347 )
348 })
349 }
350
351 /// Override the completion-drain idle timeout (default 60 s). The drain gives up only after this
352 /// long with no trailing notification; it does not cap total drain time.
353 pub fn set_completion_drain_timeout(&mut self, idle_timeout: std::time::Duration) {
354 self.completion_drain_timeout = idle_timeout;
355 }
356
357 /// Subscribe to every transaction that mentions any of `program_ids`. Each arrives as
358 /// [`ManagedEvent::Transaction`], with program logs in `meta.log_messages`.
359 ///
360 /// Every `subscribe_*` call opens one WebSocket on the session's RPC endpoint; the next
361 /// `send_continue` waits until it is connected.
362 pub fn subscribe_transactions(&mut self, program_ids: Vec<Address>) {
363 self.subscriptions
364 .push(spawn_transaction_subscription_manager(
365 self.session_info.rpc_endpoint.clone(),
366 program_ids,
367 self.session_cancel.clone(),
368 self.reconnect_coordinator.clone(),
369 self.subscription_diagnostics.clone(),
370 ));
371 }
372
373 /// Subscribe to changes of every account owned by any of `program_ids`. Each change arrives
374 /// as [`ManagedEvent::AccountDiff`]. To follow single accounts across reconnects, subscribe
375 /// to their owner program and keep the diffs for their addresses.
376 /// [`crate::subscribe_account_diffs`] follows single accounts but does not reconnect.
377 pub fn subscribe_account_diffs(&mut self, program_ids: Vec<Address>) {
378 self.subscriptions
379 .push(spawn_account_diff_subscription_manager(
380 self.session_info.rpc_endpoint.clone(),
381 program_ids,
382 self.session_cancel.clone(),
383 self.reconnect_coordinator.clone(),
384 self.subscription_diagnostics.clone(),
385 ));
386 }
387
388 /// Subscribe to the results of the pre-scheduled actions in the create request. Each arrives
389 /// as [`ManagedEvent::ActionResult`].
390 pub fn subscribe_actions(&mut self) {
391 self.subscriptions.push(spawn_action_subscription_manager(
392 self.session_info.rpc_endpoint.clone(),
393 self.session_cancel.clone(),
394 self.reconnect_coordinator.clone(),
395 self.subscription_diagnostics.clone(),
396 ));
397 }
398
399 /// Subscribe to the reroute results for each original swap: re-quotes, venue probes and the
400 /// original swaps replayed beside them. One stream carries all three, as
401 /// [`ManagedEvent::Replacement`].
402 pub fn subscribe_replacements(&mut self) {
403 self.subscriptions
404 .push(spawn_replacement_subscription_manager(
405 self.session_info.rpc_endpoint.clone(),
406 self.session_cancel.clone(),
407 self.reconnect_coordinator.clone(),
408 self.subscription_diagnostics.clone(),
409 ));
410 }
411
412 /// Subscribe to the samples of the diagnostic probes in the create request. Each arrives as
413 /// [`ManagedEvent::Diagnostic`].
414 pub fn subscribe_diagnostics(&mut self) {
415 self.subscriptions
416 .push(spawn_diagnostic_subscription_manager(
417 self.session_info.rpc_endpoint.clone(),
418 self.session_cancel.clone(),
419 self.reconnect_coordinator.clone(),
420 self.subscription_diagnostics.clone(),
421 ));
422 }
423
424 /// Drain trailing notifications until every subscription delivers its
425 /// end-of-stream terminal (closing its channel), the session is cancelled,
426 /// or the data plane is found to have failed. See the `idle_timeout` arm for
427 /// how reconnecting/parked subscriptions are distinguished from a stall.
428 async fn drain_until_subscriptions_complete(
429 &mut self,
430 idle_timeout: std::time::Duration,
431 ) -> DrainOutcome {
432 drain_subscriptions_until_complete(
433 &mut self.subscriptions,
434 &self.session_cancel,
435 idle_timeout,
436 )
437 .await
438 }
439
440 /// Wait for the next event. See [`ManagedEvent`] for the order events arrive in.
441 ///
442 /// # Errors
443 ///
444 /// - [`ManagedSessionError::ControlClosed`] once the session is over.
445 /// - [`ManagedSessionError::SubscriptionFailed`] in place of `Completed` when a subscription's
446 /// stream ended early.
447 /// - [`ManagedSessionError::Cancelled`] if the session was cancelled.
448 pub async fn next_event(&mut self) -> Result<ManagedEvent, ManagedSessionError> {
449 // Serve buffered post-completion events (trailing notifications, then
450 // `Completed`); the control stream is gone once they're exhausted.
451 if let Some(buffered) = self.post_completion.as_mut() {
452 if let Some(event) = buffered.pop_front() {
453 return Ok(event);
454 }
455 // Buffer drained: surface a pending stall error so an incomplete
456 // run fails loudly, else the control stream is simply done.
457 return Err(self
458 .post_completion_error
459 .take()
460 .unwrap_or(ManagedSessionError::ControlClosed));
461 }
462
463 // Queued events are served without awaiting, so a caller pumping a
464 // backlog would otherwise never yield.
465 tokio::task::coop::consume_budget().await;
466
467 // Scope the borrows to the `select!` so the completion drain below can
468 // re-borrow `self`.
469 let event = {
470 let cancel = self.session_cancel.clone();
471 let control = self
472 .control
473 .as_mut()
474 .ok_or(ManagedSessionError::ControlClosed)?;
475 let subscriptions = &mut self.subscriptions;
476 // Control first: its task stops reading the socket, keepalive
477 // included, while its queue is full, so a subscription backlog must
478 // never hold control events back.
479 match recv_queued(&mut control.events) {
480 Some(event) => ManagedEvent::from(event),
481 None => {
482 if let Some(event) = try_next_subscription_event(subscriptions) {
483 return Ok(event);
484 }
485 tokio::select! {
486 biased;
487 _ = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
488 event = control.events.recv() => {
489 event.map(ManagedEvent::from).ok_or(ManagedSessionError::ControlClosed)?
490 }
491 event = wait_any_subscription_event(subscriptions) => event,
492 }
493 }
494 }
495 };
496
497 // Bind the payload so the re-emitted `Completed` below carries it.
498 let ManagedEvent::Completed { summary } = event else {
499 return Ok(event);
500 };
501
502 // Flush trailing notifications up to each subscription's terminal,
503 // delivering them before `Completed` so none are dropped.
504 let (mut buffered, terminal): (VecDeque<ManagedEvent>, _) = match self
505 .drain_until_subscriptions_complete(self.completion_drain_timeout)
506 .await
507 {
508 DrainOutcome::Complete(events) => {
509 (events.into(), Ok(ManagedEvent::Completed { summary }))
510 }
511 // The data plane stalled before every subscription finished:
512 // trailing notifications are missing, so report failure rather
513 // than a silently-truncated `Completed`. Deliver whatever was
514 // drained first, then surface the error once the buffer empties.
515 DrainOutcome::Stalled(events) => (
516 events.into(),
517 Err(ManagedSessionError::SubscriptionFailed(
518 "completion drain stalled: subscriptions did not deliver their \
519 end-of-stream terminals; the captured stream is incomplete"
520 .to_string(),
521 )),
522 ),
523 };
524 match terminal {
525 Ok(completed) => buffered.push_back(completed),
526 Err(err) => self.post_completion_error = Some(err),
527 }
528 let first = buffered.pop_front();
529 self.post_completion = Some(buffered);
530 match first {
531 Some(event) => Ok(event),
532 // Nothing buffered and the run failed: surface the error now.
533 None => Err(self
534 .post_completion_error
535 .take()
536 .unwrap_or(ManagedSessionError::ControlClosed)),
537 }
538 }
539
540 /// Wait until the session control channel and every subscription are connected, then send
541 /// a continue. Build `params` with [`crate::Continue`].
542 ///
543 /// Call this once per [`ManagedEvent::ReadyForContinue`].
544 ///
545 /// # Errors
546 ///
547 /// - [`ManagedSessionError::ControlFailed`] or [`ManagedSessionError::SubscriptionFailed`]
548 /// if a connection gave up.
549 /// - [`ManagedSessionError::ContinueSend`] if the session has ended.
550 /// - [`ManagedSessionError::Cancelled`] if the session was cancelled.
551 pub async fn send_continue(
552 &mut self,
553 params: ContinueParams,
554 ) -> Result<(), ManagedSessionError> {
555 self.wait_all_up().await?;
556 self.control_mut()?
557 .send_continue(params)
558 .await
559 .map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
560 }
561
562 /// Wait until the session control channel and every subscription are connected, then send
563 /// a `continueTo`: execute through `params.slot`, or with `batch_index`, up to just before
564 /// that batch of it. Call this once per [`ManagedEvent::ReadyForContinue`].
565 ///
566 /// The session then sends [`ManagedEvent::Paused`], where you can read state, and
567 /// [`ManagedEvent::ReadyForContinue`], which you answer. Rules for `params`:
568 ///
569 /// - `slot` must be after the last executed slot. Otherwise `next_event` returns an
570 /// `InvalidRequest` [`ManagedEvent::Error`] and the session stays where it is.
571 /// - `slot` must have a block. A skipped slot has none, and the session does not stop at
572 /// it: it runs on to the end of the range.
573 /// - With a [`ManagedEvent::DiscoveryBatch`], pass its `slot` and `batch_index` to pause
574 /// just before the matching batch.
575 ///
576 /// To run your transactions just before slot `n`, pause at `n - 1`, then send them with the
577 /// next continue. They run and commit before slot `n`'s block:
578 ///
579 /// ```no_run
580 /// use simulator_client::{Continue, ContinueToParams, ManagedBacktestSession, ManagedEvent};
581 /// use solana_transaction::versioned::VersionedTransaction;
582 ///
583 /// async fn run_before(
584 /// session: &mut ManagedBacktestSession,
585 /// n: u64,
586 /// tx: &VersionedTransaction,
587 /// ) -> Result<(), Box<dyn std::error::Error>> {
588 /// let pause = ContinueToParams { slot: n - 1, batch_index: None };
589 /// session.send_continue_to(pause).await?;
590 /// loop {
591 /// match session.next_event().await? {
592 /// ManagedEvent::ReadyForContinue => break,
593 /// ManagedEvent::Error(err) => return Err(err.into()),
594 /// _ => {}
595 /// }
596 /// }
597 /// let step = Continue::builder().build().push_transaction(tx)?.into_params();
598 /// session.send_continue(step).await?;
599 /// Ok(())
600 /// }
601 /// ```
602 ///
603 /// If slot `n - 1` may be skipped, or to skip the round trip, schedule the transaction
604 /// instead: a [`ScheduledAction`](simulator_api::ScheduledAction) with a `BeforeSlot` anchor
605 /// and [`ActionKind::Send`](simulator_api::ActionKind::Send).
606 ///
607 /// # Errors
608 ///
609 /// As [`Self::send_continue`].
610 pub async fn send_continue_to(
611 &mut self,
612 params: ContinueToParams,
613 ) -> Result<(), ManagedSessionError> {
614 self.wait_all_up().await?;
615 self.control_mut()?
616 .send_continue_to(params)
617 .await
618 .map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
619 }
620
621 /// Wait for the first `ReadyForContinue`, from which the session's RPC endpoint serves the
622 /// state before the start slot executes (the end of slot `start_slot - 1`). Earlier events
623 /// (only `Status` in practice) are discarded.
624 ///
625 /// # Errors
626 ///
627 /// [`ManagedSessionError::CompletedBeforeReady`], [`ManagedSessionError::Remote`] on an
628 /// `Error` event, or any error of [`Self::next_event`]. The session is not shut down; call
629 /// [`Self::shutdown`].
630 pub async fn wait_until_ready(&mut self) -> Result<(), ManagedSessionError> {
631 loop {
632 match self.next_event().await? {
633 ManagedEvent::ReadyForContinue => return Ok(()),
634 ManagedEvent::Completed { .. } => {
635 return Err(ManagedSessionError::CompletedBeforeReady);
636 }
637 ManagedEvent::Error(err) => return Err(ManagedSessionError::Remote(err)),
638 _ => {}
639 }
640 }
641 }
642
643 /// On every `ReadyForContinue`, send `step.clone()` until `Completed`; every other event,
644 /// `Paused` included, goes to `on_event`. Any `Error` event, terminal or not, stops the loop
645 /// and returns `Remote`. Always shuts the session down before returning. A caller that already
646 /// consumed a ready (e.g. via [`Self::wait_until_ready`]) sends its first
647 /// [`Self::send_continue`] itself.
648 ///
649 /// Returns the summary carried by `Completed`.
650 ///
651 /// # Errors
652 ///
653 /// [`ManagedSessionError::Remote`] on an `Error` event, or any error of [`Self::next_event`]
654 /// and [`Self::send_continue`].
655 pub async fn run_to_completion(
656 mut self,
657 step: ContinueParams,
658 mut on_event: impl FnMut(ManagedEvent),
659 ) -> Result<Option<SessionSummary>, ManagedSessionError> {
660 let result = async {
661 loop {
662 match self.next_event().await? {
663 ManagedEvent::ReadyForContinue => {
664 self.send_continue(step.clone()).await?;
665 }
666 ManagedEvent::Completed { summary } => return Ok(summary),
667 ManagedEvent::Error(err) => return Err(ManagedSessionError::Remote(err)),
668 other => on_event(other),
669 }
670 }
671 }
672 .await;
673 self.shutdown().await;
674 result
675 }
676
677 /// Cancel the session, closing it on the server, and wait until its connections have
678 /// stopped.
679 pub async fn shutdown(mut self) {
680 self.session_cancel.cancel();
681 if let Some(control) = self.control.take() {
682 control.join().await;
683 }
684 for sub in std::mem::take(&mut self.subscriptions) {
685 // A manager parked on a full queue exits only once the queue closes.
686 drop(sub.notifications);
687 let _ = sub.join.await;
688 }
689 }
690
691 fn control_mut(&mut self) -> Result<&mut ControlHandle, ManagedSessionError> {
692 self.control
693 .as_mut()
694 .ok_or(ManagedSessionError::ControlClosed)
695 }
696
697 async fn wait_all_up(&self) -> Result<(), ManagedSessionError> {
698 let control = self
699 .control
700 .as_ref()
701 .ok_or(ManagedSessionError::ControlClosed)?
702 .status
703 .clone();
704 let subscriptions = self
705 .subscriptions
706 .iter()
707 .map(|s| s.status.clone())
708 .collect();
709 wait_connections_up(control, subscriptions, &self.session_cancel).await
710 }
711}
712
713/// Give an unset `disconnect_timeout_secs` a window wide enough for this
714/// client's reconnect budget, so a management redeploy is a reattach rather
715/// than a lost session. A parallel create is left alone — the server's parallel
716/// default is already longer, and lowering it would shorten the batch's window.
717fn set_default_disconnect_timeout(create: &mut CreateBacktestSessionRequest) {
718 let params = match create {
719 CreateBacktestSessionRequest::V1(CreateBacktestSessionRequestV1 {
720 parallel: true, ..
721 }) => return,
722 CreateBacktestSessionRequest::V1(CreateBacktestSessionRequestV1 { request, .. })
723 | CreateBacktestSessionRequest::V0(request) => request,
724 };
725 params
726 .disconnect_timeout_secs
727 .get_or_insert(DEFAULT_DISCONNECT_TIMEOUT_SECS);
728}
729
730/// Block until the control connection and every subscription connection report
731/// `Up`, returning an error if any reports `Failed` or the token is cancelled.
732/// Shared by the single-session and parallel sub-session drivers.
733pub(super) async fn wait_connections_up(
734 mut control: watch::Receiver<ConnectionStatus>,
735 mut subscriptions: Vec<watch::Receiver<ConnectionStatus>>,
736 cancel: &CancellationToken,
737) -> Result<(), ManagedSessionError> {
738 loop {
739 let control_status = control.borrow().clone();
740 if let ConnectionStatus::Failed(why) = &control_status {
741 return Err(ManagedSessionError::ControlFailed(why.clone()));
742 }
743
744 let mut all_subscriptions_up = true;
745 for subscription in &subscriptions {
746 match &*subscription.borrow() {
747 ConnectionStatus::Failed(why) => {
748 return Err(ManagedSessionError::SubscriptionFailed(why.clone()));
749 }
750 ConnectionStatus::Up => {}
751 _ => all_subscriptions_up = false,
752 }
753 }
754
755 if control_status == ConnectionStatus::Up && all_subscriptions_up {
756 return Ok(());
757 }
758
759 tokio::select! {
760 _ = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
761 _ = control.changed() => {}
762 _ = wait_any_subscription_change(&mut subscriptions) => {}
763 }
764 }
765}
766
767/// Drain trailing notifications until every subscription delivers its
768/// end-of-stream terminal (closing its channel), `cancel` fires, or the data
769/// plane is found to have stalled. Shared by the single-session and parallel
770/// sub-session drivers. See
771/// [`ManagedBacktestSession::drain_until_subscriptions_complete`].
772///
773/// `idle_timeout` bounds the gap *between* notifications, not total drain time,
774/// so a slow-but-flowing stream (large backlog over a slow link) is never
775/// truncated. A subscription that's `Down` — reconnecting, or parked behind the
776/// reconnect coordinator waiting for siblings to free bandwidth — is *not* a
777/// stall: it resumes via `replayFromSlot` or exhausts its budget and reports
778/// `Failed`. So the idle gap only declares a `Stalled` outcome when an open
779/// subscription is still `Up` (connected but not delivering — a genuinely hung
780/// data plane); a subscription that closed in `Failed` left a truncated stream.
781pub(super) async fn drain_subscriptions_until_complete(
782 subscriptions: &mut [SubscriptionHandle],
783 cancel: &CancellationToken,
784 idle_timeout: std::time::Duration,
785) -> DrainOutcome {
786 let mut events = Vec::new();
787 if subscriptions.is_empty() {
788 return DrainOutcome::Complete(events);
789 }
790 loop {
791 while let Some(event) = try_next_subscription_event(subscriptions) {
792 events.push(event);
793 }
794 if subscriptions.iter().all(|s| s.notifications.is_closed()) {
795 let any_failed = subscriptions
796 .iter()
797 .any(|s| matches!(*s.status.borrow(), ConnectionStatus::Failed(_)));
798 return if any_failed {
799 DrainOutcome::Stalled(events)
800 } else {
801 DrainOutcome::Complete(events)
802 };
803 }
804 tokio::select! {
805 biased;
806 // A cancel is an intentional stop, not a data-plane failure.
807 _ = cancel.cancelled() => return DrainOutcome::Complete(events),
808 // Idle gap elapsed. A still-`Up` subscription should be delivering
809 // but isn't — a hung data plane (stall). If the open subscriptions
810 // are all reconnecting/parked (`Down`), keep waiting: the
811 // coordinator is deferring them on purpose, not failing.
812 _ = tokio::time::sleep(idle_timeout) => {
813 let any_up = subscriptions.iter().any(|s| {
814 !s.notifications.is_closed()
815 && matches!(*s.status.borrow(), ConnectionStatus::Up)
816 });
817 if any_up {
818 return DrainOutcome::Stalled(events);
819 }
820 }
821 received = recv_any_open_subscription(subscriptions) => {
822 // `None` means a channel closed; the loop re-checks all-closed.
823 if let Some(event) = received {
824 events.push(event);
825 }
826 }
827 }
828 }
829}
830
831impl Drop for ManagedBacktestSession {
832 fn drop(&mut self) {
833 self.session_cancel.cancel();
834 }
835}
836
837pub(super) async fn wait_any_subscription_change(
838 subscriptions: &mut [watch::Receiver<ConnectionStatus>],
839) {
840 if subscriptions.is_empty() {
841 std::future::pending::<()>().await;
842 return;
843 }
844 let _ =
845 futures::future::select_all(subscriptions.iter_mut().map(|s| Box::pin(s.changed()))).await;
846}
847
848pub(super) async fn wait_any_subscription_event(
849 subscriptions: &mut [SubscriptionHandle],
850) -> ManagedEvent {
851 loop {
852 if let Some(event) = try_next_subscription_event(subscriptions) {
853 return event;
854 }
855
856 let futures: Vec<_> = subscriptions
857 .iter_mut()
858 .filter(|s| !s.notifications.is_closed())
859 .map(|s| Box::pin(s.notifications.recv()))
860 .collect();
861
862 if futures.is_empty() {
863 std::future::pending::<()>().await;
864 }
865
866 let (notification, _, _) = futures::future::select_all(futures).await;
867 if let Some(notification) = notification {
868 return notification.into();
869 }
870 }
871}
872
873/// Await the next notification from any still-open subscription channel,
874/// returning `None` when one closes. Unlike [`wait_any_subscription_event`],
875/// which never resolves on closure, this lets the completion drain observe
876/// per-channel end-of-stream.
877pub(super) async fn recv_any_open_subscription(
878 subscriptions: &mut [SubscriptionHandle],
879) -> Option<ManagedEvent> {
880 let futures: Vec<_> = subscriptions
881 .iter_mut()
882 .filter(|s| !s.notifications.is_closed())
883 .map(|s| Box::pin(s.notifications.recv()))
884 .collect();
885
886 if futures.is_empty() {
887 return None;
888 }
889
890 let (notification, _, _) = futures::future::select_all(futures).await;
891 notification.map(Into::into)
892}
893
894pub(super) fn try_next_subscription_event(
895 subscriptions: &mut [SubscriptionHandle],
896) -> Option<ManagedEvent> {
897 for subscription in subscriptions {
898 if let Some(notification) = recv_queued(&mut subscription.notifications) {
899 return Some(notification.into());
900 }
901 }
902 None
903}
904
905/// Not `try_recv`, which parks the thread on a message still being written and so consumes a
906/// `block_on` task's pending wakeup. Unconstrained so a spent coop budget never hides a queued
907/// message.
908fn recv_queued<T>(receiver: &mut mpsc::Receiver<T>) -> Option<T> {
909 tokio::task::coop::unconstrained(receiver.recv())
910 .now_or_never()
911 .flatten()
912}
913
914impl From<ControlEvent> for ManagedEvent {
915 fn from(event: ControlEvent) -> Self {
916 match event {
917 ControlEvent::ReadyForContinue => Self::ReadyForContinue,
918 ControlEvent::Paused(event) => Self::Paused(event),
919 ControlEvent::DiscoveryBatch(event) => Self::DiscoveryBatch(event),
920 ControlEvent::Slot(slot) => Self::Slot(slot),
921 ControlEvent::Status(status) => Self::Status(status),
922 ControlEvent::Completed { summary } => Self::Completed { summary },
923 ControlEvent::Error(error) => Self::Error(error),
924 }
925 }
926}
927
928impl From<SubscriptionNotification> for ManagedEvent {
929 fn from(notification: SubscriptionNotification) -> Self {
930 match notification {
931 SubscriptionNotification::Transaction(transaction) => Self::Transaction(transaction),
932 SubscriptionNotification::AccountDiff(diff) => Self::AccountDiff(diff),
933 SubscriptionNotification::ActionResult(result) => Self::ActionResult(result),
934 SubscriptionNotification::Diagnostic(sample) => Self::Diagnostic(sample),
935 SubscriptionNotification::Replacement(replacement) => Self::Replacement(replacement),
936 }
937 }
938}
939
940#[cfg(test)]
941mod tests {
942 use std::{
943 future::Future,
944 pin::Pin,
945 sync::Mutex,
946 task::{Poll, Waker},
947 };
948
949 use futures::{StreamExt, stream::FuturesUnordered};
950 use simulator_api::{CreateSessionParams, MAX_DISCONNECT_TIMEOUT_SECS};
951
952 use super::*;
953 use crate::{
954 CreateSession,
955 managed::RECONNECT_MAX_TOTAL,
956 subscriptions::{DiagnosticContext, DiagnosticNotification},
957 };
958
959 fn notification() -> SubscriptionNotification {
960 SubscriptionNotification::Diagnostic(DiagnosticNotification {
961 context: DiagnosticContext { slot: 0 },
962 slot: 0,
963 probe_index: 0,
964 label: None,
965 market: String::new(),
966 usd_value: 0,
967 pairs: Vec::new(),
968 router_slot: None,
969 results: None,
970 account_hashes: Vec::new(),
971 err: None,
972 })
973 }
974
975 /// Driver and sibling under one `FuturesUnordered` on a `block_on` thread, the sibling waking
976 /// mid-poll while senders on other threads write the driver's queue.
977 #[test]
978 fn subscription_reads_keep_a_sibling_wakeup_on_the_block_on_thread() {
979 const SENDERS: usize = 4;
980 const ROUNDS: usize = 2_000;
981
982 let runtime = tokio::runtime::Builder::new_multi_thread()
983 .enable_all()
984 .build()
985 .unwrap();
986 let (sender, notifications) = mpsc::channel(1_024);
987 let (_status_tx, status) = watch::channel(ConnectionStatus::Up);
988 let mut subscriptions = vec![SubscriptionHandle {
989 status,
990 notifications,
991 join: runtime.spawn(async {}),
992 }];
993 // Concurrent writers, so a read often meets a slot claimed but not yet written.
994 for _ in 0..SENDERS {
995 let sender = sender.clone();
996 std::thread::spawn(move || {
997 while sender.blocking_send(notification()).is_ok() {
998 std::thread::sleep(Duration::from_micros(20));
999 }
1000 });
1001 }
1002
1003 let (done_tx, done) = std::sync::mpsc::channel();
1004 std::thread::spawn(move || {
1005 let sibling = Arc::new(Mutex::new(None::<Waker>));
1006 let driver = {
1007 let sibling = sibling.clone();
1008 async move {
1009 for _ in 0..ROUNDS {
1010 while try_next_subscription_event(&mut subscriptions).is_some() {}
1011 if let Some(waker) = sibling.lock().unwrap().as_ref() {
1012 waker.wake_by_ref();
1013 }
1014 // Spins to meet the next message while it is being written.
1015 while try_next_subscription_event(&mut subscriptions).is_none() {}
1016 wait_any_subscription_event(&mut subscriptions).await;
1017 }
1018 }
1019 };
1020 let sibling = std::future::poll_fn(move |cx| {
1021 *sibling.lock().unwrap() = Some(cx.waker().clone());
1022 Poll::<()>::Pending
1023 });
1024 // Never woken, so a pass over the other two ends without the yield that would wake
1025 // the task again.
1026 let idle = std::future::pending::<()>();
1027 let mut sessions: FuturesUnordered<Pin<Box<dyn Future<Output = ()>>>> =
1028 FuturesUnordered::new();
1029 sessions.push(Box::pin(driver));
1030 sessions.push(Box::pin(sibling));
1031 sessions.push(Box::pin(idle));
1032 runtime.block_on(sessions.next());
1033 let _ = done_tx.send(());
1034 });
1035
1036 assert!(
1037 done.recv_timeout(Duration::from_secs(30)).is_ok(),
1038 "the sessions stopped: a subscription read consumed the block_on thread's wakeup"
1039 );
1040 }
1041
1042 fn params(disconnect_timeout_secs: Option<u16>) -> CreateSessionParams {
1043 CreateSession::builder()
1044 .start_slot(1)
1045 .slot_count(1)
1046 .maybe_disconnect_timeout_secs(disconnect_timeout_secs)
1047 .build()
1048 .into_params()
1049 .expect("valid create params")
1050 }
1051
1052 #[test]
1053 fn unset_disconnect_timeout_defaults_on_single_sessions_only() {
1054 let cases: [(&str, CreateBacktestSessionRequest, Option<u16>); 4] = [
1055 (
1056 "v0 unset",
1057 CreateBacktestSessionRequest::V0(params(None)),
1058 Some(DEFAULT_DISCONNECT_TIMEOUT_SECS),
1059 ),
1060 (
1061 "v0 explicit",
1062 CreateBacktestSessionRequest::V0(params(Some(42))),
1063 Some(42),
1064 ),
1065 (
1066 "v1 single unset",
1067 CreateBacktestSessionRequestV1 {
1068 request: params(None),
1069 parallel: false,
1070 name: None,
1071 create_token: None,
1072 }
1073 .into(),
1074 Some(DEFAULT_DISCONNECT_TIMEOUT_SECS),
1075 ),
1076 (
1077 "v1 parallel unset keeps the server's parallel default",
1078 CreateBacktestSessionRequestV1 {
1079 request: params(None),
1080 parallel: true,
1081 name: None,
1082 create_token: None,
1083 }
1084 .into(),
1085 None,
1086 ),
1087 ];
1088
1089 for (name, mut create, expected) in cases {
1090 set_default_disconnect_timeout(&mut create);
1091 let (request, _) = create.into_request_and_parallel();
1092 assert_eq!(request.disconnect_timeout_secs, expected, "{name}");
1093 }
1094 }
1095
1096 #[test]
1097 fn default_disconnect_timeout_covers_the_reconnect_budget_without_clamping() {
1098 assert!(u64::from(DEFAULT_DISCONNECT_TIMEOUT_SECS) > RECONNECT_MAX_TOTAL.as_secs());
1099 const { assert!(DEFAULT_DISCONNECT_TIMEOUT_SECS <= MAX_DISCONNECT_TIMEOUT_SECS) };
1100 }
1101}