simulator-client 0.29.0

Async WebSocket client for the Solana simulator backtest API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
use std::{
    collections::VecDeque,
    sync::{Arc, OnceLock},
    time::Duration,
};

use futures::FutureExt;
use simulator_api::{
    BacktestError, BacktestStatus, ContinueParams, ContinueToParams, CreateBacktestSessionRequest,
    CreateBacktestSessionRequestV1, DiscoveryBatchEvent, PausedEvent, SessionSummary,
};
use solana_address::Address;
use solana_client::nonblocking::rpc_client::RpcClient;
use solana_commitment_config::CommitmentConfig;
use solana_transaction_status::EncodedConfirmedTransactionWithStatusMeta;
use thiserror::Error;
use tokio::sync::{mpsc, watch};
use tokio_util::sync::CancellationToken;

use super::{
    ConnectionStatus, ControlEvent, ControlHandle, DEFAULT_DISCONNECT_TIMEOUT_SECS,
    ReconnectCoordinator, SessionInfo, StartSessionParams, SubscriptionDiagnostics,
    SubscriptionHandle, SubscriptionNotification, spawn_account_diff_subscription_manager,
    spawn_action_subscription_manager, spawn_control_manager,
    spawn_diagnostic_subscription_manager, spawn_replacement_subscription_manager,
    spawn_transaction_subscription_manager,
};
use crate::subscriptions::{
    AccountDiffNotification, ActionResultNotification, DiagnosticNotification,
    ReplacementNotification,
};

/// Why `start` could not create a managed session; carried by [`ManagedSessionError::Create`].
#[derive(Debug, Error)]
pub enum CreateError {
    /// The server refused the create request. Retry later when
    /// [`BacktestError::is_retryable`] is true, as for insufficient capacity
    /// ([`BacktestError::Internal`]). Otherwise fix what the error names.
    #[error("server rejected the request: {0}")]
    Rejected(BacktestError),

    /// The server could not be reached, or the connection dropped before the session existed,
    /// past the retry budget. Retry later.
    #[error("{0}")]
    Connection(String),

    /// The server's reply does not fit this client, such as a parallel create without
    /// per-session ranges. Stop: upgrade `simulator-client`.
    #[error("{0}")]
    Protocol(String),
}

impl CreateError {
    /// Whether calling `start` again later, with the same request, may succeed.
    pub fn is_retryable(&self) -> bool {
        match self {
            Self::Rejected(err) => err.is_retryable(),
            Self::Connection(_) => true,
            Self::Protocol(_) => false,
        }
    }
}

/// Why a managed session call failed.
///
/// The managed layer has already retried what it could, so none of these is worth retrying on
/// the same session: each variant says what to do instead. [`Self::is_retryable`] says whether
/// a new session may succeed.
#[derive(Debug, Error)]
pub enum ManagedSessionError {
    /// `start` could not create the session. Match on [`CreateError`] for why, or call
    /// [`CreateError::is_retryable`].
    #[error("session create failed: {0}")]
    Create(CreateError),

    /// The session control channel is closed, so the session is over. `next_event` returns this
    /// after `Completed` has been delivered, once the connection has failed past the retry
    /// budget, and (on a [`ManagedBacktestSession`]) after a terminal [`ManagedEvent::Error`].
    /// Stop driving the session.
    #[error("control channel closed")]
    ControlClosed,

    /// The session control channel gave up before a continue could be sent: the retry budget ran
    /// out, the server ended the session, or reattaching was rejected. Start a new session.
    #[error("control failed: {0}")]
    ControlFailed(String),

    /// A subscription gave up, so its notifications are incomplete. `send_continue` returns this
    /// when a subscription ran out of retries; `next_event` returns it in place of `Completed`
    /// when a subscription stopped delivering before its stream ended. Rerun the session if you
    /// need every notification.
    #[error("subscription failed: {0}")]
    SubscriptionFailed(String),

    /// The session was cancelled: [`StartSessionParams::parent_cancel`] fired or, for a
    /// [`ParallelSubSession`](super::ParallelSubSession), its run was shut down. Stop.
    #[error("cancelled")]
    Cancelled,

    /// The server refused the API key when the session control channel connected (HTTP 401 or
    /// 403). Never retried: fix the key.
    #[error("API key rejected: HTTP {0}")]
    ApiKeyRejected(http::StatusCode),

    /// The session control channel closed while a continue was being handed to it: the session
    /// has ended. Call `next_event` to see why, or stop.
    #[error("control closed while sending continue: {0}")]
    ContinueSend(String),

    /// The server reported an error. Returned by [`ManagedBacktestSession::wait_until_ready`] and
    /// [`ManagedBacktestSession::run_to_completion`] on any [`ManagedEvent::Error`], terminal or
    /// not. Fix what it names and start a new session.
    #[error("server error: {0}")]
    Remote(BacktestError),

    /// The session sent `Completed` before its first `ReadyForContinue`. Returned by
    /// [`ManagedBacktestSession::wait_until_ready`].
    #[error("session completed before it was ready to continue")]
    CompletedBeforeReady,
}

