Skip to main content

simulator_client/managed/
session.rs

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