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