impl ManagedSessionError {
    /// Whether starting a new session with the same request, after a backoff, may succeed.
    ///
    /// - `Create`: as [`CreateError::is_retryable`].
    /// - `Remote`: as [`BacktestError::is_retryable`].
    /// - `ControlFailed`, `SubscriptionFailed`: true; a connection ran out of retries.
    /// - `ControlClosed`, `ContinueSend`, `Cancelled`, `ApiKeyRejected`, `CompletedBeforeReady`:
    ///   false.
    pub fn is_retryable(&self) -> bool {
        match self {
            Self::Create(err) => err.is_retryable(),
            Self::Remote(err) => err.is_retryable(),
            Self::ControlFailed(_) | Self::SubscriptionFailed(_) => true,
            Self::ControlClosed
            | Self::ContinueSend(_)
            | Self::Cancelled
            | Self::ApiKeyRejected(_)
            | Self::CompletedBeforeReady => false,
        }
    }
}

/// An event from a managed session, returned by `next_event`.
///
/// One stream carries both the session control channel's events and the notifications of every
/// `subscribe_*` call.
///
/// # Order
///
/// - Control events arrive in the order the server sent them, starting with `Status` updates
///   while the session starts.
/// - Each subscription's notifications arrive in order. Across subscriptions, and between
///   notifications and control events, there is no order: a `Transaction` can arrive after the
///   `Slot` or `ReadyForContinue` that follows it.
/// - Every notification arrives before `Completed`: on `Completed`, the session waits for each
///   subscription to finish its stream.
/// - After `Completed`, `next_event` returns [`ManagedSessionError::ControlClosed`].
/// - If a subscription stops delivering before its stream ends, `next_event` returns the
///   notifications it has, then [`ManagedSessionError::SubscriptionFailed`] in place of
///   `Completed`.
/// - After a reconnect, a subscription sends the last slot it delivered again. Dedupe
///   transactions by signature, and account diffs by (signature, account, slot).
#[derive(Debug)]
pub enum ManagedEvent {
    /// The session is waiting for your next [`ManagedBacktestSession::send_continue`] or
    /// [`ManagedBacktestSession::send_continue_to`]. Read and change state through the session's
    /// RPC endpoint now.
    ReadyForContinue,
    /// The session stopped where a `send_continue_to` asked. Read state now, but do not answer
    /// it: a `ReadyForContinue` always follows, and that is the event to answer.
    Paused(PausedEvent),
    /// An upcoming batch matches a discovery filter from the create request. Send
    /// `send_continue_to(slot, batch_index)` to pause just before it executes.
    DiscoveryBatch(DiscoveryBatchEvent),
    /// The slot that just executed. A skipped slot has no block and sends none.
    Slot(u64),
    /// A progress update, while the session starts and during each continue.
    Status(BacktestStatus),
    /// The session replayed its last slot. Every notification has arrived before this; the next
    /// `next_event` returns [`ManagedSessionError::ControlClosed`].
    Completed {
        /// `None` unless the session was created with `send_summary`.
        summary: Option<SessionSummary>,
    },
    /// The server reported an error. When [`BacktestError::is_terminal`] is true the session is
    /// over: stop driving it. Otherwise it keeps running. Per-transaction `SimulationError`s
    /// never arrive here; they are logged.
    Error(BacktestError),
    /// From [`ManagedBacktestSession::subscribe_transactions`]: a transaction in the shape
    /// `getTransaction` returns. Program logs are in `meta.log_messages`.
    Transaction(Box<EncodedConfirmedTransactionWithStatusMeta>),
    /// From [`ManagedBacktestSession::subscribe_account_diffs`]: one changed account.
    AccountDiff(AccountDiffNotification),
    /// From [`ManagedBacktestSession::subscribe_actions`]: the result of one pre-scheduled
    /// action.
    ActionResult(ActionResultNotification),
    /// From [`ManagedBacktestSession::subscribe_diagnostics`]: one diagnostic probe sample.
    Diagnostic(DiagnosticNotification),
    /// From [`ManagedBacktestSession::subscribe_replacements`]: one reroute result for an
    /// original swap.
    Replacement(Box<ReplacementNotification>),
}

/// Idle backstop for the completion drain: if no trailing notification arrives
/// for this long after `Completed`, assume the data plane is stalled and stop
/// waiting. Bounds the gap *between* notifications, not total drain time, so a
/// slow-but-flowing stream (large backlog over a slow link) is never truncated.
const DEFAULT_COMPLETION_DRAIN_TIMEOUT: Duration = Duration::from_secs(60);

/// Result of [`ManagedBacktestSession::drain_until_subscriptions_complete`].
pub(super) enum DrainOutcome {
    /// Every subscription delivered its terminal (channels closed), or the
    /// session was cancelled. The drained events are complete up to the stop.
    Complete(Vec<ManagedEvent>),
    /// The idle backstop fired with subscriptions still open — trailing
    /// notifications never arrived, so the run is incomplete. Carries whatever
    /// was drained before the stall.
    Stalled(Vec<ManagedEvent>),
}

