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