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