/// A session that reconnects on its own.
///
/// 1. [`Self::start`] it.
/// 2. Call `subscribe_*` for the notifications you need.
/// 3. Drive it: read [`Self::next_event`], and answer each [`ManagedEvent::ReadyForContinue`]
///    with one [`Self::send_continue`] or [`Self::send_continue_to`]. Never answer
///    [`ManagedEvent::Paused`]: a `ReadyForContinue` follows it, and answering both sends two
///    continues. [`Self::run_to_completion`] runs this loop for you.
/// 4. [`Self::shutdown`] it. Dropping it instead cancels the session without waiting for its
///    tasks to stop.
///
/// See the [module docs](crate::managed) for what happens when a connection drops.
pub struct ManagedBacktestSession {
    session_info: SessionInfo,
    /// Built on first [`Self::rpc`] call, so sessions that never read state skip the HTTP client.
    rpc: OnceLock<RpcClient>,
    control: Option<ControlHandle>,
    subscriptions: Vec<SubscriptionHandle>,
    session_cancel: CancellationToken,
    /// Notifications drained on `Completed`, followed by `Completed`; served in
    /// order by `next_event`. `None` until completion.
    post_completion: Option<VecDeque<ManagedEvent>>,
    /// Surfaced after `post_completion` drains: set when the completion drain
    /// stalled (idle backstop fired with subscriptions still open), so a
    /// silently-truncated run fails loudly instead of reporting `Completed`.
    post_completion_error: Option<ManagedSessionError>,
    completion_drain_timeout: Duration,
    /// Shared across a parallel batch so this session's subscription reconnects
    /// step aside for still-streaming siblings. `None` for a standalone session.
    reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
    subscription_diagnostics: Arc<SubscriptionDiagnostics>,
}

impl ManagedBacktestSession {
    /// Create a session and return once the server has created it.
    ///
    /// `url` may be a bare host (see [`StartSessionParams::url`]). Build `create` with
    /// [`crate::CreateSession`] and `into_request`. Use [`Self::start_with_params`] for extra
    /// headers or your own cancellation token.
    ///
    /// # Errors
    ///
    /// - [`ManagedSessionError::ApiKeyRejected`] if the server refuses the API key.
    /// - [`ManagedSessionError::Create`] if the server rejects the create request, or the
    ///   connection fails past the retry budget.
    pub async fn start(
        url: String,
        api_key: String,
        create: CreateBacktestSessionRequest,
    ) -> Result<Self, ManagedSessionError> {
        Self::start_with_params(
            StartSessionParams::builder()
                .url(url)
                .api_key(api_key)
                .create(create)
                .build(),
            None,
        )
        .await
    }

    /// Like [`Self::start`], from explicit [`StartSessionParams`]. Pass `None` for
    /// `reconnect_coordinator`; it is internal plumbing for parallel runs.
    ///
    /// A create that leaves `disconnect_timeout_secs` unset gets
    /// [`DEFAULT_DISCONNECT_TIMEOUT_SECS`], so the server keeps the session while the client
    /// reconnects.
    ///
    /// # Errors
    ///
    /// As [`Self::start`], plus [`ManagedSessionError::Cancelled`] if
    /// [`StartSessionParams::parent_cancel`] fires first.
    pub async fn start_with_params(
        params: StartSessionParams,
        reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
    ) -> Result<Self, ManagedSessionError> {
        let StartSessionParams {
            url,
            api_key,
            extra_headers,
            mut create,
            parent_cancel,
            subscription_diagnostics,
        } = params;
        set_default_disconnect_timeout(&mut create);
        let session_cancel = parent_cancel.child_token();
        let mut control =
            spawn_control_manager(url, api_key, extra_headers, create, session_cancel.clone());

        let session_info = tokio::select! {
            biased;
            _ = parent_cancel.cancelled() => {
                session_cancel.cancel();
                control.join().await;
                return Err(ManagedSessionError::Cancelled);
            }
            result = control.wait_for_session() => result?,
        };

        Ok(Self {
            session_info,
            rpc: OnceLock::new(),
            control: Some(control),
            subscriptions: Vec::new(),
            session_cancel,
            post_completion: None,
            post_completion_error: None,
            completion_drain_timeout: DEFAULT_COMPLETION_DRAIN_TIMEOUT,
            reconnect_coordinator,
            subscription_diagnostics,
        })
    }

    /// Metadata reported by the server when the session was created.
    pub fn session_info(&self) -> &SessionInfo {
        &self.session_info
    }

    /// RPC client (`confirmed` commitment) for the session's chain state at its current slot;
    /// serves from the first `ReadyForContinue` until `Completed`, and 502s after.
    pub fn rpc(&self) -> &RpcClient {
        self.rpc.get_or_init(|| {
            RpcClient::new_with_commitment(
                self.session_info.rpc_endpoint.clone(),
                CommitmentConfig::confirmed(),
            )
        })
    }

    /// Override the completion-drain idle timeout (default 60 s). The drain gives up only after this
    /// long with no trailing notification; it does not cap total drain time.
    pub fn set_completion_drain_timeout(&mut self, idle_timeout: std::time::Duration) {
        self.completion_drain_timeout = idle_timeout;
    }

    /// Subscribe to every transaction that mentions any of `program_ids`. Each arrives as
    /// [`ManagedEvent::Transaction`], with program logs in `meta.log_messages`.
    ///
    /// Every `subscribe_*` call opens one WebSocket on the session's RPC endpoint; the next
    /// `send_continue` waits until it is connected.
    pub fn subscribe_transactions(&mut self, program_ids: Vec<Address>) {
        self.subscriptions
            .push(spawn_transaction_subscription_manager(
                self.session_info.rpc_endpoint.clone(),
                program_ids,
                self.session_cancel.clone(),
                self.reconnect_coordinator.clone(),
                self.subscription_diagnostics.clone(),
            ));
    }

