Skip to main content

simulator_client/managed/
session.rs

1use std::{collections::VecDeque, sync::Arc, time::Duration};
2
3use simulator_api::{
4    AgentStatsReport, BacktestError, BacktestStatus, ContinueParams, ContinueToParams,
5    CreateBacktestSessionRequest, DiscoveryBatchEvent, PausedEvent, SessionSummary,
6};
7use solana_address::Address;
8use solana_transaction_status::EncodedConfirmedTransactionWithStatusMeta;
9use thiserror::Error;
10use tokio::sync::watch;
11use tokio_util::sync::CancellationToken;
12
13use super::{
14    ConnectionStatus, ControlEvent, ControlHandle, ReconnectCoordinator, SessionInfo,
15    StartSessionParams, SubscriptionDiagnostics, SubscriptionHandle, SubscriptionNotification,
16    spawn_account_diff_subscription_manager, spawn_action_subscription_manager,
17    spawn_control_manager, spawn_transaction_subscription_manager,
18};
19use crate::subscriptions::{AccountDiffNotification, ActionResultNotification};
20
21/// Error returned by the high-level managed session wrapper.
22#[derive(Debug, Error)]
23pub enum ManagedSessionError {
24    #[error("session create failed: {0}")]
25    Create(String),
26
27    #[error("control channel closed")]
28    ControlClosed,
29
30    #[error("control failed: {0}")]
31    ControlFailed(String),
32
33    #[error("subscription failed: {0}")]
34    SubscriptionFailed(String),
35
36    #[error("cancelled")]
37    Cancelled,
38
39    #[error("control closed while sending continue: {0}")]
40    ContinueSend(String),
41}
42
43#[derive(Debug)]
44pub enum ManagedEvent {
45    ReadyForContinue,
46    /// Server paused at a `ContinueTo` target. The session is ready for
47    /// another `Continue` or `ContinueTo` from this point.
48    Paused(PausedEvent),
49    /// Server discovered an upcoming batch matching a registered
50    /// `DiscoveryFilter`. Send `send_continue_to(slot, batch_index)` to pause
51    /// immediately before it executes.
52    DiscoveryBatch(DiscoveryBatchEvent),
53    Slot(u64),
54    Status(BacktestStatus),
55    /// `agent_stats` is always `None` for [`super::ParallelSubSession`] —
56    /// the multiplexed wire carries only the summary.
57    Completed {
58        summary: Option<SessionSummary>,
59        agent_stats: Option<Vec<AgentStatsReport>>,
60    },
61    Error(BacktestError),
62    Transaction(Box<EncodedConfirmedTransactionWithStatusMeta>),
63    AccountDiff(AccountDiffNotification),
64    ActionResult(ActionResultNotification),
65}
66
67/// Idle backstop for the completion drain: if no trailing notification arrives
68/// for this long after `Completed`, assume the data plane is stalled and stop
69/// waiting. Bounds the gap *between* notifications, not total drain time, so a
70/// slow-but-flowing stream (large backlog over a slow link) is never truncated.
71const DEFAULT_COMPLETION_DRAIN_TIMEOUT: Duration = Duration::from_secs(60);
72
73/// Result of [`ManagedBacktestSession::drain_until_subscriptions_complete`].
74pub(super) enum DrainOutcome {
75    /// Every subscription delivered its terminal (channels closed), or the
76    /// session was cancelled. The drained events are complete up to the stop.
77    Complete(Vec<ManagedEvent>),
78    /// The idle backstop fired with subscriptions still open — trailing
79    /// notifications never arrived, so the run is incomplete. Carries whatever
80    /// was drained before the stall.
81    Stalled(Vec<ManagedEvent>),
82}
83
84/// High-level managed backtest session.
85///
86/// This wrapper owns the control manager, supported subscription managers,
87/// cancellation, status gating, and shutdown order. Callers only need to react
88/// to [`ManagedEvent`]s and send [`ContinueParams`] after `ReadyForContinue`.
89pub struct ManagedBacktestSession {
90    session_info: SessionInfo,
91    control: Option<ControlHandle>,
92    subscriptions: Vec<SubscriptionHandle>,
93    session_cancel: CancellationToken,
94    /// Notifications drained on `Completed`, followed by `Completed`; served in
95    /// order by `next_event`. `None` until completion.
96    post_completion: Option<VecDeque<ManagedEvent>>,
97    /// Surfaced after `post_completion` drains: set when the completion drain
98    /// stalled (idle backstop fired with subscriptions still open), so a
99    /// silently-truncated run fails loudly instead of reporting `Completed`.
100    post_completion_error: Option<ManagedSessionError>,
101    completion_drain_timeout: Duration,
102    /// Shared across a parallel batch so this session's subscription reconnects
103    /// step aside for still-streaming siblings. `None` for a standalone session.
104    reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
105    subscription_diagnostics: Arc<SubscriptionDiagnostics>,
106}
107
108impl ManagedBacktestSession {
109    /// Start a standalone managed session with an internally owned cancellation
110    /// token and its own diagnostics counters.
111    pub async fn start(
112        url: String,
113        api_key: String,
114        create: CreateBacktestSessionRequest,
115    ) -> Result<Self, ManagedSessionError> {
116        Self::start_with_params(
117            StartSessionParams::builder()
118                .url(url)
119                .api_key(api_key)
120                .create(create)
121                .build(),
122            None,
123        )
124        .await
125    }
126
127    /// Start a managed session from explicit [`StartSessionParams`].
128    ///
129    /// `reconnect_coordinator` is an optional coordinator shared across sibling
130    /// sessions in a parallel batch; a dropped subscription parks on it until
131    /// streaming siblings finish, then reconnects into the freed bandwidth. It
132    /// is handed to the subscription managers spawned by `subscribe_*`. Pass
133    /// `None` for a standalone session.
134    pub async fn start_with_params(
135        params: StartSessionParams,
136        reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
137    ) -> Result<Self, ManagedSessionError> {
138        let StartSessionParams {
139            url,
140            api_key,
141            create,
142            parent_cancel,
143            subscription_diagnostics,
144        } = params;
145        let session_cancel = parent_cancel.child_token();
146        let mut control = spawn_control_manager(url, api_key, create, session_cancel.clone());
147
148        let session_info = tokio::select! {
149            biased;
150            _ = parent_cancel.cancelled() => {
151                session_cancel.cancel();
152                control.join().await;
153                return Err(ManagedSessionError::Cancelled);
154            }
155            result = control.wait_for_session() => {
156                result.map_err(ManagedSessionError::Create)?
157            }
158        };
159
160        Ok(Self {
161            session_info,
162            control: Some(control),
163            subscriptions: Vec::new(),
164            session_cancel,
165            post_completion: None,
166            post_completion_error: None,
167            completion_drain_timeout: DEFAULT_COMPLETION_DRAIN_TIMEOUT,
168            reconnect_coordinator,
169            subscription_diagnostics,
170        })
171    }
172
173    /// Metadata reported by the server when the session was created.
174    pub fn session_info(&self) -> &SessionInfo {
175        &self.session_info
176    }
177
178    /// Override the completion-drain idle timeout (default
179    /// [`DEFAULT_COMPLETION_DRAIN_TIMEOUT`]). The drain gives up only after this
180    /// long with no trailing notification; it does not cap total drain time.
181    pub fn set_completion_drain_timeout(&mut self, idle_timeout: std::time::Duration) {
182        self.completion_drain_timeout = idle_timeout;
183    }
184
185    /// Subscribe to transaction notifications for the configured programs.
186    pub fn subscribe_transactions(&mut self, program_ids: Vec<Address>) {
187        self.subscriptions
188            .push(spawn_transaction_subscription_manager(
189                self.session_info.rpc_endpoint.clone(),
190                program_ids,
191                self.session_cancel.clone(),
192                self.reconnect_coordinator.clone(),
193                self.subscription_diagnostics.clone(),
194            ));
195    }
196
197    /// Subscribe to account-diff notifications for the configured programs.
198    pub fn subscribe_account_diffs(&mut self, program_ids: Vec<Address>) {
199        self.subscriptions
200            .push(spawn_account_diff_subscription_manager(
201                self.session_info.rpc_endpoint.clone(),
202                program_ids,
203                self.session_cancel.clone(),
204                self.reconnect_coordinator.clone(),
205                self.subscription_diagnostics.clone(),
206            ));
207    }
208
209    /// Subscribe to scheduled-action results. Actions themselves are registered
210    /// in `CreateSessionParams`; this only attaches the result consumer.
211    pub fn subscribe_actions(&mut self) {
212        self.subscriptions.push(spawn_action_subscription_manager(
213            self.session_info.rpc_endpoint.clone(),
214            self.session_cancel.clone(),
215            self.reconnect_coordinator.clone(),
216            self.subscription_diagnostics.clone(),
217        ));
218    }
219
220    /// Drain trailing notifications until every subscription delivers its
221    /// end-of-stream terminal (closing its channel), the session is cancelled,
222    /// or the data plane is found to have failed. See the `idle_timeout` arm for
223    /// how reconnecting/parked subscriptions are distinguished from a stall.
224    async fn drain_until_subscriptions_complete(
225        &mut self,
226        idle_timeout: std::time::Duration,
227    ) -> DrainOutcome {
228        drain_subscriptions_until_complete(
229            &mut self.subscriptions,
230            &self.session_cancel,
231            idle_timeout,
232        )
233        .await
234    }
235
236    /// Receive the next control or subscription event.
237    ///
238    /// On `Completed`, trailing subscription notifications are drained and
239    /// delivered before the `Completed` event.
240    pub async fn next_event(&mut self) -> Result<ManagedEvent, ManagedSessionError> {
241        // Serve buffered post-completion events (trailing notifications, then
242        // `Completed`); the control stream is gone once they're exhausted.
243        if let Some(buffered) = self.post_completion.as_mut() {
244            if let Some(event) = buffered.pop_front() {
245                return Ok(event);
246            }
247            // Buffer drained: surface a pending stall error so an incomplete
248            // run fails loudly, else the control stream is simply done.
249            return Err(self
250                .post_completion_error
251                .take()
252                .unwrap_or(ManagedSessionError::ControlClosed));
253        }
254
255        if let Some(event) = try_next_subscription_event(&mut self.subscriptions) {
256            return Ok(event);
257        }
258
259        // Scope the borrows to the `select!` so the completion drain below can
260        // re-borrow `self`.
261        let event = {
262            let cancel = self.session_cancel.clone();
263            let control = self
264                .control
265                .as_mut()
266                .ok_or(ManagedSessionError::ControlClosed)?;
267            let subscriptions = &mut self.subscriptions;
268            tokio::select! {
269                biased;
270                _ = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
271                event = control.events.recv() => {
272                    event.map(ManagedEvent::from).ok_or(ManagedSessionError::ControlClosed)?
273                }
274                event = wait_any_subscription_event(subscriptions) => event,
275            }
276        };
277
278        // Bind the payload so the re-emitted `Completed` below carries it.
279        let ManagedEvent::Completed {
280            summary,
281            agent_stats,
282        } = event
283        else {
284            return Ok(event);
285        };
286
287        // Flush trailing notifications up to each subscription's terminal,
288        // delivering them before `Completed` so none are dropped.
289        let (mut buffered, terminal): (VecDeque<ManagedEvent>, _) = match self
290            .drain_until_subscriptions_complete(self.completion_drain_timeout)
291            .await
292        {
293            DrainOutcome::Complete(events) => (
294                events.into(),
295                Ok(ManagedEvent::Completed {
296                    summary,
297                    agent_stats,
298                }),
299            ),
300            // The data plane stalled before every subscription finished:
301            // trailing notifications are missing, so report failure rather
302            // than a silently-truncated `Completed`. Deliver whatever was
303            // drained first, then surface the error once the buffer empties.
304            DrainOutcome::Stalled(events) => (
305                events.into(),
306                Err(ManagedSessionError::SubscriptionFailed(
307                    "completion drain stalled: subscriptions did not deliver their \
308                     end-of-stream terminals; the captured stream is incomplete"
309                        .to_string(),
310                )),
311            ),
312        };
313        match terminal {
314            Ok(completed) => buffered.push_back(completed),
315            Err(err) => self.post_completion_error = Some(err),
316        }
317        let first = buffered.pop_front();
318        self.post_completion = Some(buffered);
319        match first {
320            Some(event) => Ok(event),
321            // Nothing buffered and the run failed: surface the error now.
322            None => Err(self
323                .post_completion_error
324                .take()
325                .unwrap_or(ManagedSessionError::ControlClosed)),
326        }
327    }
328
329    /// Wait until the control connection and all subscription connections are
330    /// up, then send a `Continue` request.
331    ///
332    /// Call this after receiving [`ManagedEvent::ReadyForContinue`] or
333    /// [`ManagedEvent::Paused`]. If there are no subscriptions, only the
334    /// control connection is gated.
335    pub async fn send_continue(
336        &mut self,
337        params: ContinueParams,
338    ) -> Result<(), ManagedSessionError> {
339        self.wait_all_up().await?;
340        self.control_mut()?
341            .send_continue(params)
342            .await
343            .map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
344    }
345
346    /// Wait until the control connection and all subscription connections are
347    /// up, then send a `ContinueTo` request to step to a specific slot/batch
348    /// boundary.
349    ///
350    /// Pair with [`ManagedEvent::DiscoveryBatch`] to drive a discovery-paced
351    /// loop: receive a discovery event, send `ContinueTo(slot, batch_index)`,
352    /// and wait for [`ManagedEvent::Paused`] before inspecting state.
353    pub async fn send_continue_to(
354        &mut self,
355        params: ContinueToParams,
356    ) -> Result<(), ManagedSessionError> {
357        self.wait_all_up().await?;
358        self.control_mut()?
359            .send_continue_to(params)
360            .await
361            .map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
362    }
363
364    /// Cancel the session and join all manager tasks.
365    pub async fn shutdown(mut self) {
366        self.session_cancel.cancel();
367        if let Some(control) = self.control.take() {
368            control.join().await;
369        }
370        for sub in std::mem::take(&mut self.subscriptions) {
371            let _ = sub.join.await;
372        }
373    }
374
375    fn control_mut(&mut self) -> Result<&mut ControlHandle, ManagedSessionError> {
376        self.control
377            .as_mut()
378            .ok_or(ManagedSessionError::ControlClosed)
379    }
380
381    async fn wait_all_up(&self) -> Result<(), ManagedSessionError> {
382        let control = self
383            .control
384            .as_ref()
385            .ok_or(ManagedSessionError::ControlClosed)?
386            .status
387            .clone();
388        let subscriptions = self
389            .subscriptions
390            .iter()
391            .map(|s| s.status.clone())
392            .collect();
393        wait_connections_up(control, subscriptions, &self.session_cancel).await
394    }
395}
396
397/// Block until the control connection and every subscription connection report
398/// `Up`, returning an error if any reports `Failed` or the token is cancelled.
399/// Shared by the single-session and parallel sub-session drivers.
400pub(super) async fn wait_connections_up(
401    mut control: watch::Receiver<ConnectionStatus>,
402    mut subscriptions: Vec<watch::Receiver<ConnectionStatus>>,
403    cancel: &CancellationToken,
404) -> Result<(), ManagedSessionError> {
405    loop {
406        let control_status = control.borrow().clone();
407        if let ConnectionStatus::Failed(why) = &control_status {
408            return Err(ManagedSessionError::ControlFailed(why.clone()));
409        }
410
411        let mut all_subscriptions_up = true;
412        for subscription in &subscriptions {
413            match &*subscription.borrow() {
414                ConnectionStatus::Failed(why) => {
415                    return Err(ManagedSessionError::SubscriptionFailed(why.clone()));
416                }
417                ConnectionStatus::Up => {}
418                _ => all_subscriptions_up = false,
419            }
420        }
421
422        if control_status == ConnectionStatus::Up && all_subscriptions_up {
423            return Ok(());
424        }
425
426        tokio::select! {
427            _ = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
428            _ = control.changed() => {}
429            _ = wait_any_subscription_change(&mut subscriptions) => {}
430        }
431    }
432}
433
434/// Drain trailing notifications until every subscription delivers its
435/// end-of-stream terminal (closing its channel), `cancel` fires, or the data
436/// plane is found to have stalled. Shared by the single-session and parallel
437/// sub-session drivers. See
438/// [`ManagedBacktestSession::drain_until_subscriptions_complete`].
439///
440/// `idle_timeout` bounds the gap *between* notifications, not total drain time,
441/// so a slow-but-flowing stream (large backlog over a slow link) is never
442/// truncated. A subscription that's `Down` — reconnecting, or parked behind the
443/// reconnect coordinator waiting for siblings to free bandwidth — is *not* a
444/// stall: it resumes via `replayFromSlot` or exhausts its budget and reports
445/// `Failed`. So the idle gap only declares a `Stalled` outcome when an open
446/// subscription is still `Up` (connected but not delivering — a genuinely hung
447/// data plane); a subscription that closed in `Failed` left a truncated stream.
448pub(super) async fn drain_subscriptions_until_complete(
449    subscriptions: &mut [SubscriptionHandle],
450    cancel: &CancellationToken,
451    idle_timeout: std::time::Duration,
452) -> DrainOutcome {
453    let mut events = Vec::new();
454    if subscriptions.is_empty() {
455        return DrainOutcome::Complete(events);
456    }
457    loop {
458        while let Some(event) = try_next_subscription_event(subscriptions) {
459            events.push(event);
460        }
461        if subscriptions.iter().all(|s| s.notifications.is_closed()) {
462            let any_failed = subscriptions
463                .iter()
464                .any(|s| matches!(*s.status.borrow(), ConnectionStatus::Failed(_)));
465            return if any_failed {
466                DrainOutcome::Stalled(events)
467            } else {
468                DrainOutcome::Complete(events)
469            };
470        }
471        tokio::select! {
472            biased;
473            // A cancel is an intentional stop, not a data-plane failure.
474            _ = cancel.cancelled() => return DrainOutcome::Complete(events),
475            // Idle gap elapsed. A still-`Up` subscription should be delivering
476            // but isn't — a hung data plane (stall). If the open subscriptions
477            // are all reconnecting/parked (`Down`), keep waiting: the
478            // coordinator is deferring them on purpose, not failing.
479            _ = tokio::time::sleep(idle_timeout) => {
480                let any_up = subscriptions.iter().any(|s| {
481                    !s.notifications.is_closed()
482                        && matches!(*s.status.borrow(), ConnectionStatus::Up)
483                });
484                if any_up {
485                    return DrainOutcome::Stalled(events);
486                }
487            }
488            received = recv_any_open_subscription(subscriptions) => {
489                // `None` means a channel closed; the loop re-checks all-closed.
490                if let Some(event) = received {
491                    events.push(event);
492                }
493            }
494        }
495    }
496}
497
498impl Drop for ManagedBacktestSession {
499    fn drop(&mut self) {
500        self.session_cancel.cancel();
501    }
502}
503
504pub(super) async fn wait_any_subscription_change(
505    subscriptions: &mut [watch::Receiver<ConnectionStatus>],
506) {
507    if subscriptions.is_empty() {
508        std::future::pending::<()>().await;
509        return;
510    }
511    let _ =
512        futures::future::select_all(subscriptions.iter_mut().map(|s| Box::pin(s.changed()))).await;
513}
514
515pub(super) async fn wait_any_subscription_event(
516    subscriptions: &mut [SubscriptionHandle],
517) -> ManagedEvent {
518    loop {
519        if let Some(event) = try_next_subscription_event(subscriptions) {
520            return event;
521        }
522
523        let futures: Vec<_> = subscriptions
524            .iter_mut()
525            .filter(|s| !s.notifications.is_closed())
526            .map(|s| Box::pin(s.notifications.recv()))
527            .collect();
528
529        if futures.is_empty() {
530            std::future::pending::<()>().await;
531        }
532
533        let (notification, _, _) = futures::future::select_all(futures).await;
534        if let Some(notification) = notification {
535            return notification.into();
536        }
537    }
538}
539
540/// Await the next notification from any still-open subscription channel,
541/// returning `None` when one closes. Unlike [`wait_any_subscription_event`],
542/// which never resolves on closure, this lets the completion drain observe
543/// per-channel end-of-stream.
544pub(super) async fn recv_any_open_subscription(
545    subscriptions: &mut [SubscriptionHandle],
546) -> Option<ManagedEvent> {
547    let futures: Vec<_> = subscriptions
548        .iter_mut()
549        .filter(|s| !s.notifications.is_closed())
550        .map(|s| Box::pin(s.notifications.recv()))
551        .collect();
552
553    if futures.is_empty() {
554        return None;
555    }
556
557    let (notification, _, _) = futures::future::select_all(futures).await;
558    notification.map(Into::into)
559}
560
561pub(super) fn try_next_subscription_event(
562    subscriptions: &mut [SubscriptionHandle],
563) -> Option<ManagedEvent> {
564    for subscription in subscriptions {
565        if let Ok(notification) = subscription.notifications.try_recv() {
566            return Some(notification.into());
567        }
568    }
569    None
570}
571
572impl From<ControlEvent> for ManagedEvent {
573    fn from(event: ControlEvent) -> Self {
574        match event {
575            ControlEvent::ReadyForContinue => Self::ReadyForContinue,
576            ControlEvent::Paused(event) => Self::Paused(event),
577            ControlEvent::DiscoveryBatch(event) => Self::DiscoveryBatch(event),
578            ControlEvent::Slot(slot) => Self::Slot(slot),
579            ControlEvent::Status(status) => Self::Status(status),
580            ControlEvent::Completed {
581                summary,
582                agent_stats,
583            } => Self::Completed {
584                summary,
585                agent_stats,
586            },
587            ControlEvent::Error(error) => Self::Error(error),
588        }
589    }
590}
591
592impl From<SubscriptionNotification> for ManagedEvent {
593    fn from(notification: SubscriptionNotification) -> Self {
594        match notification {
595            SubscriptionNotification::Transaction(transaction) => Self::Transaction(transaction),
596            SubscriptionNotification::AccountDiff(diff) => Self::AccountDiff(diff),
597            SubscriptionNotification::ActionResult(result) => Self::ActionResult(result),
598        }
599    }
600}