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 {
486            summary,
487            agent_stats: None,
488        },
489        SessionEventKind::Status { status } => ControlEvent::Status(status),
490        SessionEventKind::Success => return None,
491    })
492}
493
494/// Read the next control frame with a bounded timeout, skipping non-text frames.
495async fn next_response(
496    ws: &mut Ws,
497    timeout: std::time::Duration,
498) -> Result<BacktestResponse, String> {
499    let deadline = tokio::time::Instant::now() + timeout;
500    loop {
501        let msg = tokio::time::timeout_at(deadline, ws.next())
502            .await
503            .map_err(|_| format!("handshake timeout after {timeout:?}"))?;
504
505        let Some(msg) = msg else {
506            return Err("ws ended during handshake".into());
507        };
508        let msg = msg.map_err(|e| format!("ws read: {}", err_chain(&e)))?;
509
510        let text = match msg {
511            Message::Text(t) => t,
512            Message::Binary(b) => match String::from_utf8(b) {
513                Ok(t) => t,
514                Err(_) => continue,
515            },
516            Message::Close(frame) => {
517                return Err(format!("remote close during handshake: {frame:?}"));
518            }
519            _ => continue,
520        };
521
522        return serde_json::from_str::<BacktestResponse>(&text)
523            .map_err(|e| format!("deserialize: {}; raw={text}", err_chain(&e)));
524    }
525}
526
527/// High-level managed parallel session: owns the single multiplexed control
528/// connection and hands out one [`ParallelSubSession`] per server-created
529/// sub-session for the driver to run concurrently.
530pub struct ManagedParallelSession {
531    control_session_id: ControlSessionId,
532    control: Option<ParallelControlHandle>,
533    sub_sessions: Vec<ParallelSubSession>,
534    session_cancel: CancellationToken,
535}
536
537impl ManagedParallelSession {
538    /// Start a parallel session from explicit [`StartSessionParams`].
539    ///
540    /// `params.subscription_diagnostics` is shared by every sub-session, so its
541    /// counters aggregate the whole parallel run.
542    pub async fn start_with_params(
543        params: StartSessionParams,
544    ) -> Result<Self, ManagedSessionError> {
545        let StartSessionParams {
546            url,
547            api_key,
548            create,
549            parent_cancel,
550            subscription_diagnostics,
551        } = params;
552        let session_cancel = parent_cancel.child_token();
553        let mut control =
554            spawn_parallel_control_manager(url, api_key, create, session_cancel.clone());
555
556        let created = tokio::select! {
557            biased;
558            _ = parent_cancel.cancelled() => {
559                session_cancel.cancel();
560                control.join().await;
561                return Err(ManagedSessionError::Cancelled);
562            }
563            result = control.wait_created() => {
564                result.map_err(ManagedSessionError::Create)?
565            }
566        };
567
568        // One coordinator shared across the sub-sessions: their data planes share
569        // the client's link, so a dropped subscription parks until its streaming
570        // siblings finish before reconnecting into the freed bandwidth.
571        let reconnect_coordinator = Arc::new(ReconnectCoordinator::new());
572        let sub_sessions = created
573            .sessions
574            .into_iter()
575            .map(|s| ParallelSubSession {
576                session_info: s.info,
577                events: s.events,
578                continues: control.continues.clone(),
579                status: control.status.clone(),
580                subscriptions: Vec::new(),
581                session_cancel: session_cancel.child_token(),
582                post_completion: None,
583                post_completion_error: None,
584                reconnect_coordinator: Some(reconnect_coordinator.clone()),
585                subscription_diagnostics: subscription_diagnostics.clone(),
586                start_slot: s.start_slot,
587                end_slot: s.end_slot,
588            })
589            .collect();
590
591        Ok(Self {
592            control_session_id: created.control_session_id,
593            control: Some(control),
594            sub_sessions,
595            session_cancel,
596        })
597    }
598
599    /// The server-assigned id grouping these sub-sessions (used for reconnect).
600    pub fn control_session_id(&self) -> ControlSessionId {
601        self.control_session_id
602    }
603
604    /// Take the sub-sessions for driving. Returns them once; subsequent calls
605    /// yield an empty vec.
606    pub fn take_sub_sessions(&mut self) -> Vec<ParallelSubSession> {
607        std::mem::take(&mut self.sub_sessions)
608    }
609
610    /// Cancel the session and join the control task.
611    pub async fn shutdown(mut self) {
612        self.session_cancel.cancel();
613        if let Some(control) = self.control.take() {
614            control.join().await;
615        }
616    }
617}
618
619impl Drop for ManagedParallelSession {
620    fn drop(&mut self) {
621        self.session_cancel.cancel();
622    }
623}
624
625/// One sub-session of a parallel run. Mirrors the driver-facing surface of
626/// [`super::ManagedBacktestSession`]: control events arrive over a demuxed
627/// channel from the shared control connection, while transactions flow over this
628/// sub-session's own data-plane subscription managers.
629pub struct ParallelSubSession {
630    session_info: SessionInfo,
631    events: mpsc::UnboundedReceiver<ControlEvent>,
632    continues: mpsc::Sender<TaggedContinue>,
633    status: watch::Receiver<ConnectionStatus>,
634    subscriptions: Vec<SubscriptionHandle>,
635    session_cancel: CancellationToken,
636    /// Trailing notifications drained on `Completed`, followed by `Completed`;
637    /// served in order by `next_event`. `None` until completion.
638    post_completion: Option<VecDeque<ManagedEvent>>,
639    /// Surfaced after `post_completion` drains: set when the completion drain
640    /// stalled, so a silently-truncated sub-session fails loudly.
641    post_completion_error: Option<ManagedSessionError>,
642    /// Coordinator shared across the parallel batch's sub-sessions so their
643    /// subscription reconnects step aside for still-streaming siblings.
644    reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
645    subscription_diagnostics: Arc<SubscriptionDiagnostics>,
646    /// Server-authoritative slot range for this sub-session (from
647    /// `SessionsCreatedV2`).
648    start_slot: u64,
649    end_slot: u64,
650}
651
652impl ParallelSubSession {
653    pub fn session_info(&self) -> &SessionInfo {
654        &self.session_info
655    }
656
657    /// Server-authoritative `(start_slot, end_slot)` for this sub-session.
658    pub fn range(&self) -> (u64, u64) {
659        (self.start_slot, self.end_slot)
660    }
661
662    pub fn subscribe_transactions(&mut self, program_ids: Vec<Address>) {
663        self.subscriptions
664            .push(spawn_transaction_subscription_manager(
665                self.session_info.rpc_endpoint.clone(),
666                program_ids,
667                self.session_cancel.clone(),
668                self.reconnect_coordinator.clone(),
669                self.subscription_diagnostics.clone(),
670            ));
671    }
672
673    pub fn subscribe_account_diffs(&mut self, program_ids: Vec<Address>) {
674        self.subscriptions
675            .push(spawn_account_diff_subscription_manager(
676                self.session_info.rpc_endpoint.clone(),
677                program_ids,
678                self.session_cancel.clone(),
679                self.reconnect_coordinator.clone(),
680                self.subscription_diagnostics.clone(),
681            ));
682    }
683
684    /// Subscribe to scheduled-action results for this sub-session.
685    pub fn subscribe_actions(&mut self) {
686        self.subscriptions.push(spawn_action_subscription_manager(
687            self.session_info.rpc_endpoint.clone(),
688            self.session_cancel.clone(),
689            self.reconnect_coordinator.clone(),
690            self.subscription_diagnostics.clone(),
691        ));
692    }
693
694    /// Receive the next control or subscription event for this sub-session. On
695    /// `Completed`, trailing subscription notifications are drained and delivered
696    /// before the `Completed` event, mirroring [`super::ManagedBacktestSession`].
697    pub async fn next_event(&mut self) -> Result<ManagedEvent, ManagedSessionError> {
698        // Serve buffered post-completion events (trailing notifications, then
699        // `Completed`); the control stream is gone once they're exhausted.
700        if let Some(buffered) = self.post_completion.as_mut() {
701            if let Some(event) = buffered.pop_front() {
702                return Ok(event);
703            }
704            // Buffer drained: surface a pending stall error so an incomplete
705            // run fails loudly, else the control stream is simply done.
706            return Err(self
707                .post_completion_error
708                .take()
709                .unwrap_or(ManagedSessionError::ControlClosed));
710        }
711
712        if let Some(event) = try_next_subscription_event(&mut self.subscriptions) {
713            return Ok(event);
714        }
715
716        // Scope the borrows to the `select!` so the completion drain can
717        // re-borrow `self`.
718        let event = {
719            let cancel = &self.session_cancel;
720            let subscriptions = &mut self.subscriptions;
721            tokio::select! {
722                biased;
723                _ = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
724                event = self.events.recv() => {
725                    event.map(ManagedEvent::from).ok_or(ManagedSessionError::ControlClosed)?
726                }
727                event = wait_any_subscription_event(subscriptions) => event,
728            }
729        };
730
731        // Bind the payload so the re-emitted `Completed` below carries it.
732        let ManagedEvent::Completed {
733            summary,
734            agent_stats,
735        } = event
736        else {
737            return Ok(event);
738        };
739
740        // Flush trailing notifications up to each subscription's terminal,
741        // delivering them before `Completed`, mirroring
742        // [`super::ManagedBacktestSession`].
743        let (mut buffered, terminal): (VecDeque<ManagedEvent>, _) = match self
744            .drain_until_subscriptions_complete(COMPLETION_DRAIN_TIMEOUT)
745            .await
746        {
747            DrainOutcome::Complete(events) => (
748                events.into(),
749                Ok(ManagedEvent::Completed {
750                    summary,
751                    agent_stats,
752                }),
753            ),
754            // The data plane stalled before every subscription finished:
755            // trailing notifications are missing, so report failure rather
756            // than a silently-truncated `Completed`.
757            DrainOutcome::Stalled(events) => (
758                events.into(),
759                Err(ManagedSessionError::SubscriptionFailed(
760                    "completion drain stalled: subscriptions did not deliver their \
761                     end-of-stream terminals; the captured stream is incomplete"
762                        .to_string(),
763                )),
764            ),
765        };
766        match terminal {
767            Ok(completed) => buffered.push_back(completed),
768            Err(err) => self.post_completion_error = Some(err),
769        }
770        let first = buffered.pop_front();
771        self.post_completion = Some(buffered);
772        match first {
773            Some(event) => Ok(event),
774            None => Err(self
775                .post_completion_error
776                .take()
777                .unwrap_or(ManagedSessionError::ControlClosed)),
778        }
779    }
780
781    /// Wait until the shared control connection and this sub-session's
782    /// subscriptions are up, then route a `Continue` as `ContinueSessionV1`.
783    pub async fn send_continue(
784        &mut self,
785        params: ContinueParams,
786    ) -> Result<(), ManagedSessionError> {
787        self.wait_all_up().await?;
788        self.continues
789            .send((self.session_info.session_id, params))
790            .await
791            .map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
792    }
793
794    /// See [`drain_subscriptions_until_complete`].
795    async fn drain_until_subscriptions_complete(
796        &mut self,
797        idle_timeout: std::time::Duration,
798    ) -> DrainOutcome {
799        drain_subscriptions_until_complete(
800            &mut self.subscriptions,
801            &self.session_cancel,
802            idle_timeout,
803        )
804        .await
805    }
806
807    /// Cancel this sub-session's subscriptions and join them. The shared control
808    /// connection is owned by [`ManagedParallelSession`] and is not touched here.
809    pub async fn shutdown(mut self) {
810        self.session_cancel.cancel();
811        for sub in std::mem::take(&mut self.subscriptions) {
812            let _ = sub.join.await;
813        }
814    }
815
816    async fn wait_all_up(&self) -> Result<(), ManagedSessionError> {
817        let subscriptions = self
818            .subscriptions
819            .iter()
820            .map(|s| s.status.clone())
821            .collect();
822        wait_connections_up(self.status.clone(), subscriptions, &self.session_cancel).await
823    }
824}
825
826impl Drop for ParallelSubSession {
827    fn drop(&mut self) {
828        self.session_cancel.cancel();
829    }
830}