    /// Subscribe to changes of every account owned by any of `program_ids`. Each change arrives
    /// as [`ManagedEvent::AccountDiff`]. To follow single accounts across reconnects, subscribe
    /// to their owner program and keep the diffs for their addresses.
    /// [`crate::subscribe_account_diffs`] follows single accounts but does not reconnect.
    pub fn subscribe_account_diffs(&mut self, program_ids: Vec<Address>) {
        self.subscriptions
            .push(spawn_account_diff_subscription_manager(
                self.session_info.rpc_endpoint.clone(),
                program_ids,
                self.session_cancel.clone(),
                self.reconnect_coordinator.clone(),
                self.subscription_diagnostics.clone(),
            ));
    }

    /// Subscribe to the results of the pre-scheduled actions in the create request. Each arrives
    /// as [`ManagedEvent::ActionResult`].
    pub fn subscribe_actions(&mut self) {
        self.subscriptions.push(spawn_action_subscription_manager(
            self.session_info.rpc_endpoint.clone(),
            self.session_cancel.clone(),
            self.reconnect_coordinator.clone(),
            self.subscription_diagnostics.clone(),
        ));
    }

    /// Subscribe to the reroute results for each original swap: re-quotes, venue probes and the
    /// original swaps replayed beside them. One stream carries all three, as
    /// [`ManagedEvent::Replacement`].
    pub fn subscribe_replacements(&mut self) {
        self.subscriptions
            .push(spawn_replacement_subscription_manager(
                self.session_info.rpc_endpoint.clone(),
                self.session_cancel.clone(),
                self.reconnect_coordinator.clone(),
                self.subscription_diagnostics.clone(),
            ));
    }

    /// Subscribe to the samples of the diagnostic probes in the create request. Each arrives as
    /// [`ManagedEvent::Diagnostic`].
    pub fn subscribe_diagnostics(&mut self) {
        self.subscriptions
            .push(spawn_diagnostic_subscription_manager(
                self.session_info.rpc_endpoint.clone(),
                self.session_cancel.clone(),
                self.reconnect_coordinator.clone(),
                self.subscription_diagnostics.clone(),
            ));
    }

    /// Drain trailing notifications until every subscription delivers its
    /// end-of-stream terminal (closing its channel), the session is cancelled,
    /// or the data plane is found to have failed. See the `idle_timeout` arm for
    /// how reconnecting/parked subscriptions are distinguished from a stall.
    async fn drain_until_subscriptions_complete(
        &mut self,
        idle_timeout: std::time::Duration,
    ) -> DrainOutcome {
        drain_subscriptions_until_complete(
            &mut self.subscriptions,
            &self.session_cancel,
            idle_timeout,
        )
        .await
    }

    /// Wait for the next event. See [`ManagedEvent`] for the order events arrive in.
    ///
    /// # Errors
    ///
    /// - [`ManagedSessionError::ControlClosed`] once the session is over.
    /// - [`ManagedSessionError::SubscriptionFailed`] in place of `Completed` when a subscription's
    ///   stream ended early.
    /// - [`ManagedSessionError::Cancelled`] if the session was cancelled.
    pub async fn next_event(&mut self) -> Result<ManagedEvent, ManagedSessionError> {
        // Serve buffered post-completion events (trailing notifications, then
        // `Completed`); the control stream is gone once they're exhausted.
        if let Some(buffered) = self.post_completion.as_mut() {
            if let Some(event) = buffered.pop_front() {
                return Ok(event);
            }
            // Buffer drained: surface a pending stall error so an incomplete
            // run fails loudly, else the control stream is simply done.
            return Err(self
                .post_completion_error
                .take()
                .unwrap_or(ManagedSessionError::ControlClosed));
        }

        // Queued events are served without awaiting, so a caller pumping a
        // backlog would otherwise never yield.
        tokio::task::coop::consume_budget().await;

        // Scope the borrows to the `select!` so the completion drain below can
        // re-borrow `self`.
        let event = {
            let cancel = self.session_cancel.clone();
            let control = self
                .control
                .as_mut()
                .ok_or(ManagedSessionError::ControlClosed)?;
            let subscriptions = &mut self.subscriptions;
            // Control first: its task stops reading the socket, keepalive
            // included, while its queue is full, so a subscription backlog must
            // never hold control events back.
            match recv_queued(&mut control.events) {
                Some(event) => ManagedEvent::from(event),
                None => {
                    if let Some(event) = try_next_subscription_event(subscriptions) {
                        return Ok(event);
                    }
                    tokio::select! {
                        biased;
                        _ = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
                        event = control.events.recv() => {
                            event.map(ManagedEvent::from).ok_or(ManagedSessionError::ControlClosed)?
                        }
                        event = wait_any_subscription_event(subscriptions) => event,
                    }
                }
            }
        };

        // Bind the payload so the re-emitted `Completed` below carries it.
        let ManagedEvent::Completed { summary } = event else {
            return Ok(event);
        };

        // Flush trailing notifications up to each subscription's terminal,
        // delivering them before `Completed` so none are dropped.
        let (mut buffered, terminal): (VecDeque<ManagedEvent>, _) = match self
            .drain_until_subscriptions_complete(self.completion_drain_timeout)
            .await
        {
            DrainOutcome::Complete(events) => {
                (events.into(), Ok(ManagedEvent::Completed { summary }))
            }
            // The data plane stalled before every subscription finished:
            // trailing notifications are missing, so report failure rather
            // than a silently-truncated `Completed`. Deliver whatever was
            // drained first, then surface the error once the buffer empties.
            DrainOutcome::Stalled(events) => (
                events.into(),
                Err(ManagedSessionError::SubscriptionFailed(
                    "completion drain stalled: subscriptions did not deliver their \
                     end-of-stream terminals; the captured stream is incomplete"
                        .to_string(),
                )),
            ),
        };
        match terminal {
            Ok(completed) => buffered.push_back(completed),
            Err(err) => self.post_completion_error = Some(err),
        }
        let first = buffered.pop_front();
        self.post_completion = Some(buffered);
        match first {
            Some(event) => Ok(event),
            // Nothing buffered and the run failed: surface the error now.
            None => Err(self
                .post_completion_error
                .take()
                .unwrap_or(ManagedSessionError::ControlClosed)),
        }
    }

