Skip to main content

simulator_client/
session.rs

1use std::{
2    borrow::Cow,
3    collections::{BTreeMap, VecDeque},
4    future::Future,
5    time::Duration,
6};
7
8use futures::{SinkExt, StreamExt, stream};
9use simulator_api::{
10    AccountData, AccountModifications, BacktestError, BacktestRequest, BacktestResponse,
11    BacktestStatus, ContinueParams, CreateBacktestSessionRequest, CreateBacktestSessionRequestV1,
12    SequencedResponse, SessionId, SessionSummary,
13};
14use solana_address::Address;
15use solana_client::{
16    nonblocking::rpc_client::RpcClient,
17    rpc_response::{Response, RpcLogsResponse},
18};
19use solana_commitment_config::CommitmentConfig;
20use thiserror::Error;
21use tokio::net::TcpStream;
22use tokio_tungstenite::{
23    MaybeTlsStream, WebSocketStream,
24    tungstenite::{
25        Error as WsError, Message,
26        error::ProtocolError,
27        protocol::{CloseFrame, frame::coding::CloseCode},
28    },
29};
30
31use crate::{
32    BacktestClientError, BacktestClientResult, Continue,
33    injection::ProgramModError,
34    subscriptions::{
35        AccountDiffNotification, AccountDiffSubscriptionHandle, LogSubscriptionHandle,
36        SubscriptionError,
37    },
38};
39
40/// Outcome of waiting for readiness on a backtest session.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum ReadyOutcome {
43    /// The session is ready to accept a `Continue` request.
44    Ready,
45    /// The session completed before becoming ready.
46    Completed,
47}
48
49impl ReadyOutcome {
50    pub fn is_completed(&self) -> bool {
51        matches!(self, Self::Completed)
52    }
53}
54
55/// Summary of responses collected while advancing a backtest.
56#[derive(Debug, Default)]
57pub struct ContinueResult {
58    /// Number of slot notifications observed.
59    pub slot_notifications: u64,
60    /// Last slot received via notification.
61    pub last_slot: Option<u64>,
62    /// Status messages received.
63    pub statuses: Vec<BacktestStatus>,
64    /// Whether the session became ready for the next `Continue`.
65    pub ready_for_continue: bool,
66    /// Whether the session completed while advancing.
67    pub completed: bool,
68}
69
70/// Mutable state for driving a session with `advance_step`.
71#[derive(Debug)]
72pub struct AdvanceState {
73    /// Expected number of slot notifications for this step.
74    pub expected_slots: u64,
75    /// Count of slot notifications received so far.
76    pub slot_notifications: u64,
77    /// Most recent slot notification.
78    pub last_slot: Option<u64>,
79    /// Status messages received so far.
80    pub statuses: Vec<BacktestStatus>,
81    /// Whether the session is ready for another `Continue`.
82    pub ready_for_continue: bool,
83    /// Whether the session completed while advancing.
84    pub completed: bool,
85    /// Session summary received on completion (if send_summary was enabled).
86    pub summary: Option<SessionSummary>,
87}
88
89impl AdvanceState {
90    /// Create new tracking state for a step that expects `expected_slots` notifications.
91    pub fn new(expected_slots: u64) -> Self {
92        Self {
93            expected_slots,
94            slot_notifications: 0,
95            last_slot: None,
96            statuses: Vec::new(),
97            ready_for_continue: false,
98            completed: false,
99            summary: None,
100        }
101    }
102
103    /// Return true when the step is complete based on readiness and slot count.
104    pub fn is_done(&self, wait_for_slots: bool) -> bool {
105        if self.completed {
106            return true;
107        }
108
109        if !self.ready_for_continue {
110            return false;
111        }
112
113        !wait_for_slots || self.slot_notifications >= self.expected_slots
114    }
115}
116
117/// Coverage of a session's observed slot notifications and completion state.
118#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
119pub struct SessionCoverage {
120    completed: bool,
121    highest_slot_seen: Option<u64>,
122}
123
124impl SessionCoverage {
125    /// Record a slot notification.
126    pub fn observe_slot(&mut self, slot: u64) {
127        self.highest_slot_seen = Some(
128            self.highest_slot_seen
129                .map_or(slot, |current| current.max(slot)),
130        );
131    }
132
133    /// Mark the session as completed.
134    pub fn mark_completed(&mut self) {
135        self.completed = true;
136    }
137
138    /// Update coverage state from a backtest response.
139    pub fn observe_response(&mut self, response: &BacktestResponse) {
140        match response {
141            BacktestResponse::SlotNotification(slot) => self.observe_slot(*slot),
142            BacktestResponse::Completed { .. } => self.mark_completed(),
143            _ => {}
144        }
145    }
146
147    /// Return whether completion has been observed.
148    pub fn is_completed(&self) -> bool {
149        self.completed
150    }
151
152    /// Return the highest slot observed via slot notifications.
153    pub fn highest_slot_seen(&self) -> Option<u64> {
154        self.highest_slot_seen
155    }
156
157    /// Validate that the session covered the range ending at `expected_end_slot`.
158    ///
159    /// Completion is the server's own assertion that it replayed every block in
160    /// the range, so it is what carries coverage; observed slots cannot add to
161    /// it, since a skipped tail leaves them below `expected_end_slot` on a
162    /// complete run. They can still contradict it: a slot past the range
163    /// belongs to another session, so these events were misrouted.
164    pub fn validate_end_slot(&self, expected_end_slot: u64) -> Result<(), CoverageError> {
165        if !self.completed {
166            return Err(CoverageError::NotCompleted);
167        }
168
169        let Some(actual_end_slot) = self.highest_slot_seen else {
170            return Err(CoverageError::NoSlotsObserved);
171        };
172
173        if actual_end_slot > expected_end_slot {
174            return Err(CoverageError::RangeOverrun {
175                actual_end_slot,
176                expected_end_slot,
177            });
178        }
179
180        Ok(())
181    }
182}
183
184/// Coverage validation failures for a backtest session.
185#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
186pub enum CoverageError {
187    #[error("ended before completion")]
188    NotCompleted,
189    #[error("completed without slot notifications")]
190    NoSlotsObserved,
191    #[error("observed slot {actual_end_slot} beyond the requested end slot {expected_end_slot}")]
192    RangeOverrun {
193        actual_end_slot: u64,
194        expected_end_slot: u64,
195    },
196}
197
198/// Active backtest session over a WebSocket connection.
199///
200/// Dropping the session sends a best-effort close frame if a Tokio runtime is
201/// available. Call [`BacktestSession::close`] to request server-side cleanup.
202///
203/// The connection is not managed: it never reconnects, and a close — including
204/// the `1012` the management service sends when it hands a live session off
205/// during a redeploy — leaves the session running server-side until its
206/// `disconnect_timeout_secs` elapses. Reclaim it by reconnecting with
207/// [`crate::BacktestClient::attach_session`] and then
208/// [`BacktestSession::resume_attached_session`], or use
209/// [`crate::ManagedBacktestSession`] and get that loop for free.
210pub struct BacktestSession {
211    ws: Option<WebSocketStream<MaybeTlsStream<TcpStream>>>,
212    session_id: Option<SessionId>,
213    session_name: Option<String>,
214    rpc_endpoint: Option<String>,
215    task_id: Option<String>,
216    rpc: Option<RpcClient>,
217    last_sequence: Option<u64>,
218    pub(crate) ready_for_continue: bool,
219    request_timeout: Option<Duration>,
220    log_raw: bool,
221    backlog: VecDeque<(Option<u64>, BacktestResponse)>,
222}
223
224impl BacktestSession {
225    pub(crate) fn new(
226        ws: WebSocketStream<MaybeTlsStream<TcpStream>>,
227        request_timeout: Option<Duration>,
228        log_raw: bool,
229    ) -> Self {
230        Self {
231            ws: Some(ws),
232            session_id: None,
233            session_name: None,
234            rpc_endpoint: None,
235            task_id: None,
236            rpc: None,
237            last_sequence: None,
238            ready_for_continue: false,
239            request_timeout,
240            log_raw,
241            backlog: VecDeque::new(),
242        }
243    }
244
245    /// Return the server-assigned session id, if known.
246    pub fn session_id(&self) -> Option<SessionId> {
247        self.session_id
248    }
249
250    pub fn session_name(&self) -> Option<&str> {
251        self.session_name.as_deref()
252    }
253
254    /// Return the session-scoped RPC endpoint if provided.
255    pub fn rpc_endpoint(&self) -> Option<&str> {
256        self.rpc_endpoint.as_deref()
257    }
258
259    /// Return the opaque `task_id` reported by the server for this session,
260    /// if any.
261    pub fn task_id(&self) -> Option<&str> {
262        self.task_id.as_deref()
263    }
264
265    /// Return the highest sequenced control-websocket response observed so far.
266    pub fn last_sequence(&self) -> Option<u64> {
267        self.last_sequence
268    }
269
270    /// Return the RPC client for this session's endpoint.
271    ///
272    /// Always available after [`BacktestClient::create_session`](crate::BacktestClient::create_session) completes.
273    pub fn rpc(&self) -> &RpcClient {
274        self.rpc
275            .as_ref()
276            .expect("rpc is set during session creation")
277    }
278
279    /// Return whether the session is currently ready to accept `Continue`.
280    pub fn is_ready_for_continue(&self) -> bool {
281        self.ready_for_continue
282    }
283
284    /// Update internal readiness state based on a response.
285    pub fn apply_response(&mut self, response: &BacktestResponse) {
286        match response {
287            BacktestResponse::ReadyForContinue | BacktestResponse::Paused(_) => {
288                self.ready_for_continue = true;
289            }
290            BacktestResponse::Completed { .. } => {
291                self.ready_for_continue = false;
292            }
293            _ => {}
294        }
295    }
296
297    fn ws_mut(&mut self) -> BacktestClientResult<&mut WebSocketStream<MaybeTlsStream<TcpStream>>> {
298        self.ws.as_mut().ok_or_else(|| BacktestClientError::Closed {
299            reason: "websocket closed".to_string(),
300        })
301    }
302
303    pub(crate) async fn create_with_request(
304        &mut self,
305        request: CreateBacktestSessionRequest,
306        rpc_base_url: String,
307        mut on_parallel_session_created: Option<&mut (dyn FnMut(SessionId) + Send)>,
308    ) -> BacktestClientResult<CreateRequestResult> {
309        let expect_parallel = matches!(
310            &request,
311            CreateBacktestSessionRequest::V1(CreateBacktestSessionRequestV1 { parallel: true, .. })
312        );
313        self.send(&BacktestRequest::CreateBacktestSession(request), None)
314            .await?;
315        let mut streamed_parallel_session_ids = Vec::new();
316        let mut streamed_parallel_task_ids: Vec<Option<String>> = Vec::new();
317        // Collect intermediate messages (e.g. Status, SlotNotification) in a local buffer.
318        // Pushing them back on self.backlog can cause re-reading of the same message,
319        // triggering an infinite loop.
320        let mut pending: Vec<(Option<u64>, BacktestResponse)> = Vec::new();
321
322        loop {
323            let response =
324                self.next_response(None)
325                    .await?
326                    .ok_or_else(|| BacktestClientError::Closed {
327                        reason: "websocket ended before SessionCreated".to_string(),
328                    })?;
329
330            match response {
331                BacktestResponse::SessionCreated {
332                    session_id,
333                    session_name,
334                    rpc_endpoint,
335                    task_id,
336                } => {
337                    if expect_parallel {
338                        if let Some(callback) = on_parallel_session_created.as_mut() {
339                            (**callback)(session_id);
340                        }
341                        streamed_parallel_session_ids.push(session_id);
342                        streamed_parallel_task_ids.push(task_id);
343                        continue;
344                    }
345                    let created_session_id = session_id;
346                    let created_task_id = task_id.clone();
347                    self.session_id = Some(session_id);
348                    self.session_name = session_name;
349                    self.task_id = task_id;
350                    let resolved = resolve_rpc_url(&rpc_base_url, &rpc_endpoint);
351                    self.rpc = Some(RpcClient::new_with_commitment(
352                        resolved.clone(),
353                        CommitmentConfig::confirmed(),
354                    ));
355                    self.rpc_endpoint = Some(resolved);
356                    self.backlog.extend(pending);
357                    return Ok(CreateRequestResult::Single {
358                        session_id: created_session_id,
359                        task_id: created_task_id,
360                    });
361                }
362                BacktestResponse::SessionsCreatedV2 {
363                    session_ids,
364                    task_ids,
365                    ..
366                } => {
367                    if expect_parallel && session_ids.is_empty() {
368                        self.backlog.extend(pending);
369                        return Ok(CreateRequestResult::Parallel {
370                            session_ids: streamed_parallel_session_ids,
371                            task_ids: streamed_parallel_task_ids,
372                        });
373                    }
374                    let task_ids = align_task_ids(task_ids, session_ids.len());
375                    self.backlog.extend(pending);
376                    return Ok(CreateRequestResult::Parallel {
377                        session_ids,
378                        task_ids,
379                    });
380                }
381                BacktestResponse::ReadyForContinue => {
382                    self.ready_for_continue = true;
383                }
384                BacktestResponse::Error(err) => return Err(BacktestClientError::Remote(err)),
385                other => {
386                    pending.push((self.last_sequence, other));
387                }
388            }
389        }
390    }
391
392    pub(crate) async fn attach(
393        &mut self,
394        session_id: SessionId,
395        last_sequence: Option<u64>,
396        rpc_base_url: String,
397    ) -> BacktestClientResult<()> {
398        self.send(
399            &BacktestRequest::AttachBacktestSession {
400                session_id,
401                last_sequence,
402            },
403            None,
404        )
405        .await?;
406
407        self.wait_for_response(
408            || BacktestClientError::Closed {
409                reason: "websocket ended before SessionAttached".to_string(),
410            },
411            move |session, response| match response {
412                BacktestResponse::SessionAttached {
413                    session_id,
414                    session_name,
415                    rpc_endpoint,
416                    task_id,
417                } => {
418                    session.session_id = Some(session_id);
419                    session.session_name = session_name;
420                    session.task_id = task_id;
421                    let resolved = resolve_rpc_url(&rpc_base_url, &rpc_endpoint);
422                    session.rpc = Some(RpcClient::new_with_commitment(
423                        resolved.clone(),
424                        CommitmentConfig::confirmed(),
425                    ));
426                    session.rpc_endpoint = Some(resolved);
427                    Ok(Some(()))
428                }
429                BacktestResponse::ReadyForContinue => {
430                    session.ready_for_continue = true;
431                    Ok(None)
432                }
433                BacktestResponse::Error(err) => Err(BacktestClientError::Remote(err)),
434                other => {
435                    session.backlog.push_back((session.last_sequence, other));
436                    Ok(None)
437                }
438            },
439        )
440        .await
441    }
442
443    /// Sent after reattaching and rebuilding any dependent subscriptions so the
444    /// manager can resume a session that was paused for handoff.
445    pub async fn resume_attached_session(&mut self) -> BacktestClientResult<()> {
446        self.send(&BacktestRequest::ResumeAttachedSession, None)
447            .await?;
448
449        self.wait_for_response(
450            || BacktestClientError::Closed {
451                reason: "websocket ended before ResumeAttachedSession acknowledgement".to_string(),
452            },
453            |session, response| match response {
454                BacktestResponse::Success => Ok(Some(())),
455                BacktestResponse::Error(err) => Err(BacktestClientError::Remote(err)),
456                other => {
457                    session.backlog.push_back((session.last_sequence, other));
458                    Ok(None)
459                }
460            },
461        )
462        .await
463    }
464
465    async fn wait_for_response<T, E, F>(
466        &mut self,
467        closed_error: E,
468        mut handle_response: F,
469    ) -> BacktestClientResult<T>
470    where
471        E: FnOnce() -> BacktestClientError,
472        F: FnMut(&mut Self, BacktestResponse) -> BacktestClientResult<Option<T>>,
473    {
474        let mut closed_error = Some(closed_error);
475
476        loop {
477            let response = self
478                .next_response(None)
479                .await?
480                .ok_or_else(|| closed_error.take().expect("closed error set")())?;
481
482            if let Some(result) = handle_response(self, response)? {
483                return Ok(result);
484            }
485        }
486    }
487
488    /// Send a raw backtest request over the WebSocket.
489    pub async fn send(
490        &mut self,
491        request: &BacktestRequest,
492        timeout: Option<Duration>,
493    ) -> BacktestClientResult<()> {
494        let text = serde_json::to_string(request)
495            .map_err(|source| BacktestClientError::SerializeRequest { source })?;
496
497        let request_timeout = self.request_timeout;
498        let timeout = timeout.or(request_timeout);
499
500        let send_fut = self.ws_mut()?.send(Message::Text(text));
501        let send_result = match timeout {
502            Some(duration) => tokio::time::timeout(duration, send_fut)
503                .await
504                .map_err(|_| BacktestClientError::Timeout {
505                    action: "sending",
506                    duration,
507                })?,
508            None => send_fut.await,
509        };
510
511        send_result.map_err(|source| BacktestClientError::WebSocket {
512            action: "sending",
513            source: Box::new(source),
514        })?;
515
516        Ok(())
517    }
518
519    /// Receive the next response, using the backlog first.
520    pub async fn next_response(
521        &mut self,
522        timeout: Option<Duration>,
523    ) -> BacktestClientResult<Option<BacktestResponse>> {
524        if let Some((sequence, response)) = self.backlog.pop_front() {
525            self.last_sequence = sequence.or(self.last_sequence);
526            return Ok(Some(response));
527        }
528
529        let text = match self.next_text(timeout).await? {
530            Some(text) => text,
531            None => return Ok(None),
532        };
533
534        let (sequence, response) = match serde_json::from_str::<SequencedResponse>(&text) {
535            Ok(sequenced) => (Some(sequenced.seq_id), sequenced.response),
536            Err(_) => {
537                let response =
538                    serde_json::from_str::<BacktestResponse>(&text).map_err(|source| {
539                        BacktestClientError::DeserializeResponse {
540                            raw: text.clone(),
541                            source,
542                        }
543                    })?;
544                (None, response)
545            }
546        };
547        self.last_sequence = sequence.or(self.last_sequence);
548
549        Ok(Some(response))
550    }
551
552    /// Receive the next response and update readiness state.
553    pub async fn next_event(
554        &mut self,
555        timeout: Option<Duration>,
556    ) -> BacktestClientResult<Option<BacktestResponse>> {
557        let response = self.next_response(timeout).await?;
558        if let Some(ref response) = response {
559            self.apply_response(response);
560        }
561        Ok(response)
562    }
563
564    /// Stream responses, updating readiness state as items arrive.
565    ///
566    /// This consumes the session and yields responses until the connection ends.
567    pub fn responses(
568        self,
569        timeout: Option<Duration>,
570    ) -> impl futures::Stream<Item = BacktestClientResult<BacktestResponse>> {
571        stream::unfold(Some(self), move |state| async move {
572            let mut session = match state {
573                Some(session) => session,
574                None => return None,
575            };
576
577            match session.next_response(timeout).await {
578                Ok(Some(response)) => {
579                    session.apply_response(&response);
580                    Some((Ok(response), Some(session)))
581                }
582                Ok(None) => None,
583                Err(err) => Some((Err(err), None)),
584            }
585        })
586    }
587
588    /// Wait for the session to become ready or completed.
589    pub async fn ensure_ready(
590        &mut self,
591        timeout: Option<Duration>,
592    ) -> BacktestClientResult<ReadyOutcome> {
593        if self.ready_for_continue {
594            return Ok(ReadyOutcome::Ready);
595        }
596
597        loop {
598            let response =
599                self.next_response(timeout)
600                    .await?
601                    .ok_or_else(|| BacktestClientError::Closed {
602                        reason: "websocket ended while waiting for ReadyForContinue".to_string(),
603                    })?;
604
605            match response {
606                BacktestResponse::ReadyForContinue => {
607                    self.ready_for_continue = true;
608                    return Ok(ReadyOutcome::Ready);
609                }
610                BacktestResponse::Completed { .. } => return Ok(ReadyOutcome::Completed),
611                BacktestResponse::Error(err) => return Err(BacktestClientError::Remote(err)),
612                _ => {}
613            }
614        }
615    }
616
617    /// Wait for a specific status to be emitted.
618    pub async fn wait_for_status(
619        &mut self,
620        desired: BacktestStatus,
621        timeout: Option<Duration>,
622    ) -> BacktestClientResult<()> {
623        let desired = std::mem::discriminant(&desired);
624
625        loop {
626            let response =
627                self.next_response(timeout)
628                    .await?
629                    .ok_or_else(|| BacktestClientError::Closed {
630                        reason: "websocket ended while waiting for status".to_string(),
631                    })?;
632
633            match response {
634                BacktestResponse::Status { status }
635                    if std::mem::discriminant(&status) == desired =>
636                {
637                    return Ok(());
638                }
639                BacktestResponse::Error(err) => return Err(BacktestClientError::Remote(err)),
640                BacktestResponse::Completed { summary } => {
641                    return Err(BacktestClientError::UnexpectedResponse {
642                        context: "waiting for status",
643                        response: Box::new(BacktestResponse::Completed { summary }),
644                    });
645                }
646                _ => {}
647            }
648        }
649    }
650
651    /// Push a response onto the end of the receive backlog.
652    pub(crate) fn push_backlog(&mut self, response: BacktestResponse) {
653        self.backlog.push_back((None, response));
654    }
655
656    /// Send a `Continue` request and reset readiness.
657    pub async fn send_continue(
658        &mut self,
659        params: ContinueParams,
660        timeout: Option<Duration>,
661    ) -> BacktestClientResult<()> {
662        self.ready_for_continue = false;
663        self.send(&BacktestRequest::Continue(params), timeout).await
664    }
665
666    /// Read and apply a single response while advancing.
667    pub async fn advance_step<F>(
668        &mut self,
669        state: &mut AdvanceState,
670        wait_for_slots: bool,
671        timeout: Option<Duration>,
672        on_event: &mut F,
673    ) -> BacktestClientResult<()>
674    where
675        F: FnMut(&BacktestResponse),
676    {
677        let Some(response) = self.next_response(timeout).await? else {
678            return Err(BacktestClientError::Closed {
679                reason: "websocket ended while awaiting continue responses".to_string(),
680            });
681        };
682
683        if self.log_raw {
684            tracing::debug!("<- {response:?}");
685        }
686
687        on_event(&response);
688
689        match response {
690            BacktestResponse::ReadyForContinue => {
691                self.ready_for_continue = true;
692                state.ready_for_continue = true;
693            }
694            BacktestResponse::SlotNotification(slot) => {
695                state.slot_notifications += 1;
696                state.last_slot = Some(slot);
697            }
698            BacktestResponse::Status { status } => {
699                state.statuses.push(status);
700            }
701            BacktestResponse::Success => {}
702            BacktestResponse::Completed { summary } => {
703                state.completed = true;
704                state.summary = summary;
705            }
706            BacktestResponse::Error(err @ BacktestError::SimulationError { .. }) => {
707                tracing::warn!(error = %crate::error::err_chain(&err), "simulation error");
708            }
709            BacktestResponse::Error(err) => return Err(BacktestClientError::Remote(err)),
710            BacktestResponse::SessionCreated { .. }
711            | BacktestResponse::SessionAttached { .. }
712            | BacktestResponse::SessionsCreatedV2 { .. }
713            | BacktestResponse::ParallelSessionAttachedV2 { .. }
714            | BacktestResponse::SessionEventV2 { .. }
715            | BacktestResponse::Paused(_)
716            | BacktestResponse::DiscoveryBatch(_) => {
717                return Err(BacktestClientError::UnexpectedResponse {
718                    context: "continuing",
719                    response: Box::new(response),
720                });
721            }
722        }
723
724        if wait_for_slots && state.slot_notifications > state.expected_slots {
725            tracing::warn!(
726                "received {} slot notifications (expected {})",
727                state.slot_notifications,
728                state.expected_slots
729            );
730        }
731
732        Ok(())
733    }
734
735    /// Advance until the session becomes ready for another `Continue`.
736    pub async fn continue_until_ready<F>(
737        &mut self,
738        cont: Continue,
739        timeout: Option<Duration>,
740        mut on_event: F,
741    ) -> BacktestClientResult<ContinueResult>
742    where
743        F: FnMut(&BacktestResponse),
744    {
745        let expected_slots = cont.advance_count;
746        self.advance_internal(
747            cont.into_params(),
748            expected_slots,
749            false,
750            timeout,
751            &mut on_event,
752        )
753        .await
754    }
755
756    /// Advance and wait for both readiness and slot notifications.
757    pub async fn advance<F>(
758        &mut self,
759        cont: Continue,
760        timeout: Option<Duration>,
761        mut on_event: F,
762    ) -> BacktestClientResult<ContinueResult>
763    where
764        F: FnMut(&BacktestResponse),
765    {
766        let expected_slots = cont.advance_count;
767        self.advance_internal(
768            cont.into_params(),
769            expected_slots,
770            true,
771            timeout,
772            &mut on_event,
773        )
774        .await
775    }
776
777    async fn advance_internal<F>(
778        &mut self,
779        params: ContinueParams,
780        expected_slots: u64,
781        wait_for_slots: bool,
782        timeout: Option<Duration>,
783        on_event: &mut F,
784    ) -> BacktestClientResult<ContinueResult>
785    where
786        F: FnMut(&BacktestResponse),
787    {
788        self.send_continue(params, timeout).await?;
789
790        let mut state = AdvanceState::new(expected_slots);
791        while !state.is_done(wait_for_slots) {
792            self.advance_step(&mut state, wait_for_slots, timeout, on_event)
793                .await?;
794        }
795
796        Ok(ContinueResult {
797            slot_notifications: state.slot_notifications,
798            last_slot: state.last_slot,
799            statuses: state.statuses,
800            ready_for_continue: state.ready_for_continue,
801            completed: state.completed,
802        })
803    }
804
805    /// Build a program-data account modification from raw ELF bytes.
806    ///
807    /// Derives the `ProgramData` address from `program_id`, queries the session's RPC endpoint
808    /// for the current slot and rent-exempt minimum, then returns a modification map ready to
809    /// pass to [`Continue::builder().modify_accounts(...)`](crate::Continue).
810    ///
811    /// The deploy slot is set to `current_slot - 1` so the program appears deployed before the
812    /// next executed slot.
813    pub async fn modify_program(
814        &self,
815        program_id: &str,
816        elf: &[u8],
817    ) -> Result<BTreeMap<Address, AccountData>, ProgramModError> {
818        let rpc = self.rpc.as_ref().ok_or(ProgramModError::NoRpcEndpoint)?;
819        crate::injection::modify_program_via_rpc(rpc, program_id, elf).await
820    }
821
822    /// Modify accounts on the session's RPC endpoint via the custom `modifyAccounts` method.
823    ///
824    /// Returns the number of accounts modified on success.
825    pub async fn modify_accounts(
826        &self,
827        modifications: &AccountModifications,
828    ) -> BacktestClientResult<usize> {
829        let rpc_endpoint =
830            self.rpc_endpoint
831                .as_deref()
832                .ok_or_else(|| BacktestClientError::Closed {
833                    reason: "no RPC endpoint available".to_string(),
834                })?;
835
836        crate::rpc::modify_accounts(rpc_endpoint, modifications).await
837    }
838
839    /// Subscribe to program log notifications using the session's RPC endpoint.
840    ///
841    /// Equivalent to calling [`subscribe_program_logs`](crate::subscribe_program_logs) with
842    /// the endpoint from [`rpc_endpoint`](Self::rpc_endpoint), which is set after
843    /// [`BacktestClient::create_session`](crate::BacktestClient::create_session) completes.
844    pub async fn subscribe_program_logs<F, Fut>(
845        &self,
846        program_id: &str,
847        commitment: CommitmentConfig,
848        on_notification: F,
849    ) -> Result<LogSubscriptionHandle, SubscriptionError>
850    where
851        F: Fn(Response<RpcLogsResponse>) -> Fut + Send + Sync + 'static,
852        Fut: Future<Output = ()> + Send + 'static,
853    {
854        let rpc_endpoint = self
855            .rpc_endpoint
856            .as_deref()
857            .ok_or(SubscriptionError::NoRpcEndpoint)?;
858        crate::subscriptions::subscribe_program_logs(
859            rpc_endpoint,
860            program_id,
861            commitment,
862            on_notification,
863        )
864        .await
865    }
866
867    /// Subscribe to account diff notifications using the session's RPC endpoint.
868    ///
869    /// Equivalent to calling [`subscribe_account_diffs`](crate::subscribe_account_diffs) with
870    /// the endpoint from [`rpc_endpoint`](Self::rpc_endpoint), which is set after
871    /// [`BacktestClient::create_session`](crate::BacktestClient::create_session) completes.
872    pub async fn subscribe_account_diffs<F, Fut>(
873        &self,
874        account: &str,
875        on_notification: F,
876    ) -> Result<AccountDiffSubscriptionHandle, SubscriptionError>
877    where
878        F: Fn(AccountDiffNotification) -> Fut + Send + Sync + 'static,
879        Fut: Future<Output = ()> + Send + 'static,
880    {
881        let rpc_endpoint = self
882            .rpc_endpoint
883            .as_deref()
884            .ok_or(SubscriptionError::NoRpcEndpoint)?;
885        crate::subscriptions::subscribe_account_diffs(rpc_endpoint, account, on_notification).await
886    }
887
888    /// Request server cleanup and close the underlying WebSocket.
889    ///
890    /// This is idempotent and will return `Ok(())` if the connection is already closed.
891    pub async fn close(&mut self, timeout: Option<Duration>) -> BacktestClientResult<()> {
892        self.close_with_frame(timeout, None).await
893    }
894
895    /// Close the session with a specific WebSocket close frame.
896    pub async fn close_with_frame(
897        &mut self,
898        timeout: Option<Duration>,
899        frame: Option<CloseFrame<'static>>,
900    ) -> BacktestClientResult<()> {
901        if self.ws.is_none() {
902            return Ok(());
903        }
904
905        let mut sent = false;
906        match self
907            .send(&BacktestRequest::CloseBacktestSession, timeout)
908            .await
909        {
910            Ok(()) => sent = true,
911            Err(err) if is_close_ok(&err) => {}
912            Err(err) => return Err(err),
913        }
914
915        if sent {
916            let response = match self.next_response(timeout).await {
917                Ok(Some(r)) => r,
918                Ok(None) => {
919                    self.ws.take();
920                    return Ok(());
921                }
922                Err(BacktestClientError::Closed { .. }) => {
923                    self.ws.take();
924                    return Ok(());
925                }
926                Err(BacktestClientError::WebSocket {
927                    action: "receiving",
928                    source,
929                }) if is_reset_without_close(&source) => {
930                    self.ws.take();
931                    return Ok(());
932                }
933                Err(err) => return Err(err),
934            };
935
936            match response {
937                BacktestResponse::Success | BacktestResponse::Completed { .. } => {}
938                BacktestResponse::Error(err) => return Err(BacktestClientError::Remote(err)),
939                other => {
940                    return Err(BacktestClientError::UnexpectedResponse {
941                        context: "closing session",
942                        response: Box::new(other),
943                    });
944                }
945            }
946        }
947
948        // Flush our close frame and drop — don't read the peer's close back: the
949        // management loop exits on CloseBacktestSession and never sends one.
950        if let Some(mut ws) = self.ws.take()
951            && let Err(source) = ws.close(frame).await
952            && !is_ws_closed_error(&source)
953        {
954            return Err(BacktestClientError::WebSocket {
955                action: "closing",
956                source: Box::new(source),
957            });
958        }
959        Ok(())
960    }
961
962    /// Close the session with a close code and reason.
963    pub async fn close_with_reason(
964        &mut self,
965        timeout: Option<Duration>,
966        code: CloseCode,
967        reason: impl Into<String>,
968    ) -> BacktestClientResult<()> {
969        let frame = CloseFrame {
970            code,
971            reason: Cow::Owned(reason.into()),
972        };
973        self.close_with_frame(timeout, Some(frame)).await
974    }
975
976    /// Drop the connection without sending `CloseBacktestSession`, so the server
977    /// reaps the session via its disconnect timeout (the dropped-connection path)
978    /// rather than the prompt teardown [`close`](Self::close) requests.
979    ///
980    /// Consumes the session so [`Drop`] can't run its best-effort close: the taken
981    /// stream is dropped here, closing the socket with a bare FIN.
982    pub fn abort(mut self) {
983        let _ws = self.ws.take();
984    }
985
986    async fn next_text(
987        &mut self,
988        timeout: Option<Duration>,
989    ) -> BacktestClientResult<Option<String>> {
990        loop {
991            let request_timeout = self.request_timeout;
992            let timeout = timeout.or(request_timeout);
993
994            let next_fut = self.ws_mut()?.next();
995            let msg = match timeout {
996                Some(duration) => tokio::time::timeout(duration, next_fut)
997                    .await
998                    .map_err(|_| BacktestClientError::Timeout {
999                        action: "receiving",
1000                        duration,
1001                    })?,
1002                None => next_fut.await,
1003            };
1004
1005            let Some(msg) = msg else {
1006                return Ok(None);
1007            };
1008
1009            let msg = match msg {
1010                Ok(msg) => msg,
1011                Err(source) => {
1012                    return Err(BacktestClientError::WebSocket {
1013                        action: "receiving",
1014                        source: Box::new(source),
1015                    });
1016                }
1017            };
1018
1019            match msg {
1020                Message::Text(text) => {
1021                    if self.log_raw {
1022                        tracing::debug!("<- raw: {text}");
1023                    }
1024                    return Ok(Some(text));
1025                }
1026                Message::Binary(bin) => match String::from_utf8(bin) {
1027                    Ok(text) => {
1028                        if self.log_raw {
1029                            tracing::debug!("<- raw(bin): {text}");
1030                        }
1031                        return Ok(Some(text));
1032                    }
1033                    Err(err) => {
1034                        tracing::warn!("discarding non-utf8 binary message: {err}");
1035                        continue;
1036                    }
1037                },
1038                Message::Close(frame) => {
1039                    let reason = close_reason(frame);
1040                    return Err(BacktestClientError::Closed { reason });
1041                }
1042                Message::Ping(_) | Message::Pong(_) => continue,
1043                Message::Frame(_) => continue,
1044            }
1045        }
1046    }
1047}
1048
1049impl std::fmt::Debug for BacktestSession {
1050    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1051        f.debug_struct("BacktestSession")
1052            .field("session_id", &self.session_id)
1053            .field("rpc_endpoint", &self.rpc_endpoint)
1054            .field(
1055                "rpc",
1056                &self
1057                    .rpc
1058                    .as_ref()
1059                    .map(|_| "<RpcClient>")
1060                    .unwrap_or("<not set>"),
1061            )
1062            .field("ready_for_continue", &self.ready_for_continue)
1063            .field("request_timeout", &self.request_timeout)
1064            .finish_non_exhaustive()
1065    }
1066}
1067
1068#[derive(Debug)]
1069pub(crate) enum CreateRequestResult {
1070    Single {
1071        session_id: SessionId,
1072        task_id: Option<String>,
1073    },
1074    Parallel {
1075        session_ids: Vec<SessionId>,
1076        task_ids: Vec<Option<String>>,
1077    },
1078}
1079
1080/// Pad or truncate a server-supplied `task_ids` slice to match `session_ids` length.
1081/// Older servers omit `task_ids` entirely; treat that as an all-`None` slice.
1082fn align_task_ids(mut task_ids: Vec<Option<String>>, expected_len: usize) -> Vec<Option<String>> {
1083    if task_ids.len() < expected_len {
1084        task_ids.resize(expected_len, None);
1085    } else if task_ids.len() > expected_len {
1086        task_ids.truncate(expected_len);
1087    }
1088    task_ids
1089}
1090
1091impl Drop for BacktestSession {
1092    fn drop(&mut self) {
1093        let Some(ws) = self.ws.take() else {
1094            return;
1095        };
1096
1097        if let Ok(handle) = tokio::runtime::Handle::try_current() {
1098            handle.spawn(async move {
1099                let mut ws = ws;
1100                let _ = ws.close(None).await;
1101            });
1102        }
1103    }
1104}
1105
1106fn resolve_rpc_url(base: &str, endpoint: &str) -> String {
1107    if endpoint.starts_with("http://") || endpoint.starts_with("https://") {
1108        endpoint.to_string()
1109    } else {
1110        format!("{}/{}", base, endpoint.trim_start_matches('/'))
1111    }
1112}
1113
1114fn close_reason(frame: Option<CloseFrame<'static>>) -> String {
1115    match frame {
1116        Some(frame) => format!("{:?}: {}", frame.code, frame.reason),
1117        None => "no close frame".to_string(),
1118    }
1119}
1120
1121fn is_reset_without_close(err: &WsError) -> bool {
1122    matches!(
1123        err,
1124        WsError::Protocol(ProtocolError::ResetWithoutClosingHandshake)
1125    )
1126}
1127
1128fn is_ws_closed_error(err: &WsError) -> bool {
1129    matches!(
1130        err,
1131        WsError::ConnectionClosed
1132            | WsError::AlreadyClosed
1133            | WsError::Protocol(ProtocolError::ResetWithoutClosingHandshake)
1134    )
1135}
1136
1137fn is_close_ok(err: &BacktestClientError) -> bool {
1138    match err {
1139        BacktestClientError::Closed { .. } => true,
1140        BacktestClientError::WebSocket { source, .. } => is_ws_closed_error(source),
1141        _ => false,
1142    }
1143}
1144
1145#[cfg(test)]
1146mod tests {
1147    use super::*;
1148
1149    #[test]
1150    fn coverage_tracks_slot_and_completion_from_responses() {
1151        let mut coverage = SessionCoverage::default();
1152        coverage.observe_response(&BacktestResponse::SlotNotification(10));
1153        coverage.observe_response(&BacktestResponse::SlotNotification(12));
1154        coverage.observe_response(&BacktestResponse::Completed { summary: None });
1155
1156        assert!(coverage.is_completed());
1157        assert_eq!(coverage.highest_slot_seen(), Some(12));
1158    }
1159
1160    #[test]
1161    fn coverage_validate_end_slot_requires_completion_and_observed_slots() {
1162        let mut coverage = SessionCoverage::default();
1163        assert_eq!(
1164            coverage.validate_end_slot(5),
1165            Err(CoverageError::NotCompleted)
1166        );
1167
1168        coverage.mark_completed();
1169        assert_eq!(
1170            coverage.validate_end_slot(5),
1171            Err(CoverageError::NoSlotsObserved)
1172        );
1173
1174        coverage.observe_slot(5);
1175        assert_eq!(coverage.validate_end_slot(5), Ok(()));
1176    }
1177
1178    #[test]
1179    fn coverage_accepts_a_completed_range_whose_trailing_slots_were_skipped() {
1180        // Slot 5 produced no block, so nothing announced it and nothing will.
1181        let mut coverage = SessionCoverage::default();
1182        coverage.observe_slot(4);
1183        coverage.mark_completed();
1184
1185        assert_eq!(coverage.validate_end_slot(5), Ok(()));
1186    }
1187
1188    #[test]
1189    fn coverage_rejects_a_slot_beyond_the_requested_range() {
1190        // Slots past `end_slot` belong to another session.
1191        let mut coverage = SessionCoverage::default();
1192        coverage.observe_slot(6);
1193        coverage.mark_completed();
1194
1195        assert_eq!(
1196            coverage.validate_end_slot(5),
1197            Err(CoverageError::RangeOverrun {
1198                actual_end_slot: 6,
1199                expected_end_slot: 5,
1200            })
1201        );
1202    }
1203}