Skip to main content

simulator_client/managed/
mod.rs

1//! Connection-managed wrappers over the backtest WebSocket protocol.
2//!
3//! Most callers should use [`ManagedBacktestSession`]. It owns the control and
4//! subscription manager tasks, waits for session creation, gates `Continue`
5//! sends on live connections, and provides one shutdown path.
6//!
7//! The control and subscription WebSockets are each owned by a dedicated task
8//! that handles its own lifecycle: connect, handshake, keepalive, reconnect.
9//! Workload code interacts via channels and a status watcher, never with the
10//! WebSocket directly.
11//!
12//! Reconnect doubles as session handoff. The management service closes live
13//! control WebSockets with code `1012` when it is redeployed; the session
14//! itself keeps running and waits to be claimed. The control task's reconnect
15//! handshake sends `AttachBacktestSession` + `ResumeAttachedSession` instead of
16//! a create, so the session resumes with the responses missed in between
17//! replayed from the last observed sequence number. Nothing above this layer
18//! observes the restart beyond a [`ConnectionStatus::Down`] blip.
19
20use std::{
21    future::Future,
22    sync::{
23        Arc,
24        atomic::{AtomicU64, AtomicUsize, Ordering},
25    },
26    time::{Duration, Instant},
27};
28
29use bon::Builder;
30use futures::SinkExt;
31use rand::RngExt;
32use simulator_api::{BacktestError, BacktestRequest, CreateBacktestSessionRequest, SessionId};
33use tokio::{
34    net::TcpStream,
35    sync::{Notify, OwnedSemaphorePermit, Semaphore, watch},
36};
37use tokio_tungstenite::{
38    MaybeTlsStream, WebSocketStream, connect_async,
39    tungstenite::{Error as WsError, Message, client::IntoClientRequest, http::HeaderValue},
40};
41use tokio_util::sync::CancellationToken;
42use tracing::warn;
43
44use crate::error::err_chain;
45
46mod control;
47mod parallel;
48mod session;
49mod subscription;
50
51pub use control::{ControlEvent, ControlHandle, spawn_control_manager};
52pub use parallel::{ManagedParallelSession, ParallelSubSession};
53pub use session::{ManagedBacktestSession, ManagedEvent, ManagedSessionError};
54pub use subscription::{
55    SubscriptionHandle, SubscriptionNotification, spawn_account_diff_subscription_manager,
56    spawn_action_subscription_manager, spawn_transaction_subscription_manager,
57};
58
59/// Timeout for the initial WebSocket connect (TCP + TLS + HTTP upgrade).
60pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
61
62/// Timeout for any single response during a handshake (Create, Attach, Resume,
63/// subscribe ack). Does not apply to per-message reads during an established
64/// session — those are bounded by ping/pong liveness instead.
65///
66/// Set generously because the management service can park subscribe upgrades
67/// for the duration of session startup (observed ~100s on cold runtimes); a
68/// shorter timeout fires before management can forward the subscribe message
69/// and gets reported as "subscribe ack timeout" even though the session is
70/// fine. The proper fix is server-side (reject parked upgrades cleanly), but
71/// this keeps the client from giving up early in the meantime.
72pub const HANDSHAKE_RESPONSE_TIMEOUT: Duration = Duration::from_secs(120);
73
74/// How often to send a WebSocket ping during an established connection.
75pub const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(15);
76
77/// How long without inbound traffic before declaring the connection dead.
78/// Roughly three missed pings.
79pub const KEEPALIVE_MISS_DEADLINE: Duration = Duration::from_secs(45);
80
81/// Total budget for the graceful close handshake (close request + close frame).
82/// A supervisor's SIGTERM→SIGKILL grace must exceed this or the close is cut short.
83pub const GRACEFUL_CLOSE_TIMEOUT: Duration = Duration::from_secs(5);
84
85pub const RECONNECT_INITIAL_BACKOFF: Duration = Duration::from_secs(1);
86pub const RECONNECT_MAX_BACKOFF: Duration = Duration::from_secs(30);
87pub const RECONNECT_BACKOFF_MULTIPLIER: f64 = 2.0;
88pub const RECONNECT_JITTER: f64 = 0.2;
89pub const RECONNECT_MAX_TOTAL: Duration = Duration::from_secs(5 * 60);
90pub const RECONNECT_MAX_ATTEMPTS: u32 = 20;
91
92/// Reconnect attempts that fire immediately, before the cross-session reconnect
93/// gate engages. A transient drop recovers fast; only once these rapid retries
94/// are exhausted does a session fall back to waiting for siblings to drain.
95pub const RECONNECT_UNGATED_ATTEMPTS: u32 = 5;
96
97/// A connection that stays `Up` for this long resets the reconnect counter.
98pub const RECONNECT_UPTIME_RESET: Duration = Duration::from_secs(30);
99
100/// `disconnect_timeout_secs` applied to a single-session create that leaves it
101/// unset — how long the server keeps the session alive with no client attached.
102///
103/// The server's own default is tens of seconds, which is shorter than the
104/// reconnect budget below: a session whose management host is redeployed gets
105/// reclaimed while this client is still retrying. Cover the whole budget plus a
106/// margin for the attach + resume handshake. Stays under the server's 900s cap.
107pub const DEFAULT_DISCONNECT_TIMEOUT_SECS: u16 = RECONNECT_MAX_TOTAL.as_secs() as u16 + 60;
108
109/// Connection state as observed from outside the manager task.
110///
111/// `Down` is a transient "currently not connected, manager is retrying"
112/// state. `Failed` is terminal; the retry budget was exhausted.
113#[derive(Clone, Debug, PartialEq, Eq)]
114pub enum ConnectionStatus {
115    Up,
116    Down,
117    Failed(String),
118}
119
120/// Identity of a created backtest session.
121#[derive(Clone, Debug)]
122pub struct SessionInfo {
123    pub session_id: SessionId,
124    pub rpc_endpoint: String,
125    /// Opaque `task_id` reported by the server for this session, if any.
126    pub task_id: Option<String>,
127}
128
129/// Parameters shared by [`ManagedBacktestSession`] and
130/// [`ManagedParallelSession`] startup.
131///
132/// A standalone session only needs `url`, `api_key` and `create`; the rest
133/// default to a session-owned cancellation token and its own counters.
134#[derive(Debug, Clone, Builder)]
135pub struct StartSessionParams {
136    /// Backtest WebSocket base URL.
137    pub url: String,
138    pub api_key: String,
139    pub create: CreateBacktestSessionRequest,
140    /// Cancelling this aborts startup and stops the manager tasks.
141    #[builder(default)]
142    pub parent_cancel: CancellationToken,
143    /// Collects data-plane counters from every subscription the session spawns;
144    /// share one across sessions to aggregate a whole run.
145    #[builder(default)]
146    pub subscription_diagnostics: Arc<SubscriptionDiagnostics>,
147}
148
149/// Data-plane diagnostics counters, shared across every subscription manager a
150/// run spawns.
151#[derive(Debug, Default)]
152pub struct SubscriptionDiagnostics {
153    /// Excludes each subscription task's first connection.
154    reconnects: AtomicU64,
155}
156
157impl SubscriptionDiagnostics {
158    pub(crate) fn record_reconnect(&self) {
159        self.reconnects.fetch_add(1, Ordering::Relaxed);
160    }
161
162    pub fn reconnects(&self) -> u64 {
163        self.reconnects.load(Ordering::Relaxed)
164    }
165}
166
167/// Tracks reconnect attempts and enforces the reconnect policy.
168pub(crate) struct ReconnectBudget {
169    attempts: u32,
170    started_at: std::time::Instant,
171    current_backoff: Duration,
172}
173
174impl ReconnectBudget {
175    pub fn new() -> Self {
176        Self {
177            attempts: 0,
178            started_at: std::time::Instant::now(),
179            current_backoff: RECONNECT_INITIAL_BACKOFF,
180        }
181    }
182
183    pub fn reset(&mut self) {
184        self.attempts = 0;
185        self.started_at = std::time::Instant::now();
186        self.current_backoff = RECONNECT_INITIAL_BACKOFF;
187    }
188
189    pub fn attempt(&self) -> u32 {
190        self.attempts
191    }
192
193    /// Discount time the subscription spent parked behind the reconnect
194    /// coordinator. Parking is deliberate waiting for siblings to free the
195    /// link, not retry thrashing, so it must not count against the wall-clock
196    /// budget — otherwise a session that correctly steps aside for minutes is
197    /// failed the moment it reconnects. The attempt-count ceiling still bounds
198    /// total retries.
199    pub fn discount_parked(&mut self, parked: Duration) {
200        self.started_at += parked;
201    }
202
203    /// Record an attempt and return its backoff, or `None` if the budget is
204    /// exhausted.
205    pub fn next_backoff(&mut self) -> Option<Duration> {
206        if self.attempts >= RECONNECT_MAX_ATTEMPTS
207            || self.started_at.elapsed() >= RECONNECT_MAX_TOTAL
208        {
209            return None;
210        }
211        self.attempts += 1;
212        let backoff = with_jitter(self.current_backoff);
213        self.current_backoff = std::cmp::min(
214            RECONNECT_MAX_BACKOFF,
215            Duration::from_secs_f64(
216                self.current_backoff.as_secs_f64() * RECONNECT_BACKOFF_MULTIPLIER,
217            ),
218        );
219        Some(backoff)
220    }
221}
222
223/// Coordinates subscription reconnects across a parallel batch sharing one
224/// bandwidth-constrained link.
225///
226/// A dropped subscription competing with its still-streaming siblings just
227/// starves — the handshake can't get through a saturated pipe. So once a session
228/// has burned its fast ungated attempts, it stops fighting and **parks until no
229/// sibling is streaming** (the connected sessions have finished and freed their
230/// bandwidth), then reconnects into the quiet link and resumes via
231/// `replayFromSlot`. Stepping aside also speeds the streaming siblings up, so the
232/// batch drains and the parked sessions recover — serially, one at a time, since
233/// at a tight rate only one stream fits.
234pub struct ReconnectCoordinator {
235    /// Subscriptions currently `Up` and streaming. A parked session waits for
236    /// this to reach zero before reconnecting.
237    streaming: AtomicUsize,
238    /// Woken whenever `streaming` decreases, so parked sessions re-check.
239    drained: Notify,
240    /// One in-flight reconnect handshake at a time, so the all-parked case
241    /// recovers serially rather than storming the link the moment it goes quiet.
242    handshake: Arc<Semaphore>,
243}
244
245impl Default for ReconnectCoordinator {
246    fn default() -> Self {
247        Self::new()
248    }
249}
250
251impl ReconnectCoordinator {
252    pub fn new() -> Self {
253        Self {
254            streaming: AtomicUsize::new(0),
255            drained: Notify::new(),
256            handshake: Arc::new(Semaphore::new(1)),
257        }
258    }
259
260    /// Mark this subscription as streaming until the returned guard drops.
261    /// Call once a (re)subscribe succeeds; the guard's `Drop` decrements the
262    /// count and wakes any sibling parked in [`Self::reconnect_slot`]. RAII so
263    /// a panicking or aborted task can't leak the count and wedge the batch.
264    pub fn enter(self: &Arc<Self>) -> StreamingGuard {
265        self.streaming.fetch_add(1, Ordering::SeqCst);
266        StreamingGuard(self.clone())
267    }
268
269    /// Park until no sibling is streaming, then take the single reconnect slot.
270    /// The returned permit must be held across connect + subscribe and dropped
271    /// once [`Self::enter`] has been called (or the attempt failed), so the next
272    /// parked session proceeds only after this one is streaming again. Returns
273    /// `None` if cancelled.
274    pub async fn reconnect_slot(&self, cancel: &CancellationToken) -> Option<OwnedSemaphorePermit> {
275        loop {
276            // Wait for the link to go quiet. Register interest before reading so
277            // a `leave()` between the check and the wait isn't lost.
278            loop {
279                let drained = self.drained.notified();
280                if self.streaming.load(Ordering::SeqCst) == 0 {
281                    break;
282                }
283                tokio::select! {
284                    biased;
285                    _ = cancel.cancelled() => return None,
286                    _ = drained => {}
287                }
288            }
289            let permit = tokio::select! {
290                biased;
291                _ = cancel.cancelled() => return None,
292                p = self.handshake.clone().acquire_owned() => p.ok()?,
293            };
294            // A sibling may have re-entered while we queued for the permit; if so,
295            // release it and wait for quiet again rather than reconnect into
296            // contention.
297            if self.streaming.load(Ordering::SeqCst) == 0 {
298                return Some(permit);
299            }
300        }
301    }
302}
303
304/// Holds a [`ReconnectCoordinator`]'s streaming count for the lifetime of one
305/// connection; decrements and wakes parked siblings on drop.
306pub struct StreamingGuard(Arc<ReconnectCoordinator>);
307
308impl Drop for StreamingGuard {
309    fn drop(&mut self) {
310        self.0.streaming.fetch_sub(1, Ordering::SeqCst);
311        self.0.drained.notify_waiters();
312    }
313}
314
315fn with_jitter(d: Duration) -> Duration {
316    let jitter = rand::rng().random_range(-RECONNECT_JITTER..RECONNECT_JITTER);
317    let secs = (d.as_secs_f64() * (1.0 + jitter)).max(0.0);
318    Duration::from_secs_f64(secs)
319}
320
321/// Sleep for `delay`, returning early on cancellation. Returns `true` if the
322/// sleep completed, `false` if cancelled.
323pub(crate) async fn cancellable_sleep(delay: Duration, cancel: &CancellationToken) -> bool {
324    tokio::select! {
325        _ = tokio::time::sleep(delay) => true,
326        _ = cancel.cancelled() => false,
327    }
328}
329
330/// A managed control WebSocket stream.
331pub(super) type Ws = WebSocketStream<MaybeTlsStream<TcpStream>>;
332
333/// Open a control WebSocket to `url`, attaching the API-key header, bounded by
334/// [`CONNECT_TIMEOUT`]. Shared by the single-session and parallel managers.
335pub(super) async fn connect_ws(url: &str, api_key: &str) -> Result<Ws, String> {
336    let mut request = url
337        .into_client_request()
338        .map_err(|e| format!("build request: {}", err_chain(&e)))?;
339    request.headers_mut().insert(
340        "X-API-Key",
341        HeaderValue::from_str(api_key).map_err(|e| format!("api key header: {}", err_chain(&e)))?,
342    );
343
344    let connect = tokio::time::timeout(CONNECT_TIMEOUT, connect_async(request))
345        .await
346        .map_err(|_| format!("connect timeout after {CONNECT_TIMEOUT:?}"))?
347        .map_err(|e| format!("connect: {}", err_chain(&e)))?;
348    Ok(connect.0)
349}
350
351/// Serialize and send a `BacktestRequest` over a control WebSocket.
352pub(super) async fn send_request(ws: &mut Ws, req: &BacktestRequest) -> Result<(), String> {
353    let text = serde_json::to_string(req).map_err(|e| format!("serialize: {}", err_chain(&e)))?;
354    ws.send(Message::Text(text))
355        .await
356        .map_err(|e| format!("send: {}", err_chain(&e)))
357}
358
359/// Resolve a server-reported `rpc_endpoint` to an absolute URL: pass through an
360/// already-absolute endpoint, otherwise join it onto the control `base`.
361pub(super) fn resolve_rpc_url(base: &str, endpoint: &str) -> String {
362    if endpoint.starts_with("http://") || endpoint.starts_with("https://") {
363        endpoint.to_string()
364    } else {
365        format!("{}/{}", base, endpoint.trim_start_matches('/'))
366    }
367}
368
369/// Outcome of a control-WS handshake (create/attach/resume).
370pub(super) enum HandshakeError {
371    /// Recoverable (network blip, or the session is momentarily contended).
372    Transient(String),
373    /// Unrecoverable — the server rejected the session outright.
374    Fatal(String),
375}
376
377/// Classify a `BacktestError` returned during a handshake `stage`: a contended
378/// session is expected to become claimable shortly (transient); anything else is
379/// fatal.
380pub(super) fn handshake_error_for_response(
381    stage: &'static str,
382    err: BacktestError,
383) -> HandshakeError {
384    match err {
385        BacktestError::SessionOwnershipBusy { .. } => {
386            HandshakeError::Transient(format!("{stage} contended: {}", err_chain(&err)))
387        }
388        _ => HandshakeError::Fatal(format!("{stage} rejected: {}", err_chain(&err))),
389    }
390}
391
392/// Why a control task's message loop exited. Shared by the single-session and
393/// parallel control managers.
394pub(super) enum MessageLoopExit {
395    /// Server reported the session(s) done, or the driver(s) dropped the request
396    /// channel. Calls for a graceful WS close.
397    SessionEnded,
398    /// Cancellation token fired. Still graceful-closes so the server reaps the
399    /// runtime now instead of after the disconnect timeout.
400    Cancelled,
401    /// Connection lost — attempt to reconnect.
402    ConnectionLost(String),
403    /// Protocol or application error with no sensible recovery.
404    Terminal(String),
405}
406
407/// Publish a `ConnectionStatus` transition, suppressing no-op updates.
408pub(super) fn publish_status(
409    status_tx: &watch::Sender<ConnectionStatus>,
410    status: ConnectionStatus,
411) {
412    status_tx.send_if_modified(|current| {
413        if *current == status {
414            false
415        } else {
416            *current = status;
417            true
418        }
419    });
420}
421
422/// Send `CloseBacktestSession` then the WS close frame, bounded by a single
423/// [`GRACEFUL_CLOSE_TIMEOUT`] budget. The close request makes the server reap
424/// the runtime(s) immediately instead of waiting out the disconnect timeout; the
425/// close frame is best-effort cleanup.
426pub(super) async fn graceful_close(ws: &mut Ws) {
427    let _ = tokio::time::timeout(GRACEFUL_CLOSE_TIMEOUT, async {
428        let _ = send_request(ws, &BacktestRequest::CloseBacktestSession).await;
429        let _ = ws.close(None).await;
430    })
431    .await;
432}
433
434/// An inbound control frame, classified for the message loop.
435pub(super) enum InboundFrame {
436    /// A text (or UTF-8 binary) payload to parse.
437    Text(String),
438    /// A frame with no application payload (ping/pong/raw/non-UTF-8 binary).
439    Ignore,
440    /// The connection ended or errored; carries the loss reason.
441    Lost(String),
442}
443
444/// Classify the result of `ws.next()` for a control message loop.
445pub(super) fn classify_inbound(msg: Option<Result<Message, WsError>>) -> InboundFrame {
446    match msg {
447        Some(Ok(Message::Text(t))) => InboundFrame::Text(t),
448        Some(Ok(Message::Binary(b))) => match String::from_utf8(b) {
449            Ok(t) => InboundFrame::Text(t),
450            Err(_) => InboundFrame::Ignore,
451        },
452        Some(Ok(Message::Pong(_) | Message::Ping(_) | Message::Frame(_))) => InboundFrame::Ignore,
453        Some(Ok(Message::Close(frame))) => InboundFrame::Lost(format!("remote close: {frame:?}")),
454        Some(Err(e)) => InboundFrame::Lost(format!("ws read: {}", err_chain(&e))),
455        None => InboundFrame::Lost("ws stream ended".into()),
456    }
457}
458
459/// Send a keepalive ping unless inbound traffic has been silent past the
460/// deadline. Returns the loss reason if the connection should be considered
461/// dead, else `None`.
462pub(super) async fn send_keepalive_ping(ws: &mut Ws, last_inbound: Instant) -> Option<String> {
463    if last_inbound.elapsed() > KEEPALIVE_MISS_DEADLINE {
464        return Some(format!("no traffic for {:?}", last_inbound.elapsed()));
465    }
466    if let Err(e) = ws.send(Message::Ping(vec![])).await {
467        return Some(format!("ping send: {}", err_chain(&e)));
468    }
469    None
470}
471
472/// A control WebSocket task: connect, handshake, run a message loop, reconnect.
473/// [`run_control_loop`] drives the shared connect/backoff/exit state machine;
474/// implementors supply the protocol-specific handshake and message loop.
475pub(super) trait ControlConnection: Send + 'static {
476    fn url(&self) -> &str;
477    fn api_key(&self) -> &str;
478    fn cancel(&self) -> &CancellationToken;
479    /// Prefix for reconnect log lines, e.g. `"control"` / `"parallel control"`.
480    fn label(&self) -> &'static str;
481    fn status_tx(&self) -> &watch::Sender<ConnectionStatus>;
482    /// Fail the pending create one-shot with `reason` (no-op once fired).
483    fn fail_pending(&mut self, reason: String);
484    /// Create on first connect, attach/resume on reconnect.
485    fn handshake(&mut self, ws: Ws) -> impl Future<Output = Result<Ws, HandshakeError>> + Send;
486    /// Drive the established connection until it exits.
487    fn message_loop(&mut self, ws: Ws) -> impl Future<Output = MessageLoopExit> + Send;
488
489    fn publish(&self, status: ConnectionStatus) {
490        publish_status(self.status_tx(), status);
491    }
492
493    fn finish_failed(&mut self, reason: String) {
494        self.fail_pending(reason.clone());
495        self.publish(ConnectionStatus::Failed(reason));
496    }
497}
498
499/// Drive a [`ControlConnection`] through its connect → handshake → run →
500/// reconnect lifecycle until the session ends, is cancelled, or the reconnect
501/// budget is exhausted.
502pub(super) async fn run_control_loop<T: ControlConnection>(mut task: T) {
503    let mut budget = ReconnectBudget::new();
504
505    loop {
506        if task.cancel().is_cancelled() {
507            task.fail_pending("cancelled before session created".to_string());
508            return;
509        }
510        task.publish(ConnectionStatus::Down);
511
512        let ws = match connect_ws(task.url(), task.api_key()).await {
513            Ok(ws) => ws,
514            Err(why) => {
515                if let Some(delay) = budget.next_backoff() {
516                    warn!(attempt = budget.attempt(), error = %why, ?delay, "{} connect failed, retrying", task.label());
517                    if !cancellable_sleep(delay, task.cancel()).await {
518                        return;
519                    }
520                    continue;
521                }
522                task.finish_failed(format!("connect: {why}"));
523                return;
524            }
525        };
526
527        let ws = match task.handshake(ws).await {
528            Ok(ws) => ws,
529            Err(HandshakeError::Fatal(why)) => {
530                task.finish_failed(format!("handshake: {why}"));
531                return;
532            }
533            Err(HandshakeError::Transient(why)) => {
534                if let Some(delay) = budget.next_backoff() {
535                    warn!(attempt = budget.attempt(), error = %why, ?delay, "{} handshake failed, retrying", task.label());
536                    if !cancellable_sleep(delay, task.cancel()).await {
537                        return;
538                    }
539                    continue;
540                }
541                task.finish_failed(format!("handshake: {why}"));
542                return;
543            }
544        };
545
546        task.publish(ConnectionStatus::Up);
547        let connected_at = Instant::now();
548
549        match task.message_loop(ws).await {
550            MessageLoopExit::SessionEnded | MessageLoopExit::Cancelled => return,
551            MessageLoopExit::ConnectionLost(why) => {
552                if connected_at.elapsed() >= RECONNECT_UPTIME_RESET {
553                    budget.reset();
554                }
555                if let Some(delay) = budget.next_backoff() {
556                    warn!(attempt = budget.attempt(), reason = %why, ?delay, "{} connection lost, reconnecting", task.label());
557                    if !cancellable_sleep(delay, task.cancel()).await {
558                        return;
559                    }
560                    continue;
561                }
562                task.finish_failed(format!("connection lost: {why}"));
563                return;
564            }
565            MessageLoopExit::Terminal(why) => {
566                task.finish_failed(why);
567                return;
568            }
569        }
570    }
571}
572
573#[cfg(test)]
574mod tests {
575    use super::*;
576
577    #[test]
578    fn budget_exhausts_after_max_attempts() {
579        let mut b = ReconnectBudget::new();
580        for _ in 0..RECONNECT_MAX_ATTEMPTS {
581            assert!(b.next_backoff().is_some());
582        }
583        assert!(b.next_backoff().is_none());
584    }
585
586    #[test]
587    fn budget_reset_restores_full_budget() {
588        let mut b = ReconnectBudget::new();
589        b.next_backoff();
590        b.next_backoff();
591        b.reset();
592        assert_eq!(b.attempt(), 0);
593    }
594
595    #[test]
596    fn streaming_guard_balances_the_count() {
597        let coord = Arc::new(ReconnectCoordinator::new());
598        assert_eq!(coord.streaming.load(Ordering::SeqCst), 0);
599        let g = coord.enter();
600        assert_eq!(coord.streaming.load(Ordering::SeqCst), 1);
601        drop(g);
602        assert_eq!(coord.streaming.load(Ordering::SeqCst), 0);
603    }
604
605    #[tokio::test]
606    async fn reconnect_slot_available_when_link_is_quiet() {
607        let coord = Arc::new(ReconnectCoordinator::new());
608        let cancel = CancellationToken::new();
609        assert!(coord.reconnect_slot(&cancel).await.is_some());
610    }
611
612    #[tokio::test]
613    async fn reconnect_slot_unparks_when_last_sibling_leaves() {
614        let coord = Arc::new(ReconnectCoordinator::new());
615        let cancel = CancellationToken::new();
616        let guard = coord.enter(); // streaming == 1, so a slot request must park
617
618        let waiter = tokio::spawn({
619            let coord = coord.clone();
620            let cancel = cancel.clone();
621            async move { coord.reconnect_slot(&cancel).await.is_some() }
622        });
623
624        // While a sibling streams, the parked request stays pending.
625        tokio::task::yield_now().await;
626        assert!(!waiter.is_finished());
627
628        drop(guard); // streaming -> 0, wakes the parked request
629        assert!(waiter.await.unwrap());
630    }
631
632    #[tokio::test]
633    async fn reconnect_slot_returns_none_on_cancel_while_parked() {
634        let coord = Arc::new(ReconnectCoordinator::new());
635        let _guard = coord.enter(); // keep the link busy so the request parks
636        let cancel = CancellationToken::new();
637        cancel.cancel();
638        assert!(coord.reconnect_slot(&cancel).await.is_none());
639    }
640
641    #[test]
642    fn discount_parked_does_not_consume_the_budget() {
643        let mut b = ReconnectBudget::new();
644        // A long park must leave the full attempt budget intact afterwards.
645        b.discount_parked(2 * RECONNECT_MAX_TOTAL);
646        for _ in 0..RECONNECT_MAX_ATTEMPTS {
647            assert!(b.next_backoff().is_some());
648        }
649    }
650}