    /// Wait until the session control channel and every subscription are connected, then send
    /// a continue. Build `params` with [`crate::Continue`].
    ///
    /// Call this once per [`ManagedEvent::ReadyForContinue`].
    ///
    /// # Errors
    ///
    /// - [`ManagedSessionError::ControlFailed`] or [`ManagedSessionError::SubscriptionFailed`]
    ///   if a connection gave up.
    /// - [`ManagedSessionError::ContinueSend`] if the session has ended.
    /// - [`ManagedSessionError::Cancelled`] if the session was cancelled.
    pub async fn send_continue(
        &mut self,
        params: ContinueParams,
    ) -> Result<(), ManagedSessionError> {
        self.wait_all_up().await?;
        self.control_mut()?
            .send_continue(params)
            .await
            .map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
    }

    /// Wait until the session control channel and every subscription are connected, then send
    /// a `continueTo`: execute through `params.slot`, or with `batch_index`, up to just before
    /// that batch of it. Call this once per [`ManagedEvent::ReadyForContinue`].
    ///
    /// The session then sends [`ManagedEvent::Paused`], where you can read state, and
    /// [`ManagedEvent::ReadyForContinue`], which you answer. Rules for `params`:
    ///
    /// - `slot` must be after the last executed slot. Otherwise `next_event` returns an
    ///   `InvalidRequest` [`ManagedEvent::Error`] and the session stays where it is.
    /// - `slot` must have a block. A skipped slot has none, and the session does not stop at
    ///   it: it runs on to the end of the range.
    /// - With a [`ManagedEvent::DiscoveryBatch`], pass its `slot` and `batch_index` to pause
    ///   just before the matching batch.
    ///
    /// To run your transactions just before slot `n`, pause at `n - 1`, then send them with the
    /// next continue. They run and commit before slot `n`'s block:
    ///
    /// ```no_run
    /// use simulator_client::{Continue, ContinueToParams, ManagedBacktestSession, ManagedEvent};
    /// use solana_transaction::versioned::VersionedTransaction;
    ///
    /// async fn run_before(
    ///     session: &mut ManagedBacktestSession,
    ///     n: u64,
    ///     tx: &VersionedTransaction,
    /// ) -> Result<(), Box<dyn std::error::Error>> {
    ///     let pause = ContinueToParams { slot: n - 1, batch_index: None };
    ///     session.send_continue_to(pause).await?;
    ///     loop {
    ///         match session.next_event().await? {
    ///             ManagedEvent::ReadyForContinue => break,
    ///             ManagedEvent::Error(err) => return Err(err.into()),
    ///             _ => {}
    ///         }
    ///     }
    ///     let step = Continue::builder().build().push_transaction(tx)?.into_params();
    ///     session.send_continue(step).await?;
    ///     Ok(())
    /// }
    /// ```
    ///
    /// If slot `n - 1` may be skipped, or to skip the round trip, schedule the transaction
    /// instead: a [`ScheduledAction`](simulator_api::ScheduledAction) with a `BeforeSlot` anchor
    /// and [`ActionKind::Send`](simulator_api::ActionKind::Send).
    ///
    /// # Errors
    ///
    /// As [`Self::send_continue`].
    pub async fn send_continue_to(
        &mut self,
        params: ContinueToParams,
    ) -> Result<(), ManagedSessionError> {
        self.wait_all_up().await?;
        self.control_mut()?
            .send_continue_to(params)
            .await
            .map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
    }

    /// Wait for the first `ReadyForContinue`, from which the session's RPC endpoint serves the
    /// state before the start slot executes (the end of slot `start_slot - 1`). Earlier events
    /// (only `Status` in practice) are discarded.
    ///
    /// # Errors
    ///
    /// [`ManagedSessionError::CompletedBeforeReady`], [`ManagedSessionError::Remote`] on an
    /// `Error` event, or any error of [`Self::next_event`]. The session is not shut down; call
    /// [`Self::shutdown`].
    pub async fn wait_until_ready(&mut self) -> Result<(), ManagedSessionError> {
        loop {
            match self.next_event().await? {
                ManagedEvent::ReadyForContinue => return Ok(()),
                ManagedEvent::Completed { .. } => {
                    return Err(ManagedSessionError::CompletedBeforeReady);
                }
                ManagedEvent::Error(err) => return Err(ManagedSessionError::Remote(err)),
                _ => {}
            }
        }
    }

