Skip to main content

simulator_client/managed/
parallel.rs

1//! ParallelControlManager — owns the multiplexed parallel-control WebSocket.
2//!
3//! A single control connection drives N server-created sub-sessions. The server
4//! splits the requested range, streams one `SessionCreated` per sub-session plus
5//! a terminal `SessionsCreatedV2`, then multiplexes per-session control events as
6//! `SessionEventV2 { session_id, seq_id, event }`. This task demultiplexes those
7//! into one [`ControlEvent`] channel per sub-session and routes each driver's
8//! `Continue` back as `ContinueSessionV1`. On reconnect it re-attaches with
9//! `AttachParallelControlSessionV2` and the per-session sequence cursors, dropping
10//! any replayed events the driver already saw.
11//!
12//! Transactions are NOT multiplexed: each sub-session exposes its own
13//! `rpc_endpoint`, so [`ParallelSubSession`] spawns its own data-plane
14//! subscription managers exactly like [`super::ManagedBacktestSession`].
15
16use std::{
17    collections::{HashMap, VecDeque},
18    sync::Arc,
19};
20
21use futures::StreamExt;
22use http::HeaderMap;
23use simulator_api::{
24    BacktestError, BacktestRequest, BacktestResponse, ContinueParams, ContinueSessionRequestV1,
25    ControlSessionId, CreateBacktestSessionRequest, SessionEventKind, SessionId,
26};
27use solana_address::Address;
28use tokio::{
29    sync::{mpsc, oneshot, watch},
30    task::JoinHandle,
31};
32use tokio_tungstenite::tungstenite::Message;
33use tokio_util::sync::CancellationToken;
34use tracing::{debug, info, warn};
35
36use super::{
37    ConnectionStatus, ControlConnection, ControlEvent, HANDSHAKE_RESPONSE_TIMEOUT, HandshakeError,
38    InboundFrame, KEEPALIVE_INTERVAL, ManagedEvent, ManagedSessionError, MessageLoopExit,
39    ReconnectCoordinator, SessionInfo, StartSessionParams, SubscriptionDiagnostics,
40    SubscriptionHandle, Ws, classify_inbound, graceful_close, handshake_error_for_response,
41    resolve_rpc_url, run_control_loop, send_keepalive_ping, send_request,
42    session::{
43        DrainOutcome, drain_subscriptions_until_complete, try_next_subscription_event,
44        wait_any_subscription_event, wait_connections_up,
45    },
46    spawn_account_diff_subscription_manager, spawn_action_subscription_manager,
47    spawn_transaction_subscription_manager,
48};
49use crate::{error::err_chain, urls::http_base_from_ws_url};
50
51/// Per-read timeout while streaming the create response. Generous because the
52/// server may park between `SessionCreated`s waiting for sub-session capacity.
53const CREATE_RESPONSE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(900);
54/// Capacity of the shared `Continue` request channel feeding the control task.
55/// One in-flight `Continue` per sub-session is the steady state.
56const CONTINUE_CHANNEL_CAPACITY: usize = 256;
57/// Liveness backstop for a sub-session's completion drain (see
58/// [`super::ManagedBacktestSession`]'s equivalent).
59const COMPLETION_DRAIN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
60
61/// A `Continue` request tagged with the sub-session it targets.
62type TaggedContinue = (SessionId, ContinueParams);
63
64/// Result of the parallel-create handshake handed back to the caller.
65struct ParallelCreated {
66    control_session_id: ControlSessionId,
67    control_session_name: Option<String>,
68    sessions: Vec<CreatedSubSession>,
69}
70
71struct CreatedSubSession {
72    info: SessionInfo,
73    events: mpsc::UnboundedReceiver<ControlEvent>,
74    /// Server-authoritative sub-session range, back-filled from
75    /// `SessionsCreatedV2` before the create handshake returns (a server that
76    /// omits the ranges is rejected as too old, so this is never left at `0`).
77    start_slot: u64,
78    end_slot: u64,
79}
80
81/// Handle to a running [`ParallelControlTask`].
82struct ParallelControlHandle {
83    continues: mpsc::Sender<TaggedContinue>,
84    status: watch::Receiver<ConnectionStatus>,
85    created: Option<oneshot::Receiver<Result<ParallelCreated, String>>>,
86    join: JoinHandle<()>,
87}
88
89impl ParallelControlHandle {
90    /// Resolve once the parallel create handshake has produced the sub-session
91    /// set (or failed). Consumes the one-shot; callable only once.
92    async fn wait_created(&mut self) -> Result<ParallelCreated, String> {
93        let rx = self
94            .created
95            .take()
96            .ok_or_else(|| "parallel create already consumed".to_string())?;
97        rx.await
98            .map_err(|_| "control manager exited before creating sessions".to_string())?
99    }
100
101    /// Await the control task's exit; dropping the request channels nudges it to
102    /// stop if the caller is giving up.
103    async fn join(self) {
104        drop(self.continues);
105        let _ = self.join.await;
106    }
107}
108
109fn spawn_parallel_control_manager(
110    url: String,
111    api_key: String,
112    extra_headers: HeaderMap,
113    create: CreateBacktestSessionRequest,
114    cancel: CancellationToken,
115) -> ParallelControlHandle {
116    let (continues_tx, continues_rx) = mpsc::channel::<TaggedContinue>(CONTINUE_CHANNEL_CAPACITY);
117    let (status_tx, status_rx) = watch::channel(ConnectionStatus::Down);
118    let (created_tx, created_rx) = oneshot::channel::<Result<ParallelCreated, String>>();
119
120    let task = ParallelControlTask {
121        url,
122        api_key,
123        extra_headers,
124        create: Some(create),
125        control_session_id: None,
126        event_txs: HashMap::new(),
127        last_sequences: HashMap::new(),
128        completed: std::collections::HashSet::new(),
129        continues_rx,
130        status_tx,
131        created_tx: Some(created_tx),
132        cancel,
133    };
134
135    let join = tokio::spawn(run_control_loop(task));
136
137    ParallelControlHandle {
138        continues: continues_tx,
139        status: status_rx,
140        created: Some(created_rx),
141        join,
142    }
143}
144
145struct ParallelControlTask {
146    url: String,
147    api_key: String,
148    extra_headers: HeaderMap,
149    /// Set on first connect; consumed and cleared after the create handshake.
150    create: Option<CreateBacktestSessionRequest>,
151    /// Populated after create; used to build `AttachParallelControlSessionV2`.
152    control_session_id: Option<ControlSessionId>,
153    /// Per-sub-session demux senders, keyed by `session_id`. Unbounded so a
154    /// slow driver never head-of-line blocks the shared control connection.
155    event_txs: HashMap<SessionId, mpsc::UnboundedSender<ControlEvent>>,
156    /// Highest `seq_id` delivered per sub-session — the reconnect cursor and the
157    /// replay-dedup key.
158    last_sequences: HashMap<SessionId, u64>,
159    /// Sub-sessions that have reported `Completed`. Once all have, the control
160    /// stream is done and the task closes gracefully.
161    completed: std::collections::HashSet<String>,
162    continues_rx: mpsc::Receiver<TaggedContinue>,
163    status_tx: watch::Sender<ConnectionStatus>,
164    created_tx: Option<oneshot::Sender<Result<ParallelCreated, String>>>,
165    cancel: CancellationToken,
166}
167
168impl ControlConnection for ParallelControlTask {
169    fn url(&self) -> &str {
170        &self.url
171    }
172    fn api_key(&self) -> &str {
173        &self.api_key
174    }
175    fn extra_headers(&self) -> &HeaderMap {
176        &self.extra_headers
177    }
178    fn cancel(&self) -> &CancellationToken {
179        &self.cancel
180    }
181    fn label(&self) -> &'static str {
182        "parallel control"
183    }
184    fn status_tx(&self) -> &watch::Sender<ConnectionStatus> {
185        &self.status_tx
186    }
187
188    fn fail_pending(&mut self, reason: String) {
189        if let Some(tx) = self.created_tx.take() {
190            let _ = tx.send(Err(reason));
191        }
192    }
193
194    async fn handshake(&mut self, ws: Ws) -> Result<Ws, HandshakeError> {
195        if let Some(control_session_id) = self.control_session_id {
196            self.attach(ws, &control_session_id).await
197        } else if let Some(create) = self.create.clone() {
198            // Clone rather than take: a transient drop mid-create must leave the
199            // request intact so the reconnect can recreate. `create_sessions`
200            // clears it (and sets `control_session_id`) only on success, after
201            // which reconnects route to `attach` above.
202            self.create_sessions(ws, create).await
203        } else {
204            Err(HandshakeError::Fatal(
205                "no create request and no control_session_id".into(),
206            ))
207        }
208    }
209
210    async fn message_loop(&mut self, mut ws: Ws) -> MessageLoopExit {
211        let mut ping_timer = tokio::time::interval(KEEPALIVE_INTERVAL);
212        ping_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
213        let mut last_inbound = std::time::Instant::now();
214
215        let exit = loop {
216            tokio::select! {
217                biased;
218                _ = self.cancel.cancelled() => break MessageLoopExit::Cancelled,
219
220                _ = ping_timer.tick() => {
221                    if let Some(why) = send_keepalive_ping(&mut ws, last_inbound).await {
222                        break MessageLoopExit::ConnectionLost(why);
223                    }
224                }
225
226                msg = ws.next() => {
227                    last_inbound = std::time::Instant::now();
228                    match classify_inbound(msg) {
229                        InboundFrame::Text(t) => {
230                            if let Some(exit) = self.handle_text(&t) {
231                                break exit;
232                            }
233                        }
234                        InboundFrame::Ignore => {}
235                        InboundFrame::Lost(why) => break MessageLoopExit::ConnectionLost(why),
236                    }
237                }
238
239                req = self.continues_rx.recv() => {
240                    match req {
241                        Some((session_id, request)) => {
242                            let msg = BacktestRequest::ContinueSessionV1(ContinueSessionRequestV1 { session_id, request });
243                            if let Err(e) = send_request(&mut ws, &msg).await {
244                                break MessageLoopExit::ConnectionLost(format!("continue send: {e}"));
245                            }
246                        }
247                        None => break MessageLoopExit::SessionEnded,
248                    }
249                }
250            }
251        };
252
253        if matches!(
254            exit,
255            MessageLoopExit::SessionEnded | MessageLoopExit::Cancelled
256        ) {
257            graceful_close(&mut ws).await;
258        }
259        exit
260    }
261}
262
263impl ParallelControlTask {
264    /// First-connect handshake: send the parallel create, collect each streamed
265    /// `SessionCreated`, and finish on `SessionsCreatedV2`. Fires `created_tx`
266    /// with the sub-session set so the caller can begin driving.
267    async fn create_sessions(
268        &mut self,
269        mut ws: Ws,
270        create: CreateBacktestSessionRequest,
271    ) -> Result<Ws, HandshakeError> {
272        send_request(&mut ws, &BacktestRequest::CreateBacktestSession(create))
273            .await
274            .map_err(HandshakeError::Transient)?;
275
276        let rpc_base = http_base_from_ws_url(&self.url);
277        let mut sessions: Vec<CreatedSubSession> = Vec::new();
278
279        loop {
280            let response = next_response(&mut ws, CREATE_RESPONSE_TIMEOUT)
281                .await
282                .map_err(HandshakeError::Transient)?;
283            match response {
284                BacktestResponse::SessionCreated {
285                    session_id,
286                    session_name,
287                    rpc_endpoint,
288                    task_id,
289                } => {
290                    let (event_tx, event_rx) = mpsc::unbounded_channel::<ControlEvent>();
291                    self.event_txs.insert(session_id, event_tx);
292                    sessions.push(CreatedSubSession {
293                        info: SessionInfo {
294                            rpc_endpoint: resolve_rpc_url(&rpc_base, &rpc_endpoint),
295                            session_id,
296                            session_name,
297                            task_id,
298                        },
299                        events: event_rx,
300                        start_slot: 0,
301                        end_slot: 0,
302                    });
303                }
304                BacktestResponse::SessionEventV2 {
305                    session_id,
306                    seq_id,
307                    event,
308                } => {
309                    self.route_event(&session_id, seq_id, event);
310                }
311                BacktestResponse::SessionsCreatedV2 {
312                    control_session_id,
313                    control_session_name,
314                    session_ids,
315                    start_slots,
316                    end_slots,
317                    ..
318                } => {
319                    info!(
320                        %control_session_id,
321                        sessions = sessions.len(),
322                        "parallel sessions created"
323                    );
324                    // Bind each sub-session to its server-authoritative range
325                    // (parallel arrays keyed by session_id), so the driver never
326                    // re-derives the split or guesses the range from the first slot.
327                    // Absent or mismatched-length arrays mean the server is too old
328                    // to report ranges; fail loudly rather than silently leaving
329                    // sub-sessions at `(0, 0)` (which degrades to advance-by-one).
330                    if session_ids.len() != start_slots.len()
331                        || session_ids.len() != end_slots.len()
332                    {
333                        return Err(HandshakeError::Fatal(format!(
334                            "server did not report per-sub-session ranges \
335                             (session_ids={}, start_slots={}, end_slots={}); \
336                             server is too old for the multiplexed parallel client",
337                            session_ids.len(),
338                            start_slots.len(),
339                            end_slots.len(),
340                        )));
341                    }
342                    for ((id, start), end) in session_ids.iter().zip(&start_slots).zip(&end_slots) {
343                        if let Some(s) = sessions.iter_mut().find(|s| s.info.session_id == *id) {
344                            s.start_slot = *start;
345                            s.end_slot = *end;
346                        }
347                    }
348                    self.control_session_id = Some(control_session_id);
349                    // Create succeeded: drop the request so reconnects re-attach
350                    // instead of recreating.
351                    self.create = None;
352                    if let Some(tx) = self.created_tx.take() {
353                        let _ = tx.send(Ok(ParallelCreated {
354                            control_session_id,
355                            control_session_name,
356                            sessions,
357                        }));
358                    }
359                    return Ok(ws);
360                }
361                BacktestResponse::Error(err) => {
362                    return Err(HandshakeError::Fatal(format!(
363                        "server error: {}",
364                        err_chain(&err)
365                    )));
366                }
367                _ => {}
368            }
369        }
370    }
371
372    /// Reconnect handshake: re-attach with the per-session sequence cursors and
373    /// wait for `ParallelSessionAttachedV2`. Replayed events arrive in the
374    /// message loop and are deduplicated by `last_sequences`.
375    async fn attach(
376        &mut self,
377        mut ws: Ws,
378        control_session_id: &ControlSessionId,
379    ) -> Result<Ws, HandshakeError> {
380        send_request(
381            &mut ws,
382            &BacktestRequest::AttachParallelControlSessionV2 {
383                control_session_id: *control_session_id,
384                last_sequences: self.last_sequences.clone().into_iter().collect(),
385            },
386        )
387        .await
388        .map_err(HandshakeError::Transient)?;
389
390        loop {
391            let response = next_response(&mut ws, HANDSHAKE_RESPONSE_TIMEOUT)
392                .await
393                .map_err(HandshakeError::Transient)?;
394            match response {
395                BacktestResponse::ParallelSessionAttachedV2 { .. } => {
396                    debug!(%control_session_id, "parallel control reattached");
397                    return Ok(ws);
398                }
399                BacktestResponse::SessionEventV2 {
400                    session_id,
401                    seq_id,
402                    event,
403                } => {
404                    self.route_event(&session_id, seq_id, event);
405                }
406                BacktestResponse::Error(err) => {
407                    return Err(handshake_error_for_response("attach", err));
408                }
409                _ => {}
410            }
411        }
412    }
413
414    /// Parse one inbound control frame. Returns `Some(exit)` when the loop should
415    /// stop (all sub-sessions completed, or a fatal control-session error).
416    fn handle_text(&mut self, text: &str) -> Option<MessageLoopExit> {
417        let response = match serde_json::from_str::<BacktestResponse>(text) {
418            Ok(r) => r,
419            Err(e) => {
420                warn!(error = %err_chain(&e), "discarding undeserializable parallel control message");
421                return None;
422            }
423        };
424
425        match response {
426            BacktestResponse::SessionEventV2 {
427                session_id,
428                seq_id,
429                event,
430            } => {
431                self.route_event(&session_id, seq_id, event);
432                if self.completed.len() == self.event_txs.len() && !self.event_txs.is_empty() {
433                    return Some(MessageLoopExit::SessionEnded);
434                }
435            }
436            BacktestResponse::Error(err) => {
437                if err.is_terminal() {
438                    return Some(MessageLoopExit::Terminal(format!(
439                        "control session error: {}",
440                        err_chain(&err)
441                    )));
442                }
443                warn!(error = %err_chain(&err), "non-terminal parallel control error");
444            }
445            other => {
446                debug!(?other, "ignoring unexpected parallel control response");
447            }
448        }
449        None
450    }
451
452    /// Route one multiplexed event to its sub-session, deduplicating replays by
453    /// per-session sequence and tracking completion.
454    fn route_event(&mut self, session_id: &SessionId, seq_id: u64, event: SessionEventKind) {
455        // Advance the per-session sequence cursor, dropping replays. Update in
456        // place when the session is already known so the steady-state path
457        // doesn't re-allocate the key on every event.
458        match self.last_sequences.get_mut(session_id) {
459            Some(last) if seq_id <= *last => return,
460            Some(last) => *last = seq_id,
461            None => {
462                self.last_sequences.insert(*session_id, seq_id);
463            }
464        }
465
466        let is_completed = matches!(event, SessionEventKind::Completed { .. });
467        let Some(control_event) = session_event_to_control(event) else {
468            return;
469        };
470        if let Some(tx) = self.event_txs.get(session_id) {
471            // Ignore send error if the driver has finished and dropped its receiver.
472            let _ = tx.send(control_event);
473        }
474        if is_completed {
475            self.completed.insert(session_id.to_string());
476        }
477    }
478}
479
480/// Map a multiplexed `SessionEventKind` onto the driver-facing [`ControlEvent`].
481/// `Success` carries no driver signal and is dropped (`None`).
482fn session_event_to_control(event: SessionEventKind) -> Option<ControlEvent> {
483    Some(match event {
484        SessionEventKind::ReadyForContinue => ControlEvent::ReadyForContinue,
485        SessionEventKind::SlotNotification(slot) => ControlEvent::Slot(slot),
486        SessionEventKind::Paused(event) => ControlEvent::Paused(event),
487        SessionEventKind::DiscoveryBatch(event) => ControlEvent::DiscoveryBatch(event),
488        // Per-tx simulation errors (e.g. a sanitization failure) are non-fatal:
489        // swallow them here instead of routing to the driver.
490        SessionEventKind::Error(error)
491            if matches!(error, BacktestError::SimulationError { .. }) =>
492        {
493            warn!(error = %err_chain(&error), "simulation error");
494            return None;
495        }
496        SessionEventKind::Error(error) => ControlEvent::Error(error),
497        SessionEventKind::Completed { summary } => ControlEvent::Completed { summary },
498        SessionEventKind::Status { status } => ControlEvent::Status(status),
499        SessionEventKind::Success => return None,
500    })
501}
502
503/// Read the next control frame with a bounded timeout, skipping non-text frames.
504async fn next_response(
505    ws: &mut Ws,
506    timeout: std::time::Duration,
507) -> Result<BacktestResponse, String> {
508    let deadline = tokio::time::Instant::now() + timeout;
509    loop {
510        let msg = tokio::time::timeout_at(deadline, ws.next())
511            .await
512            .map_err(|_| format!("handshake timeout after {timeout:?}"))?;
513
514        let Some(msg) = msg else {
515            return Err("ws ended during handshake".into());
516        };
517        let msg = msg.map_err(|e| format!("ws read: {}", err_chain(&e)))?;
518
519        let text = match msg {
520            Message::Text(t) => t,
521            Message::Binary(b) => match String::from_utf8(b) {
522                Ok(t) => t,
523                Err(_) => continue,
524            },
525            Message::Close(frame) => {
526                return Err(format!("remote close during handshake: {frame:?}"));
527            }
528            _ => continue,
529        };
530
531        return serde_json::from_str::<BacktestResponse>(&text)
532            .map_err(|e| format!("deserialize: {}; raw={text}", err_chain(&e)));
533    }
534}
535
536/// High-level managed parallel session: owns the single multiplexed control
537/// connection and hands out one [`ParallelSubSession`] per server-created
538/// sub-session for the driver to run concurrently.
539pub struct ManagedParallelSession {
540    control_session_id: ControlSessionId,
541    control_session_name: Option<String>,
542    control: Option<ParallelControlHandle>,
543    sub_sessions: Vec<ParallelSubSession>,
544    session_cancel: CancellationToken,
545}
546
547impl ManagedParallelSession {
548    /// Start a parallel session from explicit [`StartSessionParams`].
549    ///
550    /// `params.subscription_diagnostics` is shared by every sub-session, so its
551    /// counters aggregate the whole parallel run.
552    pub async fn start_with_params(
553        params: StartSessionParams,
554    ) -> Result<Self, ManagedSessionError> {
555        let StartSessionParams {
556            url,
557            api_key,
558            extra_headers,
559            create,
560            parent_cancel,
561            subscription_diagnostics,
562        } = params;
563        let session_cancel = parent_cancel.child_token();
564        let mut control = spawn_parallel_control_manager(
565            url,
566            api_key,
567            extra_headers,
568            create,
569            session_cancel.clone(),
570        );
571
572        let created = tokio::select! {
573            biased;
574            _ = parent_cancel.cancelled() => {
575                session_cancel.cancel();
576                control.join().await;
577                return Err(ManagedSessionError::Cancelled);
578            }
579            result = control.wait_created() => {
580                result.map_err(ManagedSessionError::Create)?
581            }
582        };
583
584        // One coordinator shared across the sub-sessions: their data planes share
585        // the client's link, so a dropped subscription parks until its streaming
586        // siblings finish before reconnecting into the freed bandwidth.
587        let reconnect_coordinator = Arc::new(ReconnectCoordinator::new());
588        let sub_sessions = created
589            .sessions
590            .into_iter()
591            .map(|s| ParallelSubSession {
592                session_info: s.info,
593                events: s.events,
594                continues: control.continues.clone(),
595                status: control.status.clone(),
596                subscriptions: Vec::new(),
597                session_cancel: session_cancel.child_token(),
598                post_completion: None,
599                post_completion_error: None,
600                reconnect_coordinator: Some(reconnect_coordinator.clone()),
601                subscription_diagnostics: subscription_diagnostics.clone(),
602                start_slot: s.start_slot,
603                end_slot: s.end_slot,
604            })
605            .collect();
606
607        Ok(Self {
608            control_session_id: created.control_session_id,
609            control_session_name: created.control_session_name,
610            control: Some(control),
611            sub_sessions,
612            session_cancel,
613        })
614    }
615
616    /// The server-assigned id grouping these sub-sessions (used for reconnect).
617    pub fn control_session_id(&self) -> ControlSessionId {
618        self.control_session_id
619    }
620
621    pub fn control_session_name(&self) -> Option<&str> {
622        self.control_session_name.as_deref()
623    }
624
625    /// Take the sub-sessions for driving. Returns them once; subsequent calls
626    /// yield an empty vec.
627    pub fn take_sub_sessions(&mut self) -> Vec<ParallelSubSession> {
628        std::mem::take(&mut self.sub_sessions)
629    }
630
631    /// Cancel the session and join the control task.
632    pub async fn shutdown(mut self) {
633        self.session_cancel.cancel();
634        if let Some(control) = self.control.take() {
635            control.join().await;
636        }
637    }
638}
639
640impl Drop for ManagedParallelSession {
641    fn drop(&mut self) {
642        self.session_cancel.cancel();
643    }
644}
645
646/// One sub-session of a parallel run. Mirrors the driver-facing surface of
647/// [`super::ManagedBacktestSession`]: control events arrive over a demuxed
648/// channel from the shared control connection, while transactions flow over this
649/// sub-session's own data-plane subscription managers.
650pub struct ParallelSubSession {
651    session_info: SessionInfo,
652    events: mpsc::UnboundedReceiver<ControlEvent>,
653    continues: mpsc::Sender<TaggedContinue>,
654    status: watch::Receiver<ConnectionStatus>,
655    subscriptions: Vec<SubscriptionHandle>,
656    session_cancel: CancellationToken,
657    /// Trailing notifications drained on `Completed`, followed by `Completed`;
658    /// served in order by `next_event`. `None` until completion.
659    post_completion: Option<VecDeque<ManagedEvent>>,
660    /// Surfaced after `post_completion` drains: set when the completion drain
661    /// stalled, so a silently-truncated sub-session fails loudly.
662    post_completion_error: Option<ManagedSessionError>,
663    /// Coordinator shared across the parallel batch's sub-sessions so their
664    /// subscription reconnects step aside for still-streaming siblings.
665    reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
666    subscription_diagnostics: Arc<SubscriptionDiagnostics>,
667    /// Server-authoritative slot range for this sub-session (from
668    /// `SessionsCreatedV2`).
669    start_slot: u64,
670    end_slot: u64,
671}
672
673impl ParallelSubSession {
674    pub fn session_info(&self) -> &SessionInfo {
675        &self.session_info
676    }
677
678    /// Server-authoritative `(start_slot, end_slot)` for this sub-session.
679    pub fn range(&self) -> (u64, u64) {
680        (self.start_slot, self.end_slot)
681    }
682
683    pub fn subscribe_transactions(&mut self, program_ids: Vec<Address>) {
684        self.subscriptions
685            .push(spawn_transaction_subscription_manager(
686                self.session_info.rpc_endpoint.clone(),
687                program_ids,
688                self.session_cancel.clone(),
689                self.reconnect_coordinator.clone(),
690                self.subscription_diagnostics.clone(),
691            ));
692    }
693
694    pub fn subscribe_account_diffs(&mut self, program_ids: Vec<Address>) {
695        self.subscriptions
696            .push(spawn_account_diff_subscription_manager(
697                self.session_info.rpc_endpoint.clone(),
698                program_ids,
699                self.session_cancel.clone(),
700                self.reconnect_coordinator.clone(),
701                self.subscription_diagnostics.clone(),
702            ));
703    }
704
705    /// Subscribe to scheduled-action results for this sub-session.
706    pub fn subscribe_actions(&mut self) {
707        self.subscriptions.push(spawn_action_subscription_manager(
708            self.session_info.rpc_endpoint.clone(),
709            self.session_cancel.clone(),
710            self.reconnect_coordinator.clone(),
711            self.subscription_diagnostics.clone(),
712        ));
713    }
714
715    /// Receive the next control or subscription event for this sub-session. On
716    /// `Completed`, trailing subscription notifications are drained and delivered
717    /// before the `Completed` event, mirroring [`super::ManagedBacktestSession`].
718    pub async fn next_event(&mut self) -> Result<ManagedEvent, ManagedSessionError> {
719        // Serve buffered post-completion events (trailing notifications, then
720        // `Completed`); the control stream is gone once they're exhausted.
721        if let Some(buffered) = self.post_completion.as_mut() {
722            if let Some(event) = buffered.pop_front() {
723                return Ok(event);
724            }
725            // Buffer drained: surface a pending stall error so an incomplete
726            // run fails loudly, else the control stream is simply done.
727            return Err(self
728                .post_completion_error
729                .take()
730                .unwrap_or(ManagedSessionError::ControlClosed));
731        }
732
733        if let Some(event) = try_next_subscription_event(&mut self.subscriptions) {
734            return Ok(event);
735        }
736
737        // Scope the borrows to the `select!` so the completion drain can
738        // re-borrow `self`.
739        let event = {
740            let cancel = &self.session_cancel;
741            let subscriptions = &mut self.subscriptions;
742            tokio::select! {
743                biased;
744                _ = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
745                event = self.events.recv() => {
746                    event.map(ManagedEvent::from).ok_or(ManagedSessionError::ControlClosed)?
747                }
748                event = wait_any_subscription_event(subscriptions) => event,
749            }
750        };
751
752        // Bind the payload so the re-emitted `Completed` below carries it.
753        let ManagedEvent::Completed { summary } = event else {
754            return Ok(event);
755        };
756
757        // Flush trailing notifications up to each subscription's terminal,
758        // delivering them before `Completed`, mirroring
759        // [`super::ManagedBacktestSession`].
760        let (mut buffered, terminal): (VecDeque<ManagedEvent>, _) = match self
761            .drain_until_subscriptions_complete(COMPLETION_DRAIN_TIMEOUT)
762            .await
763        {
764            DrainOutcome::Complete(events) => {
765                (events.into(), Ok(ManagedEvent::Completed { summary }))
766            }
767            // The data plane stalled before every subscription finished:
768            // trailing notifications are missing, so report failure rather
769            // than a silently-truncated `Completed`.
770            DrainOutcome::Stalled(events) => (
771                events.into(),
772                Err(ManagedSessionError::SubscriptionFailed(
773                    "completion drain stalled: subscriptions did not deliver their \
774                     end-of-stream terminals; the captured stream is incomplete"
775                        .to_string(),
776                )),
777            ),
778        };
779        match terminal {
780            Ok(completed) => buffered.push_back(completed),
781            Err(err) => self.post_completion_error = Some(err),
782        }
783        let first = buffered.pop_front();
784        self.post_completion = Some(buffered);
785        match first {
786            Some(event) => Ok(event),
787            None => Err(self
788                .post_completion_error
789                .take()
790                .unwrap_or(ManagedSessionError::ControlClosed)),
791        }
792    }
793
794    /// Wait until the shared control connection and this sub-session's
795    /// subscriptions are up, then route a `Continue` as `ContinueSessionV1`.
796    pub async fn send_continue(
797        &mut self,
798        params: ContinueParams,
799    ) -> Result<(), ManagedSessionError> {
800        self.wait_all_up().await?;
801        self.continues
802            .send((self.session_info.session_id, params))
803            .await
804            .map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
805    }
806
807    /// See [`drain_subscriptions_until_complete`].
808    async fn drain_until_subscriptions_complete(
809        &mut self,
810        idle_timeout: std::time::Duration,
811    ) -> DrainOutcome {
812        drain_subscriptions_until_complete(
813            &mut self.subscriptions,
814            &self.session_cancel,
815            idle_timeout,
816        )
817        .await
818    }
819
820    /// Cancel this sub-session's subscriptions and join them. The shared control
821    /// connection is owned by [`ManagedParallelSession`] and is not touched here.
822    pub async fn shutdown(mut self) {
823        self.session_cancel.cancel();
824        for sub in std::mem::take(&mut self.subscriptions) {
825            // A manager parked on a full queue exits only once the queue closes.
826            drop(sub.notifications);
827            let _ = sub.join.await;
828        }
829    }
830
831    async fn wait_all_up(&self) -> Result<(), ManagedSessionError> {
832        let subscriptions = self
833            .subscriptions
834            .iter()
835            .map(|s| s.status.clone())
836            .collect();
837        wait_connections_up(self.status.clone(), subscriptions, &self.session_cancel).await
838    }
839}
840
841impl Drop for ParallelSubSession {
842    fn drop(&mut self) {
843        self.session_cancel.cancel();
844    }
845}