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