    /// On every `ReadyForContinue`, send `step.clone()` until `Completed`; every other event,
    /// `Paused` included, goes to `on_event`. Any `Error` event, terminal or not, stops the loop
    /// and returns `Remote`. Always shuts the session down before returning. A caller that already
    /// consumed a ready (e.g. via [`Self::wait_until_ready`]) sends its first
    /// [`Self::send_continue`] itself.
    ///
    /// Returns the summary carried by `Completed`.
    ///
    /// # Errors
    ///
    /// [`ManagedSessionError::Remote`] on an `Error` event, or any error of [`Self::next_event`]
    /// and [`Self::send_continue`].
    pub async fn run_to_completion(
        mut self,
        step: ContinueParams,
        mut on_event: impl FnMut(ManagedEvent),
    ) -> Result<Option<SessionSummary>, ManagedSessionError> {
        let result = async {
            loop {
                match self.next_event().await? {
                    ManagedEvent::ReadyForContinue => {
                        self.send_continue(step.clone()).await?;
                    }
                    ManagedEvent::Completed { summary } => return Ok(summary),
                    ManagedEvent::Error(err) => return Err(ManagedSessionError::Remote(err)),
                    other => on_event(other),
                }
            }
        }
        .await;
        self.shutdown().await;
        result
    }

    /// Cancel the session, closing it on the server, and wait until its connections have
    /// stopped.
    pub async fn shutdown(mut self) {
        self.session_cancel.cancel();
        if let Some(control) = self.control.take() {
            control.join().await;
        }
        for sub in std::mem::take(&mut self.subscriptions) {
            // A manager parked on a full queue exits only once the queue closes.
            drop(sub.notifications);
            let _ = sub.join.await;
        }
    }

    fn control_mut(&mut self) -> Result<&mut ControlHandle, ManagedSessionError> {
        self.control
            .as_mut()
            .ok_or(ManagedSessionError::ControlClosed)
    }

    async fn wait_all_up(&self) -> Result<(), ManagedSessionError> {
        let control = self
            .control
            .as_ref()
            .ok_or(ManagedSessionError::ControlClosed)?
            .status
            .clone();
        let subscriptions = self
            .subscriptions
            .iter()
            .map(|s| s.status.clone())
            .collect();
        wait_connections_up(control, subscriptions, &self.session_cancel).await
    }
}

/// Give an unset `disconnect_timeout_secs` a window wide enough for this
/// client's reconnect budget, so a management redeploy is a reattach rather
/// than a lost session. A parallel create is left alone — the server's parallel
/// default is already longer, and lowering it would shorten the batch's window.
fn set_default_disconnect_timeout(create: &mut CreateBacktestSessionRequest) {
    let params = match create {
        CreateBacktestSessionRequest::V1(CreateBacktestSessionRequestV1 {
            parallel: true, ..
        }) => return,
        CreateBacktestSessionRequest::V1(CreateBacktestSessionRequestV1 { request, .. })
        | CreateBacktestSessionRequest::V0(request) => request,
    };
    params
        .disconnect_timeout_secs
        .get_or_insert(DEFAULT_DISCONNECT_TIMEOUT_SECS);
}

/// Block until the control connection and every subscription connection report
/// `Up`, returning an error if any reports `Failed` or the token is cancelled.
/// Shared by the single-session and parallel sub-session drivers.
pub(super) async fn wait_connections_up(
    mut control: watch::Receiver<ConnectionStatus>,
    mut subscriptions: Vec<watch::Receiver<ConnectionStatus>>,
    cancel: &CancellationToken,
) -> Result<(), ManagedSessionError> {
    loop {
        let control_status = control.borrow().clone();
        if let ConnectionStatus::Failed(why) = &control_status {
            return Err(ManagedSessionError::ControlFailed(why.clone()));
        }

        let mut all_subscriptions_up = true;
        for subscription in &subscriptions {
            match &*subscription.borrow() {
                ConnectionStatus::Failed(why) => {
                    return Err(ManagedSessionError::SubscriptionFailed(why.clone()));
                }
                ConnectionStatus::Up => {}
                _ => all_subscriptions_up = false,
            }
        }

        if control_status == ConnectionStatus::Up && all_subscriptions_up {
            return Ok(());
        }

        tokio::select! {
            _ = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
            _ = control.changed() => {}
            _ = wait_any_subscription_change(&mut subscriptions) => {}
        }
    }
}

