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