/// Drain trailing notifications until every subscription delivers its
/// end-of-stream terminal (closing its channel), `cancel` fires, or the data
/// plane is found to have stalled. Shared by the single-session and parallel
/// sub-session drivers. See
/// [`ManagedBacktestSession::drain_until_subscriptions_complete`].
///
/// `idle_timeout` bounds the gap *between* notifications, not total drain time,
/// so a slow-but-flowing stream (large backlog over a slow link) is never
/// truncated. A subscription that's `Down` — reconnecting, or parked behind the
/// reconnect coordinator waiting for siblings to free bandwidth — is *not* a
/// stall: it resumes via `replayFromSlot` or exhausts its budget and reports
/// `Failed`. So the idle gap only declares a `Stalled` outcome when an open
/// subscription is still `Up` (connected but not delivering — a genuinely hung
/// data plane); a subscription that closed in `Failed` left a truncated stream.
pub(super) async fn drain_subscriptions_until_complete(
    subscriptions: &mut [SubscriptionHandle],
    cancel: &CancellationToken,
    idle_timeout: std::time::Duration,
) -> DrainOutcome {
    let mut events = Vec::new();
    if subscriptions.is_empty() {
        return DrainOutcome::Complete(events);
    }
    loop {
        while let Some(event) = try_next_subscription_event(subscriptions) {
            events.push(event);
        }
        if subscriptions.iter().all(|s| s.notifications.is_closed()) {
            let any_failed = subscriptions
                .iter()
                .any(|s| matches!(*s.status.borrow(), ConnectionStatus::Failed(_)));
            return if any_failed {
                DrainOutcome::Stalled(events)
            } else {
                DrainOutcome::Complete(events)
            };
        }
        tokio::select! {
            biased;
            // A cancel is an intentional stop, not a data-plane failure.
            _ = cancel.cancelled() => return DrainOutcome::Complete(events),
            // Idle gap elapsed. A still-`Up` subscription should be delivering
            // but isn't — a hung data plane (stall). If the open subscriptions
            // are all reconnecting/parked (`Down`), keep waiting: the
            // coordinator is deferring them on purpose, not failing.
            _ = tokio::time::sleep(idle_timeout) => {
                let any_up = subscriptions.iter().any(|s| {
                    !s.notifications.is_closed()
                        && matches!(*s.status.borrow(), ConnectionStatus::Up)
                });
                if any_up {
                    return DrainOutcome::Stalled(events);
                }
            }
            received = recv_any_open_subscription(subscriptions) => {
                // `None` means a channel closed; the loop re-checks all-closed.
                if let Some(event) = received {
                    events.push(event);
                }
            }
        }
    }
}

impl Drop for ManagedBacktestSession {
    fn drop(&mut self) {
        self.session_cancel.cancel();
    }
}

pub(super) async fn wait_any_subscription_change(
    subscriptions: &mut [watch::Receiver<ConnectionStatus>],
) {
    if subscriptions.is_empty() {
        std::future::pending::<()>().await;
        return;
    }
    let _ =
        futures::future::select_all(subscriptions.iter_mut().map(|s| Box::pin(s.changed()))).await;
}

pub(super) async fn wait_any_subscription_event(
    subscriptions: &mut [SubscriptionHandle],
) -> ManagedEvent {
    loop {
        if let Some(event) = try_next_subscription_event(subscriptions) {
            return event;
        }

        let futures: Vec<_> = subscriptions
            .iter_mut()
            .filter(|s| !s.notifications.is_closed())
            .map(|s| Box::pin(s.notifications.recv()))
            .collect();

        if futures.is_empty() {
            std::future::pending::<()>().await;
        }

        let (notification, _, _) = futures::future::select_all(futures).await;
        if let Some(notification) = notification {
            return notification.into();
        }
    }
}

/// Await the next notification from any still-open subscription channel,
/// returning `None` when one closes. Unlike [`wait_any_subscription_event`],
/// which never resolves on closure, this lets the completion drain observe
/// per-channel end-of-stream.
pub(super) async fn recv_any_open_subscription(
    subscriptions: &mut [SubscriptionHandle],
) -> Option<ManagedEvent> {
    let futures: Vec<_> = subscriptions
        .iter_mut()
        .filter(|s| !s.notifications.is_closed())
        .map(|s| Box::pin(s.notifications.recv()))
        .collect();

    if futures.is_empty() {
        return None;
    }

    let (notification, _, _) = futures::future::select_all(futures).await;
    notification.map(Into::into)
}

pub(super) fn try_next_subscription_event(
    subscriptions: &mut [SubscriptionHandle],
) -> Option<ManagedEvent> {
    for subscription in subscriptions {
        if let Some(notification) = recv_queued(&mut subscription.notifications) {
            return Some(notification.into());
        }
    }
    None
}

/// Not `try_recv`, which parks the thread on a message still being written and so consumes a
/// `block_on` task's pending wakeup. Unconstrained so a spent coop budget never hides a queued
/// message.
fn recv_queued<T>(receiver: &mut mpsc::Receiver<T>) -> Option<T> {
    tokio::task::coop::unconstrained(receiver.recv())
        .now_or_never()
        .flatten()
}

impl From<ControlEvent> for ManagedEvent {
    fn from(event: ControlEvent) -> Self {
        match event {
            ControlEvent::ReadyForContinue => Self::ReadyForContinue,
            ControlEvent::Paused(event) => Self::Paused(event),
            ControlEvent::DiscoveryBatch(event) => Self::DiscoveryBatch(event),
            ControlEvent::Slot(slot) => Self::Slot(slot),
            ControlEvent::Status(status) => Self::Status(status),
            ControlEvent::Completed { summary } => Self::Completed { summary },
            ControlEvent::Error(error) => Self::Error(error),
        }
    }
}

impl From<SubscriptionNotification> for ManagedEvent {
    fn from(notification: SubscriptionNotification) -> Self {
        match notification {
            SubscriptionNotification::Transaction(transaction) => Self::Transaction(transaction),
            SubscriptionNotification::AccountDiff(diff) => Self::AccountDiff(diff),
            SubscriptionNotification::ActionResult(result) => Self::ActionResult(result),
            SubscriptionNotification::Diagnostic(sample) => Self::Diagnostic(sample),
            SubscriptionNotification::Replacement(replacement) => Self::Replacement(replacement),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::{
        future::Future,
        pin::Pin,
        sync::Mutex,
        task::{Poll, Waker},
    };

    use futures::{StreamExt, stream::FuturesUnordered};
    use simulator_api::{CreateSessionParams, MAX_DISCONNECT_TIMEOUT_SECS};

    use super::*;
    use crate::{
        CreateSession,
        managed::RECONNECT_MAX_TOTAL,
        subscriptions::{DiagnosticContext, DiagnosticNotification},
    };

    fn notification() -> SubscriptionNotification {
        SubscriptionNotification::Diagnostic(DiagnosticNotification {
            context: DiagnosticContext { slot: 0 },
            slot: 0,
            probe_index: 0,
            label: None,
            market: String::new(),
            usd_value: 0,
            pairs: Vec::new(),
            router_slot: None,
            results: None,
            account_hashes: Vec::new(),
            err: None,
        })
    }

    /// Driver and sibling under one `FuturesUnordered` on a `block_on` thread, the sibling waking
    /// mid-poll while senders on other threads write the driver's queue.
    #[test]
    fn subscription_reads_keep_a_sibling_wakeup_on_the_block_on_thread() {
        const SENDERS: usize = 4;
        const ROUNDS: usize = 2_000;

        let runtime = tokio::runtime::Builder::new_multi_thread()
            .enable_all()
            .build()
            .unwrap();
        let (sender, notifications) = mpsc::channel(1_024);
        let (_status_tx, status) = watch::channel(ConnectionStatus::Up);
        let mut subscriptions = vec![SubscriptionHandle {
            status,
            notifications,
            join: runtime.spawn(async {}),
        }];
        // Concurrent writers, so a read often meets a slot claimed but not yet written.
        for _ in 0..SENDERS {
            let sender = sender.clone();
            std::thread::spawn(move || {
                while sender.blocking_send(notification()).is_ok() {
                    std::thread::sleep(Duration::from_micros(20));
                }
            });
        }

        let (done_tx, done) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let sibling = Arc::new(Mutex::new(None::<Waker>));
            let driver = {
                let sibling = sibling.clone();
                async move {
                    for _ in 0..ROUNDS {
                        while try_next_subscription_event(&mut subscriptions).is_some() {}
                        if let Some(waker) = sibling.lock().unwrap().as_ref() {
                            waker.wake_by_ref();
                        }
                        // Spins to meet the next message while it is being written.
                        while try_next_subscription_event(&mut subscriptions).is_none() {}
                        wait_any_subscription_event(&mut subscriptions).await;
                    }
                }
            };
            let sibling = std::future::poll_fn(move |cx| {
                *sibling.lock().unwrap() = Some(cx.waker().clone());
                Poll::<()>::Pending
            });
            // Never woken, so a pass over the other two ends without the yield that would wake
            // the task again.
            let idle = std::future::pending::<()>();
            let mut sessions: FuturesUnordered<Pin<Box<dyn Future<Output = ()>>>> =
                FuturesUnordered::new();
            sessions.push(Box::pin(driver));
            sessions.push(Box::pin(sibling));
            sessions.push(Box::pin(idle));
            runtime.block_on(sessions.next());
            let _ = done_tx.send(());
        });

        assert!(
            done.recv_timeout(Duration::from_secs(30)).is_ok(),
            "the sessions stopped: a subscription read consumed the block_on thread's wakeup"
        );
    }

    fn params(disconnect_timeout_secs: Option<u16>) -> CreateSessionParams {
        CreateSession::builder()
            .start_slot(1)
            .slot_count(1)
            .maybe_disconnect_timeout_secs(disconnect_timeout_secs)
            .build()
            .into_params()
            .expect("valid create params")
    }

    #[test]
    fn unset_disconnect_timeout_defaults_on_single_sessions_only() {
        let cases: [(&str, CreateBacktestSessionRequest, Option<u16>); 4] = [
            (
                "v0 unset",
                CreateBacktestSessionRequest::V0(params(None)),
                Some(DEFAULT_DISCONNECT_TIMEOUT_SECS),
            ),
            (
                "v0 explicit",
                CreateBacktestSessionRequest::V0(params(Some(42))),
                Some(42),
            ),
            (
                "v1 single unset",
                CreateBacktestSessionRequestV1 {
                    request: params(None),
                    parallel: false,
                    name: None,
                    create_token: None,
                }
                .into(),
                Some(DEFAULT_DISCONNECT_TIMEOUT_SECS),
            ),
            (
                "v1 parallel unset keeps the server's parallel default",
                CreateBacktestSessionRequestV1 {
                    request: params(None),
                    parallel: true,
                    name: None,
                    create_token: None,
                }
                .into(),
                None,
            ),
        ];

        for (name, mut create, expected) in cases {
            set_default_disconnect_timeout(&mut create);
            let (request, _) = create.into_request_and_parallel();
            assert_eq!(request.disconnect_timeout_secs, expected, "{name}");
        }
    }

    #[test]
    fn default_disconnect_timeout_covers_the_reconnect_budget_without_clamping() {
        assert!(u64::from(DEFAULT_DISCONNECT_TIMEOUT_SECS) > RECONNECT_MAX_TOTAL.as_secs());
        const { assert!(DEFAULT_DISCONNECT_TIMEOUT_SECS <= MAX_DISCONNECT_TIMEOUT_SECS) };
    }
}