Skip to main content

simulator_api/
lib.rs

1//! Wire types for the Termina simulator's backtest API.
2//!
3//! This crate defines the JSON the server and its clients exchange: requests and responses on the
4//! session control channel, payloads on the session's RPC endpoint, and the bodies of the HTTP
5//! endpoints. It does no I/O.
6//!
7//! Most users want [`simulator-client`](https://docs.rs/simulator-client) instead. It sends these
8//! types for you, reconnects and reattaches, and re-exports this crate as
9//! `simulator_client::simulator_api`, so the versions always match. Depend on `simulator-api`
10//! directly only to speak the protocol over your own transport.
11//!
12//! # Message envelope
13//!
14//! Every message on the session control channel (`wss://<host>/backtest`) is a JSON object with a
15//! `method` and, when the variant carries data, `params`:
16//!
17//! ```json
18//! {"method": "continue", "params": {"advanceCount": 10}}
19//! {"method": "readyForContinue"}
20//! ```
21//!
22//! - Requests are [`BacktestRequest`] and responses are [`BacktestResponse`]. The `method` is the
23//!   variant name in camelCase.
24//! - Unless `disconnectTimeoutSecs` is 0, a single session wraps what the running session streams
25//!   in a [`SequencedResponse`] (unset counts: it defaults to 30), which adds a top-level sequence
26//!   number, `seqId`: `{"seqId": 7, "method": "slotNotification", "params": 1234}`. Keep the last
27//!   one you received: you need it to reattach.
28//! - Startup `status` updates, `sessionCreated`, `sessionAttached`, `success` and errors sent before
29//!   the session runs carry no `seqId`. Parse a [`SequencedResponse`] first and fall back to a bare
30//!   [`BacktestResponse`].
31//! - Parallel sessions report through `sessionEventV2`
32//!   ([`BacktestResponse::SessionEventV2`]), which carries its own per-session `seq_id`.
33//!
34//! # Session endpoints
35//!
36//! 1. Send `createBacktestSessionV2` ([`BacktestRequest::CreateBacktestSessionV2`]) to the server
37//!    and skip the `status` frames.
38//! 2. The reply is `sessionGranted`, or `sessionsGranted` when `parallel` is set. Each
39//!    [`SessionGrant`](session_endpoint::SessionGrant) holds the session's endpoint and a token.
40//!    Stop reading: the close frame after the grant is normal. Never send `closeBacktestSession`
41//!    to the server. A close with code 1012 before the reply means the server is draining and
42//!    started no session: send the create again, to the same URL, after a backoff.
43//! 3. Open [`SessionGrant::control_url`](session_endpoint::SessionGrant::control_url) with the
44//!    token in the `x-token` header. Within 30 seconds, send `attachBacktestSession` with no
45//!    `last_sequence`. The answer is `sessionAttached`.
46//! 4. Continue as in lifecycle steps 3 to 5 below: `continue`, the streamed responses, and
47//!    `closeBacktestSession`. `resumeAttachedSession` is not needed.
48//! 5. The session's RPC endpoint is
49//!    [`SessionGrant::rpc_url`](session_endpoint::SessionGrant::rpc_url) with the token in a
50//!    header, or [`SessionGrant::rpc_url_with_token`](session_endpoint::SessionGrant::rpc_url_with_token).
51//! 6. An HTTP 401 from the session is final: the token is wrong.
52//!
53//! The lifecycle below starts with `createBacktestSession`; use it without session endpoints.
54//!
55//! # Session lifecycle
56//!
57//! 1. Send `createBacktestSession` with [`CreateSessionParams`], or with
58//!    [`CreateBacktestSessionRequestV1`] to name the session or split the range across parallel
59//!    sessions. While the session starts, the server sends `status` updates.
60//! 2. The server replies `sessionCreated` with the `session_id` and the session's RPC endpoint
61//!    (`rpc_endpoint`, a path on the server's host: `/backtest/<session_id>`), then
62//!    `readyForContinue`.
63//! 3. Send `continue` ([`ContinueParams`]) to execute the next `advanceCount` blocks, with any user
64//!    transactions and account overrides, or `continueTo` ([`ContinueToParams`]) to pause at a
65//!    slot or before a batch. The server streams `status`, `slotNotification`, `paused` and
66//!    `discoveryBatch`, then sends `readyForContinue` again. Answer only `readyForContinue`: a
67//!    `continueTo` gets `paused` first, and answering both sends two continues.
68//! 4. Between steps, read and change state through the session's RPC endpoint.
69//! 5. After the last slot the server sends `completed`, with a [`SessionSummary`] when
70//!    `sendSummary` was set. Send `closeBacktestSession` to end the session; the server replies
71//!    `success`.
72//!
73//! An `error` response carries a [`BacktestError`]. [`BacktestError::is_terminal`] tells you
74//! whether the session is over, and [`BacktestError::is_retryable`] whether sending the request
75//! again later can succeed.
76//!
77//! A parallel create sends `sessionCreated` for each session, then `sessionsCreatedV2` with a
78//! `control_session_id` and one `session_ids` entry per session. Drive each session with
79//! `continueSessionV1`, `continueToSessionV1` and `closeSessionV1`, which name it by `sessionId`.
80//! `closeSessionV1` ends one session and sends no reply. `closeBacktestSession` ends the whole
81//! parallel run and closes the connection without a reply.
82//!
83//! **Reattach.** When the connection drops, the session waits `disconnectTimeoutSecs` for you to
84//! come back: 30 seconds when unset (900 for a parallel run), at most
85//! [`MAX_DISCONNECT_TIMEOUT_SECS`]. With `0`, the session ends with the connection. To reattach:
86//!
87//! 1. Open a new session control channel.
88//! 2. Send `attachBacktestSession` with the `session_id` and the last sequence number you received
89//!    as `last_sequence`. A parallel run sends `attachParallelControlSessionV2` with its
90//!    `control_session_id` and `last_sequences`, one per session.
91//! 3. The server replies `sessionAttached` (or `parallelSessionAttachedV2`) and replays every
92//!    response after those sequence numbers.
93//! 4. For a single session, rebuild your subscriptions, then send `resumeAttachedSession`; the
94//!    server replies `success`. A parallel run needs no resume.
95//!
96//! # Wire casing
97//!
98//! Casing depends on where a field sits. These names are the contract and do not change.
99//!
100//! | Where | Casing | Examples |
101//! |---|---|---|
102//! | `method` names and enum values on the session control channel | camelCase | `createBacktestSession`, `readyForContinue`, `startingRuntime` |
103//! | Fields declared on a [`BacktestRequest`] or [`BacktestResponse`] variant | snake_case | `session_id`, `last_sequence`, `rpc_endpoint`, `control_session_id`, `last_sequences`, `seq_id` (in `sessionEventV2`) |
104//! | Fields of a params struct, such as [`CreateSessionParams`], [`ContinueParams`] or [`ScheduledAction`] | camelCase | `startSlot`, `disconnectTimeoutSecs`, `advanceCount`, `modifyAccountStates`, `sessionId` (in `continueSessionV1`) |
105//! | The [`SequencedResponse`] wrapper | camelCase | `seqId` |
106//! | [`BacktestError`] | camelCase variant name, snake_case fields | `{"bundleNotFound": {"start_slot": 1, "end_slot": 2}}` |
107//! | HTTP request and response bodies and query parameters | snake_case, enum values too | `start_slot`, `bundle_size`, `request_id`, `"in_progress"` |
108//!
109//! So `sessionCreated` arrives as:
110//!
111//! ```json
112//! {"method": "sessionCreated", "params": {"session_id": "backtest_…", "rpc_endpoint": "…"}}
113//! ```
114//!
115//! # Encoded fields
116//!
117//! | Field | Encoding |
118//! |---|---|
119//! | [`CreateSessionParams::actions`], [`ScheduledAction::transactions`], and `slots` in a `beforeSlot` or `afterSlot` [`ActionAnchor`] | One string: base64 (standard, padded) of the zstd-compressed JSON of the whole list. Each list decompresses to at most 256 MiB. `actions` nests: each action in it keeps its own encoded `transactions` and `slots`. |
120//! | Each transaction in [`ScheduledAction::transactions`] and [`ContinueParams::transactions`] | base64 of the transaction's standard wire bytes, the bytes `sendTransaction` takes, for a legacy, v0 or v1 transaction. Build it with `simulator_client::encode_transaction`. wincode writes these bytes; bincode does not: it drops a v1 transaction's version marker. |
121//! | [`AccountData::data`] | [`EncodedBinary`] of the raw account bytes: `{"data": "<base64>", "encoding": "base64"}` |
122//! | [`DiscoveryBatchEvent::transactions`] | [`EncodedBinary`] of a wincode-serialized `VersionedTransaction`. Decode with `simulator_client::decode_transaction`. |
123//! | [`ProgramOverride::elf`] | base64 of the program binary |
124//! | Addresses, mints and program IDs | base58 strings |
125//! | [`AccountModifications`] | A JSON object keyed by base58 address |
126//! | [`SessionId`] and [`ControlSessionId`] | `backtest_<uuid>` and `parallel_<uuid>` |
127//!
128//! # Modules
129//!
130//! | Module | Contents |
131//! |---|---|
132//! | crate root | Requests, responses, session parameters, scheduled actions, account overrides, errors and HTTP bodies |
133//! | [`venue`] | Venue templates for rerouting directly to a venue |
134//! | [`replacement`] | `replacementSubscribe` notifications |
135//! | [`route_plan`] | Routes hop by hop, as the router quotes them and as transactions report them |
136//! | [`reroute_report`] | Reports built from reroute results |
137//! | [`mints`] | The stablecoins and major mints the reroute reports price against |
138//! | [`token`] | The SPL token-account layout, for building token account overrides |
139//! | [`subscribe_config`] | Options a subscription adds to its config object |
140//! | [`session_name`] | Session name rules |
141//! | [`usage`] | `GET /usage` bodies |
142//! | [`geyser_route`] | How a gRPC client names its session |
143//!
144//! # Compatibility
145//!
146//! - If you depend on both crates, use the `simulator-api` version your `simulator-client`
147//!   depends on, or reach this crate through `simulator_client::simulator_api`.
148//! - A new field is added with a default, so a message without it still parses. Unknown fields
149//!   are ignored.
150//! - An incompatible change to a message ships as a new versioned variant or type next to the old
151//!   one, such as [`CreateBacktestSessionRequestV1`] or `sessionsCreatedV2`.
152//! - An unknown `method` or enum value is a parse error. A client older than the server can fail
153//!   on a new response or status, so keep the client up to date.
154//! - Before 1.0, a minor release can break the Rust API. The changelog lists every break.
155
156#![warn(missing_docs)]
157
158use std::{
159    collections::{BTreeMap, BTreeSet, HashMap, HashSet},
160    fmt,
161    num::{NonZeroU64, NonZeroUsize},
162    str::FromStr,
163    sync::Arc,
164};
165
166use base64::{
167    DecodeError as Base64DecodeError, Engine as _, engine::general_purpose::STANDARD as BASE64,
168};
169use parking_lot::RwLock;
170use serde::{Deserialize, Serialize};
171use session_name::{CreateToken, InvalidSessionName, RequestedName};
172use solana_account::AccountSharedData;
173
174mod dataset_jobs;
175mod datasets;
176mod session_id;
177mod session_type;
178mod slot_range;
179
180pub use dataset_jobs::{
181    DatasetJobListResponse, DatasetJobPhase, DatasetJobRequest, DatasetJobSpec,
182    DatasetJobStatusResponse, DatasetLocation, PredictTable, Progress,
183};
184pub use datasets::{
185    DatasetContents, DatasetDate, DatasetDeleteRequest, DatasetDeleteResponse, DatasetFile,
186    DatasetListQuery, DatasetListResponse, DatasetPartition, DatasetParts, DatasetScope,
187    DatasetSummary, DatasetVersion, HeldSlots,
188};
189pub use reroute_report::SwapMode;
190pub use session_id::{ControlSessionId, SessionId};
191pub use session_type::SessionType;
192pub use slot_range::{
193    InvalidSlotWindows, InvertedSlotRange, NoSlotWindows, SlotRange, SlotWindows,
194};
195/// Solana account address used throughout this API; re-exported so callers need not pin a
196/// matching `solana-address` version.
197pub use solana_address::Address;
198/// Why a string is not a valid [`Address`]; carried by this API's parse errors.
199pub use solana_address::error::ParseAddressError;
200pub use venue::{
201    AMOUNT_WIDTH, DerivedAccount, ParseVenueTemplateError, Seed, TakerSlots, TemplateAccount,
202    TemplateInstruction, TemplateResolver, VenueTemplate,
203};
204
205#[doc(hidden)]
206pub mod client_identity;
207pub mod geyser_route;
208pub mod mints;
209pub mod replacement;
210pub mod reroute_report;
211pub mod route_plan;
212pub mod session_endpoint;
213pub mod session_name;
214pub mod subscribe_config;
215pub mod token;
216pub mod usage;
217pub mod venue;
218#[doc(hidden)]
219pub mod ws_compression;
220
221/// A request you send on the session control channel.
222///
223/// Serialized as `{"method": "<variantName>", "params": …}`; a variant without data has no
224/// `params`. Fields declared on a variant itself are snake_case on the wire.
225///
226/// ```
227/// use simulator_api::{BacktestRequest, ContinueParams};
228///
229/// let next = BacktestRequest::Continue(ContinueParams {
230///     advance_count: 10,
231///     ..ContinueParams::default()
232/// });
233/// assert_eq!(
234///     serde_json::to_string(&next)?,
235///     r#"{"method":"continue","params":{"advanceCount":10,"transactions":[],"modifyAccountStates":{}}}"#,
236/// );
237/// # Ok::<(), serde_json::Error>(())
238/// ```
239#[allow(
240    clippy::large_enum_variant,
241    reason = "decoded once per message and consumed by value; boxing the create variant would \
242              change every caller's construction for no measurable gain"
243)]
244#[derive(Debug, Serialize, Deserialize)]
245#[serde(tag = "method", content = "params", rename_all = "camelCase")]
246pub enum BacktestRequest {
247    /// `createBacktestSession`: start a session, or a parallel run.
248    CreateBacktestSession(CreateBacktestSessionRequest),
249    /// `continue`: execute the next blocks of a single session.
250    Continue(ContinueParams),
251    /// `continueTo`: run a single session up to a slot, or to just before a batch in it.
252    ContinueTo(ContinueToParams),
253    /// `continueSessionV1`: [`Self::Continue`] for one session of a parallel run.
254    ContinueSessionV1(ContinueSessionRequestV1),
255    /// `continueToSessionV1`: [`Self::ContinueTo`] for one session of a parallel run.
256    ContinueToSessionV1(ContinueToSessionRequestV1),
257    /// `closeBacktestSession`: end the session; the server replies `success` and closes the
258    /// connection. On a parallel run it ends every session and closes the connection without a
259    /// reply.
260    CloseBacktestSession,
261    /// `closeSessionV1`: end one session of a parallel run.
262    CloseSessionV1(CloseSessionRequestV1),
263    /// `attachBacktestSession`: reattach to a single session after the connection dropped. The
264    /// server replies `sessionAttached`, replays what you missed, then waits for
265    /// [`Self::ResumeAttachedSession`].
266    AttachBacktestSession {
267        /// The session to reattach to, from `sessionCreated`.
268        session_id: SessionId,
269        /// The last sequence number (`seqId`) you received. The server replays every response
270        /// after it; `None` replays everything it still holds.
271        last_sequence: Option<u64>,
272    },
273    /// `resumeAttachedSession`: sent after reattaching and rebuilding your subscriptions. The
274    /// session stays paused until you send it.
275    ResumeAttachedSession,
276    /// `attachParallelControlSessionV2`: reattach to a parallel run. The server replies
277    /// `parallelSessionAttachedV2` and replays each session's missed events. No resume is needed.
278    AttachParallelControlSessionV2 {
279        /// The parallel run to reattach to, from `sessionsCreatedV2`.
280        control_session_id: ControlSessionId,
281        /// The last per-session `seq_id` you received, by session.
282        /// The server replays each session's events after it; a session left out replays
283        /// everything the server still holds for it.
284        #[serde(default)]
285        last_sequences: BTreeMap<SessionId, u64>,
286    },
287    /// As `createBacktestSession`, but the client then uses the session's own endpoint. The reply is `sessionGranted`, or `sessionsGranted` when `parallel` is set.
288    CreateBacktestSessionV2(CreateBacktestSessionRequestV1),
289}
290
291/// The `params` of `createBacktestSession`, in either version. Untagged: the server tells them
292/// apart by shape.
293#[derive(Debug, Clone, Serialize, Deserialize)]
294#[serde(untagged)]
295pub enum CreateBacktestSessionRequest {
296    /// Adds a session name and parallel sessions to [`CreateSessionParams`].
297    V1(CreateBacktestSessionRequestV1),
298    /// [`CreateSessionParams`] alone: one unnamed session.
299    V0(CreateSessionParams),
300}
301
302impl CreateBacktestSessionRequest {
303    #[doc(hidden)]
304    pub fn try_into_request_options(
305        self,
306    ) -> Result<CreateBacktestSessionRequestOptions, InvalidSessionName> {
307        match self {
308            Self::V0(request) => Ok(CreateBacktestSessionRequestOptions {
309                request,
310                parallel: false,
311                name: None,
312            }),
313            Self::V1(CreateBacktestSessionRequestV1 {
314                request,
315                parallel,
316                name,
317                create_token,
318            }) => {
319                let name = name
320                    .map(|name| {
321                        name.try_into()
322                            .map(|name| RequestedName { name, create_token })
323                    })
324                    .transpose()?;
325                Ok(CreateBacktestSessionRequestOptions {
326                    request,
327                    parallel,
328                    name,
329                })
330            }
331        }
332    }
333
334    /// The session parameters and whether the range is split across parallel sessions.
335    pub fn into_request_and_parallel(self) -> (CreateSessionParams, bool) {
336        match self {
337            Self::V0(request) => (request, false),
338            Self::V1(CreateBacktestSessionRequestV1 {
339                request,
340                parallel,
341                name: _,
342                create_token: _,
343            }) => (request, parallel),
344        }
345    }
346}
347
348impl From<CreateSessionParams> for CreateBacktestSessionRequest {
349    fn from(value: CreateSessionParams) -> Self {
350        Self::V0(value)
351    }
352}
353
354impl From<CreateBacktestSessionRequestV1> for CreateBacktestSessionRequest {
355    fn from(value: CreateBacktestSessionRequestV1) -> Self {
356        Self::V1(value)
357    }
358}
359
360impl From<CreateBacktestSessionRequest> for CreateBacktestSessionRequestV1 {
361    fn from(value: CreateBacktestSessionRequest) -> Self {
362        match value {
363            CreateBacktestSessionRequest::V1(v1) => v1,
364            CreateBacktestSessionRequest::V0(request) => Self {
365                request,
366                parallel: false,
367                name: None,
368                create_token: None,
369            },
370        }
371    }
372}
373
374/// The `params` of `createBacktestSession` when you name the session or split it into parallel
375/// sessions. The [`CreateSessionParams`] fields sit at the same level as these.
376///
377/// ```no_run
378/// use simulator_api::{
379///     BacktestRequest, CreateBacktestSessionRequestV1, CreateSessionParams,
380///     session_name::CreateToken,
381/// };
382///
383/// let request = CreateBacktestSessionRequestV1 {
384///     request: CreateSessionParams::builder()
385///         .start_slot(380_000_000)
386///         .end_slot(380_000_099)
387///         .send_summary(true)
388///         .capacity_wait_timeout_secs(900)
389///         .disconnect_timeout_secs(300)
390///         .build(),
391///     parallel: false,
392///     name: Some("sol-usdc-baseline".to_string()),
393///     // Keep this request: resending it after a reconnect reclaims the name.
394///     create_token: Some(CreateToken::random()),
395/// };
396/// let message = serde_json::to_string(&BacktestRequest::CreateBacktestSession(request.into()))?;
397/// # Ok::<(), serde_json::Error>(())
398/// ```
399#[derive(Debug, Clone, Serialize, Deserialize)]
400#[serde(rename_all = "camelCase")]
401pub struct CreateBacktestSessionRequestV1 {
402    /// The session parameters, flattened into this object on the wire.
403    #[serde(flatten)]
404    pub request: CreateSessionParams,
405    /// Split the range into one session per available bundle and run them in parallel, as
406    /// [`split_range`] splits it. The server replies `sessionsCreatedV2`. Default `false`.
407    #[serde(default)]
408    pub parallel: bool,
409    /// The session's name, or the whole parallel run's when `parallel` is set; the server picks one
410    /// when unset. 1 to 100 letters, digits, `-`, `_` or `.`, starting and ending with a letter
411    /// or digit. Case-insensitive: it is stored lowercased. Names are never reused, so a taken
412    /// one fails with [`BacktestError::SessionNameTaken`]. See
413    /// [`SessionName`](session_name::SessionName).
414    // Not `SessionName`: an unparseable name would fall through the untagged enum to V0 and be lost.
415    #[serde(default, skip_serializing_if = "Option::is_none")]
416    pub name: Option<String>,
417    /// Wire name `createToken`. Identifies this create request, so resending the same request
418    /// after a reconnect reclaims its `name` instead of failing with
419    /// [`BacktestError::SessionNameTaken`]. Make one with
420    /// [`CreateToken::random`](session_name::CreateToken::random) and reuse it only for
421    /// resends of this request.
422    #[serde(default, skip_serializing_if = "Option::is_none")]
423    pub create_token: Option<CreateToken>,
424}
425
426#[doc(hidden)]
427#[derive(Debug, Clone)]
428pub struct CreateBacktestSessionRequestOptions {
429    pub request: CreateSessionParams,
430    pub parallel: bool,
431    pub name: Option<RequestedName>,
432}
433
434/// The `params` of `continueSessionV1`.
435#[derive(Debug, Serialize, Deserialize)]
436#[serde(rename_all = "camelCase")]
437pub struct ContinueSessionRequestV1 {
438    /// Wire name `sessionId`: the session of the parallel run to continue.
439    pub session_id: SessionId,
440    #[allow(missing_docs)]
441    pub request: ContinueParams,
442}
443
444/// The `params` of `continueToSessionV1`.
445#[derive(Debug, Clone, Serialize, Deserialize)]
446#[serde(rename_all = "camelCase")]
447pub struct ContinueToSessionRequestV1 {
448    /// Wire name `sessionId`: the session of the parallel run to step.
449    pub session_id: SessionId,
450    #[allow(missing_docs)]
451    pub request: ContinueToParams,
452}
453
454/// The `params` of `closeSessionV1`.
455#[derive(Debug, Serialize, Deserialize)]
456#[serde(rename_all = "camelCase")]
457pub struct CloseSessionRequestV1 {
458    /// Wire name `sessionId`: the session of the parallel run to end.
459    pub session_id: SessionId,
460}
461
462/// A filter registered at session creation describing which upcoming batches
463/// the session should announce ahead of execution via
464/// [`BacktestResponse::DiscoveryBatch`] (and its session-event twins). Each
465/// filter describes an event of interest (e.g. a specific program executing);
466/// the session "discovers" the batch in which that event will occur and
467/// emits a `DiscoveryBatch` so the client can pause immediately before it.
468#[serde_with::serde_as]
469#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
470#[serde(tag = "kind", content = "value", rename_all = "camelCase")]
471pub enum DiscoveryFilter {
472    /// Discover batches containing a transaction that invokes this program.
473    ProgramExecuted(#[serde_as(as = "serde_with::DisplayFromStr")] Address),
474    /// Discover batches containing a market maker's write to its pricing state: a transaction
475    /// that invokes one of `programs`, moves no token balance and, unless `accounts` is empty,
476    /// writes one of `accounts`. Besides price updates this also matches the maker's other
477    /// token-free writes, such as configuration.
478    OracleUpdate {
479        /// The market maker's programs.
480        #[serde_as(as = "BTreeSet<serde_with::DisplayFromStr>")]
481        programs: BTreeSet<Address>,
482        /// A write through a lookup table whose addresses did not resolve counts as a write to one
483        /// of these, since those accounts are unknown here.
484        #[serde_as(as = "BTreeSet<serde_with::DisplayFromStr>")]
485        #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
486        accounts: BTreeSet<Address>,
487    },
488    /// Discover batches containing a transaction that invokes `program` and writes one of
489    /// `accounts`, so an empty set matches nothing. A write through a lookup table whose addresses
490    /// did not resolve counts, as for [`Self::OracleUpdate`].
491    ProgramWrite {
492        /// The program the transaction must invoke.
493        #[serde_as(as = "serde_with::DisplayFromStr")]
494        program: Address,
495        /// Accounts the transaction must write one of.
496        #[serde_as(as = "BTreeSet<serde_with::DisplayFromStr>")]
497        accounts: BTreeSet<Address>,
498    },
499}
500
501/// Per-transaction facts a [`DiscoveryFilter`] can inspect when deciding
502/// whether to match. Callers build this once per transaction and feed it to
503/// every registered filter; new variants add fields here rather than growing
504/// the [`DiscoveryFilter::matches`] signature.
505#[doc(hidden)]
506pub struct TxMatchContext {
507    /// Programs invoked by the transaction (top-level + CPI observed in logs).
508    pub invoked_programs: HashSet<Address>,
509    /// Whether any token account's balance changed.
510    pub moves_tokens: bool,
511    /// Accounts the transaction may write, by the batcher's writability rule: its static keys and
512    /// the lookup-table addresses resolved for it.
513    pub written_accounts: Vec<Address>,
514    /// Whether it writes through a lookup table whose addresses did not resolve, so
515    /// `written_accounts` can't name them.
516    pub writes_via_unresolved_lookup: bool,
517}
518
519impl DiscoveryFilter {
520    /// Return `true` when this filter is satisfied by the transaction
521    /// described by `ctx`.
522    #[doc(hidden)]
523    pub fn matches(&self, ctx: &TxMatchContext) -> bool {
524        match self {
525            Self::ProgramExecuted(target) => ctx.invoked_programs.contains(target),
526            Self::OracleUpdate { programs, accounts } => {
527                !ctx.moves_tokens
528                    && ctx
529                        .invoked_programs
530                        .iter()
531                        .any(|program| programs.contains(program))
532                    && (accounts.is_empty() || writes_one_of(ctx, accounts))
533            }
534            Self::ProgramWrite { program, accounts } => {
535                ctx.invoked_programs.contains(program) && writes_one_of(ctx, accounts)
536            }
537        }
538    }
539}
540
541fn writes_one_of(ctx: &TxMatchContext, accounts: &BTreeSet<Address>) -> bool {
542    !accounts.is_empty()
543        && (ctx.writes_via_unresolved_lookup
544            || ctx
545                .written_accounts
546                .iter()
547                .any(|account| accounts.contains(account)))
548}
549
550/// Deserializes from a non-empty list of base58 addresses.
551#[derive(Debug, Clone, PartialEq, Eq, Hash)]
552pub struct NonEmptyAccounts(BTreeSet<Address>);
553
554impl NonEmptyAccounts {
555    /// The accounts, in address order.
556    pub fn iter(&self) -> impl Iterator<Item = &Address> {
557        self.0.iter()
558    }
559}
560
561impl Serialize for NonEmptyAccounts {
562    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
563        serde_with::As::<BTreeSet<serde_with::DisplayFromStr>>::serialize(&self.0, serializer)
564    }
565}
566
567impl<'de> Deserialize<'de> for NonEmptyAccounts {
568    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
569        let accounts: BTreeSet<Address> =
570            serde_with::As::<BTreeSet<serde_with::DisplayFromStr>>::deserialize(deserializer)?;
571        Self::try_from(accounts).map_err(serde::de::Error::custom)
572    }
573}
574
575/// A [`NonEmptyAccounts`] built from no accounts.
576#[derive(Debug, thiserror::Error)]
577#[error("no accounts listed")]
578pub struct EmptyAccounts;
579
580impl TryFrom<BTreeSet<Address>> for NonEmptyAccounts {
581    type Error = EmptyAccounts;
582
583    fn try_from(accounts: BTreeSet<Address>) -> Result<Self, Self::Error> {
584        if accounts.is_empty() {
585            Err(EmptyAccounts)
586        } else {
587            Ok(Self(accounts))
588        }
589    }
590}
591
592/// The two mints a swap trades, without a direction: a maker quotes a pair both ways, so
593/// `(a, b)` and `(b, a)` are the same pair. Normalized on construction and on deserialization,
594/// which is what makes the set lookup direction-agnostic. On the wire, an array of two base58
595/// mints.
596#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
597#[serde(try_from = "[String; 2]", into = "[String; 2]")]
598pub struct MintPair([Address; 2]);
599
600impl MintPair {
601    /// The pair of `one` and `other`, in either order.
602    pub fn new(one: Address, other: Address) -> Self {
603        Self(if one <= other {
604            [one, other]
605        } else {
606            [other, one]
607        })
608    }
609
610    /// The two mints, lower address first.
611    pub fn mints(&self) -> (Address, Address) {
612        (self.0[0], self.0[1])
613    }
614}
615
616/// A [`MintPair`] mint that is not a valid base58 address.
617#[derive(Debug, thiserror::Error)]
618#[error("invalid mint {mint} in pair")]
619pub struct ParseMintPairError {
620    mint: String,
621    source: ParseAddressError,
622}
623
624impl TryFrom<[String; 2]> for MintPair {
625    type Error = ParseMintPairError;
626
627    fn try_from([one, other]: [String; 2]) -> Result<Self, Self::Error> {
628        fn parse(mint: String) -> Result<Address, ParseMintPairError> {
629            Address::from_str(&mint).map_err(|source| ParseMintPairError { mint, source })
630        }
631        Ok(Self::new(parse(one)?, parse(other)?))
632    }
633}
634
635impl From<MintPair> for [String; 2] {
636    fn from(pair: MintPair) -> Self {
637        let (one, other) = pair.mints();
638        [one.to_string(), other.to_string()]
639    }
640}
641
642/// Restricts which detected swaps are rerouted. A transaction is rerouted when at least one
643/// of its swaps trades a listed pair; the rest replay unchanged, counted as `swaps_filtered`.
644/// A filter with no pairs is rejected: omit the filter to reroute every pair.
645#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
646#[serde(rename_all = "camelCase")]
647pub struct RerouteFilter {
648    /// A swap matches when the mints it trades are one of these pairs, either direction.
649    #[serde(default)]
650    pub pairs: BTreeSet<MintPair>,
651}
652
653impl RerouteFilter {
654    /// An empty filter admits nothing, which creation-time validation rejects: omit the filter
655    /// to admit everything.
656    pub fn is_empty(&self) -> bool {
657        self.pairs.is_empty()
658    }
659
660    /// Whether a swap from `input` to `output` trades a listed pair, in either direction.
661    pub fn matches_mints(&self, input: &Address, output: &Address) -> bool {
662        self.pairs.contains(&MintPair::new(*input, *output))
663    }
664
665    /// Whether any listed pair trades `mint`. An atomic arbitrage trades one mint with itself, so
666    /// it is admitted by the book naming that mint rather than by a pair it can never match.
667    pub fn mentions_mint(&self, mint: &Address) -> bool {
668        self.pairs.iter().any(|pair| {
669            let (one, other) = pair.mints();
670            one == *mint || other == *mint
671        })
672    }
673}
674
675/// How an action's transactions run. Only meaningful for an action that carries
676/// transactions: one that carries none is a schedule entry for `account_overrides`.
677#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
678#[serde(rename_all = "camelCase")]
679pub enum ActionKind {
680    /// Runs against session state without committing. Each transaction's writes are
681    /// visible to the next one in the same action and to nothing else, so the replay is
682    /// unaffected.
683    #[default]
684    Simulate,
685    /// Executes and commits to the session ledger. The writes are visible to every later
686    /// slot, including the historical transactions that follow — a deliberate change to
687    /// the replayed world, not a simulation of one. Rejected under `replay_account_state`,
688    /// where the recording restamps account state and the commit would be lost.
689    Send,
690}
691
692/// Where a [`ScheduledAction`] fires.
693///
694/// Tagged by `at`: `{"at": "afterEverySlot", "everyNSlots": 10}`.
695#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
696#[serde(tag = "at", rename_all = "camelCase")]
697pub enum ActionAnchor {
698    /// At the start of each slot, before its transactions execute and before
699    /// reroute quoting. Fires the entry for the current slot, if any.
700    BeforeSlot {
701        /// The slots the action fires at. With transactions, one per transaction: transaction
702        /// `i` fires at `slots[i]`. Encoded on the wire as base64 of the zstd-compressed JSON
703        /// list.
704        #[serde(default, with = "compressed")]
705        slots: Vec<u64>,
706    },
707    /// At the end of each slot, after its transactions execute but before it
708    /// finalizes. Fires the entry for the current slot, if any.
709    AfterSlot {
710        /// As for [`Self::BeforeSlot`].
711        #[serde(default, with = "compressed")]
712        slots: Vec<u64>,
713    },
714    /// Where `beforeSlot` fires, at every slot that is a multiple of
715    /// `every_n_slots`. The whole sequence fires at each, so a sequence repeated
716    /// across a range is sent once rather than once per slot. A slot that
717    /// carried no block fires nothing.
718    #[serde(rename_all = "camelCase")]
719    BeforeEverySlot {
720        /// Wire name `everyNSlots`. Default 1: every slot.
721        #[serde(default = "every_slot")]
722        every_n_slots: NonZeroU64,
723    },
724    /// Where `afterSlot` fires, at every slot that is a multiple of
725    /// `every_n_slots`. The whole sequence fires at each. A slot that carried no
726    /// block fires nothing.
727    #[serde(rename_all = "camelCase")]
728    AfterEverySlot {
729        /// Wire name `everyNSlots`. Default 1: every slot.
730        #[serde(default = "every_slot")]
731        every_n_slots: NonZeroU64,
732    },
733    /// Fires entry `i` of `transactions` alone before `batches[i]`.
734    BeforeBatch {
735        /// Parallel to `transactions`.
736        #[serde(default, with = "compressed")]
737        batches: Vec<BatchPosition>,
738    },
739    /// Before each batch matching `filter` executes. The whole sequence fires at
740    /// each matching batch.
741    BeforeMatch {
742        /// Which batches to fire before.
743        filter: DiscoveryFilter,
744    },
745    /// After each batch matching `filter` commits. The whole sequence fires at
746    /// each matching batch.
747    AfterMatch {
748        /// Which batches to fire after.
749        filter: DiscoveryFilter,
750    },
751    /// After each batch that changed one of `accounts`, decided from the state the batch left
752    /// rather than from the accounts its transactions lock. The whole sequence fires at each such
753    /// batch. Only under `replayAccountState`, whose recording holds the accounts each batch
754    /// changed.
755    AfterChange {
756        /// The accounts whose change fires the sequence.
757        accounts: NonEmptyAccounts,
758    },
759}
760
761const fn every_slot() -> NonZeroU64 {
762    NonZeroU64::MIN
763}
764
765#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
766#[serde(rename_all = "camelCase")]
767/// A batch of a block, by its slot and its place among the block's batches.
768pub struct BatchPosition {
769    /// The block's slot.
770    pub slot: u64,
771    /// Which of the block's batches.
772    pub batch_index: u32,
773}
774
775/// Upper bound on a decompressed transactions blob, guarding the server against
776/// a decompression bomb in client input. A per-slot override schedule runs about
777/// 2.8 KiB a slot, so this clears a 50k-slot range with room to spare.
778const MAX_ACTION_TRANSACTIONS_BYTES: u64 = 256 * 1024 * 1024;
779const PROGRAM_OWNERS: [Address; 4] = [
780    solana_sdk_ids::bpf_loader_upgradeable::ID,
781    solana_sdk_ids::bpf_loader::ID,
782    solana_sdk_ids::bpf_loader_deprecated::ID,
783    solana_sdk_ids::loader_v4::ID,
784];
785
786/// serde adapter that stores any value as a base64-encoded, zstd-compressed JSON
787/// blob on the wire, so transaction bytes never travel raw. Used via
788/// `#[serde(with = "compressed")]` on [`ScheduledAction`]'s `transactions` field
789/// and [`ActionAnchor`]'s `slots` field.
790mod compressed {
791    use std::io::Read;
792
793    use base64::Engine as _;
794    use serde::{Deserialize, Deserializer, Serialize, Serializer, de::DeserializeOwned};
795
796    use super::{BASE64, MAX_ACTION_TRANSACTIONS_BYTES};
797
798    /// zstd compression level; `0` selects zstd's default (level 3).
799    const COMPRESSION_LEVEL: i32 = 0;
800
801    pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
802    where
803        T: Serialize,
804        S: Serializer,
805    {
806        let json = serde_json::to_vec(value).map_err(serde::ser::Error::custom)?;
807        let compressed = zstd::stream::encode_all(json.as_slice(), COMPRESSION_LEVEL)
808            .map_err(serde::ser::Error::custom)?;
809        serializer.serialize_str(&BASE64.encode(compressed))
810    }
811
812    pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
813    where
814        T: DeserializeOwned,
815        D: Deserializer<'de>,
816    {
817        let blob = String::deserialize(deserializer)?;
818        let compressed = BASE64
819            .decode(blob.as_bytes())
820            .map_err(serde::de::Error::custom)?;
821        let json = decode_capped(&compressed, MAX_ACTION_TRANSACTIONS_BYTES)
822            .map_err(serde::de::Error::custom)?;
823        serde_json::from_slice(&json).map_err(serde::de::Error::custom)
824    }
825
826    /// Refuses a blob over `cap` rather than truncating it: reading to the cap alone leaves
827    /// malformed JSON, and an untagged enum reports that as no variant matching at all.
828    fn decode_capped(compressed: &[u8], cap: u64) -> std::io::Result<Vec<u8>> {
829        let mut json = Vec::new();
830        zstd::stream::read::Decoder::new(compressed)
831            .and_then(|d| Read::take(d, cap + 1).read_to_end(&mut json))?;
832        match json.len() as u64 > cap {
833            true => Err(std::io::Error::other(format!(
834                "decompressed blob is over the {cap} byte ceiling"
835            ))),
836            false => Ok(json),
837        }
838    }
839
840    #[cfg(test)]
841    mod tests {
842        use super::*;
843
844        #[test]
845        fn a_blob_over_the_ceiling_names_it_instead_of_truncating() {
846            let compressed = zstd::stream::encode_all([b'a'; 1024].as_slice(), 0).unwrap();
847            let error = decode_capped(&compressed, 64).unwrap_err();
848            assert!(error.to_string().contains("64 byte ceiling"), "{error}");
849        }
850
851        #[test]
852        fn a_blob_at_the_ceiling_is_kept_whole() {
853            let compressed = zstd::stream::encode_all([b'a'; 64].as_slice(), 0).unwrap();
854            assert_eq!(decode_capped(&compressed, 64).unwrap().len(), 64);
855        }
856    }
857}
858
859/// A sequence of transactions the server runs automatically during a backtest,
860/// with results streamed over the `actionSubscribe` subscription.
861///
862/// Each transaction runs as given:
863///
864/// - Its signatures are not verified.
865/// - Its recent blockhash is not checked, so `Hash::default()` works, unless it uses a durable
866///   nonce.
867/// - Nothing rejects a duplicate: the same transaction can run again, in this action or another.
868/// - Its fee payer pays the fee, so it needs lamports. Fund it with `account_overrides` or an
869///   earlier action.
870///
871/// Pass actions in [`CreateSessionParams::actions`]. These two fund a wallet at the first
872/// slot, then simulate a transaction after every tenth slot and return the wallet's state:
873///
874/// ```no_run
875/// use std::{collections::BTreeMap, num::NonZeroU64};
876///
877/// use simulator_api::{
878///     AccountData, AccountModifications, ActionAnchor, ActionKind, Address, CreateSessionParams,
879///     ScheduledAction,
880/// };
881///
882/// /// `encoded_tx` comes from `simulator_client::encode_transaction`.
883/// fn params(
884///     wallet: Address,
885///     encoded_tx: String,
886/// ) -> Result<CreateSessionParams, std::num::TryFromIntError> {
887///     let fund = ScheduledAction {
888///         anchor: ActionAnchor::BeforeSlot { slots: vec![380_000_000] },
889///         kind: ActionKind::Simulate,
890///         transactions: Vec::new(),
891///         // 10 SOL, in lamports.
892///         account_overrides: AccountModifications::from(BTreeMap::from([(
893///             wallet,
894///             AccountData::system_account(10_000_000_000),
895///         )])),
896///         feeds_reroute: false,
897///         return_accounts: Vec::new(),
898///         label: Some("fund".to_string()),
899///         resolve: None,
900///         within: None,
901///     };
902///     let probe = ScheduledAction {
903///         anchor: ActionAnchor::AfterEverySlot { every_n_slots: NonZeroU64::try_from(10_u64)? },
904///         kind: ActionKind::Simulate,
905///         transactions: vec![encoded_tx],
906///         account_overrides: AccountModifications::default(),
907///         feeds_reroute: false,
908///         return_accounts: vec![wallet],
909///         label: Some("probe".to_string()),
910///         resolve: None,
911///         within: None,
912///     };
913///     Ok(CreateSessionParams::builder()
914///         .start_slot(380_000_000)
915///         .end_slot(380_000_099)
916///         .actions(vec![fund, probe])
917///         .build())
918/// }
919/// ```
920#[serde_with::serde_as]
921#[derive(Debug, Clone, Serialize, Deserialize)]
922#[serde(rename_all = "camelCase")]
923pub struct ScheduledAction {
924    /// Where the action fires.
925    pub anchor: ActionAnchor,
926    /// Ignored when `transactions` is empty — that action is a schedule entry, not a run.
927    #[serde(default)]
928    pub kind: ActionKind,
929    /// Base64-encoded transactions, carried over the wire as a base64-encoded,
930    /// zstd-compressed blob. For a slot anchor (`beforeSlot`/`afterSlot`),
931    /// entry `i` fires at `slots[i]` — the two lists must be the same length,
932    /// and repeating a slot runs its entries there in order as one sequence.
933    /// For match anchors the whole list fires, in order, at each matching
934    /// batch, and for every-slot anchors at each slot the cadence names. For
935    /// `simulate`, each transaction's writes are visible to the next
936    /// without committing to the session ledger. Empty under `feeds_reroute`
937    /// makes the action declarative: `account_overrides` is then the whole payload.
938    /// Encode each with `simulator_client::encode_transaction`.
939    #[serde(default, with = "compressed")]
940    pub transactions: Vec<String>,
941    /// Account state overrides seeding the first transaction's simulation, per
942    /// `simulateTransaction` `modifyAccountStates` semantics. Invalid for
943    /// `kind: send`. Without transactions they are themselves the contribution to
944    /// the session's override schedule, `feeds_reroute` or not.
945    #[serde(default)]
946    pub account_overrides: AccountModifications,
947    /// Feed the account state this action ends with to the session's override schedule, where it
948    /// applies from the anchored slot to reroute candidates, later scheduled actions and account
949    /// reads by address, per account until a later action names the same one. Requires a
950    /// `beforeSlot` anchor.
951    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
952    pub feeds_reroute: bool,
953    /// Accounts whose post-execution state to return, following
954    /// `simulateTransaction` semantics; reflects cumulative state after the
955    /// final transaction.
956    #[serde_as(as = "Vec<serde_with::DisplayFromStr>")]
957    #[serde(default)]
958    pub return_accounts: Vec<Address>,
959    /// Optional client tag echoed back on each `actionSubscribe` result to correlate it to this action.
960    #[serde(default)]
961    pub label: Option<String>,
962    /// Rewrites the action's transactions from live state each time it fires. What each variant
963    /// needs of them is checked only when the session starts.
964    #[serde(default, skip_serializing_if = "Option::is_none")]
965    pub resolve: Option<TxResolver>,
966    /// Fires only at the slots of its anchor within these windows. Takes one `{start, end}` object
967    /// or a list. Rejected on an action that contributes to the override schedule.
968    #[serde(default, skip_serializing_if = "Option::is_none")]
969    pub within: Option<SlotWindows>,
970}
971
972impl ScheduledAction {
973    /// Whether the action's resulting state has to be simulated before it can be
974    /// published — a slot's overrides are then unknown until the action runs.
975    pub fn is_computed_override(&self) -> bool {
976        self.feeds_reroute && !self.transactions.is_empty()
977    }
978
979    /// Whether firing the action asks the session's metis router.
980    pub fn asks_router(&self) -> bool {
981        matches!(self.resolve, Some(TxResolver::Requote { .. }))
982    }
983
984    fn validate_resolve(&self) -> Result<(), TxResolverError> {
985        let Some(resolver) = &self.resolve else {
986            return Ok(());
987        };
988        match self.kind {
989            ActionKind::Send => return Err(TxResolverError::Send),
990            ActionKind::Simulate => {}
991        }
992        match resolver {
993            TxResolver::LiquidityArrays { .. } if self.transactions.len() != 1 => {
994                return Err(TxResolverError::TransactionCount {
995                    got: self.transactions.len(),
996                });
997            }
998            TxResolver::QuoteStamp | TxResolver::Requote { .. } if self.transactions.is_empty() => {
999                return Err(TxResolverError::NoTransactions);
1000            }
1001            TxResolver::LiquidityArrays { .. }
1002            | TxResolver::QuoteStamp
1003            | TxResolver::Requote { .. } => {}
1004        }
1005        if self.feeds_reroute {
1006            return Err(TxResolverError::FeedsReroute);
1007        }
1008        Ok(())
1009    }
1010}
1011
1012/// Checks each action's [`ScheduledAction::resolve`] against the rest of the action, as the
1013/// server does when the session starts.
1014pub fn validate_resolvers(actions: &[ScheduledAction]) -> Result<(), ActionResolveError> {
1015    actions
1016        .iter()
1017        .enumerate()
1018        .try_for_each(|(action, scheduled)| {
1019            scheduled
1020                .validate_resolve()
1021                .map_err(|source| ActionResolveError { action, source })
1022        })
1023}
1024
1025/// Opens a transaction outcome's `err` when the action's [`TxResolver`] failed, so nothing was
1026/// simulated; the outcome's `unresolved` flag is what marks one.
1027pub const RESOLVE_FAILURE_PREFIX: &str = "resolve: ";
1028
1029/// How a [`ScheduledAction`] rewrites its transactions from live state each time it fires.
1030/// Only valid for `kind: simulate` and without `feeds_reroute`.
1031///
1032/// Tagged by `type`; fields are camelCase: `{"type": "liquidityArrays", "pool": "…",
1033/// "inputMint": "…", "arrayKeyIndices": [3, 4]}`.
1034#[serde_with::serde_as]
1035#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1036#[serde(
1037    tag = "type",
1038    rename_all = "camelCase",
1039    rename_all_fields = "camelCase"
1040)]
1041#[allow(missing_docs)]
1042pub enum TxResolver {
1043    /// Points a single-pool swap at the liquidity arrays (CLMM tick arrays) it reads at the pool's
1044    /// price when the action fires, instead of the ones it was built with. The action's one
1045    /// transaction must be v0 with no address lookup tables, and every array key index must name
1046    /// a static key that is neither a signer nor an invoked program.
1047    LiquidityArrays {
1048        /// The pool the swap trades against.
1049        #[serde_as(as = "serde_with::DisplayFromStr")]
1050        pool: Address,
1051        /// Must be one of the pool's two mints.
1052        #[serde_as(as = "serde_with::DisplayFromStr")]
1053        input_mint: Address,
1054        /// Indices into the transaction's static account keys holding the swap's liquidity
1055        /// arrays, in the order the swap reads them.
1056        array_key_indices: ArrayKeyIndices,
1057    },
1058    /// Re-stamps each transaction's one-step Jupiter route through a venue that prices a stale
1059    /// quote short (Scorch, Flux) as quoted at the slot the action fires. The transaction must
1060    /// carry such a route. Unlike `liquidityArrays`, a slot anchor may repeat the transaction
1061    /// once per slot.
1062    QuoteStamp,
1063    /// Replaces each transaction's one-step Jupiter route with the one the session's metis router
1064    /// quotes for these terms, for a venue whose quote stamp only its own router can issue
1065    /// (HumidiFi). The route is quoted ahead of the slots it fires at and reused only while its
1066    /// stamp is fresh, and the router's accounts must be the ones the transaction already names.
1067    /// Needs the metis sidecar, which the session then starts.
1068    Requote {
1069        /// The venue's program, the route's only one.
1070        #[serde_as(as = "serde_with::DisplayFromStr")]
1071        dex: Address,
1072        #[serde_as(as = "serde_with::DisplayFromStr")]
1073        input_mint: Address,
1074        #[serde_as(as = "serde_with::DisplayFromStr")]
1075        output_mint: Address,
1076        /// Exact-in, in input-mint base units.
1077        amount: u64,
1078        slippage_bps: u16,
1079    },
1080}
1081
1082/// One or more distinct indices into a transaction's static account keys. On the wire, a JSON
1083/// array of numbers; build one with `ArrayKeyIndices::try_from(vec![3, 4])`.
1084#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1085#[serde(try_from = "Vec<u8>", into = "Vec<u8>")]
1086pub struct ArrayKeyIndices {
1087    first: u8,
1088    rest: Vec<u8>,
1089}
1090
1091impl ArrayKeyIndices {
1092    /// The indices, in order.
1093    pub fn iter(&self) -> impl Iterator<Item = u8> + '_ {
1094        std::iter::once(self.first).chain(self.rest.iter().copied())
1095    }
1096
1097    #[allow(missing_docs)]
1098    pub fn count(&self) -> NonZeroUsize {
1099        NonZeroUsize::MIN.saturating_add(self.rest.len())
1100    }
1101}
1102
1103/// Why a list is not valid [`ArrayKeyIndices`].
1104#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1105#[allow(missing_docs)]
1106pub enum ArrayKeyIndicesError {
1107    #[error("no arrayKeyIndices")]
1108    Empty,
1109    #[error("arrayKeyIndex {index} repeated")]
1110    Duplicate { index: u8 },
1111}
1112
1113impl TryFrom<Vec<u8>> for ArrayKeyIndices {
1114    type Error = ArrayKeyIndicesError;
1115
1116    fn try_from(indices: Vec<u8>) -> Result<Self, Self::Error> {
1117        let Some((&first, rest)) = indices.split_first() else {
1118            return Err(ArrayKeyIndicesError::Empty);
1119        };
1120        let mut seen = [false; 256];
1121        match indices
1122            .iter()
1123            .find(|&&index| std::mem::replace(&mut seen[usize::from(index)], true))
1124        {
1125            Some(&index) => Err(ArrayKeyIndicesError::Duplicate { index }),
1126            None => Ok(Self {
1127                first,
1128                rest: rest.to_vec(),
1129            }),
1130        }
1131    }
1132}
1133
1134impl From<ArrayKeyIndices> for Vec<u8> {
1135    fn from(indices: ArrayKeyIndices) -> Self {
1136        std::iter::once(indices.first).chain(indices.rest).collect()
1137    }
1138}
1139
1140/// Why a [`ScheduledAction::resolve`] does not fit its action.
1141#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1142pub enum TxResolverError {
1143    /// The action has `kind: send`; resolvers only rewrite simulations.
1144    #[error("resolve is not valid for kind: send")]
1145    Send,
1146    /// A `liquidityArrays` action carries other than exactly one transaction.
1147    #[error("resolve rewrites exactly one transaction, and the action carries {got}")]
1148    TransactionCount {
1149        /// How many transactions the action carries.
1150        got: usize,
1151    },
1152    /// A `quoteStamp` action carries no transactions.
1153    #[error("resolve needs a transaction to rewrite")]
1154    NoTransactions,
1155    /// The action also sets `feedsReroute`.
1156    #[error("resolve cannot be combined with feedsReroute")]
1157    FeedsReroute,
1158}
1159
1160/// A [`TxResolverError`] and the action it is in.
1161#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1162#[error("action {action}: {source}")]
1163pub struct ActionResolveError {
1164    /// The action's index in [`CreateSessionParams::actions`].
1165    pub action: usize,
1166    /// What is wrong with it.
1167    #[source]
1168    pub source: TxResolverError,
1169}
1170
1171/// Most pools, `markets` and `candidates` together, one [`DiagnosticProbeParams`] can name.
1172pub const MAX_DIAGNOSTIC_MARKETS: usize = 64;
1173/// Most `usdValues` one [`DiagnosticProbeParams`] can name.
1174pub const MAX_DIAGNOSTIC_USD_VALUES: usize = 16;
1175/// Most pairs one [`DiagnosticMarketPairs`] can name.
1176pub const MAX_DIAGNOSTIC_MARKET_PAIRS: usize = 16;
1177
1178/// Probe markets through the router's `/diagnostic` endpoint as the session runs, and stream
1179/// the results over `diagnosticSubscribe`.
1180///
1181/// A probe reports what the router would have priced against the state it has seen, not what the
1182/// venue would have filled onchain. Each firing makes [`Self::fires`] round trips to the router while
1183/// the replay waits. Checked by [`Self::validate`] when the session is created.
1184#[serde_with::serde_as]
1185#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1186#[serde(rename_all = "camelCase")]
1187pub struct DiagnosticProbeParams {
1188    /// When to probe: `afterSlot` or `afterEverySlot` only.
1189    pub anchor: ActionAnchor,
1190    /// Market (pool) addresses to probe, no repeats; with `candidates`, 1 to
1191    /// [`MAX_DIAGNOSTIC_MARKETS`] in all.
1192    #[serde_as(as = "Vec<serde_with::DisplayFromStr>")]
1193    pub markets: Vec<Address>,
1194    /// Wire name `usdValues`: trade sizes in whole US dollars, 1 to
1195    /// [`MAX_DIAGNOSTIC_USD_VALUES`] of them, none 0. Each market is probed at each size.
1196    pub usd_values: Vec<u32>,
1197    /// Tag echoed back on each `diagnosticSubscribe` result.
1198    #[serde(default)]
1199    pub label: Option<String>,
1200    /// Markets probed only for these pairs, both ways, each input sized from a `/quote` of its
1201    /// mint at the slot, or by metis from `usdValues` if that fails; every other market is
1202    /// answered for every pair it holds.
1203    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1204    pub pairs: Vec<DiagnosticMarketPairs>,
1205    /// Pools the router may not hold, each probed from the first fire its account exists at.
1206    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1207    pub candidates: Vec<DiagnosticCandidate>,
1208    /// The pairs a candidate is probed for: those of them it holds. One holding none of them is
1209    /// never probed.
1210    #[serde_as(as = "Vec<[serde_with::DisplayFromStr; 2]>")]
1211    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1212    pub candidate_pairs: Vec<[Address; 2]>,
1213    /// Fires only at the slots of its anchor that fall within this range.
1214    #[serde(default, skip_serializing_if = "Option::is_none")]
1215    pub within: Option<SlotRange>,
1216}
1217
1218/// A pool the router may not hold, probed for [`DiagnosticProbeParams::candidate_pairs`].
1219#[serde_with::serde_as]
1220#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1221#[serde(rename_all = "camelCase")]
1222pub struct DiagnosticCandidate {
1223    #[serde_as(as = "serde_with::DisplayFromStr")]
1224    #[allow(missing_docs)]
1225    pub market: Address,
1226    /// The program owning the pool's account; on a mismatch the pool is never probed.
1227    #[serde_as(as = "serde_with::DisplayFromStr")]
1228    pub owner: Address,
1229    /// A lookup table the pool's swaps use, if any.
1230    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
1231    #[serde(default, skip_serializing_if = "Option::is_none")]
1232    pub address_lookup_table: Option<Address>,
1233}
1234
1235/// The mint pairs one probed market is answered for.
1236#[serde_with::serde_as]
1237#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1238#[serde(rename_all = "camelCase")]
1239pub struct DiagnosticMarketPairs {
1240    /// A market from [`DiagnosticProbeParams::markets`], named at most once.
1241    #[serde_as(as = "serde_with::DisplayFromStr")]
1242    pub market: Address,
1243    /// 1 to [`MAX_DIAGNOSTIC_MARKET_PAIRS`] pairs of two different mints, each probed both ways.
1244    #[serde_as(as = "Vec<[serde_with::DisplayFromStr; 2]>")]
1245    pub pairs: Vec<[Address; 2]>,
1246}
1247
1248/// Why a [`DiagnosticProbeParams`] is rejected at session creation.
1249#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1250#[allow(missing_docs)]
1251pub enum DiagnosticProbeError {
1252    /// `markets` and `candidates` are both empty.
1253    #[error("a diagnostic probe names no markets")]
1254    NoMarkets,
1255    #[error("a diagnostic probe names no usdValues")]
1256    NoUsdValues,
1257    /// `markets` and `candidates` together are longer than [`MAX_DIAGNOSTIC_MARKETS`].
1258    #[error("a diagnostic probe names {got} markets, over the ceiling of {MAX_DIAGNOSTIC_MARKETS}")]
1259    TooManyMarkets {
1260        /// How many pools the probe names.
1261        got: usize,
1262    },
1263    /// `usdValues` is longer than [`MAX_DIAGNOSTIC_USD_VALUES`].
1264    #[error(
1265        "a diagnostic probe names {got} usdValues, over the ceiling of {MAX_DIAGNOSTIC_USD_VALUES}"
1266    )]
1267    TooManyUsdValues {
1268        /// How many sizes the probe names.
1269        got: usize,
1270    },
1271    /// `usdValues` contains 0.
1272    #[error("a diagnostic probe names usdValue 0, which the router reads as no size at all")]
1273    ZeroUsdValue,
1274    /// A market appears twice across `markets` and `candidates`.
1275    #[error("a diagnostic probe names market {market} more than once")]
1276    DuplicateMarket { market: Address },
1277    /// `pairs` names a market that is not in `markets`.
1278    #[error("a diagnostic probe names pairs for market {market}, which it does not probe")]
1279    PairsOfUnprobedMarket {
1280        /// The market missing from `markets`.
1281        market: Address,
1282    },
1283    #[error("a diagnostic probe names pairs for market {market} more than once")]
1284    DuplicatePairsMarket { market: Address },
1285    /// A market's pair list is empty or longer than [`MAX_DIAGNOSTIC_MARKET_PAIRS`].
1286    #[error(
1287        "a diagnostic probe names {got} pairs for market {market}, outside \
1288         1..={MAX_DIAGNOSTIC_MARKET_PAIRS}"
1289    )]
1290    PairCount {
1291        market: Address,
1292        /// How many pairs it names.
1293        got: usize,
1294    },
1295    /// A pair names the same mint twice.
1296    #[error("a diagnostic probe pairs mint {mint} with itself on market {market}")]
1297    SelfPair { market: Address, mint: Address },
1298    /// `candidatePairs` is empty or longer than [`MAX_DIAGNOSTIC_MARKET_PAIRS`] while
1299    /// `candidates` is not.
1300    #[error(
1301        "a diagnostic probe names {got} candidate pairs for its candidates, outside \
1302         1..={MAX_DIAGNOSTIC_MARKET_PAIRS}"
1303    )]
1304    CandidatePairCount {
1305        /// How many candidate pairs it names.
1306        got: usize,
1307    },
1308    /// A candidate pair names the same mint twice.
1309    #[error("a diagnostic probe pairs mint {mint} with itself for its candidates")]
1310    CandidateSelfPair {
1311        /// The repeated mint.
1312        mint: Address,
1313    },
1314    /// The anchor is not `afterSlot` or `afterEverySlot`.
1315    #[error(
1316        "a diagnostic probe anchors at {anchor}; probing the router is an await, and only the \
1317         slot-end hook has a point for one, so only afterSlot and afterEverySlot are supported"
1318    )]
1319    UnsupportedAnchor {
1320        /// The anchor's wire name.
1321        anchor: &'static str,
1322    },
1323}
1324
1325impl DiagnosticProbeParams {
1326    /// Round-trips one anchor costs.
1327    pub fn fires(&self) -> usize {
1328        self.pools() * self.usd_values.len()
1329    }
1330
1331    fn pools(&self) -> usize {
1332        self.markets.len() + self.candidates.len()
1333    }
1334
1335    /// Checks the probe as the server does when the session is created.
1336    pub fn validate(&self) -> Result<(), DiagnosticProbeError> {
1337        if self.pools() == 0 {
1338            return Err(DiagnosticProbeError::NoMarkets);
1339        }
1340        if self.usd_values.is_empty() {
1341            return Err(DiagnosticProbeError::NoUsdValues);
1342        }
1343        if self.pools() > MAX_DIAGNOSTIC_MARKETS {
1344            return Err(DiagnosticProbeError::TooManyMarkets { got: self.pools() });
1345        }
1346        if self.usd_values.len() > MAX_DIAGNOSTIC_USD_VALUES {
1347            return Err(DiagnosticProbeError::TooManyUsdValues {
1348                got: self.usd_values.len(),
1349            });
1350        }
1351        if self.usd_values.contains(&0) {
1352            return Err(DiagnosticProbeError::ZeroUsdValue);
1353        }
1354        let mut seen = HashSet::with_capacity(self.markets.len());
1355        if let Some(market) = self.markets.iter().find(|market| !seen.insert(**market)) {
1356            return Err(DiagnosticProbeError::DuplicateMarket { market: *market });
1357        }
1358        let mut paired = HashSet::with_capacity(self.pairs.len());
1359        for DiagnosticMarketPairs { market, pairs } in &self.pairs {
1360            let market = *market;
1361            if !seen.contains(&market) {
1362                return Err(DiagnosticProbeError::PairsOfUnprobedMarket { market });
1363            }
1364            if !paired.insert(market) {
1365                return Err(DiagnosticProbeError::DuplicatePairsMarket { market });
1366            }
1367            match pairs_fault(pairs) {
1368                Some(PairsFault::Count(got)) => {
1369                    return Err(DiagnosticProbeError::PairCount { market, got });
1370                }
1371                Some(PairsFault::SelfPair(mint)) => {
1372                    return Err(DiagnosticProbeError::SelfPair { market, mint });
1373                }
1374                None => {}
1375            }
1376        }
1377        if let Some(DiagnosticCandidate { market, .. }) = self
1378            .candidates
1379            .iter()
1380            .find(|candidate| !seen.insert(candidate.market))
1381        {
1382            return Err(DiagnosticProbeError::DuplicateMarket { market: *market });
1383        }
1384        if !self.candidates.is_empty() {
1385            match pairs_fault(&self.candidate_pairs) {
1386                Some(PairsFault::Count(got)) => {
1387                    return Err(DiagnosticProbeError::CandidatePairCount { got });
1388                }
1389                Some(PairsFault::SelfPair(mint)) => {
1390                    return Err(DiagnosticProbeError::CandidateSelfPair { mint });
1391                }
1392                None => {}
1393            }
1394        }
1395        match &self.anchor {
1396            ActionAnchor::AfterSlot { .. } | ActionAnchor::AfterEverySlot { .. } => Ok(()),
1397            ActionAnchor::BeforeSlot { .. } => Err(DiagnosticProbeError::UnsupportedAnchor {
1398                anchor: "beforeSlot",
1399            }),
1400            ActionAnchor::BeforeEverySlot { .. } => Err(DiagnosticProbeError::UnsupportedAnchor {
1401                anchor: "beforeEverySlot",
1402            }),
1403            ActionAnchor::BeforeBatch { .. } => Err(DiagnosticProbeError::UnsupportedAnchor {
1404                anchor: "beforeBatch",
1405            }),
1406            ActionAnchor::BeforeMatch { .. } => Err(DiagnosticProbeError::UnsupportedAnchor {
1407                anchor: "beforeMatch",
1408            }),
1409            ActionAnchor::AfterMatch { .. } => Err(DiagnosticProbeError::UnsupportedAnchor {
1410                anchor: "afterMatch",
1411            }),
1412            ActionAnchor::AfterChange { .. } => Err(DiagnosticProbeError::UnsupportedAnchor {
1413                anchor: "afterChange",
1414            }),
1415        }
1416    }
1417}
1418
1419enum PairsFault {
1420    Count(usize),
1421    SelfPair(Address),
1422}
1423
1424fn pairs_fault(pairs: &[[Address; 2]]) -> Option<PairsFault> {
1425    if !(1..=MAX_DIAGNOSTIC_MARKET_PAIRS).contains(&pairs.len()) {
1426        return Some(PairsFault::Count(pairs.len()));
1427    }
1428    pairs
1429        .iter()
1430        .find(|[a, b]| a == b)
1431        .map(|[mint, _]| PairsFault::SelfPair(*mint))
1432}
1433
1434/// One ordered contribution to a slot's override state.
1435#[derive(Debug, Clone)]
1436enum OverrideContribution {
1437    Static(HashMap<Address, AccountSharedData>),
1438    Pending,
1439    Resolved(HashMap<Address, AccountSharedData>),
1440    Failed,
1441}
1442
1443#[derive(Debug, Clone, Default)]
1444struct OverrideScheduleInner {
1445    entries: BTreeMap<u64, Vec<(u32, OverrideContribution)>>,
1446    /// Every account some contribution names. The geyser rewrite path asks `active_for` about each
1447    /// account event it sees, and almost none are overridden; without this the miss walks every
1448    /// entry up to the slot.
1449    keys: HashSet<Address>,
1450}
1451
1452impl OverrideScheduleInner {
1453    fn new(entries: BTreeMap<u64, Vec<(u32, OverrideContribution)>>) -> Self {
1454        let keys = entries
1455            .values()
1456            .flatten()
1457            .filter_map(|(_, contribution)| match contribution {
1458                OverrideContribution::Static(accounts)
1459                | OverrideContribution::Resolved(accounts) => Some(accounts.keys().copied()),
1460                OverrideContribution::Pending | OverrideContribution::Failed => None,
1461            })
1462            .flatten()
1463            .collect();
1464        Self { entries, keys }
1465    }
1466}
1467
1468/// Slot-keyed account overrides, carried forward per account. Clones share the same runtime
1469/// resolutions so the session, reroute engine, and geyser pump observe one schedule.
1470#[doc(hidden)]
1471#[derive(Debug, Clone, Default)]
1472pub struct OverrideSchedule {
1473    inner: Arc<RwLock<OverrideScheduleInner>>,
1474}
1475
1476impl From<BTreeMap<u64, HashMap<Address, AccountSharedData>>> for OverrideSchedule {
1477    fn from(entries: BTreeMap<u64, HashMap<Address, AccountSharedData>>) -> Self {
1478        Self {
1479            inner: Arc::new(RwLock::new(OverrideScheduleInner::new(
1480                entries
1481                    .into_iter()
1482                    .map(|(slot, accounts)| {
1483                        (slot, vec![(0, OverrideContribution::Static(accounts))])
1484                    })
1485                    .collect(),
1486            ))),
1487        }
1488    }
1489}
1490
1491impl OverrideSchedule {
1492    pub fn is_empty(&self) -> bool {
1493        self.inner.read().entries.is_empty()
1494    }
1495
1496    /// Slots at which some entry activates, ascending.
1497    pub fn slots(&self) -> impl Iterator<Item = u64> + '_ {
1498        self.inner
1499            .read()
1500            .entries
1501            .keys()
1502            .copied()
1503            .collect::<Vec<_>>()
1504            .into_iter()
1505    }
1506
1507    /// Everything active at `slot`, resolved per account.
1508    pub fn active_at(&self, slot: u64) -> HashMap<Address, AccountSharedData> {
1509        self.inner.read().entries.range(..=slot).fold(
1510            HashMap::new(),
1511            |mut active, (_, contributions)| {
1512                active.extend(fold_contributions(contributions));
1513                active
1514            },
1515        )
1516    }
1517
1518    /// The override active for `key` at `slot`, if any.
1519    pub fn active_for(&self, key: &Address, slot: u64) -> Option<AccountSharedData> {
1520        let inner = self.inner.read();
1521        if !inner.keys.contains(key) {
1522            return None;
1523        }
1524        inner
1525            .entries
1526            .range(..=slot)
1527            .rev()
1528            .find_map(|(_, contributions)| {
1529                contributions
1530                    .iter()
1531                    .rev()
1532                    .find_map(|(_, contribution)| match contribution {
1533                        OverrideContribution::Static(accounts)
1534                        | OverrideContribution::Resolved(accounts) => accounts.get(key).cloned(),
1535                        OverrideContribution::Pending | OverrideContribution::Failed => None,
1536                    })
1537            })
1538    }
1539
1540    /// Final values activated in `(after, up_to]`, deduplicated per account.
1541    pub fn newly_active(
1542        &self,
1543        after: Option<u64>,
1544        up_to: u64,
1545    ) -> Vec<(Address, AccountSharedData)> {
1546        let lower = after.map_or(std::ops::Bound::Unbounded, std::ops::Bound::Excluded);
1547        self.inner
1548            .read()
1549            .entries
1550            .range((lower, std::ops::Bound::Included(up_to)))
1551            .flat_map(|(_, contributions)| fold_contributions(contributions))
1552            .collect::<HashMap<_, _>>()
1553            .into_iter()
1554            .collect()
1555    }
1556
1557    /// Resolve one computed contribution; `None` marks the action failed, contributing no accounts.
1558    /// Counting failures is the caller's job — it also sees the errors returned here.
1559    pub fn resolve(
1560        &self,
1561        slot: u64,
1562        action_index: u32,
1563        accounts: Option<HashMap<Address, AccountSharedData>>,
1564    ) -> Result<(), String> {
1565        let mut inner = self.inner.write();
1566        let OverrideScheduleInner { entries, keys } = &mut *inner;
1567        let contribution = entries
1568            .get_mut(&slot)
1569            .and_then(|contributions| {
1570                contributions
1571                    .iter_mut()
1572                    .find(|(index, _)| *index == action_index)
1573                    .map(|(_, contribution)| contribution)
1574            })
1575            .ok_or_else(|| {
1576                format!("override action {action_index} has no contribution at slot {slot}")
1577            })?;
1578        if !matches!(contribution, OverrideContribution::Pending) {
1579            return Err(format!(
1580                "override action {action_index} at slot {slot} is not pending"
1581            ));
1582        }
1583        *contribution = match accounts {
1584            Some(accounts) => {
1585                keys.extend(accounts.keys().copied());
1586                OverrideContribution::Resolved(accounts)
1587            }
1588            None => OverrideContribution::Failed,
1589        };
1590        Ok(())
1591    }
1592}
1593
1594fn fold_contributions(
1595    contributions: &[(u32, OverrideContribution)],
1596) -> HashMap<Address, AccountSharedData> {
1597    let mut accounts = HashMap::new();
1598    for (_, contribution) in contributions {
1599        match contribution {
1600            OverrideContribution::Static(next) | OverrideContribution::Resolved(next) => {
1601                accounts.extend(next.iter().map(|(key, account)| (*key, account.clone())));
1602            }
1603            OverrideContribution::Pending | OverrideContribution::Failed => {}
1604        }
1605    }
1606    accounts
1607}
1608
1609/// Validate and compile the publishing actions into the slot-keyed override schedule every
1610/// simulation surface consumes — reroute candidates and scheduled-action runs alike. Static
1611/// contributions are immediately available; computed contributions retain their action order as
1612/// pending entries until the action scheduler resolves them.
1613///
1614/// `feeds_reroute` actions contribute their end-state; a declarative override action (account
1615/// overrides, no transactions) contributes without the flag, so overrides stay usable in a
1616/// session that never reroutes.
1617fn decode_override_actions(actions: &[ScheduledAction]) -> Result<OverrideSchedule, String> {
1618    let mut entries: BTreeMap<u64, Vec<(u32, OverrideContribution)>> = BTreeMap::new();
1619    for (action_index, action) in actions.iter().enumerate().filter(|(_, action)| {
1620        action.feeds_reroute
1621            || (action.transactions.is_empty() && !action.account_overrides.0.is_empty())
1622    }) {
1623        // Without this an action that meant to send would feed the schedule instead, silently.
1624        if action.kind == ActionKind::Send {
1625            return Err("account overrides are not valid for kind: send".to_string());
1626        }
1627        if action.transactions.is_empty() && action.account_overrides.0.is_empty() {
1628            return Err(
1629                "feedsReroute needs something to feed: transactions to simulate, or \
1630                 accountOverrides"
1631                    .to_string(),
1632            );
1633        }
1634        let ActionAnchor::BeforeSlot { slots } = &action.anchor else {
1635            return Err("scheduled account overrides require a beforeSlot anchor".to_string());
1636        };
1637        if action.within.is_some() {
1638            return Err("scheduled account overrides cannot be bounded by within".to_string());
1639        }
1640        let accounts = decode_account_modifications(&action.account_overrides)?;
1641        let contribution = if action.transactions.is_empty() {
1642            OverrideContribution::Static(accounts)
1643        } else {
1644            OverrideContribution::Pending
1645        };
1646        // Deduplicated: a slot repeated in one action would push two contributions sharing an
1647        // action index, and `resolve` only ever finds the first — leaving the second pending.
1648        for slot in slots.iter().copied().collect::<BTreeSet<_>>() {
1649            entries
1650                .entry(slot)
1651                .or_default()
1652                .push((action_index as u32, contribution.clone()));
1653        }
1654    }
1655    Ok(OverrideSchedule {
1656        inner: Arc::new(RwLock::new(OverrideScheduleInner::new(entries))),
1657    })
1658}
1659
1660/// Decode account overrides into engine override form, rejecting
1661/// executable/program accounts (cached program binaries make program overrides
1662/// stale).
1663#[allow(
1664    deprecated,
1665    reason = "`PROGRAM_OWNERS` remains the canonical loader-owner list"
1666)]
1667#[doc(hidden)]
1668pub fn decode_account_modifications(
1669    modifications: &AccountModifications,
1670) -> Result<HashMap<Address, AccountSharedData>, String> {
1671    modifications
1672        .0
1673        .iter()
1674        .map(|(address, data)| {
1675            let account = data
1676                .to_account()
1677                .map_err(|error| format!("invalid account data for {address}: {error}"))?;
1678            if account.executable || PROGRAM_OWNERS.contains(&account.owner) {
1679                return Err(format!(
1680                    "overriding executable/program accounts is not supported (account {address})"
1681                ));
1682            }
1683            Ok((*address, AccountSharedData::from(account)))
1684        })
1685        .collect()
1686}
1687
1688/// Server-side ceiling on [`CreateSessionParams::disconnect_timeout_secs`]:
1689/// 900 seconds (15 minutes). A larger request is silently clamped to this, so
1690/// clients must keep their reconnect budget under it to survive a detach.
1691pub const MAX_DISCONNECT_TIMEOUT_SECS: u16 = 900;
1692
1693/// A router whose historical swaps a session can reroute. Lowercase on the wire; parsing
1694/// ignores case and surrounding spaces.
1695#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
1696#[serde(rename_all = "lowercase", try_from = "String")]
1697pub enum SwapAggregator {
1698    /// `jupiter`, the default.
1699    Jupiter,
1700    /// `okx`.
1701    Okx,
1702    /// `titan`.
1703    Titan,
1704    /// `dflow`.
1705    Dflow,
1706}
1707
1708impl SwapAggregator {
1709    /// Every aggregator a session can reroute, in `Ord` order.
1710    pub const ALL: [Self; 4] = [Self::Jupiter, Self::Okx, Self::Titan, Self::Dflow];
1711
1712    /// Matches the serialized spelling and the aggregator labels in the per-reroute rows.
1713    pub const fn as_str(self) -> &'static str {
1714        match self {
1715            Self::Jupiter => "jupiter",
1716            Self::Okx => "okx",
1717            Self::Titan => "titan",
1718            Self::Dflow => "dflow",
1719        }
1720    }
1721}
1722
1723impl std::fmt::Display for SwapAggregator {
1724    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1725        f.write_str(self.as_str())
1726    }
1727}
1728
1729/// Why a string is not a [`SwapAggregator`] or a [`RerouteAggregators`] list.
1730#[derive(Debug, thiserror::Error)]
1731pub enum ParseAggregatorError {
1732    /// Not one of `jupiter`, `okx`, `titan` or `dflow`; carries the input.
1733    #[error("unknown swap aggregator {0:?}; expected one of jupiter, okx, titan, dflow")]
1734    Unknown(String),
1735    /// A session that admits no aggregator drives the whole reroute apparatus and reroutes nothing.
1736    #[error("name at least one aggregator (jupiter, okx, titan, dflow)")]
1737    NoAggregator,
1738}
1739
1740impl TryFrom<String> for SwapAggregator {
1741    type Error = ParseAggregatorError;
1742
1743    fn try_from(value: String) -> Result<Self, Self::Error> {
1744        value.parse()
1745    }
1746}
1747
1748impl std::str::FromStr for SwapAggregator {
1749    type Err = ParseAggregatorError;
1750
1751    fn from_str(s: &str) -> Result<Self, Self::Err> {
1752        match s.trim().to_ascii_lowercase().as_str() {
1753            "jupiter" => Ok(Self::Jupiter),
1754            "okx" => Ok(Self::Okx),
1755            "titan" => Ok(Self::Titan),
1756            "dflow" => Ok(Self::Dflow),
1757            _ => Err(ParseAggregatorError::Unknown(s.to_string())),
1758        }
1759    }
1760}
1761
1762/// The aggregators a session reroutes. Jupiter alone by default: the router builds Jupiter replacements,
1763/// so other aggregators' order flow is a cross-router counterfactual a session asks for
1764/// deliberately. On the wire, an array such as `["jupiter", "okx"]`. Also parsed from one
1765/// comma-separated string (`"jupiter,okx"`) so a flag or an env var carries the set.
1766#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1767#[serde(transparent)]
1768pub struct RerouteAggregators(BTreeSet<SwapAggregator>);
1769
1770impl Default for RerouteAggregators {
1771    fn default() -> Self {
1772        Self([SwapAggregator::Jupiter].into_iter().collect())
1773    }
1774}
1775
1776impl RerouteAggregators {
1777    /// The set of `aggregators`; repeats collapse.
1778    pub fn new(aggregators: impl IntoIterator<Item = SwapAggregator>) -> Self {
1779        Self(aggregators.into_iter().collect())
1780    }
1781
1782    /// Admits every aggregator; the default is Jupiter alone.
1783    pub fn all() -> Self {
1784        Self::new(SwapAggregator::ALL)
1785    }
1786
1787    #[allow(missing_docs)]
1788    pub fn contains(&self, aggregator: SwapAggregator) -> bool {
1789        self.0.contains(&aggregator)
1790    }
1791
1792    #[allow(missing_docs)]
1793    pub fn is_empty(&self) -> bool {
1794        self.0.is_empty()
1795    }
1796}
1797
1798impl std::fmt::Display for RerouteAggregators {
1799    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1800        let mut aggregators = self.0.iter();
1801        if let Some(first) = aggregators.next() {
1802            write!(f, "{first}")?;
1803        }
1804        aggregators.try_for_each(|aggregator| write!(f, ",{aggregator}"))
1805    }
1806}
1807
1808impl std::str::FromStr for RerouteAggregators {
1809    type Err = ParseAggregatorError;
1810
1811    fn from_str(s: &str) -> Result<Self, Self::Err> {
1812        let aggregators: BTreeSet<SwapAggregator> = s
1813            .split(',')
1814            .filter(|aggregator| !aggregator.trim().is_empty())
1815            .map(str::parse)
1816            .collect::<Result<_, _>>()?;
1817        if aggregators.is_empty() {
1818            return Err(ParseAggregatorError::NoAggregator);
1819        }
1820        Ok(Self(aggregators))
1821    }
1822}
1823
1824/// Where a rerouted swap ran in its transaction.
1825#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
1826#[serde(rename_all = "kebab-case", try_from = "String")]
1827pub enum SwapScope {
1828    /// A router instruction of the transaction's own, rerouted in its place.
1829    TopLevel,
1830    /// A router another instruction CPI'd, rerouted on its own for a funded stand-in taker.
1831    Nested,
1832    /// A venue call no router reading owns, read from the transaction's flows and re-quoted on
1833    /// its own the same way.
1834    Venue,
1835}
1836
1837impl SwapScope {
1838    /// Every scope a session can reroute, in `Ord` order.
1839    pub const ALL: [Self; 3] = [Self::TopLevel, Self::Nested, Self::Venue];
1840
1841    /// Matches the serialized spelling (`top-level` or `nested`).
1842    pub const fn as_str(self) -> &'static str {
1843        match self {
1844            Self::TopLevel => "top-level",
1845            Self::Nested => "nested",
1846            Self::Venue => "venue",
1847        }
1848    }
1849}
1850
1851impl std::fmt::Display for SwapScope {
1852    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1853        f.write_str(self.as_str())
1854    }
1855}
1856
1857/// Why a string is not a [`SwapScope`] or a [`RerouteScopes`] list.
1858#[derive(Debug, thiserror::Error)]
1859pub enum ParseScopeError {
1860    /// Not `top-level`, `nested` or `venue`; carries the input.
1861    #[error("unknown swap scope {0:?}; expected one of top-level, nested, venue")]
1862    Unknown(String),
1863    /// A session that admits no scope reroutes nothing.
1864    #[error("name at least one swap scope (top-level, nested, venue)")]
1865    NoScope,
1866}
1867
1868impl TryFrom<String> for SwapScope {
1869    type Error = ParseScopeError;
1870
1871    fn try_from(value: String) -> Result<Self, Self::Error> {
1872        value.parse()
1873    }
1874}
1875
1876impl std::str::FromStr for SwapScope {
1877    type Err = ParseScopeError;
1878
1879    fn from_str(s: &str) -> Result<Self, Self::Err> {
1880        match s.trim().to_ascii_lowercase().as_str() {
1881            "top-level" => Ok(Self::TopLevel),
1882            "nested" => Ok(Self::Nested),
1883            "venue" => Ok(Self::Venue),
1884            _ => Err(ParseScopeError::Unknown(s.to_string())),
1885        }
1886    }
1887}
1888
1889/// Which swaps a session reroutes, by where they ran. Top-level router instructions alone by
1890/// default. Parsed from one comma-separated string so a flag or an env var carries the set.
1891#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1892#[serde(transparent)]
1893pub struct RerouteScopes(BTreeSet<SwapScope>);
1894
1895impl Default for RerouteScopes {
1896    fn default() -> Self {
1897        Self([SwapScope::TopLevel].into_iter().collect())
1898    }
1899}
1900
1901impl RerouteScopes {
1902    /// The set of `scopes`; repeats collapse.
1903    pub fn new(scopes: impl IntoIterator<Item = SwapScope>) -> Self {
1904        Self(scopes.into_iter().collect())
1905    }
1906
1907    /// Admits every scope; the default is `top-level` alone.
1908    pub fn all() -> Self {
1909        Self::new(SwapScope::ALL)
1910    }
1911
1912    #[allow(missing_docs)]
1913    pub fn contains(&self, scope: SwapScope) -> bool {
1914        self.0.contains(&scope)
1915    }
1916
1917    #[allow(missing_docs)]
1918    pub fn is_empty(&self) -> bool {
1919        self.0.is_empty()
1920    }
1921
1922    /// Whether this is [`Self::default`] (`top-level` alone).
1923    pub fn is_default(&self) -> bool {
1924        *self == Self::default()
1925    }
1926}
1927
1928impl std::fmt::Display for RerouteScopes {
1929    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1930        let mut scopes = self.0.iter();
1931        if let Some(first) = scopes.next() {
1932            write!(f, "{first}")?;
1933        }
1934        scopes.try_for_each(|scope| write!(f, ",{scope}"))
1935    }
1936}
1937
1938impl std::str::FromStr for RerouteScopes {
1939    type Err = ParseScopeError;
1940
1941    fn from_str(s: &str) -> Result<Self, Self::Err> {
1942        let scopes: BTreeSet<SwapScope> = s
1943            .split(',')
1944            .filter(|scope| !scope.trim().is_empty())
1945            .map(str::parse)
1946            .collect::<Result<_, _>>()?;
1947        if scopes.is_empty() {
1948            return Err(ParseScopeError::NoScope);
1949        }
1950        Ok(Self(scopes))
1951    }
1952}
1953
1954/// Rerouting historical swaps through the router: each admitted swap is rerouted and the
1955/// routed transaction is *simulated* just before the original executes — never
1956/// committed, so the replay is unaffected. Each simulation reads the state of the batch its
1957/// original belonged to; reroutes never observe one another.
1958///
1959/// Presence is the switch, which makes "a knob but no rerouting" unrepresentable rather than a
1960/// validation error.
1961///
1962/// Silent defaults: an empty object (`"reroute": {}`) reroutes Jupiter's swaps only, every pair,
1963/// through the router (`requote: true`), with no venue templates, no failed original swaps and no
1964/// atomic arbitrage.
1965#[serde_with::serde_as]
1966#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1967#[serde(rename_all = "camelCase")]
1968pub struct RerouteParams {
1969    /// Whose original swaps to reroute. Default: Jupiter's alone. This also limits rerouting
1970    /// directly to a venue: only swaps from these aggregators reach the templates.
1971    #[serde(default)]
1972    pub aggregators: RerouteAggregators,
1973    /// Where an admitted swap may have run to be rerouted. [`Self::aggregators`] names the
1974    /// router either way, so admitting Jupiter admits a Jupiter route a bot CPI'd once
1975    /// [`SwapScope::Nested`] is on.
1976    #[serde(default, skip_serializing_if = "RerouteScopes::is_default")]
1977    pub scopes: RerouteScopes,
1978    /// Restrict rerouting to the mint pairs of interest — a maker's own book. Absent: every
1979    /// detected swap on an admitted aggregator is rerouted.
1980    #[serde(default, skip_serializing_if = "Option::is_none")]
1981    pub filter: Option<RerouteFilter>,
1982    /// Also reroute swaps whose historical transaction failed, when the allowlist admits the
1983    /// failure as one rerouting can answer (a slippage rejection, or a failure after the swap
1984    /// already ran).
1985    ///
1986    /// Off by default. The original swap realised nothing for these, so nothing compares with
1987    /// it, and they are counted apart: `swaps_detected` and `swaps_rerouted` exclude them, and
1988    /// every row carries `original_failed`. `l1` in the name means the original (onchain) swap.
1989    #[serde(default)]
1990    pub detect_failed_l1_swaps: bool,
1991    /// Also reroute atomic arbitrage — swaps whose input and output mint are the same. Each cycle
1992    /// is quoted leg by leg and built back as one circular route. A cycle that can't be split into
1993    /// legs fails with a `cycle_*` category. Off by default: a transaction holding a cycle is then
1994    /// left out as filtered.
1995    #[serde(default)]
1996    pub circular_arbs: bool,
1997    /// Reroute detected swaps through the router.
1998    ///
1999    /// On by default. Turn it off to reroute only directly to a venue, with
2000    /// [`Self::venue_templates`]: the session then runs without the router, which a venue the
2001    /// router cannot route does not need.
2002    #[serde(default = "RerouteParams::default_requote")]
2003    pub requote: bool,
2004    /// Instruction templates to probe against the hops this session detects, alongside the
2005    /// re-quoting: each hop whose direction and mode a template names is instantiated through
2006    /// it, funded, simulated and scored against what the historical hop filled. Empty: no
2007    /// rerouting directly to a venue.
2008    ///
2009    /// The templates decide only how a hop is priced. [`Self::aggregators`] still decides which
2010    /// original swaps reach them, so a session that only reroutes directly to a venue must list
2011    /// every router whose hops it wants priced.
2012    ///
2013    /// `directFill` on the wire.
2014    #[serde(rename = "directFill", default, skip_serializing_if = "Vec::is_empty")]
2015    pub venue_templates: Vec<VenueTemplate>,
2016    /// Pools for the router to consider on top of the markets it already knows. Each must hold
2017    /// an account at the start of the range: a pool that exists nowhere onchain gets its
2018    /// accounts from an account override anchored at the first slot. Requires [`Self::requote`].
2019    #[serde_as(as = "BTreeSet<serde_with::DisplayFromStr>")]
2020    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
2021    pub extra_markets: BTreeSet<Address>,
2022    /// Price each swap as late in its quote slot as it could have been, instead of at the slot's
2023    /// start: after the slot's last transaction, or just before the swap's own batch when it
2024    /// lands in that slot.
2025    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2026    pub quote_late_in_slot: bool,
2027}
2028
2029/// Hand-written rather than derived: `requote` defaults to ON, and a derived `Default` would
2030/// give the opposite of what deserializing an empty object gives.
2031impl Default for RerouteParams {
2032    fn default() -> Self {
2033        Self {
2034            aggregators: RerouteAggregators::default(),
2035            scopes: RerouteScopes::default(),
2036            filter: None,
2037            detect_failed_l1_swaps: false,
2038            circular_arbs: false,
2039            requote: Self::default_requote(),
2040            venue_templates: Vec::new(),
2041            extra_markets: BTreeSet::new(),
2042            quote_late_in_slot: false,
2043        }
2044    }
2045}
2046
2047/// `<base>,<quote>` in base58 — the spelling a CLI flag or env var carries.
2048impl std::str::FromStr for MintPair {
2049    type Err = String;
2050
2051    fn from_str(s: &str) -> Result<Self, Self::Err> {
2052        let (base, quote) = s
2053            .split_once(',')
2054            .ok_or_else(|| format!("expected two comma-separated mints, got {s:?}"))?;
2055        Self::try_from([base.trim().to_owned(), quote.trim().to_owned()])
2056            .map_err(|error| error.to_string())
2057    }
2058}
2059
2060impl std::fmt::Display for MintPair {
2061    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2062        let (one, other) = self.mints();
2063        write!(f, "{one},{other}")
2064    }
2065}
2066
2067impl RerouteParams {
2068    const fn default_requote() -> bool {
2069        true
2070    }
2071
2072    /// Whether this block asks for anything at all — a session with neither re-quoting nor a venue
2073    /// template has a reroute section that does nothing.
2074    pub const fn is_noop(&self) -> bool {
2075        !self.requote && self.venue_templates.is_empty()
2076    }
2077}
2078
2079/// Parameters required to start a new session: the `params` of `createBacktestSession`, or the
2080/// `request` of a [`CreateBacktestSessionRequestV1`]. Fields are camelCase on the wire.
2081///
2082/// Build one with [`CreateSessionParams::builder`]; only `start_slot` and `end_slot` are
2083/// required. List the ranges you can replay with `GET /available-ranges` ([`AvailableRange`]).
2084#[serde_with::serde_as]
2085#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
2086#[serde(rename_all = "camelCase")]
2087pub struct CreateSessionParams {
2088    /// First slot (inclusive) to replay. A single session must start exactly at an available
2089    /// range's `bundle_start_slot`. A parallel run may start inside a range; its first session
2090    /// then starts at that range's `bundle_start_slot`.
2091    pub start_slot: u64,
2092    /// Last slot (inclusive) to replay, at most the range's `max_bundle_end_slot`.
2093    pub end_slot: u64,
2094    /// Send a [`SessionSummary`] with `completed`. Default `false`: `completed` carries none.
2095    #[serde(default)]
2096    #[builder(default)]
2097    pub send_summary: bool,
2098    /// Reroute historical swaps. Absent: plain replay.
2099    #[serde(default, skip_serializing_if = "Option::is_none")]
2100    pub reroute: Option<RerouteParams>,
2101    /// Seconds to keep retrying while the server has no capacity for a new session, before
2102    /// failing the create. Unset or 0: fail at once when the server is busy.
2103    #[serde(default)]
2104    pub capacity_wait_timeout_secs: Option<u16>,
2105    /// Seconds the session waits for you to reattach after the session control channel drops.
2106    /// Unset: 30 (900 for a parallel run). 0: the session ends with the connection and responses
2107    /// carry no sequence number; otherwise they are wrapped in a [`SequencedResponse`]. Clamped to
2108    /// [`MAX_DISCONNECT_TIMEOUT_SECS`] (900 seconds).
2109    #[serde(default)]
2110    pub disconnect_timeout_secs: Option<u16>,
2111    /// Extra compute units to add to each transaction's `SetComputeUnitLimit` budget.
2112    /// Useful when replaying with an account override whose program uses more CU than
2113    /// the original, causing otherwise-healthy transactions to run out of budget.
2114    /// Only applied when a `SetComputeUnitLimit` instruction is already present.
2115    #[serde(default)]
2116    pub extra_compute_units: Option<u32>,
2117    /// Events of interest the session should watch for. When an upcoming
2118    /// batch matches any filter, the server emits
2119    /// [`BacktestResponse::DiscoveryBatch`] (and its session-event twins)
2120    /// ahead of execution so the client can follow up with
2121    /// [`BacktestRequest::ContinueTo`] to pause before the batch. Empty: no
2122    /// `discoveryBatch` events.
2123    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2124    #[builder(default)]
2125    pub discoveries: Vec<DiscoveryFilter>,
2126    /// Transactions the server runs automatically during the backtest, with
2127    /// results streamed over `actionSubscribe`.
2128    ///
2129    /// Compressed as a whole rather than per action: a per-slot schedule repeats
2130    /// near-identical account bytes thousands of times, and that redundancy is
2131    /// only visible across actions. Compressing each action alone leaves a
2132    /// 10k-slot schedule near the WebSocket message limit; compressing the
2133    /// vector takes the same schedule from ~28 MiB to ~1 MiB.
2134    #[serde(default, with = "compressed", skip_serializing_if = "Vec::is_empty")]
2135    #[builder(default)]
2136    pub actions: Vec<ScheduledAction>,
2137    /// Replay recorded account state for this range instead of executing its transactions,
2138    /// which is faster. Needs an account-state bundle for the range ([`BundleKind::AccountState`]).
2139    /// Nothing executes, so sending transactions, `kind: send` actions and transaction lookups
2140    /// are rejected; simulations still work.
2141    #[serde(default)]
2142    #[builder(default)]
2143    pub replay_account_state: bool,
2144    /// Markets to probe through the router as the session runs, streamed over
2145    /// `diagnosticSubscribe`.
2146    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2147    #[builder(default)]
2148    pub diagnostic_probes: Vec<DiagnosticProbeParams>,
2149}
2150
2151/// What account state replay cannot serve, worded once. Client, server and
2152/// session all reject through here, so a user meets the same explanation
2153/// wherever the request is stopped.
2154#[doc(hidden)]
2155pub mod replay_support {
2156    use super::{ActionKind, CreateSessionParams};
2157
2158    /// `getTransaction`/`getSignatureStatuses`: nothing executed, so nothing is found.
2159    pub const NO_TRANSACTIONS: &str =
2160        "Create the session without replayAccountState to execute and persist transactions.";
2161
2162    pub const SEND_TRANSACTION: &str = "Use simulateTransaction to run it against the replayed state, or create the session \
2163         without replayAccountState.";
2164
2165    pub const SEND_ACTION: &str = "Use kind: simulate, which runs against the replayed state without committing, post state \
2166         directly with an action carrying accountOverrides and no transactions, or create the \
2167         session without replayAccountState.";
2168
2169    /// States the operation, why replay cannot serve it, then the way forward.
2170    pub fn unsupported(operation: &str, remedy: &str) -> String {
2171        format!(
2172            "{operation} is not supported while account state replay is enabled: replay \
2173             reconstructs account state from the recorded delta bundle instead of executing \
2174             transactions, so this session never executes or persists any. {remedy}"
2175        )
2176    }
2177
2178    /// The one rule decidable from the request alone, so it can be caught before
2179    /// a session — or a runtime to host it — is ever created.
2180    pub fn send_action_conflict(params: &CreateSessionParams) -> Option<String> {
2181        (params.replay_account_state
2182            && params
2183                .actions
2184                .iter()
2185                .any(|action| action.kind == ActionKind::Send))
2186        .then(|| unsupported("A scheduled action with kind: send", SEND_ACTION))
2187    }
2188}
2189
2190impl CreateSessionParams {
2191    /// Whether a session needs a router sidecar (reroute quotes through it).
2192    /// Only re-quoting, or a template re-quoted through the router, needs the router; a session
2193    /// that only reroutes directly to a venue prices without it.
2194    #[doc(hidden)]
2195    pub fn requires_sidecar(&self) -> bool {
2196        self.reroute.as_ref().is_some_and(|reroute| {
2197            reroute.requote
2198                || reroute
2199                    .venue_templates
2200                    .iter()
2201                    .any(|template| template.resolve == Some(TemplateResolver::Requote))
2202        }) || !self.diagnostic_probes.is_empty()
2203            || self.actions.iter().any(ScheduledAction::asks_router)
2204    }
2205
2206    /// Whether the sidecar has to start the router with `--enable-diagnostic`. A rerouting session
2207    /// asks for the same endpoint through an operator variable the sidecar inherits; probes are a
2208    /// session parameter, so they have to ask through the launch spec.
2209    pub fn requires_diagnostic_endpoint(&self) -> bool {
2210        !self.diagnostic_probes.is_empty()
2211    }
2212
2213    /// Checks every [`Self::diagnostic_probes`] entry, as the server does.
2214    pub fn validate_diagnostic_probes(&self) -> Result<(), DiagnosticProbeError> {
2215        self.diagnostic_probes
2216            .iter()
2217            .try_for_each(DiagnosticProbeParams::validate)
2218    }
2219
2220    /// Checks every action's resolver; see [`validate_resolvers`].
2221    pub fn validate_action_resolvers(&self) -> Result<(), ActionResolveError> {
2222        validate_resolvers(&self.actions)
2223    }
2224
2225    /// Whether the session should warm its account universe before replaying.
2226    #[doc(hidden)]
2227    pub fn warms_account_universe(&self) -> bool {
2228        self.requires_sidecar()
2229            || self
2230                .reroute
2231                .as_ref()
2232                .is_some_and(|reroute| !reroute.venue_templates.is_empty())
2233    }
2234
2235    /// Whether the session reroutes swaps, that is whether [`Self::reroute`] is set.
2236    pub fn reroute_order_flow(&self) -> bool {
2237        self.reroute.is_some()
2238    }
2239
2240    /// The Override actions in [`Self::actions`], compiled into the slot-keyed schedule the
2241    /// reroute layer consumes. Same-slot actions merge account-wise, later wins.
2242    #[doc(hidden)]
2243    pub fn override_schedule(&self) -> Result<OverrideSchedule, String> {
2244        decode_override_actions(&self.actions)
2245    }
2246
2247    /// The mint pairs rerouting is restricted to, if the session named any.
2248    pub fn reroute_filter(&self) -> Option<&RerouteFilter> {
2249        self.reroute.as_ref()?.filter.as_ref()
2250    }
2251}
2252
2253/// What counts as a "non-benign" divergence for the session fail-fast
2254/// behaviour.
2255#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
2256#[serde(rename_all = "kebab-case")]
2257pub enum FailFastDivergenceKind {
2258    /// Any divergence other than a benign log diff (the full `is_divergent()` set:
2259    /// log mismatch, error mismatch, balance-diff mismatch).
2260    #[default]
2261    AnyNonBenign,
2262    /// Only divergences on transactions that touch an account currently watched by an
2263    /// account-diff subscription (subscribed directly, or owned by a subscribed program).
2264    Tracked,
2265}
2266
2267impl FailFastDivergenceKind {
2268    /// Stable string form used for CLI/env-var serialization. Matches the serde
2269    /// `kebab-case` representation.
2270    pub fn as_str(self) -> &'static str {
2271        match self {
2272            Self::AnyNonBenign => "any-non-benign",
2273            Self::Tracked => "tracked",
2274        }
2275    }
2276
2277    /// Inverse of [`Self::as_str`]; returns `None` for an unrecognized value.
2278    pub fn from_str_opt(value: &str) -> Option<Self> {
2279        match value {
2280            "any-non-benign" => Some(Self::AnyNonBenign),
2281            "tracked" => Some(Self::Tracked),
2282            _ => None,
2283        }
2284    }
2285}
2286
2287/// Account state modifications to apply.
2288#[serde_with::serde_as]
2289#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
2290pub struct AccountModifications(
2291    #[serde_as(as = "BTreeMap<serde_with::DisplayFromStr, _>")]
2292    #[serde(default)]
2293    pub BTreeMap<Address, AccountData>,
2294);
2295
2296impl From<BTreeMap<Address, AccountData>> for AccountModifications {
2297    fn from(value: BTreeMap<Address, AccountData>) -> Self {
2298        Self(value)
2299    }
2300}
2301
2302impl AccountModifications {
2303    #[allow(missing_docs)]
2304    pub fn is_empty(&self) -> bool {
2305        self.0.is_empty()
2306    }
2307}
2308
2309/// The `params` of `continue`: execute the next blocks, after your own transactions and account
2310/// overrides. Every field has a default, so `{}` advances one block.
2311///
2312/// Before the first block, the session runs `transactions` in order and commits them, then
2313/// writes `modify_account_states`. A failed user transaction does not produce an `error`
2314/// response.
2315#[serde_with::serde_as]
2316#[derive(Debug, Clone, Serialize, Deserialize)]
2317#[serde(rename_all = "camelCase")]
2318pub struct ContinueParams {
2319    #[serde(default = "ContinueParams::default_advance_count")]
2320    /// Wire name `advanceCount`: blocks to execute before the session waits again. Default 1.
2321    /// Counts blocks, not slots: a skipped slot has no block and is not counted.
2322    pub advance_count: u64,
2323    #[serde(default)]
2324    /// User transactions to execute before advancing, each the base64 of a transaction's
2325    /// standard wire bytes. Encode each with `simulator_client::encode_transaction`. Signatures
2326    /// and the recent blockhash are not checked, as for a [`ScheduledAction`]. Rejected
2327    /// in a session created with `replay_account_state`.
2328    pub transactions: Vec<String>,
2329    #[serde(default)]
2330    /// Wire name `modifyAccountStates`: account overrides, written after the user transactions
2331    /// and before the first block.
2332    pub modify_account_states: AccountModifications,
2333}
2334
2335impl Default for ContinueParams {
2336    fn default() -> Self {
2337        Self {
2338            advance_count: Self::default_advance_count(),
2339            transactions: Vec::new(),
2340            modify_account_states: AccountModifications(BTreeMap::new()),
2341        }
2342    }
2343}
2344
2345impl ContinueParams {
2346    /// The `advance_count` an absent field means: 1.
2347    pub fn default_advance_count() -> u64 {
2348        1
2349    }
2350}
2351
2352/// Payload emitted when a session halts at a caller-specified point.
2353/// `batch_index` is `None` for block-boundary pauses and `Some(n)` when the
2354/// session stopped *before* batch `n` within `slot` (no transaction from
2355/// batch `n` has been applied). While paused, RPC reads against the session
2356/// observe partial state up through batch `n - 1`. A `readyForContinue` always follows: answer
2357/// that, not this.
2358#[derive(Debug, Clone, Serialize, Deserialize)]
2359#[serde(rename_all = "camelCase")]
2360pub struct PausedEvent {
2361    #[allow(missing_docs)]
2362    pub slot: u64,
2363    /// Wire name `batchIndex`, absent at a block boundary: the batch the session paused
2364    /// before.
2365    #[serde(default, skip_serializing_if = "Option::is_none")]
2366    pub batch_index: Option<u32>,
2367}
2368
2369/// Payload emitted when the session has *discovered* an upcoming batch that
2370/// matches one or more registered [`DiscoveryFilter`]s from session creation
2371/// (for example, a batch containing a transaction that invokes a program of
2372/// interest). The `(slot, batch_index)` pair can be fed directly to
2373/// [`BacktestRequest::ContinueTo`] to pause immediately before the batch
2374/// executes. After each `Continue` / `ContinueTo`, the session emits the
2375/// next `DiscoveryBatchEvent` ahead of the next matching batch, enabling a
2376/// reactive "pause on every discovery" driver loop.
2377///
2378/// ```no_run
2379/// use simulator_api::{BacktestRequest, BacktestResponse, ContinueToParams};
2380///
2381/// /// On a discovery, inspect the matching transactions and pause just before their batch.
2382/// fn on_response(
2383///     response: &BacktestResponse,
2384/// ) -> Result<Option<BacktestRequest>, Box<dyn std::error::Error>> {
2385///     let BacktestResponse::DiscoveryBatch(event) = response else {
2386///         return Ok(None);
2387///     };
2388///     for (encoded, index) in event.transactions.iter().zip(&event.transaction_indices) {
2389///         // Raw wincode bytes; `simulator_client::decode_transaction(encoded)` parses them.
2390///         let bytes = encoded.decode()?;
2391///         println!("slot {} transaction {index}: {} bytes", event.slot, bytes.len());
2392///     }
2393///     Ok(Some(BacktestRequest::ContinueTo(ContinueToParams {
2394///         slot: event.slot,
2395///         batch_index: Some(event.batch_index),
2396///     })))
2397/// }
2398/// ```
2399#[serde_with::serde_as]
2400#[derive(Debug, Clone, Serialize, Deserialize)]
2401#[serde(rename_all = "camelCase")]
2402pub struct DiscoveryBatchEvent {
2403    /// The slot the matching batch is in.
2404    pub slot: u64,
2405    /// Wire name `batchIndex`: the matching batch's index within `slot`.
2406    pub batch_index: u32,
2407    /// Filters that matched this batch (always non-empty).
2408    pub matched: Vec<DiscoveryFilter>,
2409    /// Encoded transactions in this batch that triggered the match. Decode each
2410    /// with `simulator_client::decode_transaction` (base64 wincode of `VersionedTransaction`).
2411    pub transactions: Vec<EncodedBinary>,
2412    /// Each of `transactions`' index in its slot's block, the index Solana reports for it. Empty
2413    /// from a session that predates it.
2414    #[serde(default)]
2415    pub transaction_indices: Vec<u32>,
2416}
2417
2418/// The `params` of `continueTo`: execute up to a point, then pause there.
2419///
2420/// The session executes through `slot`, or with `batch_index`, up to just before that batch of
2421/// it. It then sends `paused` ([`PausedEvent`]) and `readyForContinue`; answer only the
2422/// `readyForContinue`.
2423///
2424/// - `slot` must be after the last executed slot. Otherwise the server sends an
2425///   [`BacktestError::InvalidRequest`] error and the session stays where it is.
2426/// - `slot` must have a block. A skipped slot has none, and the session does not stop at it: it
2427///   runs on to the end of the range.
2428/// - To run transactions just before slot `n`, pause at `n - 1` and send them with the next
2429///   `continue`, or schedule a `beforeSlot` [`ScheduledAction`] of kind [`ActionKind::Send`].
2430#[derive(Debug, Clone, Serialize, Deserialize)]
2431#[serde(rename_all = "camelCase")]
2432pub struct ContinueToParams {
2433    /// The slot to pause in, or at the end of when `batch_index` is `None`.
2434    pub slot: u64,
2435    /// Batch within the target slot at which to pause, **exclusive** — the
2436    /// session halts immediately *before* batch `n` executes, so no
2437    /// transaction in that batch has been applied yet. `None` runs the
2438    /// whole slot, pausing at the block boundary. While paused, RPC reads
2439    /// observe partial state up through batch `n - 1`.
2440    #[serde(default)]
2441    pub batch_index: Option<u32>,
2442}
2443
2444/// Supported binary encodings for account/transaction payloads.
2445#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
2446#[serde(rename_all = "lowercase")]
2447pub enum BinaryEncoding {
2448    /// `base64`: standard alphabet, padded.
2449    Base64,
2450}
2451
2452impl BinaryEncoding {
2453    #[allow(missing_docs)]
2454    pub fn encode(self, bytes: &[u8]) -> String {
2455        match self {
2456            Self::Base64 => BASE64.encode(bytes),
2457        }
2458    }
2459
2460    #[allow(missing_docs)]
2461    pub fn decode(self, data: &str) -> Result<Vec<u8>, Base64DecodeError> {
2462        match self {
2463            Self::Base64 => BASE64.decode(data),
2464        }
2465    }
2466}
2467
2468/// A blob paired with the encoding needed to decode it.
2469#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
2470#[serde(rename_all = "camelCase")]
2471pub struct EncodedBinary {
2472    /// Encoded payload.
2473    pub data: String,
2474    /// Encoding scheme used for the payload.
2475    pub encoding: BinaryEncoding,
2476}
2477
2478impl EncodedBinary {
2479    /// Wraps already-encoded `data`.
2480    pub fn new(data: String, encoding: BinaryEncoding) -> Self {
2481        Self { data, encoding }
2482    }
2483
2484    #[allow(missing_docs)]
2485    pub fn from_bytes(bytes: &[u8], encoding: BinaryEncoding) -> Self {
2486        Self {
2487            data: encoding.encode(bytes),
2488            encoding,
2489        }
2490    }
2491
2492    #[allow(missing_docs)]
2493    pub fn decode(&self) -> Result<Vec<u8>, Base64DecodeError> {
2494        self.encoding.decode(&self.data)
2495    }
2496}
2497
2498/// An account's full state, used as an account override.
2499///
2500/// On the wire: `{"data": {"data": "<base64>", "encoding": "base64"}, "executable": false,
2501/// "lamports": 1000000, "owner": "<base58>", "space": 0}`.
2502///
2503/// - The override replaces the whole account. To change a token balance, build the token
2504///   account's bytes with [`token`].
2505/// - `rent_epoch` is not carried; the session sets it to 0.
2506/// - Scheduled-action, depth and `simulateTransaction` overrides reject an executable account or
2507///   one owned by a program loader: a program cannot be overridden this way.
2508#[serde_with::serde_as]
2509#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
2510#[serde(rename_all = "camelCase")]
2511pub struct AccountData {
2512    /// Account data bytes and encoding.
2513    pub data: EncodedBinary,
2514    /// Whether the account is executable.
2515    pub executable: bool,
2516    /// Balance in lamports (1 SOL = 1,000,000,000 lamports).
2517    pub lamports: u64,
2518    #[serde_as(as = "serde_with::DisplayFromStr")]
2519    /// The owning program, base58.
2520    pub owner: Address,
2521    /// The data length in bytes. Set it to the decoded length of `data`: the account's size
2522    /// comes from `data`, not from this field.
2523    pub space: u64,
2524}
2525
2526impl AccountData {
2527    /// The account these fields describe, with `rent_epoch` 0. Fails if `data` does not
2528    /// decode.
2529    pub fn to_account(&self) -> Result<solana_account::Account, Base64DecodeError> {
2530        Ok(solana_account::Account {
2531            data: self.data.decode()?,
2532            lamports: self.lamports,
2533            owner: self.owner,
2534            executable: self.executable,
2535            rent_epoch: 0,
2536        })
2537    }
2538
2539    /// A system-owned account with no data holding `lamports`. At `0` the account does not exist.
2540    pub fn system_account(lamports: u64) -> Self {
2541        Self {
2542            data: EncodedBinary::new(String::new(), BinaryEncoding::Base64),
2543            executable: false,
2544            lamports,
2545            owner: solana_sdk_ids::system_program::ID,
2546            space: 0,
2547        }
2548    }
2549}
2550
2551/// The wire form of `account`: base64 data, `space = data.len()`. The inverse of
2552/// [`AccountData::to_account`]; `rent_epoch` is dropped because the wire does not carry it.
2553impl From<&solana_account::Account> for AccountData {
2554    fn from(account: &solana_account::Account) -> Self {
2555        Self {
2556            data: EncodedBinary::from_bytes(&account.data, BinaryEncoding::Base64),
2557            executable: account.executable,
2558            lamports: account.lamports,
2559            owner: account.owner,
2560            space: account.data.len() as u64,
2561        }
2562    }
2563}
2564
2565/// A response the server sends on the session control channel.
2566///
2567/// Serialized as `{"method": "<variantName>", "params": …}`; a variant without data has no
2568/// `params`. Fields declared on a variant itself are snake_case on the wire. Once a session runs,
2569/// its responses arrive wrapped in a [`SequencedResponse`] unless `disconnectTimeoutSecs` is 0.
2570#[derive(Debug, Clone, Serialize, Deserialize)]
2571#[serde(tag = "method", content = "params", rename_all = "camelCase")]
2572#[allow(missing_docs)]
2573pub enum BacktestResponse {
2574    /// `sessionCreated`: the session exists. For a parallel run, sent once per session.
2575    SessionCreated {
2576        /// The session's ID; keep it to reattach.
2577        session_id: SessionId,
2578        /// The session's RPC endpoint: a path on the server's host, `/backtest/<session_id>`.
2579        /// Prefix it with `https://<host>`.
2580        rpc_endpoint: String,
2581        /// The server's ID for the machine running the session. Quote it when reporting a
2582        /// problem.
2583        #[serde(default, skip_serializing_if = "Option::is_none")]
2584        task_id: Option<String>,
2585        /// The session's name, or the parallel run's for a session in one.
2586        #[serde(default, skip_serializing_if = "Option::is_none")]
2587        session_name: Option<String>,
2588    },
2589    /// `sessionAttached`: the reply to [`BacktestRequest::AttachBacktestSession`], with the
2590    /// same fields as [`Self::SessionCreated`]. The missed responses follow.
2591    SessionAttached {
2592        /// As in [`Self::SessionCreated`].
2593        session_id: SessionId,
2594        /// As in [`Self::SessionCreated`].
2595        rpc_endpoint: String,
2596        /// As in [`Self::SessionCreated`].
2597        #[serde(default, skip_serializing_if = "Option::is_none")]
2598        task_id: Option<String>,
2599        /// As in [`Self::SessionCreated`].
2600        #[serde(default, skip_serializing_if = "Option::is_none")]
2601        session_name: Option<String>,
2602    },
2603    /// `sessionsCreatedV2`: every session of a parallel run exists. The lists are parallel:
2604    /// entry `i` of each describes the same session.
2605    SessionsCreatedV2 {
2606        /// The parallel run's ID; keep it to reattach.
2607        control_session_id: ControlSessionId,
2608        /// The parallel run's name.
2609        #[serde(default, skip_serializing_if = "Option::is_none")]
2610        control_session_name: Option<String>,
2611        /// One per session.
2612        session_ids: Vec<SessionId>,
2613        /// As `task_id` in [`Self::SessionCreated`], per session.
2614        #[serde(default)]
2615        task_ids: Vec<Option<String>>,
2616        /// Per-session start/end slots, parallel to `session_ids`. The
2617        /// server's split is authoritative (a mid-bundle request anchors to the
2618        /// covering bundle), so the client binds each session to its range
2619        /// from here rather than re-deriving the split locally.
2620        #[serde(default)]
2621        start_slots: Vec<u64>,
2622        /// Each session's last slot, parallel to `session_ids`.
2623        #[serde(default)]
2624        end_slots: Vec<u64>,
2625    },
2626    /// `parallelSessionAttachedV2`: the reply to
2627    /// [`BacktestRequest::AttachParallelControlSessionV2`]. Each session's missed events follow.
2628    ParallelSessionAttachedV2 {
2629        /// The parallel run reattached to.
2630        control_session_id: ControlSessionId,
2631        session_ids: Vec<SessionId>,
2632        /// As in [`Self::SessionsCreatedV2`].
2633        #[serde(default)]
2634        task_ids: Vec<Option<String>>,
2635    },
2636    /// `readyForContinue`: the session is waiting for your next `continue` or `continueTo`.
2637    /// Read and change state through the session's RPC endpoint now.
2638    ReadyForContinue,
2639    /// `slotNotification`: the slot that just executed, as a bare number in `params`.
2640    SlotNotification(u64),
2641    /// `paused`: the session stopped where a `continueTo` asked.
2642    Paused(PausedEvent),
2643    /// `discoveryBatch`: an upcoming batch matches a [`CreateSessionParams::discoveries`]
2644    /// filter.
2645    DiscoveryBatch(DiscoveryBatchEvent),
2646    /// `error`: something failed. Check [`BacktestError::is_terminal`] to see whether the
2647    /// session is over.
2648    Error(BacktestError),
2649    /// `success`: acknowledges a request with nothing else to return, such as a single session's
2650    /// `closeBacktestSession` or `resumeAttachedSession`. A parallel run's close requests get no
2651    /// `success`.
2652    Success,
2653    /// `completed`: the session replayed its last slot. Terminal.
2654    Completed {
2655        /// Session summary with transaction statistics.
2656        /// `None` unless the session was created with `send_summary`.
2657        #[serde(skip_serializing_if = "Option::is_none")]
2658        summary: Option<SessionSummary>,
2659    },
2660    /// `status`: a progress update, while the session starts and during each `continue`.
2661    Status { status: BacktestStatus },
2662    /// `sessionEventV2`: an event from one session of a parallel run.
2663    SessionEventV2 {
2664        session_id: SessionId,
2665        /// The session's own sequence number for this event. Keep the last one per session to
2666        /// reattach.
2667        seq_id: u64,
2668        event: SessionEventKind,
2669    },
2670    /// The reply to [`BacktestRequest::CreateBacktestSessionV2`]: connect to the endpoint with the token.
2671    SessionGranted(session_endpoint::SessionGrant),
2672    /// `sessionsGranted`: the reply to a parallel [`BacktestRequest::CreateBacktestSessionV2`].
2673    SessionsGranted(session_endpoint::ParallelGrant),
2674}
2675
2676impl BacktestResponse {
2677    #[allow(missing_docs)]
2678    pub fn is_completed(&self) -> bool {
2679        matches!(self, BacktestResponse::Completed { .. })
2680    }
2681
2682    /// Whether the session is over: `completed`, or an `error` whose
2683    /// [`BacktestError::is_terminal`] is true.
2684    pub fn is_terminal(&self) -> bool {
2685        match self {
2686            BacktestResponse::Completed { .. } => true,
2687            BacktestResponse::Error(e) => e.is_terminal(),
2688            _ => false,
2689        }
2690    }
2691}
2692
2693impl From<BacktestStatus> for BacktestResponse {
2694    fn from(status: BacktestStatus) -> Self {
2695        Self::Status { status }
2696    }
2697}
2698
2699impl From<String> for BacktestResponse {
2700    fn from(message: String) -> Self {
2701        BacktestError::Internal { error: message }.into()
2702    }
2703}
2704
2705impl From<&str> for BacktestResponse {
2706    fn from(message: &str) -> Self {
2707        BacktestError::Internal {
2708            error: message.to_string(),
2709        }
2710        .into()
2711    }
2712}
2713
2714/// What happened in one session of a parallel run: the `event` of `sessionEventV2`. Each
2715/// variant means what the [`BacktestResponse`] variant of the same name means, for that session
2716/// alone.
2717#[derive(Debug, Clone, Serialize, Deserialize)]
2718#[serde(tag = "method", content = "params", rename_all = "camelCase")]
2719#[allow(missing_docs)]
2720pub enum SessionEventKind {
2721    /// As [`BacktestResponse::ReadyForContinue`].
2722    ReadyForContinue,
2723    /// As [`BacktestResponse::SlotNotification`].
2724    SlotNotification(u64),
2725    /// As [`BacktestResponse::Paused`].
2726    Paused(PausedEvent),
2727    /// As [`BacktestResponse::DiscoveryBatch`].
2728    DiscoveryBatch(DiscoveryBatchEvent),
2729    /// As [`BacktestResponse::Error`].
2730    Error(BacktestError),
2731    /// As [`BacktestResponse::Success`].
2732    Success,
2733    /// As [`BacktestResponse::Completed`]: this session is done; the others may still run.
2734    Completed {
2735        /// As in [`BacktestResponse::Completed`].
2736        #[serde(skip_serializing_if = "Option::is_none")]
2737        summary: Option<SessionSummary>,
2738    },
2739    /// As [`BacktestResponse::Status`].
2740    Status { status: BacktestStatus },
2741}
2742
2743impl SessionEventKind {
2744    /// Whether this session is over; see [`BacktestResponse::is_terminal`].
2745    pub fn is_terminal(&self) -> bool {
2746        match self {
2747            Self::Completed { .. } => true,
2748            Self::Error(e) => e.is_terminal(),
2749            _ => false,
2750        }
2751    }
2752}
2753
2754/// Wire format wrapper for responses sent over the session control channel.
2755/// Sessions whose `disconnect_timeout_secs` is not 0 (unset defaults to 30) use this to track
2756/// client position.
2757#[derive(Debug, Clone, Serialize, Deserialize)]
2758#[serde(rename_all = "camelCase")]
2759pub struct SequencedResponse {
2760    /// Wire name `seqId`: the sequence number, increasing with each response. Keep the last one
2761    /// you received; reattaching replays everything after it.
2762    pub seq_id: u64,
2763    /// The response, flattened beside `seqId`.
2764    #[serde(flatten)]
2765    pub response: BacktestResponse,
2766}
2767
2768/// Progress reported in a `status` response, as a camelCase string such as
2769/// `"startingRuntime"`. Informational: you need not act on any of them.
2770///
2771/// A `continue` reports, in order: `decodedTransactions` and `executedUserTransactions` (only
2772/// when it carries user transactions), `appliedAccountModifications`,
2773/// `readyToExecuteUserTransactions`, then `executingBlockTransactions` and
2774/// `executedBlockTransactions` for each block.
2775#[derive(Debug, Clone, Serialize, Deserialize)]
2776#[serde(rename_all = "camelCase")]
2777pub enum BacktestStatus {
2778    /// Runtime startup is in progress. Sent when the create is accepted, then about every 10
2779    /// seconds until the session is ready.
2780    StartingRuntime,
2781    /// The `continue`'s user transactions decoded.
2782    DecodedTransactions,
2783    /// The `continue`'s account overrides are written.
2784    AppliedAccountModifications,
2785    /// The `continue`'s inputs are applied; blocks run next.
2786    ReadyToExecuteUserTransactions,
2787    /// The `continue`'s user transactions ran.
2788    ExecutedUserTransactions,
2789    /// A block started executing.
2790    ExecutingBlockTransactions,
2791    /// A block finished executing.
2792    ExecutedBlockTransactions,
2793    /// Not sent by the current server.
2794    ProgramAccountsLoaded,
2795}
2796
2797impl std::fmt::Display for BacktestStatus {
2798    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2799        let s = match self {
2800            Self::StartingRuntime => "starting runtime",
2801            Self::DecodedTransactions => "decoded transactions",
2802            Self::AppliedAccountModifications => "applied account modifications",
2803            Self::ReadyToExecuteUserTransactions => "ready to execute user transactions",
2804            Self::ExecutedUserTransactions => "executed user transactions",
2805            Self::ExecutingBlockTransactions => "executing block transactions",
2806            Self::ExecutedBlockTransactions => "executed block transactions",
2807            Self::ProgramAccountsLoaded => "program accounts loaded",
2808        };
2809        f.write_str(s)
2810    }
2811}
2812
2813/// Summary of a session run with `reroute_order_flow`: how many detected swaps made it from
2814/// rerouting through simulation to a non-reverting execution, and — for a session carrying a
2815/// [`VenueTemplate`] list — how many hops each template priced. Per-swap
2816/// economics and latency land in the reroute tables, published to `dataset_uri` when set.
2817///
2818/// Fields are camelCase on the wire (`swapsDetected`), except the `venue_*` fields, which keep
2819/// their `directFill*` names (`directFillMatched`). Counts are of swaps unless a field says
2820/// otherwise; `*_bps_total` fields are sums in basis points (1 bps = 0.01%).
2821#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
2822#[serde(rename_all = "camelCase")]
2823pub struct RerouteStatsReport {
2824    /// Reroutable swaps detected in the replayed range, across the admitted aggregators.
2825    #[serde(default)]
2826    pub swaps_detected: u64,
2827    /// Detected swaps excluded before quoting — an unadmitted aggregator, an atomic arbitrage, a
2828    /// mint pair the filter does not name. Without it the gap between `swaps_detected` and
2829    /// `swaps_rerouted` reads as routing failures.
2830    #[serde(default)]
2831    pub swaps_filtered: u64,
2832    /// Swaps rerouted through the router and queued for simulation.
2833    #[serde(default)]
2834    pub swaps_rerouted: u64,
2835    /// Swaps whose routed transaction was simulated.
2836    #[serde(default)]
2837    pub swaps_simulated: u64,
2838    /// Simulated swaps whose routed transaction executed without reverting.
2839    #[serde(default)]
2840    pub swaps_succeeded: u64,
2841    /// Detected swaps the router could not route; nothing was simulated for them.
2842    #[serde(default)]
2843    pub requote_failures: u64,
2844    /// Computed override actions that failed and therefore contributed no state.
2845    #[serde(default)]
2846    pub override_setup_failures: u64,
2847    /// Blocks replayed unchanged because the router client was unavailable.
2848    #[serde(default)]
2849    pub metis_unavailable_blocks: u64,
2850    /// Quote attempts that could not be made because the router client was unavailable, summed
2851    /// over every swap left queued by each such block. Each one is retried on the next block,
2852    /// so this counts retries forced rather than swaps lost.
2853    #[serde(default)]
2854    pub quote_attempts_unavailable: u64,
2855    /// Hops a template matched, summed over [`Self::venue_template_reports`]. A hop two templates
2856    /// match counts twice. Zero when no template was configured.
2857    #[serde(rename = "directFillMatched", default)]
2858    pub venue_matched: u64,
2859    /// Probes by outcome, summed over the templates — `filled`, `reverted_*`, `unattributed`
2860    /// (ran clean, but the seeded account was gone or unreadable), `unsimulatable` (could not be
2861    /// compiled or run), `unresolved_*` (the template could not be brought up to the pass). Every
2862    /// matched hop lands in exactly one bucket.
2863    #[serde(rename = "directFillOutcomes", default)]
2864    pub venue_outcomes: BTreeMap<String, u64>,
2865    /// Probes scored against the hop they replace, summed over the templates.
2866    #[serde(rename = "directFillScored", default)]
2867    pub venue_scored: u64,
2868    /// Sum of each scored probe's change against its historical fill in basis points, over
2869    /// `venue_scored` — divide by that count for the mean. Positive always means the
2870    /// template beat the hop, whichever amount the mode fixed.
2871    #[serde(rename = "directFillBpsTotal", default)]
2872    pub venue_bps_total: i64,
2873    /// The same four counters per template, keyed by label. A template that never matched is
2874    /// present with zeros.
2875    #[serde(rename = "directFillTemplates", default)]
2876    pub venue_template_reports: BTreeMap<String, VenueTemplateReport>,
2877    /// Original swaps scored against their own historical fill at quote time.
2878    #[serde(default)]
2879    pub originals_scored: u64,
2880    /// Sum of `(quote time fill - historical fill) / historical fill` in basis points over
2881    /// `originals_scored` swaps — divide by that count for the mean.
2882    #[serde(default)]
2883    pub originals_bps_total: i64,
2884    /// Originals replayed at the position their replacements were priced at.
2885    #[serde(default)]
2886    pub originals_replayed: u64,
2887    /// `s3://` URI the reroute tables are published to at session end; `None` when they aren't.
2888    #[serde(default, skip_serializing_if = "Option::is_none")]
2889    pub dataset_uri: Option<String>,
2890}
2891
2892/// How long a session's published reroute tables stay in its owner's datasets.
2893pub const REROUTE_DATASET_RETENTION_DAYS: u32 = 30;
2894
2895/// One template's share of the venue probes; the flat `venue_*` counters on
2896/// [`RerouteStatsReport`] are the sums of these.
2897#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
2898#[serde(rename_all = "camelCase")]
2899pub struct VenueTemplateReport {
2900    /// Hops this template matched; see [`RerouteStatsReport::venue_matched`].
2901    pub matched: u64,
2902    /// This template's probes by outcome; see [`RerouteStatsReport::venue_outcomes`].
2903    pub outcomes: BTreeMap<String, u64>,
2904    /// This template's probes scored against the hop they replace.
2905    pub scored: u64,
2906    /// Wire name `bpsTotal`: the sum of this template's scored changes in basis points; divide
2907    /// by `scored` for the mean. Positive means the template beat the hop.
2908    pub bps_total: i64,
2909}
2910
2911/// Summary of transaction execution statistics for a completed session: how the replayed
2912/// transactions compare with what happened onchain. Sent with `completed` when the session was
2913/// created with `send_summary`. Fields are camelCase on the wire (`correctSimulation`).
2914///
2915/// - [`Self::total_transactions`] does not count `unsanitizable`.
2916/// - [`Self::has_deviations`] ignores `log_diff`, since log differences are usually benign.
2917#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2918#[serde(rename_all = "camelCase")]
2919pub struct SessionSummary {
2920    /// Number of simulations where simulator outcome matched onchain outcome
2921    /// (`true_success + true_failure`).
2922    pub correct_simulation: usize,
2923    /// Number of simulations where simulator outcome did not match onchain outcome
2924    /// (`false_success + false_failure`).
2925    pub incorrect_simulation: usize,
2926    /// Number of transactions that had execution errors in simulation.
2927    pub execution_errors: usize,
2928    /// Number of transactions with different balance diffs.
2929    pub balance_diff: usize,
2930    /// Number of transactions with different log diffs.
2931    pub log_diff: usize,
2932    /// Transactions skipped because they could not be sanitized (malformed message or
2933    /// unresolvable address lookup table).
2934    #[serde(default)]
2935    pub unsanitizable: usize,
2936    /// Aggregate reroute metrics, populated only for reroute-order-flow sessions. Boxed to
2937    /// keep `SessionSummary` small in the many response enums that carry it.
2938    #[serde(default, skip_serializing_if = "Option::is_none")]
2939    pub reroute_stats: Option<Box<RerouteStatsReport>>,
2940}
2941
2942impl SessionSummary {
2943    /// Returns true if there were any execution deviations (errors or mismatched results):
2944    /// `incorrect_simulation`, `execution_errors` or `balance_diff` above 0. `log_diff` does not
2945    /// count.
2946    pub fn has_deviations(&self) -> bool {
2947        self.incorrect_simulation > 0 || self.execution_errors > 0 || self.balance_diff > 0
2948    }
2949
2950    /// Total number of transactions processed: the sum of every count except
2951    /// `unsanitizable`.
2952    pub fn total_transactions(&self) -> usize {
2953        self.correct_simulation
2954            + self.incorrect_simulation
2955            + self.execution_errors
2956            + self.balance_diff
2957            + self.log_diff
2958    }
2959
2960    /// Renders the compact "N incorrect simulations, N execution errors, ..." deviation list
2961    /// shared by console reporters. `balance_label` / `log_label` let each caller keep its own
2962    /// historical wording for the trailing two counts (e.g. "balance diffs" vs
2963    /// "different balances").
2964    pub fn deviation_details(&self, balance_label: &str, log_label: &str) -> String {
2965        format!(
2966            "{} incorrect simulations, {} execution errors, {} {balance_label}, {} {log_label}",
2967            self.incorrect_simulation, self.execution_errors, self.balance_diff, self.log_diff,
2968        )
2969    }
2970}
2971
2972impl std::fmt::Display for SessionSummary {
2973    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2974        let total = self.total_transactions();
2975        write!(
2976            f,
2977            "Session summary: {total} transactions\n\
2978             \x20  - {} correct simulation\n\
2979             \x20  - {} incorrect simulation\n\
2980             \x20  - {} execution errors\n\
2981             \x20  - {} unsanitizable\n\
2982             \x20  - {} balance diffs\n\
2983             \x20  - {} log diffs",
2984            self.correct_simulation,
2985            self.incorrect_simulation,
2986            self.execution_errors,
2987            self.unsanitizable,
2988            self.balance_diff,
2989            self.log_diff,
2990        )
2991    }
2992}
2993
2994/// Error variants surfaced to backtest RPC clients: the `params` of an `error` response.
2995///
2996/// On the wire, a camelCase variant name with snake_case fields:
2997/// `{"method": "error", "params": {"bundleNotFound": {"start_slot": 1, "end_slot": 2}}}`. A
2998/// variant without fields is a bare string: `{"method": "error", "params": "noMoreBlocks"}`.
2999///
3000/// [`Self::is_terminal`] says whether a running session is over. An error that answers a create
3001/// or an attach ends that request whatever it says: no session was created or attached.
3002#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3003#[serde(rename_all = "camelCase")]
3004#[allow(missing_docs)]
3005pub enum BacktestError {
3006    /// A user transaction in a `continue` is not valid base64. Not terminal: none of that
3007    /// `continue` ran, so fix the transaction and send it again.
3008    InvalidTransactionEncoding {
3009        /// Its position in [`ContinueParams::transactions`].
3010        index: usize,
3011        error: String,
3012    },
3013    /// A user transaction in a `continue` is valid base64 but not a transaction's wire bytes.
3014    /// Not terminal: none of that `continue` ran. Encode with
3015    /// `simulator_client::encode_transaction`.
3016    InvalidTransactionFormat {
3017        /// Its position in [`ContinueParams::transactions`].
3018        index: usize,
3019        error: String,
3020    },
3021    /// An account override's `data` does not decode. Not terminal: the `continue`'s user
3022    /// transactions ran, but no override was written and no block executed.
3023    InvalidAccountEncoding {
3024        /// The account, base58.
3025        address: String,
3026        /// The encoding `data` claimed.
3027        encoding: BinaryEncoding,
3028        error: String,
3029    },
3030    /// Not sent by the current server.
3031    InvalidAccountOwner {
3032        /// The account, base58.
3033        address: String,
3034        error: String,
3035    },
3036    /// Not sent by the current server.
3037    InvalidAccountPubkey {
3038        /// The account, base58.
3039        address: String,
3040        error: String,
3041    },
3042    /// The session has no block left to execute. Terminal.
3043    NoMoreBlocks,
3044    /// The server has no bundle for the range. Terminal: pick a range from
3045    /// `GET /available-ranges`, or build one with `POST /build-bundle`.
3046    BundleNotFound {
3047        start_slot: u64,
3048        end_slot: u64,
3049    },
3050    /// The session could not start a slot. Terminal: report it with the session's `task_id`.
3051    AdvanceSlotFailed {
3052        slot: u64,
3053        error: String,
3054    },
3055    /// The session could not finish a slot. Terminal: report it with the session's `task_id`.
3056    FinalizeSlotFailed {
3057        slot: u64,
3058        error: String,
3059    },
3060    /// The request is malformed, not allowed in the session's current state, or asks for
3061    /// something the server cannot serve, such as a range that is not available. Not terminal
3062    /// for a running session; `error` says what to change.
3063    InvalidRequest {
3064        /// What is wrong, and usually how to fix it.
3065        error: String,
3066    },
3067    /// The server failed. Terminal: retry later, and report it if it persists.
3068    Internal {
3069        error: String,
3070    },
3071    /// Not sent by the current server.
3072    InvalidBlockhashFormat {
3073        slot: u64,
3074        error: String,
3075    },
3076    /// Not sent by the current server.
3077    InitializingSysvarsFailed {
3078        slot: u64,
3079        error: String,
3080    },
3081    /// The server could not load historical data the session needs, such as its starting state
3082    /// or an account. Not terminal by [`Self::is_terminal`], but during a create it fails the
3083    /// create: retry later.
3084    ClerkError {
3085        error: String,
3086    },
3087    /// An operation inside the session failed, such as reading an account. Not terminal: the
3088    /// session keeps running, and `simulator-client` only logs these.
3089    SimulationError {
3090        error: String,
3091    },
3092    /// The session named by an attach, `continueSessionV1`, `continueToSessionV1` or
3093    /// `closeSessionV1` does not exist or has ended. Not terminal.
3094    SessionNotFound {
3095        /// The ID you sent.
3096        session_id: String,
3097    },
3098    /// You tried to attach to a session created with a different API key. Not terminal: attach
3099    /// with the key that created it.
3100    SessionOwnerMismatch,
3101    /// The session is moving to another server, or another attach raced this one. Not terminal:
3102    /// retry the attach after a short backoff; a managed session does this for you. Also sent
3103    /// when attaching a session of a parallel run on its own: attach the parallel run with
3104    /// `attachParallelControlSessionV2` instead.
3105    SessionOwnershipBusy {
3106        /// Why the attach was refused.
3107        reason: String,
3108    },
3109    /// The requested range contains no produced blocks (every slot in it was
3110    /// skipped onchain), so there is nothing to execute. A user error: the
3111    /// session cannot start and the range must be adjusted. Terminal.
3112    NoProducedBlocksInRange {
3113        start_slot: u64,
3114        end_slot: u64,
3115    },
3116    /// Names are never reused, even after their session ends. Choose another name, or resend
3117    /// the original request with its `create_token` to reclaim this one.
3118    SessionNameTaken {
3119        /// The name you asked for.
3120        session_name: String,
3121    },
3122    ProgramdataNotDeployed {
3123        address: String,
3124    },
3125    /// The session stopped after `slot`, as its job asked, with what it measured through
3126    /// `slot` published. Terminal: the job relaunches it for the rest. Sent only to job sessions.
3127    Cut {
3128        slot: u64,
3129    },
3130}
3131
3132impl BacktestError {
3133    /// Whether a fresh session given the same request would refuse it too.
3134    pub fn is_refusal(&self) -> bool {
3135        match self {
3136            BacktestError::NoProducedBlocksInRange { .. }
3137            | BacktestError::ProgramdataNotDeployed { .. } => true,
3138            BacktestError::InvalidTransactionEncoding { .. }
3139            | BacktestError::InvalidTransactionFormat { .. }
3140            | BacktestError::InvalidAccountEncoding { .. }
3141            | BacktestError::InvalidAccountOwner { .. }
3142            | BacktestError::InvalidAccountPubkey { .. }
3143            | BacktestError::NoMoreBlocks
3144            | BacktestError::BundleNotFound { .. }
3145            | BacktestError::AdvanceSlotFailed { .. }
3146            | BacktestError::FinalizeSlotFailed { .. }
3147            | BacktestError::InvalidRequest { .. }
3148            | BacktestError::Internal { .. }
3149            | BacktestError::InvalidBlockhashFormat { .. }
3150            | BacktestError::InitializingSysvarsFailed { .. }
3151            | BacktestError::ClerkError { .. }
3152            | BacktestError::SimulationError { .. }
3153            | BacktestError::SessionNotFound { .. }
3154            | BacktestError::SessionOwnerMismatch
3155            | BacktestError::SessionOwnershipBusy { .. }
3156            | BacktestError::SessionNameTaken { .. }
3157            | BacktestError::Cut { .. } => false,
3158        }
3159    }
3160
3161    /// Errors the backtest cannot recover from mid-session — the single source
3162    /// of truth for terminal-error classification, shared by the response/event
3163    /// wrappers and the managed client.
3164    pub fn is_terminal(&self) -> bool {
3165        matches!(
3166            self,
3167            BacktestError::NoMoreBlocks
3168                | BacktestError::BundleNotFound { .. }
3169                | BacktestError::AdvanceSlotFailed { .. }
3170                | BacktestError::FinalizeSlotFailed { .. }
3171                | BacktestError::Internal { .. }
3172                | BacktestError::NoProducedBlocksInRange { .. }
3173                | BacktestError::ProgramdataNotDeployed { .. }
3174                | BacktestError::Cut { .. }
3175        )
3176    }
3177
3178    /// Whether the same request may succeed if you send it again later, unchanged.
3179    ///
3180    /// True for a server-side failure ([`Self::Internal`], which is also how a create reports
3181    /// insufficient capacity, and [`Self::ClerkError`]) and for [`Self::SessionOwnershipBusy`].
3182    /// Every other error names something to change first. A retryable error can still be
3183    /// terminal: then retry with a new session.
3184    pub fn is_retryable(&self) -> bool {
3185        matches!(
3186            self,
3187            BacktestError::Internal { .. }
3188                | BacktestError::ClerkError { .. }
3189                | BacktestError::SessionOwnershipBusy { .. }
3190        )
3191    }
3192}
3193
3194/// One contiguous range of slots you can replay: an entry of `GET /available-ranges`.
3195///
3196/// A single session must start at `bundle_start_slot` and end at or before
3197/// `max_bundle_end_slot`. Times are RFC 3339 UTC strings, such as `"2026-01-01T00:00:01Z"`.
3198#[derive(Debug, Clone, Default, Serialize, Deserialize)]
3199pub struct AvailableRange {
3200    /// The first slot of the range; a session's `start_slot`.
3201    pub bundle_start_slot: u64,
3202    /// When `bundle_start_slot` was produced, if known.
3203    pub bundle_start_slot_utc: Option<String>,
3204    /// The last slot a session starting here can reach.
3205    pub max_bundle_end_slot: Option<u64>,
3206    /// When `max_bundle_end_slot` was produced, if known.
3207    pub max_bundle_end_slot_utc: Option<String>,
3208    /// The range's length in slots, both ends included.
3209    pub max_bundle_size: Option<u64>,
3210    /// What the range can be used for. `None` from a server that predates the
3211    /// field, where every listed range is [`BundleKind::Blocks`].
3212    #[serde(default)]
3213    pub kind: Option<BundleKind>,
3214    /// Who the range is available to. `None` from a server that predates the
3215    /// field.
3216    #[serde(default)]
3217    pub scope: Option<RangeScope>,
3218}
3219
3220/// Who a listed range is available to.
3221#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3222#[serde(rename_all = "snake_case")]
3223pub enum RangeScope {
3224    /// Available to every caller.
3225    Global,
3226    /// Built for the calling API key, and listed only for that key.
3227    User,
3228}
3229
3230impl RangeScope {
3231    /// Stable string form matching the serde `snake_case` wire representation.
3232    pub fn as_str(self) -> &'static str {
3233        match self {
3234            Self::Global => "global",
3235            Self::User => "user",
3236        }
3237    }
3238}
3239
3240/// What a bundle build produces.
3241#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
3242#[serde(rename_all = "snake_case")]
3243pub enum BundleKind {
3244    /// The block bundle a session replays transactions from.
3245    #[default]
3246    Blocks,
3247    /// An account-state bundle covering exactly the requested range, which
3248    /// later sessions replay instead of executing transactions. Builds the
3249    /// block bundle it needs first.
3250    AccountState,
3251}
3252
3253/// Why a replayed range has to begin where a recording does. Shared so the
3254/// splitter's refusal and the service's single-session refusal cannot drift
3255/// apart.
3256pub const REPLAY_RANGE_ADVICE: &str = "replayed state is resolved by the recording that begins \
3257     where the request does, so request a range that begins where one was recorded and ends \
3258     within it";
3259
3260impl BundleKind {
3261    /// What a caller is short of, named for a coverage error.
3262    fn coverage_noun(self) -> &'static str {
3263        match self {
3264            Self::Blocks => "bundle range",
3265            Self::AccountState => "account-state bundle",
3266        }
3267    }
3268
3269    /// [`Self::coverage_noun`] pluralised, for a message about several.
3270    fn coverage_nouns(self) -> &'static str {
3271        match self {
3272            Self::Blocks => "bundle ranges",
3273            Self::AccountState => "account-state bundles",
3274        }
3275    }
3276
3277    /// Stable string form matching the serde `snake_case` wire representation.
3278    pub fn as_str(self) -> &'static str {
3279        match self {
3280            Self::Blocks => "blocks",
3281            Self::AccountState => "account_state",
3282        }
3283    }
3284
3285    /// Inverse of [`Self::as_str`]; returns `None` for an unrecognized value.
3286    pub fn from_str_opt(value: &str) -> Option<Self> {
3287        match value {
3288            "blocks" => Some(Self::Blocks),
3289            "account_state" => Some(Self::AccountState),
3290            _ => None,
3291        }
3292    }
3293}
3294
3295/// Spelled for the reader, not the wire: `blocks` shows as `transactions`.
3296/// Use [`BundleKind::as_str`] where the wire spelling is required.
3297impl fmt::Display for BundleKind {
3298    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3299        let label = match self {
3300            Self::Blocks => "transactions",
3301            Self::AccountState => "account_state",
3302        };
3303        f.pad(label)
3304    }
3305}
3306
3307/// Which side of a venue a depth job measures.
3308///
3309/// The two sources publish separate datasets over the same range, so this picks the dataset as
3310/// much as the measurement.
3311#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3312#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
3313#[serde(rename_all = "snake_case")]
3314pub enum DepthSource {
3315    /// What the venues' own onchain liquidity would have filled.
3316    #[default]
3317    Onchain,
3318    /// What the router would have quoted.
3319    Router,
3320}
3321
3322impl DepthSource {
3323    /// Stable string form matching the serde wire representation.
3324    pub const fn as_str(self) -> &'static str {
3325        match self {
3326            Self::Onchain => "onchain",
3327            Self::Router => "router",
3328        }
3329    }
3330
3331    /// Inverse of [`Self::as_str`]; returns `None` for an unrecognized value.
3332    pub fn from_str_opt(value: &str) -> Option<Self> {
3333        match value {
3334            "onchain" => Some(Self::Onchain),
3335            "router" => Some(Self::Router),
3336            _ => None,
3337        }
3338    }
3339
3340    /// A frozen identity for hashing, deliberately divorced from [`Self::as_str`].
3341    ///
3342    /// Job IDs are derived from it, so renaming what callers see must never move them, or a
3343    /// resubmit of the same measurement would trigger a second job they pay for again.
3344    #[doc(hidden)]
3345    pub const fn discriminant(self) -> u8 {
3346        match self {
3347            Self::Onchain => 0,
3348            Self::Router => 1,
3349        }
3350    }
3351}
3352
3353impl fmt::Display for DepthSource {
3354    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3355        f.write_str(self.as_str())
3356    }
3357}
3358
3359/// How often a depth job samples its source; each publishes its own dataset under the source.
3360#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3361#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
3362#[serde(rename_all = "snake_case")]
3363pub enum DepthGranularity {
3364    /// On a fixed one-slot grid (default).
3365    #[default]
3366    Slot,
3367    /// After each batch where the venue's program or an oracle update wrote an account a probe
3368    /// reads (`onchain` only).
3369    Oracle,
3370}
3371
3372impl DepthGranularity {
3373    /// Stable string form matching the serde wire representation.
3374    pub const fn as_str(self) -> &'static str {
3375        match self {
3376            Self::Slot => "slot",
3377            Self::Oracle => "oracle",
3378        }
3379    }
3380
3381    /// Whether this is [`Self::Slot`], the default.
3382    pub fn is_default(&self) -> bool {
3383        *self == Self::default()
3384    }
3385
3386    /// Frozen for job ID hashing, as [`DepthSource::discriminant`] is.
3387    #[doc(hidden)]
3388    pub const fn discriminant(self) -> u8 {
3389        match self {
3390            Self::Slot => 0,
3391            Self::Oracle => 1,
3392        }
3393    }
3394}
3395
3396impl fmt::Display for DepthGranularity {
3397    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3398        f.write_str(self.as_str())
3399    }
3400}
3401
3402/// A depth dataset: a source at a granularity it can be measured at.
3403#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
3404#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
3405#[serde(rename_all = "snake_case")]
3406pub enum DepthKind {
3407    /// On-chain depth sampled every slot.
3408    OnchainSlot,
3409    /// On-chain depth sampled at oracle updates.
3410    OnchainOracle,
3411    /// Router depth sampled every slot.
3412    RouterSlot,
3413}
3414
3415impl DepthKind {
3416    /// The source measured.
3417    pub const fn source(self) -> DepthSource {
3418        match self {
3419            Self::OnchainSlot | Self::OnchainOracle => DepthSource::Onchain,
3420            Self::RouterSlot => DepthSource::Router,
3421        }
3422    }
3423
3424    /// When the source is sampled.
3425    pub const fn granularity(self) -> DepthGranularity {
3426        match self {
3427            Self::OnchainSlot | Self::RouterSlot => DepthGranularity::Slot,
3428            Self::OnchainOracle => DepthGranularity::Oracle,
3429        }
3430    }
3431}
3432
3433/// A source asked for at a granularity it cannot be measured at.
3434#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
3435#[error("the {0} source cannot be measured at {1} granularity")]
3436pub struct UnmeasuredDepth(pub DepthSource, pub DepthGranularity);
3437
3438impl TryFrom<(DepthSource, DepthGranularity)> for DepthKind {
3439    type Error = UnmeasuredDepth;
3440
3441    fn try_from(
3442        (source, granularity): (DepthSource, DepthGranularity),
3443    ) -> Result<Self, Self::Error> {
3444        match (source, granularity) {
3445            (DepthSource::Onchain, DepthGranularity::Slot) => Ok(Self::OnchainSlot),
3446            (DepthSource::Onchain, DepthGranularity::Oracle) => Ok(Self::OnchainOracle),
3447            (DepthSource::Router, DepthGranularity::Slot) => Ok(Self::RouterSlot),
3448            (DepthSource::Router, DepthGranularity::Oracle) => {
3449                Err(UnmeasuredDepth(source, granularity))
3450            }
3451        }
3452    }
3453}
3454
3455/// The key prefix a depth job's dataset publishes under, e.g. `depth/onchain/slot`.
3456pub const fn depth_dataset_prefix(
3457    source: DepthSource,
3458    granularity: DepthGranularity,
3459) -> &'static str {
3460    match (source, granularity) {
3461        (DepthSource::Onchain, DepthGranularity::Slot) => "depth/onchain/slot",
3462        (DepthSource::Onchain, DepthGranularity::Oracle) => "depth/onchain/oracle",
3463        (DepthSource::Router, DepthGranularity::Slot) => "depth/router/slot",
3464        (DepthSource::Router, DepthGranularity::Oracle) => "depth/router/oracle",
3465    }
3466}
3467
3468/// Where `dataset` measured under the modifications with `digest` publishes: under `modified/`,
3469/// never in `dataset` itself.
3470pub fn modified_dataset_root(dataset: &str, digest: &str) -> String {
3471    format!("{MODIFIED_PREFIX}/{dataset}/{digest}")
3472}
3473
3474/// The directory under which datasets measured under modifications publish.
3475pub const MODIFIED_PREFIX: &str = "modified";
3476
3477/// What a depth job samples, per source.
3478#[derive(Debug, Clone, Serialize, Deserialize)]
3479pub struct DepthUniverseResponse {
3480    /// One entry per [`DepthSource`].
3481    pub sources: Vec<DepthSourceUniverse>,
3482}
3483
3484/// What one [`DepthSource`] samples.
3485#[derive(Debug, Clone, Serialize, Deserialize)]
3486pub struct DepthSourceUniverse {
3487    /// Which side of the venue this one measures.
3488    pub source: DepthSource,
3489    /// Dataset revision. A new revision re-samples every range.
3490    pub revision: u16,
3491    /// Market ids, as in the dataset's `market` partition.
3492    pub markets: Vec<String>,
3493    /// Venue labels, as in the dataset's `venue` partition.
3494    pub venues: Vec<String>,
3495    /// Sizes sampled per direction.
3496    pub size_rungs: usize,
3497}
3498
3499/// Server-side ceiling on [`DepthSelection::program_overrides`].
3500pub const MAX_PROGRAM_OVERRIDES: usize = 8;
3501/// Server-side ceiling on [`DepthSelection::account_overrides`].
3502pub const MAX_ACCOUNT_OVERRIDES: usize = 64;
3503/// Ceiling on a request's ELFs together.
3504pub const MAX_TOTAL_ELF_BYTES: usize = 8 * 1024 * 1024;
3505/// Ceiling on a session JSON-RPC request's body; fits [`MAX_TOTAL_ELF_BYTES`] base64-encoded.
3506pub const MAX_RPC_REQUEST_BODY_BYTES: u32 = 16 * 1024 * 1024;
3507/// Ceiling on a request's decoded account data together. The set repeats on every probe action
3508/// inside one CreateSession message.
3509pub const MAX_ACCOUNT_OVERRIDE_BYTES: usize = 128 * 1024;
3510
3511/// What a depth job measures over its slot range.
3512#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
3513pub struct DepthSelection {
3514    /// Which side of the venue to measure. The two sources publish separate
3515    /// datasets over the same range.
3516    #[serde(default)]
3517    pub source: DepthSource,
3518    /// How often to sample. Default `slot`; `oracle` needs the `onchain` source.
3519    #[serde(default, skip_serializing_if = "DepthGranularity::is_default")]
3520    pub granularity: DepthGranularity,
3521    /// Market ids to sample. Empty samples every market in the source's universe.
3522    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3523    pub markets: Vec<String>,
3524    /// Programs the probes run in place of the deployed ones. `onchain` only.
3525    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3526    pub program_overrides: Vec<ProgramOverride>,
3527    /// Accounts every probe sees in place of the recorded ones, across the whole range.
3528    /// `onchain` only.
3529    #[serde(default, skip_serializing_if = "AccountModifications::is_empty")]
3530    pub account_overrides: AccountModifications,
3531    /// Measure only the (market, venue)s L1 traded through for at least this many US dollars a
3532    /// day, in place of the universe's floor; `0` keeps every pair the universe does not deny.
3533    /// Unset, the universe's floor applies.
3534    #[serde(default, skip_serializing_if = "Option::is_none")]
3535    pub activity_floor_usd: Option<u64>,
3536}
3537
3538/// A program the probes run in place of the deployed one: `program_id` names a deployed
3539/// upgradeable (loader-v3) program, whose code becomes `elf`.
3540#[serde_with::serde_as]
3541#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3542pub struct ProgramOverride {
3543    /// The deployed program to replace, base58.
3544    #[serde_as(as = "serde_with::DisplayFromStr")]
3545    pub program_id: Address,
3546    /// The program binary (ELF) to run instead, base64 on the wire.
3547    #[serde_as(as = "serde_with::base64::Base64")]
3548    pub elf: Vec<u8>,
3549}
3550
3551/// The modifications a depth dataset was measured under, stored with each ELF inline as
3552/// `modifications.json` beside its parts. Its JSON is canonical — each account re-encoded with
3553/// `space` its data's length — so its blake3 is the dataset's digest.
3554#[doc(hidden)]
3555#[serde_with::serde_as]
3556#[derive(Debug, Clone, Serialize, Deserialize)]
3557pub struct DepthModifications {
3558    #[serde_as(as = "BTreeMap<serde_with::DisplayFromStr, serde_with::base64::Base64>")]
3559    pub programs: BTreeMap<Address, Vec<u8>>,
3560    pub accounts: AccountModifications,
3561}
3562
3563/// Request body of `POST /build-bundle`.
3564///
3565/// Construct via `..Default::default()` so a new field stays source-compatible.
3566#[derive(Debug, Clone, Default, Serialize, Deserialize)]
3567pub struct BundleBuildRequest {
3568    /// First slot to build, inclusive.
3569    pub start_slot: u64,
3570    /// Last slot to build, inclusive.
3571    pub end_slot: u64,
3572    /// Slots per bundle, above 0. Absent: the whole range is one bundle. A session replays one
3573    /// bundle, so smaller bundles allow more parallel sessions.
3574    #[serde(default)]
3575    pub bundle_size: Option<u64>,
3576    /// Optional repeat key; a resubmit dedupes the quota charge. The same key
3577    /// under a different `kind` is a distinct request.
3578    #[serde(default)]
3579    pub idempotency_key: Option<String>,
3580    /// Absent on the wire means [`BundleKind::Blocks`].
3581    #[serde(default)]
3582    pub kind: BundleKind,
3583}
3584
3585/// Where a bundle build or depth job is. snake_case on the wire: `"in_progress"`.
3586#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3587#[serde(rename_all = "snake_case")]
3588pub enum BundleBuildStatus {
3589    /// The bundle was built and is ready to use.
3590    Completed,
3591    /// The build failed and will not produce a bundle.
3592    Failed,
3593    /// The build has not finished yet; poll the status endpoint again later.
3594    InProgress,
3595    /// The outcome of the build could not be determined; do not assume success
3596    /// or failure.
3597    NeedsInvestigation,
3598}
3599
3600impl BundleBuildStatus {
3601    /// Stable string form matching the serde `snake_case` wire representation.
3602    pub fn as_str(self) -> &'static str {
3603        match self {
3604            Self::Completed => "completed",
3605            Self::Failed => "failed",
3606            Self::InProgress => "in_progress",
3607            Self::NeedsInvestigation => "needs_investigation",
3608        }
3609    }
3610}
3611
3612/// Response of the server's bundle-build endpoints.
3613#[derive(Debug, Clone, Serialize, Deserialize)]
3614#[allow(missing_docs)]
3615pub struct BundleBuildStatusResponse {
3616    /// The job ID; poll `GET /build-bundle/{request_id}` with it.
3617    pub request_id: String,
3618    pub start_slot: u64,
3619    pub end_slot: u64,
3620    /// Slots per bundle, as requested.
3621    pub bundle_size: Option<u64>,
3622    pub status: BundleBuildStatus,
3623    /// When the job was created (unix ms) — lets clients show a live ETA
3624    /// countdown by computing elapsed since this.
3625    pub created_at_unix_ms: u64,
3626    /// Absent on records predating the field, which are all `blocks`.
3627    #[serde(default)]
3628    pub kind: BundleKind,
3629    /// Server-side estimate of the seconds left on an in-progress build.
3630    /// `None` on a build that isn't running or if inputs can't be resolved.
3631    #[serde(default)]
3632    pub eta_secs: Option<u64>,
3633}
3634
3635/// A bundle the caller owns and can use now. Ordered by slot range, then kind.
3636#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
3637#[allow(missing_docs)]
3638pub struct CompletedBundle {
3639    pub start_slot: u64,
3640    pub end_slot: u64,
3641    pub kind: BundleKind,
3642    /// When the bundle became available (unix ms), where known.
3643    #[serde(default)]
3644    pub completed_at_unix_ms: Option<i64>,
3645    /// The bundle's size in bytes, where known.
3646    #[serde(default)]
3647    pub size_bytes: Option<i64>,
3648}
3649
3650/// Query of `DELETE /bundles`: the bundle to delete, by kind and exact range.
3651#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3652pub struct BundleDeleteRequest {
3653    #[allow(missing_docs)]
3654    pub start_slot: u64,
3655    #[allow(missing_docs)]
3656    pub end_slot: u64,
3657    /// Absent means [`BundleKind::Blocks`].
3658    #[serde(default)]
3659    pub kind: BundleKind,
3660}
3661
3662/// What `DELETE /bundles` removed.
3663#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3664#[allow(missing_docs)]
3665pub struct BundleDeleteResponse {
3666    pub start_slot: u64,
3667    pub end_slot: u64,
3668    pub kind: BundleKind,
3669}
3670
3671/// Response of `GET /build-bundle`.
3672#[derive(Debug, Clone, Serialize, Deserialize)]
3673pub struct BundleBuildListResponse {
3674    /// The caller's own builds, newest first. A build belongs to the endpoint
3675    /// running it, so this covers only builds requested here.
3676    pub builds: Vec<BundleBuildStatusResponse>,
3677    /// The caller's own bundles, ascending by range, wherever they were built.
3678    /// Not a view of `builds`: one build can produce several bundles, and a
3679    /// bundle outlives the record of the build that made it. `None` when the
3680    /// listing was unavailable, as opposed to `Some([])` for owning nothing.
3681    #[serde(default)]
3682    pub bundles: Option<Vec<CompletedBundle>>,
3683}
3684
3685/// Response of the server's `/snapshot-slot` endpoint. The chosen source and
3686/// import state are internal, so only the resolved slot is exposed.
3687#[derive(Debug, Clone, Serialize, Deserialize)]
3688pub struct SnapshotSlotResponse {
3689    /// The most recent slot the server has a snapshot for.
3690    pub snapshot_slot: u64,
3691}
3692
3693/// Response of `POST /datasets/credentials`: temporary, read-only credentials
3694/// plus a path, so a caller doesn't need to reconstruct the S3 layout.
3695#[derive(Debug, Clone, Serialize, Deserialize)]
3696#[allow(missing_docs)]
3697pub struct DatasetCredentialsResponse {
3698    pub access_key_id: String,
3699    pub secret_access_key: String,
3700    pub session_token: String,
3701    /// When the credentials stop working; request new ones after it.
3702    pub expiration: Option<chrono::DateTime<chrono::Utc>>,
3703    /// The shared datasets, as an `s3://` URI.
3704    pub s3_uri: String,
3705    /// Where this key's own jobs publish, when its name can be a prefix segment.
3706    /// `None` leaves the caller the shared datasets only.
3707    #[serde(default, skip_serializing_if = "Option::is_none")]
3708    pub user_s3_uri: Option<String>,
3709    pub region: Option<String>,
3710}
3711
3712/// Split a user-requested `[start_slot, end_slot]` range across the available
3713/// bundle ranges, returning a list of contiguous, non-overlapping `(start, end)`
3714/// pairs — one per bundle that the server can serve as its own session.
3715///
3716/// Each emitted `start` is a real `bundle_start_slot` and each `end` is within
3717/// the `max_bundle_end_slot` of a bundle that begins *exactly* at that start
3718/// (the server requires `start_slot == bundle_start_slot` and caps `end_slot` at
3719/// that bundle's `max_bundle_end_slot`). Among all such gap-free splits we pick
3720/// the one with the most sub-ranges, i.e. the highest parallelism: a fine-grained
3721/// (e.g. 10k) bundle grid yields one session per fine bundle instead of
3722/// collapsing onto a coarser series that overlaps the same slots — even when the
3723/// coarse and fine bundles share a start slot. A coarser bundle is only ridden
3724/// where no finer grid continues the walk, which still lets us serve a request
3725/// the coarse data covers even across a hole in the fine grid.
3726///
3727/// `kind` picks which bundles the split rides; the walk itself is the same for
3728/// either, since a recording is read slot by slot exactly as a block bundle is.
3729/// An unlabelled range, from a server predating [`AvailableRange::kind`],
3730/// counts as [`BundleKind::Blocks`].
3731///
3732/// Returns an error if the requested start cannot anchor, or if no gap-free
3733/// split reaches `requested_end`.
3734pub fn split_range(
3735    ranges: &[AvailableRange],
3736    requested: SlotRange,
3737    kind: BundleKind,
3738) -> Result<Vec<(u64, u64)>, String> {
3739    split_range_preferring(ranges, requested, kind, Prefer::Most)
3740}
3741
3742/// [`split_range`], choosing the gap-free split with the fewest sub-ranges
3743/// instead of the most. Anchors, validates and errors exactly like it: an
3744/// uncovered range names the first slot no bundle reaches.
3745pub fn split_range_fewest(
3746    ranges: &[AvailableRange],
3747    requested: SlotRange,
3748    kind: BundleKind,
3749) -> Result<Vec<(u64, u64)>, String> {
3750    split_range_preferring(ranges, requested, kind, Prefer::Fewest)
3751}
3752
3753/// Which gap-free split [`split_range_preferring`] keeps when several reach the end.
3754#[derive(Clone, Copy)]
3755enum Prefer {
3756    Most,
3757    Fewest,
3758}
3759
3760/// The walk behind [`split_range`] and [`split_range_fewest`], keeping the split
3761/// with the sub-range count `prefer` names.
3762fn split_range_preferring(
3763    ranges: &[AvailableRange],
3764    requested: SlotRange,
3765    kind: BundleKind,
3766    prefer: Prefer,
3767) -> Result<Vec<(u64, u64)>, String> {
3768    let (requested_start, requested_end) = (requested.start(), requested.end());
3769
3770    // Every advertised end per bundle start. A start can carry several ends — a
3771    // 50k snapshot bundle and the 10k bundle built on the same snapshot share a
3772    // start slot but reach different ends — so we keep them all and let the walk
3773    // pick among them.
3774    // A one-slot bundle (`end == start`) counts: a series whose last split
3775    // begins on the requested end records exactly one slot.
3776    let ends_by_start = ranges
3777        .iter()
3778        .filter(|r| r.kind.unwrap_or_default() == kind)
3779        .filter_map(|r| {
3780            r.max_bundle_end_slot
3781                .filter(|&end| end >= r.bundle_start_slot)
3782                .map(|end| (r.bundle_start_slot, end))
3783        })
3784        .fold(
3785            BTreeMap::<u64, BTreeSet<u64>>::new(),
3786            |mut ends_by_start, (start, end)| {
3787                ends_by_start.entry(start).or_default().insert(end);
3788                ends_by_start
3789            },
3790        );
3791
3792    // Anchor a request that lands mid-bundle to the covering bundle's start —
3793    // the latest bundle beginning at or before `requested_start` that still
3794    // covers it. The server's `select_parallel_requests` shares this fn and
3795    // anchors the same way, so the client must too or it would falsely reject a
3796    // start that isn't itself a bundle boundary. An exact bundle-start request
3797    // anchors to itself. (Single sessions instead require an exact bundle start
3798    // for every kind: `evaluate_requested_range`.)
3799    let Some((&anchor_start, _)) = ends_by_start.range(..=requested_start).rfind(|(_, ends)| {
3800        ends.iter()
3801            .next_back()
3802            .is_some_and(|&end| end >= requested_start)
3803    }) else {
3804        return Err(format!(
3805            "start_slot {requested_start} is not covered by any available {}",
3806            kind.coverage_noun()
3807        ));
3808    };
3809
3810    // Walk the bundle starts from `requested_end` backwards, recording for each
3811    // start the gap-free split `prefer` picks. A sub-range ends within one of its
3812    // start's bundles and the next sub-range must begin on the very next slot.
3813    let mut best_from: BTreeMap<u64, Vec<(u64, u64)>> = BTreeMap::new();
3814    for (&start, ends) in ends_by_start.range(anchor_start..=requested_end).rev() {
3815        let mut best: Option<Vec<(u64, u64)>> = None;
3816        for &end in ends {
3817            let candidate = if end >= requested_end {
3818                Some(vec![(start, requested_end)])
3819            } else {
3820                best_from.get(&(end + 1)).map(|rest| {
3821                    std::iter::once((start, end))
3822                        .chain(rest.iter().copied())
3823                        .collect()
3824                })
3825            };
3826            if let Some(candidate) = candidate
3827                && best.as_ref().is_none_or(|b| match prefer {
3828                    Prefer::Most => candidate.len() > b.len(),
3829                    Prefer::Fewest => candidate.len() < b.len(),
3830                })
3831            {
3832                best = Some(candidate);
3833            }
3834        }
3835        if let Some(best) = best {
3836            best_from.insert(start, best);
3837        }
3838    }
3839
3840    best_from.remove(&anchor_start).ok_or_else(|| {
3841        // Point at the first uncovered slot when the bundles leave a hole; fall
3842        // back to a generic message when the range is covered but cannot be
3843        // tiled to bundle boundaries.
3844        let mut covered_to = anchor_start.saturating_sub(1);
3845        for (&start, ends) in ends_by_start.range(anchor_start..=requested_end) {
3846            if start > covered_to.saturating_add(1) {
3847                break;
3848            }
3849            if let Some(&end) = ends.iter().next_back() {
3850                covered_to = covered_to.max(end);
3851            }
3852        }
3853        if covered_to < requested_end {
3854            format!("gap in coverage at slot {}", covered_to + 1)
3855        } else {
3856            format!(
3857                "no gap-free split of [{requested_start}, {requested_end}] aligns with the available {}",
3858                kind.coverage_nouns()
3859            )
3860        }
3861    })
3862}
3863
3864impl From<BacktestError> for BacktestResponse {
3865    fn from(error: BacktestError) -> Self {
3866        Self::Error(error)
3867    }
3868}
3869
3870impl std::error::Error for BacktestError {}
3871
3872impl fmt::Display for BacktestError {
3873    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3874        match self {
3875            BacktestError::InvalidTransactionEncoding { index, error } => {
3876                write!(f, "invalid transaction encoding at index {index}: {error}")
3877            }
3878            BacktestError::InvalidTransactionFormat { index, error } => {
3879                write!(f, "invalid transaction format at index {index}: {error}")
3880            }
3881            BacktestError::InvalidAccountEncoding {
3882                address,
3883                encoding,
3884                error,
3885            } => write!(
3886                f,
3887                "invalid encoding for account {address} ({encoding:?}): {error}"
3888            ),
3889            BacktestError::InvalidAccountOwner { address, error } => {
3890                write!(f, "invalid owner for account {address}: {error}")
3891            }
3892            BacktestError::InvalidAccountPubkey { address, error } => {
3893                write!(f, "invalid account pubkey {address}: {error}")
3894            }
3895            BacktestError::NoMoreBlocks => write!(f, "no more blocks available"),
3896            BacktestError::BundleNotFound {
3897                start_slot,
3898                end_slot,
3899            } => write!(
3900                f,
3901                "block bundle not found for start_slot={start_slot}, end_slot={end_slot}"
3902            ),
3903            BacktestError::AdvanceSlotFailed { slot, error } => {
3904                write!(f, "failed to advance to slot {slot}: {error}")
3905            }
3906            BacktestError::FinalizeSlotFailed { slot, error } => {
3907                write!(f, "failed to finalize slot {slot}: {error}")
3908            }
3909            BacktestError::InvalidRequest { error } => write!(f, "invalid request: {error}"),
3910            BacktestError::Internal { error } => write!(f, "internal error: {error}"),
3911            BacktestError::InvalidBlockhashFormat { slot, error } => {
3912                write!(f, "invalid blockhash at slot {slot}: {error}")
3913            }
3914            BacktestError::InitializingSysvarsFailed { slot, error } => {
3915                write!(f, "failed to initialize sysvars at slot {slot}: {error}")
3916            }
3917            BacktestError::ClerkError { error } => write!(f, "clerk error: {error}"),
3918            BacktestError::SimulationError { error } => {
3919                write!(f, "simulation error: {error}")
3920            }
3921            BacktestError::SessionNotFound { session_id } => {
3922                write!(f, "session not found: {session_id}")
3923            }
3924            BacktestError::SessionOwnerMismatch => {
3925                write!(f, "session owner mismatch")
3926            }
3927            BacktestError::SessionOwnershipBusy { reason } => {
3928                write!(f, "session ownership busy: {reason}")
3929            }
3930            BacktestError::NoProducedBlocksInRange {
3931                start_slot,
3932                end_slot,
3933            } => write!(
3934                f,
3935                "no produced blocks in requested range {start_slot}..={end_slot}; \
3936                 slot(s) may be skipped onchain"
3937            ),
3938            BacktestError::ProgramdataNotDeployed { address } => write!(
3939                f,
3940                "{address} is not a deployed upgradeable program's programdata, so its \
3941                 replacement would never run"
3942            ),
3943            BacktestError::SessionNameTaken { session_name } => {
3944                write!(f, "session name '{session_name}' is already in use")
3945            }
3946            BacktestError::Cut { slot } => write!(
3947                f,
3948                "the session was cut after slot {slot}: what it measured through that slot is \
3949                 published"
3950            ),
3951        }
3952    }
3953}
3954
3955#[cfg(test)]
3956mod tests {
3957    use rstest::rstest;
3958    use solana_account::ReadableAccount;
3959
3960    use super::*;
3961
3962    #[rstest]
3963    #[case::onchain_slot(
3964        DepthSource::Onchain,
3965        DepthGranularity::Slot,
3966        Some(DepthKind::OnchainSlot)
3967    )]
3968    #[case::onchain_oracle(
3969        DepthSource::Onchain,
3970        DepthGranularity::Oracle,
3971        Some(DepthKind::OnchainOracle)
3972    )]
3973    #[case::router_slot(
3974        DepthSource::Router,
3975        DepthGranularity::Slot,
3976        Some(DepthKind::RouterSlot)
3977    )]
3978    #[case::router_oracle(DepthSource::Router, DepthGranularity::Oracle, None)]
3979    fn only_a_source_at_a_granularity_it_measures_names_a_depth_kind(
3980        #[case] source: DepthSource,
3981        #[case] granularity: DepthGranularity,
3982        #[case] kind: Option<DepthKind>,
3983    ) {
3984        let named = DepthKind::try_from((source, granularity));
3985        assert_eq!(named.ok(), kind);
3986        if let Some(kind) = kind {
3987            assert_eq!((kind.source(), kind.granularity()), (source, granularity));
3988        }
3989    }
3990
3991    /// Request ids are derived from these, so they are a wire contract: reordering the variants
3992    /// or renumbering them would silently re-issue every caller's measurement as a second run.
3993    #[test]
3994    fn a_sources_discriminant_is_frozen_independently_of_its_label() {
3995        assert_eq!(DepthSource::Onchain.discriminant(), 0);
3996        assert_eq!(DepthSource::Router.discriminant(), 1);
3997    }
3998
3999    /// `as_str`, `from_str_opt` and serde are three tables over the same two names; one of them
4000    /// drifting would change what a stored row or a request body means.
4001    #[test]
4002    fn a_source_spells_itself_the_same_way_three_times() {
4003        for source in [DepthSource::Onchain, DepthSource::Router] {
4004            assert_eq!(
4005                serde_json::to_value(source).expect("a source serialises"),
4006                serde_json::json!(source.as_str())
4007            );
4008            assert_eq!(DepthSource::from_str_opt(source.as_str()), Some(source));
4009        }
4010    }
4011
4012    /// The crate doc's casing table is the contract raw clients code against.
4013    #[rstest]
4014    #[case::continue_params(r#"{"method": "continue", "params": {"advanceCount": 10}}"#)]
4015    #[case::attach(
4016        r#"{"method": "attachBacktestSession", "params": {"session_id": "backtest_0198f3a1c2d34e5f8a9b0c1d2e3f4a5b", "last_sequence": 7}}"#
4017    )]
4018    #[case::attach_parallel(
4019        r#"{"method": "attachParallelControlSessionV2", "params": {"control_session_id": "parallel_0198f3a1c2d34e5f8a9b0c1d2e3f4a5b", "last_sequences": {"backtest_0198f3a1c2d34e5f8a9b0c1d2e3f4a5b": 7}}}"#
4020    )]
4021    #[case::continue_v1(
4022        r#"{"method": "continueSessionV1", "params": {"sessionId": "backtest_0198f3a1c2d34e5f8a9b0c1d2e3f4a5b", "request": {"advanceCount": 1}}}"#
4023    )]
4024    #[case::resume(r#"{"method": "resumeAttachedSession"}"#)]
4025    fn a_documented_request_parses(#[case] wire: &str) {
4026        serde_json::from_str::<BacktestRequest>(wire).expect("documented request parses");
4027    }
4028
4029    /// The crate doc's casing table is the contract raw clients code against.
4030    #[rstest]
4031    #[case::session_created(
4032        r#"{"method": "sessionCreated", "params": {"session_id": "backtest_0198f3a1c2d34e5f8a9b0c1d2e3f4a5b", "rpc_endpoint": "https://host/backtest/backtest_0198f3a1c2d34e5f8a9b0c1d2e3f4a5b"}}"#
4033    )]
4034    #[case::sequenced(r#"{"seqId": 7, "method": "slotNotification", "params": 1234}"#)]
4035    #[case::ready(r#"{"method": "readyForContinue"}"#)]
4036    #[case::error(
4037        r#"{"method": "error", "params": {"bundleNotFound": {"start_slot": 1, "end_slot": 2}}}"#
4038    )]
4039    #[case::session_event(
4040        r#"{"method": "sessionEventV2", "params": {"session_id": "backtest_0198f3a1c2d34e5f8a9b0c1d2e3f4a5b", "seq_id": 3, "event": {"method": "readyForContinue"}}}"#
4041    )]
4042    fn a_documented_response_round_trips(#[case] wire: &str) {
4043        let expected: serde_json::Value = serde_json::from_str(wire).expect("valid JSON");
4044        let actual = match expected.get("seqId") {
4045            Some(_) => serde_json::to_value(
4046                serde_json::from_str::<SequencedResponse>(wire)
4047                    .expect("documented response parses"),
4048            ),
4049            None => serde_json::to_value(
4050                serde_json::from_str::<BacktestResponse>(wire).expect("documented response parses"),
4051            ),
4052        }
4053        .expect("response serialises");
4054        assert_eq!(actual, expected);
4055    }
4056
4057    #[rstest]
4058    #[case::empty(solana_account::Account { lamports: 1, rent_epoch: 7, ..Default::default() })]
4059    #[case::executable_with_data(solana_account::Account {
4060        lamports: 2,
4061        data: vec![1, 2, 3],
4062        owner: Address::from([9; 32]),
4063        executable: true,
4064        rent_epoch: u64::MAX,
4065    })]
4066    fn an_account_survives_the_wire_round_trip_apart_from_its_rent_epoch(
4067        #[case] account: solana_account::Account,
4068    ) {
4069        let wire = AccountData::from(&account);
4070
4071        assert_eq!(wire.space, account.data.len() as u64);
4072        assert_eq!(wire.data.encoding, BinaryEncoding::Base64);
4073        assert_eq!(
4074            wire.to_account().expect("base64 decodes"),
4075            solana_account::Account {
4076                rent_epoch: 0,
4077                ..account
4078            }
4079        );
4080    }
4081
4082    #[rstest]
4083    #[case::nonexistent(0)]
4084    #[case::funded(1_000_000)]
4085    fn system_account_is_an_empty_system_owned_account(#[case] lamports: u64) {
4086        assert_eq!(
4087            AccountData::system_account(lamports)
4088                .to_account()
4089                .expect("base64 decodes"),
4090            solana_account::Account {
4091                lamports,
4092                ..Default::default()
4093            }
4094        );
4095    }
4096
4097    fn address(byte: u8) -> Address {
4098        Address::from([byte; 32])
4099    }
4100
4101    #[rstest]
4102    #[case::one("jupiter", Some(&[SwapAggregator::Jupiter][..]))]
4103    #[case::several("jupiter,okx", Some(&[SwapAggregator::Jupiter, SwapAggregator::Okx][..]))]
4104    #[case::spaced_and_uppercased(" Jupiter , OKX ", Some(&[SwapAggregator::Jupiter, SwapAggregator::Okx][..]))]
4105    #[case::repeats_collapse("okx,okx", Some(&[SwapAggregator::Okx][..]))]
4106    #[case::trailing_separator("okx,", Some(&[SwapAggregator::Okx][..]))]
4107    #[case::unknown("jupiter,bogus", None)]
4108    #[case::empty("", None)]
4109    #[case::separators_only(",,", None)]
4110    fn reroute_aggregators_parse_the_shapes_a_flag_carries(
4111        #[case] input: &str,
4112        #[case] expected: Option<&[SwapAggregator]>,
4113    ) {
4114        assert_eq!(
4115            input.parse::<RerouteAggregators>().ok(),
4116            expected.map(|aggregators| RerouteAggregators::new(aggregators.iter().copied()))
4117        );
4118    }
4119
4120    /// `Display` renders `--reroute-aggregators`' default, so clap re-parses whatever it prints.
4121    #[test]
4122    fn reroute_aggregators_round_trip_through_their_rendering() {
4123        let aggregators = RerouteAggregators::new([SwapAggregator::Dflow, SwapAggregator::Jupiter]);
4124
4125        assert_eq!(aggregators.to_string(), "jupiter,dflow");
4126        assert_eq!(
4127            aggregators
4128                .to_string()
4129                .parse::<RerouteAggregators>()
4130                .unwrap(),
4131            aggregators
4132        );
4133        assert_eq!(RerouteAggregators::default().to_string(), "jupiter");
4134    }
4135
4136    #[test]
4137    fn all_lists_every_aggregator_once_in_order() {
4138        // Exhaustive: a new variant stops this compiling, a prompt to add it to `ALL`.
4139        let _tripwire = |aggregator: SwapAggregator| match aggregator {
4140            SwapAggregator::Jupiter
4141            | SwapAggregator::Okx
4142            | SwapAggregator::Titan
4143            | SwapAggregator::Dflow => (),
4144        };
4145
4146        // Strictly increasing: sorted with no repeats.
4147        assert!(SwapAggregator::ALL.is_sorted_by(|a, b| a < b));
4148    }
4149
4150    #[test]
4151    fn all_aggregators_render_and_parse_back() {
4152        let all = RerouteAggregators::all();
4153
4154        assert_eq!(all.to_string(), "jupiter,okx,titan,dflow");
4155        assert_eq!(all.to_string().parse::<RerouteAggregators>().unwrap(), all);
4156    }
4157
4158    /// The API deserializes aggregators through the same parser the flag uses, so a spelling one
4159    /// entry point accepts is not a hard error at the other.
4160    #[test]
4161    fn aggregators_deserialize_through_the_same_parser_the_flag_uses() {
4162        let params: CreateSessionParams = serde_json::from_value(
4163            serde_json::json!({"startSlot": 1, "endSlot": 2, "reroute": {"aggregators": ["Jupiter", "OKX"]}}),
4164        )
4165        .expect("decode");
4166
4167        assert_eq!(
4168            params.reroute.expect("rerouting requested").aggregators,
4169            RerouteAggregators::new([SwapAggregator::Jupiter, SwapAggregator::Okx])
4170        );
4171    }
4172
4173    /// A request that names no knob gets the narrow defaults, not the every-aggregator behaviour a
4174    /// client written before this change expected — the switch these defaults are here to make.
4175    #[test]
4176    fn params_without_the_new_reroute_fields_decode_to_the_narrow_defaults() {
4177        let params: CreateSessionParams = serde_json::from_value(
4178            serde_json::json!({"startSlot": 1, "endSlot": 2, "reroute": {}}),
4179        )
4180        .expect("decode");
4181
4182        let reroute = params.reroute.expect("rerouting requested");
4183        assert_eq!(reroute.aggregators, RerouteAggregators::default());
4184        assert!(reroute.aggregators.contains(SwapAggregator::Jupiter));
4185        assert!(!reroute.aggregators.contains(SwapAggregator::Okx));
4186        assert!(!reroute.circular_arbs);
4187        assert!(!reroute.detect_failed_l1_swaps);
4188        assert_eq!(reroute.scopes, RerouteScopes::default());
4189    }
4190
4191    #[rstest]
4192    #[case::top_level("top-level", Some(&[SwapScope::TopLevel][..]))]
4193    #[case::both(" Nested , top-level ", Some(&[SwapScope::TopLevel, SwapScope::Nested][..]))]
4194    #[case::all(
4195        "venue,nested,top-level",
4196        Some(&[SwapScope::TopLevel, SwapScope::Nested, SwapScope::Venue][..])
4197    )]
4198    #[case::unknown("nested,bogus", None)]
4199    #[case::empty(",", None)]
4200    fn reroute_scopes_parse_the_shapes_a_flag_carries(
4201        #[case] input: &str,
4202        #[case] expected: Option<&[SwapScope]>,
4203    ) {
4204        assert_eq!(
4205            input.parse::<RerouteScopes>().ok(),
4206            expected.map(|scopes| RerouteScopes::new(scopes.iter().copied()))
4207        );
4208    }
4209
4210    #[test]
4211    fn all_scopes_render_and_parse_back() {
4212        let all = RerouteScopes::all();
4213
4214        assert!(SwapScope::ALL.is_sorted_by(|a, b| a < b));
4215        assert_eq!(all.to_string(), "top-level,nested,venue");
4216        assert_eq!(all.to_string().parse::<RerouteScopes>().unwrap(), all);
4217    }
4218
4219    /// `Display` renders `--reroute-scopes`' default, so clap re-parses whatever it prints, and the
4220    /// default stays off the wire so a request written before scopes encodes as it did.
4221    #[test]
4222    fn reroute_scopes_round_trip_and_keep_the_default_off_the_wire() {
4223        let scopes = RerouteScopes::new([SwapScope::Nested, SwapScope::TopLevel]);
4224
4225        assert_eq!(scopes.to_string(), "top-level,nested");
4226        assert_eq!(scopes.to_string().parse::<RerouteScopes>().unwrap(), scopes);
4227        assert_eq!(
4228            serde_json::to_value(RerouteParams::default()).unwrap()["scopes"],
4229            serde_json::Value::Null
4230        );
4231        assert_eq!(
4232            serde_json::to_value(RerouteParams {
4233                scopes,
4234                ..RerouteParams::default()
4235            })
4236            .unwrap()["scopes"],
4237            serde_json::json!(["top-level", "nested"])
4238        );
4239    }
4240
4241    /// Presence is the switch: a replay that will never quote must not reserve a metis sidecar.
4242    #[test]
4243    fn a_request_without_reroute_reserves_no_sidecar() {
4244        let params: CreateSessionParams =
4245            serde_json::from_value(serde_json::json!({"startSlot": 1, "endSlot": 2}))
4246                .expect("decode");
4247
4248        assert!(!params.requires_sidecar());
4249    }
4250
4251    /// A per-slot override schedule is the largest thing a client sends. Each
4252    /// action alone is incompressible enough to sit near the websocket message
4253    /// limit; the redundancy lives *across* actions, so the whole vector has to
4254    /// travel as one blob. Pins both the round trip and that size property.
4255    #[test]
4256    fn a_per_slot_action_schedule_compresses_across_actions() {
4257        let slots = 2_000u64;
4258        let actions = (0..slots)
4259            .map(|slot| ScheduledAction {
4260                anchor: ActionAnchor::AfterSlot { slots: vec![slot] },
4261                kind: ActionKind::Simulate,
4262                feeds_reroute: false,
4263                transactions: Vec::new(),
4264                account_overrides: AccountModifications(BTreeMap::from([(
4265                    address(7),
4266                    AccountData {
4267                        // Realistic pool account: 2 KiB that barely moves slot to slot.
4268                        data: EncodedBinary::new(
4269                            BASE64.encode(
4270                                [&slot.to_le_bytes()[..], &[0xAB; 2040][..]]
4271                                    .concat()
4272                                    .as_slice(),
4273                            ),
4274                            BinaryEncoding::Base64,
4275                        ),
4276                        executable: false,
4277                        lamports: 15_144_966,
4278                        owner: address(9),
4279                        space: 2048,
4280                    },
4281                )])),
4282                return_accounts: Vec::new(),
4283                label: None,
4284                resolve: None,
4285                within: None,
4286            })
4287            .collect::<Vec<_>>();
4288        let params = CreateSessionParams::builder()
4289            .start_slot(1)
4290            .end_slot(slots)
4291            .actions(actions.clone())
4292            .build();
4293
4294        let encoded = serde_json::to_string(&params).expect("serialize");
4295        let raw = serde_json::to_string(&actions).expect("serialize raw actions");
4296        assert!(
4297            encoded.len() * 8 < raw.len(),
4298            "expected the schedule to compress well; got {} bytes from {} raw",
4299            encoded.len(),
4300            raw.len()
4301        );
4302
4303        let decoded: CreateSessionParams = serde_json::from_str(&encoded).expect("round trip");
4304        assert_eq!(
4305            serde_json::to_string(&decoded.actions).expect("serialize decoded"),
4306            raw
4307        );
4308    }
4309
4310    /// Absent actions stay absent on the wire, so a session without a schedule
4311    /// is unchanged by the compression.
4312    #[test]
4313    fn an_empty_action_list_is_omitted_entirely() {
4314        let params = CreateSessionParams::builder()
4315            .start_slot(1)
4316            .end_slot(2)
4317            .build();
4318        let json = serde_json::to_value(&params).expect("serialize");
4319        assert!(json.get("actions").is_none(), "{json}");
4320        let decoded: CreateSessionParams = serde_json::from_value(json).expect("round trip");
4321        assert!(decoded.actions.is_empty());
4322    }
4323
4324    /// The conflict is `send` *and* replay: neither alone is a problem, and simulate runs
4325    /// fine under replay because it never commits.
4326    #[test]
4327    fn send_actions_conflict_with_replay_only_together() {
4328        let params = |replay, kind| {
4329            CreateSessionParams::builder()
4330                .start_slot(1)
4331                .end_slot(2)
4332                .replay_account_state(replay)
4333                .actions(vec![ScheduledAction {
4334                    anchor: ActionAnchor::BeforeSlot { slots: vec![1] },
4335                    kind,
4336                    feeds_reroute: false,
4337                    transactions: vec!["dGVzdA==".to_string()],
4338                    account_overrides: Default::default(),
4339                    return_accounts: Default::default(),
4340                    label: None,
4341                    resolve: None,
4342                    within: None,
4343                }])
4344                .build()
4345        };
4346        assert!(replay_support::send_action_conflict(&params(false, ActionKind::Send)).is_none());
4347        assert!(
4348            replay_support::send_action_conflict(&params(true, ActionKind::Simulate)).is_none()
4349        );
4350        let mut publishing = params(true, ActionKind::Simulate);
4351        publishing.actions[0].feeds_reroute = true;
4352        assert!(replay_support::send_action_conflict(&publishing).is_none());
4353
4354        let conflict = replay_support::send_action_conflict(&params(true, ActionKind::Send))
4355            .expect("send under replay conflicts");
4356        assert!(conflict.contains("kind: send"), "{conflict}");
4357        assert!(conflict.contains(replay_support::SEND_ACTION), "{conflict}");
4358    }
4359
4360    fn override_entry(owner: Address, executable: bool) -> AccountData {
4361        AccountData {
4362            data: EncodedBinary::from_bytes(&[1, 2, 3], BinaryEncoding::Base64),
4363            executable,
4364            lamports: 1,
4365            owner,
4366            space: 3,
4367        }
4368    }
4369
4370    fn before() -> ActionAnchor {
4371        ActionAnchor::BeforeSlot { slots: vec![1] }
4372    }
4373
4374    fn valid() -> ScheduledAction {
4375        override_action(before(), address(3), override_entry(address(4), false))
4376    }
4377
4378    fn override_action(
4379        anchor: ActionAnchor,
4380        account: Address,
4381        data: AccountData,
4382    ) -> ScheduledAction {
4383        ScheduledAction {
4384            anchor,
4385            kind: ActionKind::default(),
4386            transactions: Vec::new(),
4387            account_overrides: AccountModifications(BTreeMap::from([(account, data)])),
4388            return_accounts: Vec::new(),
4389            label: None,
4390            feeds_reroute: true,
4391            resolve: None,
4392            within: None,
4393        }
4394    }
4395
4396    #[test]
4397    fn override_action_round_trips() {
4398        let key = address(1);
4399        let entry = override_entry(address(2), false);
4400        let action = override_action(
4401            ActionAnchor::BeforeSlot { slots: vec![5, 9] },
4402            key,
4403            entry.clone(),
4404        );
4405        let json = serde_json::to_value(&action).unwrap();
4406        assert!(
4407            json["anchor"]["slots"].is_string(),
4408            "slots travel as a compressed blob: {json}"
4409        );
4410        let back: ScheduledAction = serde_json::from_value(json).unwrap();
4411        assert_eq!(back.anchor, ActionAnchor::BeforeSlot { slots: vec![5, 9] });
4412        assert!(back.feeds_reroute);
4413        assert!(!back.is_computed_override(), "no transactions to simulate");
4414        let survived = &back.account_overrides.0[&key];
4415        assert_eq!(survived.lamports, entry.lamports);
4416        assert_eq!(survived.data.data, entry.data.data);
4417    }
4418
4419    #[rstest]
4420    #[case::unbounded(None)]
4421    #[case::bounded(Some(SlotRange::new_unchecked(5, 9).into()))]
4422    fn a_slot_bound_round_trips_and_stays_off_the_wire_when_absent(
4423        #[case] within: Option<SlotWindows>,
4424    ) {
4425        let action = ScheduledAction {
4426            within: within.clone(),
4427            ..resolved_action()
4428        };
4429        let json = serde_json::to_value(&action).unwrap();
4430        assert_eq!(json.get("within").is_some(), within.is_some(), "{json}");
4431        let back: ScheduledAction = serde_json::from_value(json).unwrap();
4432        assert_eq!(back.within, within);
4433    }
4434
4435    #[test]
4436    fn a_before_batch_anchor_round_trips_its_batches_compressed() {
4437        let anchor = ActionAnchor::BeforeBatch {
4438            batches: vec![
4439                BatchPosition {
4440                    slot: 5,
4441                    batch_index: 2,
4442                },
4443                BatchPosition {
4444                    slot: 5,
4445                    batch_index: 2,
4446                },
4447            ],
4448        };
4449
4450        let json = serde_json::to_value(&anchor).unwrap();
4451
4452        assert_eq!(json["at"], "beforeBatch");
4453        assert!(json["batches"].is_string(), "{json}");
4454        assert_eq!(
4455            serde_json::from_value::<ActionAnchor>(json).unwrap(),
4456            anchor
4457        );
4458    }
4459
4460    #[test]
4461    fn an_every_slot_anchor_round_trips_and_defaults_to_every_slot() {
4462        let anchor = ActionAnchor::AfterEverySlot {
4463            every_n_slots: NonZeroU64::new(10).unwrap(),
4464        };
4465        let json = serde_json::to_value(&anchor).unwrap();
4466        assert_eq!(
4467            json,
4468            serde_json::json!({ "at": "afterEverySlot", "everyNSlots": 10 })
4469        );
4470        assert_eq!(
4471            serde_json::from_value::<ActionAnchor>(json).unwrap(),
4472            anchor
4473        );
4474
4475        assert_eq!(
4476            serde_json::from_value::<ActionAnchor>(serde_json::json!({ "at": "beforeEverySlot" }))
4477                .unwrap(),
4478            ActionAnchor::BeforeEverySlot {
4479                every_n_slots: NonZeroU64::MIN
4480            }
4481        );
4482        assert!(
4483            serde_json::from_value::<ActionAnchor>(
4484                serde_json::json!({ "at": "beforeEverySlot", "everyNSlots": 0 })
4485            )
4486            .is_err(),
4487            "a zero cadence names no slot"
4488        );
4489    }
4490
4491    fn context(
4492        invoked: &[u8],
4493        moves_tokens: bool,
4494        written: &[u8],
4495        writes_via_unresolved_lookup: bool,
4496    ) -> TxMatchContext {
4497        TxMatchContext {
4498            invoked_programs: invoked.iter().copied().map(address).collect(),
4499            moves_tokens,
4500            written_accounts: written.iter().copied().map(address).collect(),
4501            writes_via_unresolved_lookup,
4502        }
4503    }
4504
4505    /// The venue lists programs 1 and 2, and a scoped filter names account 10.
4506    #[rstest]
4507    #[case::update(&[], context(&[1], false, &[11], false), true)]
4508    #[case::moves_tokens(&[], context(&[1], true, &[11], false), false)]
4509    #[case::second_program_of_the_set(&[], context(&[2], false, &[11], false), true)]
4510    #[case::other_program(&[], context(&[3], false, &[11], false), false)]
4511    #[case::write_to_the_scope(&[10], context(&[1], false, &[11, 10], false), true)]
4512    #[case::write_elsewhere(&[10], context(&[1], false, &[11], false), false)]
4513    #[case::unresolved_write_through_a_lookup_table(&[10], context(&[1], false, &[11], true), true)]
4514    fn an_oracle_update_is_a_token_free_write_by_a_listed_program(
4515        #[case] accounts: &[u8],
4516        #[case] ctx: TxMatchContext,
4517        #[case] expected: bool,
4518    ) {
4519        let filter = DiscoveryFilter::OracleUpdate {
4520            programs: BTreeSet::from([address(1), address(2)]),
4521            accounts: accounts.iter().copied().map(address).collect(),
4522        };
4523        assert_eq!(filter.matches(&ctx), expected);
4524    }
4525
4526    #[rstest]
4527    #[case::write_to_the_scope(&[10], context(&[1], true, &[11, 10], false), true)]
4528    #[case::another_market_s_write(&[10], context(&[1], false, &[11], false), false)]
4529    #[case::unresolved_write_through_a_lookup_table(&[10], context(&[1], false, &[11], true), true)]
4530    #[case::program_did_not_run(&[10], context(&[2], false, &[10], false), false)]
4531    #[case::empty_scope(&[], context(&[1], false, &[10], true), false)]
4532    fn a_program_write_is_a_call_to_the_program_writing_its_scope(
4533        #[case] accounts: &[u8],
4534        #[case] ctx: TxMatchContext,
4535        #[case] expected: bool,
4536    ) {
4537        let filter = DiscoveryFilter::ProgramWrite {
4538            program: address(1),
4539            accounts: accounts.iter().copied().map(address).collect(),
4540        };
4541        assert_eq!(filter.matches(&ctx), expected);
4542    }
4543
4544    #[rstest]
4545    #[case::unscoped(
4546        &[],
4547        serde_json::json!({ "kind": "oracleUpdate", "value": { "programs": [address(1).to_string()] } })
4548    )]
4549    #[case::scoped(
4550        &[2],
4551        serde_json::json!({
4552            "kind": "oracleUpdate",
4553            "value": { "programs": [address(1).to_string()], "accounts": [address(2).to_string()] }
4554        })
4555    )]
4556    fn an_oracle_update_filter_round_trips_as_kind_and_value(
4557        #[case] accounts: &[u8],
4558        #[case] expected: serde_json::Value,
4559    ) {
4560        let filter = DiscoveryFilter::OracleUpdate {
4561            programs: BTreeSet::from([address(1)]),
4562            accounts: accounts.iter().copied().map(address).collect(),
4563        };
4564        let json = serde_json::to_value(&filter).unwrap();
4565
4566        assert_eq!(json, expected);
4567        assert_eq!(
4568            serde_json::from_value::<DiscoveryFilter>(json).unwrap(),
4569            filter
4570        );
4571    }
4572
4573    #[test]
4574    fn an_after_change_anchor_round_trips_with_its_accounts() {
4575        let anchor = ActionAnchor::AfterChange {
4576            accounts: BTreeSet::from([address(1), address(2)]).try_into().unwrap(),
4577        };
4578        let json = serde_json::to_value(&anchor).unwrap();
4579
4580        assert_eq!(
4581            json,
4582            serde_json::json!({
4583                "at": "afterChange",
4584                "accounts": [address(1).to_string(), address(2).to_string()]
4585            })
4586        );
4587        assert_eq!(
4588            serde_json::from_value::<ActionAnchor>(json).unwrap(),
4589            anchor
4590        );
4591    }
4592
4593    #[rstest]
4594    #[case::empty(serde_json::json!([]))]
4595    #[case::not_an_address(serde_json::json!(["not-an-address"]))]
4596    fn an_after_change_anchor_rejects_an_unusable_account_list(
4597        #[case] accounts: serde_json::Value,
4598    ) {
4599        let json = serde_json::json!({ "at": "afterChange", "accounts": accounts });
4600        assert!(serde_json::from_value::<ActionAnchor>(json).is_err());
4601    }
4602
4603    /// A venue's vaults are token accounts, so pricing one against different inventory means
4604    /// overriding them. They were rejected outright on the grounds that prepare-stage reads would
4605    /// desync from simulation — but prepare's only use for them is clerk cache warming, and every
4606    /// simulation applies the schedule on top of whatever that warmed.
4607    #[test]
4608    fn a_token_account_override_is_accepted() {
4609        let action = override_action(
4610            before(),
4611            address(3),
4612            override_entry(spl_token_interface::ID, false),
4613        );
4614        let schedule = decode_override_actions(&[action]).expect("token overrides decode");
4615        assert!(!schedule.active_at(1).is_empty());
4616    }
4617
4618    #[rstest]
4619    #[case::executable(override_action(before(), address(3), override_entry(address(10), true)))]
4620    #[case::program_owned(override_action(
4621        before(),
4622        address(3),
4623        override_entry(PROGRAM_OWNERS[0], false),
4624    ))]
4625    #[case::after_slot_anchor(override_action(
4626        ActionAnchor::AfterSlot { slots: vec![1] },
4627        address(3),
4628        override_entry(address(4), false),
4629    ))]
4630    #[case::every_slot_anchor(override_action(
4631        ActionAnchor::BeforeEverySlot { every_n_slots: NonZeroU64::MIN },
4632        address(3),
4633        override_entry(address(4), false),
4634    ))]
4635    #[case::nothing_to_post(ScheduledAction {
4636        account_overrides: AccountModifications::default(),
4637        ..valid()
4638    })]
4639    // Otherwise an action that meant to send would silently post overrides instead.
4640    #[case::send(ScheduledAction {
4641        kind: ActionKind::Send,
4642        ..valid()
4643    })]
4644    #[case::bounded(ScheduledAction {
4645        within: Some(SlotRange::new_unchecked(0, 9).into()),
4646        ..valid()
4647    })]
4648    #[allow(deprecated, reason = "exercise the loader-owner rejection path")]
4649    fn override_actions_reject_invalid_accounts_and_shapes(#[case] action: ScheduledAction) {
4650        assert!(decode_override_actions(&[action]).is_err());
4651    }
4652
4653    fn liquidity_arrays(array_key_indices: Vec<u8>) -> TxResolver {
4654        TxResolver::LiquidityArrays {
4655            pool: address(1),
4656            input_mint: address(2),
4657            array_key_indices: array_key_indices.try_into().unwrap(),
4658        }
4659    }
4660
4661    fn resolved_action() -> ScheduledAction {
4662        ScheduledAction {
4663            anchor: ActionAnchor::AfterSlot { slots: vec![5] },
4664            kind: ActionKind::Simulate,
4665            transactions: vec!["dGVzdA==".to_string()],
4666            account_overrides: AccountModifications::default(),
4667            feeds_reroute: false,
4668            return_accounts: Vec::new(),
4669            label: None,
4670            resolve: Some(liquidity_arrays(vec![6, 7, 8])),
4671            within: None,
4672        }
4673    }
4674
4675    fn requote() -> TxResolver {
4676        TxResolver::Requote {
4677            dex: address(1),
4678            input_mint: address(2),
4679            output_mint: address(3),
4680            amount: 1_000_000_000,
4681            slippage_bps: 9900,
4682        }
4683    }
4684
4685    fn validate_session_resolvers(actions: Vec<ScheduledAction>) -> Result<(), ActionResolveError> {
4686        CreateSessionParams::builder()
4687            .start_slot(1)
4688            .end_slot(10)
4689            .actions(actions)
4690            .build()
4691            .validate_action_resolvers()
4692    }
4693
4694    #[test]
4695    fn a_liquidity_arrays_resolver_serializes_as_a_type_tagged_camel_case_object() {
4696        let resolver = liquidity_arrays(vec![6, 7, 8]);
4697        let json = serde_json::to_value(&resolver).unwrap();
4698        assert_eq!(
4699            json,
4700            serde_json::json!({
4701                "type": "liquidityArrays",
4702                "pool": address(1).to_string(),
4703                "inputMint": address(2).to_string(),
4704                "arrayKeyIndices": [6, 7, 8],
4705            })
4706        );
4707        assert_eq!(
4708            serde_json::from_value::<TxResolver>(json).unwrap(),
4709            resolver
4710        );
4711    }
4712
4713    #[test]
4714    fn a_quote_stamp_resolver_serializes_as_its_type_tag_alone() {
4715        let json = serde_json::to_value(TxResolver::QuoteStamp).unwrap();
4716        assert_eq!(json, serde_json::json!({ "type": "quoteStamp" }));
4717        assert_eq!(
4718            serde_json::from_value::<TxResolver>(json).unwrap(),
4719            TxResolver::QuoteStamp
4720        );
4721    }
4722
4723    #[test]
4724    fn a_requote_resolver_round_trips_its_terms() {
4725        let resolver = requote();
4726        let json = serde_json::to_value(&resolver).unwrap();
4727        assert_eq!(
4728            json,
4729            serde_json::json!({
4730                "type": "requote",
4731                "dex": address(1).to_string(),
4732                "inputMint": address(2).to_string(),
4733                "outputMint": address(3).to_string(),
4734                "amount": 1_000_000_000_u64,
4735                "slippageBps": 9900,
4736            })
4737        );
4738        assert_eq!(
4739            serde_json::from_value::<TxResolver>(json).unwrap(),
4740            resolver
4741        );
4742    }
4743
4744    #[test]
4745    fn only_an_action_that_requotes_needs_the_sidecar() {
4746        let params = |resolve| {
4747            CreateSessionParams::builder()
4748                .start_slot(1)
4749                .end_slot(10)
4750                .actions(vec![ScheduledAction {
4751                    resolve,
4752                    ..resolved_action()
4753                }])
4754                .build()
4755        };
4756        assert!(params(Some(requote())).requires_sidecar());
4757        assert!(!params(Some(TxResolver::QuoteStamp)).requires_sidecar());
4758    }
4759
4760    #[test]
4761    fn an_action_without_a_resolver_omits_the_key_and_reads_back_as_none() {
4762        let action = ScheduledAction {
4763            resolve: None,
4764            ..resolved_action()
4765        };
4766        let json = serde_json::to_value(&action).unwrap();
4767        assert!(json.get("resolve").is_none(), "{json}");
4768        let back: ScheduledAction = serde_json::from_value(json).unwrap();
4769        assert_eq!(back.resolve, None);
4770    }
4771
4772    #[test]
4773    fn a_well_formed_resolver_and_an_unresolved_action_pass_validation() {
4774        let unresolved = ScheduledAction {
4775            resolve: None,
4776            kind: ActionKind::Send,
4777            ..resolved_action()
4778        };
4779        assert_eq!(
4780            validate_session_resolvers(vec![unresolved, resolved_action()]),
4781            Ok(())
4782        );
4783    }
4784
4785    #[test]
4786    fn a_quote_stamp_may_rewrite_a_transaction_repeated_per_slot() {
4787        let stamped = ScheduledAction {
4788            anchor: ActionAnchor::BeforeSlot { slots: vec![5, 6] },
4789            transactions: vec!["dGVzdA==".to_string(); 2],
4790            resolve: Some(TxResolver::QuoteStamp),
4791            ..resolved_action()
4792        };
4793        assert_eq!(validate_session_resolvers(vec![stamped]), Ok(()));
4794    }
4795
4796    #[rstest]
4797    #[case::send(
4798        ScheduledAction { kind: ActionKind::Send, ..resolved_action() },
4799        TxResolverError::Send,
4800    )]
4801    #[case::no_transactions(
4802        ScheduledAction { transactions: Vec::new(), ..resolved_action() },
4803        TxResolverError::TransactionCount { got: 0 },
4804    )]
4805    #[case::two_transactions(
4806        ScheduledAction { transactions: vec!["dGVzdA==".to_string(); 2], ..resolved_action() },
4807        TxResolverError::TransactionCount { got: 2 },
4808    )]
4809    #[case::feeds_reroute(
4810        ScheduledAction { feeds_reroute: true, ..resolved_action() },
4811        TxResolverError::FeedsReroute,
4812    )]
4813    #[case::quote_stamp_without_transactions(
4814        ScheduledAction { transactions: Vec::new(), resolve: Some(TxResolver::QuoteStamp), ..resolved_action() },
4815        TxResolverError::NoTransactions,
4816    )]
4817    #[case::requote_without_transactions(
4818        ScheduledAction { transactions: Vec::new(), resolve: Some(requote()), ..resolved_action() },
4819        TxResolverError::NoTransactions,
4820    )]
4821    #[case::requote_feeding_reroute(
4822        ScheduledAction { feeds_reroute: true, resolve: Some(requote()), ..resolved_action() },
4823        TxResolverError::FeedsReroute,
4824    )]
4825    fn a_resolver_on_an_action_it_cannot_rewrite_is_rejected_at_its_index(
4826        #[case] action: ScheduledAction,
4827        #[case] expected: TxResolverError,
4828    ) {
4829        assert_eq!(
4830            validate_session_resolvers(vec![resolved_action(), action]),
4831            Err(ActionResolveError {
4832                action: 1,
4833                source: expected,
4834            })
4835        );
4836    }
4837
4838    #[rstest]
4839    #[case::empty(Vec::new(), ArrayKeyIndicesError::Empty)]
4840    #[case::duplicate(vec![6, 7, 6], ArrayKeyIndicesError::Duplicate { index: 6 })]
4841    fn array_key_indices_refuse_an_empty_or_repeating_list(
4842        #[case] indices: Vec<u8>,
4843        #[case] expected: ArrayKeyIndicesError,
4844    ) {
4845        assert_eq!(ArrayKeyIndices::try_from(indices), Err(expected));
4846    }
4847
4848    #[test]
4849    fn a_resolver_with_unusable_array_key_indices_fails_to_deserialize() {
4850        let json = serde_json::json!({
4851            "type": "liquidityArrays",
4852            "pool": address(1).to_string(),
4853            "inputMint": address(2).to_string(),
4854            "arrayKeyIndices": [6, 7, 6],
4855        });
4856        assert!(serde_json::from_value::<TxResolver>(json).is_err());
4857    }
4858
4859    fn diagnostic_probe() -> DiagnosticProbeParams {
4860        DiagnosticProbeParams {
4861            anchor: ActionAnchor::AfterEverySlot {
4862                every_n_slots: NonZeroU64::MIN,
4863            },
4864            markets: vec![address(1), address(2)],
4865            usd_values: vec![100, 25_000],
4866            label: Some("depth-0".to_owned()),
4867            pairs: Vec::new(),
4868            candidates: Vec::new(),
4869            candidate_pairs: Vec::new(),
4870            within: None,
4871        }
4872    }
4873
4874    fn with_candidate(market: u8, pairs: Vec<[Address; 2]>) -> DiagnosticProbeParams {
4875        DiagnosticProbeParams {
4876            candidates: vec![DiagnosticCandidate {
4877                market: address(market),
4878                owner: address(20),
4879                address_lookup_table: None,
4880            }],
4881            candidate_pairs: pairs,
4882            ..diagnostic_probe()
4883        }
4884    }
4885
4886    fn paired(market: u8, pairs: Vec<[Address; 2]>) -> DiagnosticProbeParams {
4887        DiagnosticProbeParams {
4888            pairs: vec![DiagnosticMarketPairs {
4889                market: address(market),
4890                pairs,
4891            }],
4892            ..diagnostic_probe()
4893        }
4894    }
4895
4896    #[rstest]
4897    #[case::no_markets(DiagnosticProbeParams { markets: Vec::new(), ..diagnostic_probe() })]
4898    #[case::no_usd_values(DiagnosticProbeParams { usd_values: Vec::new(), ..diagnostic_probe() })]
4899    #[case::too_many_markets(DiagnosticProbeParams {
4900        markets: (0..=MAX_DIAGNOSTIC_MARKETS as u8).map(address).collect(),
4901        ..diagnostic_probe()
4902    })]
4903    #[case::too_many_usd_values(DiagnosticProbeParams {
4904        usd_values: (1..=MAX_DIAGNOSTIC_USD_VALUES as u32 + 1).collect(),
4905        ..diagnostic_probe()
4906    })]
4907    #[case::zero_usd_value(DiagnosticProbeParams { usd_values: vec![0, 100], ..diagnostic_probe() })]
4908    #[case::duplicate_market(DiagnosticProbeParams {
4909        markets: vec![address(1), address(1)],
4910        ..diagnostic_probe()
4911    })]
4912    #[case::before_slot(DiagnosticProbeParams {
4913        anchor: ActionAnchor::BeforeSlot { slots: vec![1] },
4914        ..diagnostic_probe()
4915    })]
4916    #[case::before_every_slot(DiagnosticProbeParams {
4917        anchor: ActionAnchor::BeforeEverySlot { every_n_slots: NonZeroU64::MIN },
4918        ..diagnostic_probe()
4919    })]
4920    #[case::pairs_of_an_unprobed_market(paired(3, vec![[address(7), address(8)]]))]
4921    #[case::no_pairs(paired(1, Vec::new()))]
4922    #[case::too_many_pairs(paired(
4923        1,
4924        (0..=MAX_DIAGNOSTIC_MARKET_PAIRS as u8)
4925            .map(|mint| [address(7), address(mint + 8)])
4926            .collect(),
4927    ))]
4928    #[case::self_pair(paired(1, vec![[address(7), address(7)]]))]
4929    #[case::market_paired_twice(DiagnosticProbeParams {
4930        pairs: [
4931            paired(1, vec![[address(7), address(8)]]).pairs,
4932            paired(1, vec![[address(7), address(9)]]).pairs,
4933        ]
4934        .concat(),
4935        ..diagnostic_probe()
4936    })]
4937    #[case::candidate_repeating_a_market(with_candidate(1, vec![[address(7), address(8)]]))]
4938    #[case::candidate_without_pairs(with_candidate(3, Vec::new()))]
4939    #[case::candidate_self_pair(with_candidate(3, vec![[address(7), address(7)]]))]
4940    #[case::markets_and_candidates_over_the_ceiling(DiagnosticProbeParams {
4941        markets: (0..MAX_DIAGNOSTIC_MARKETS as u8).map(address).collect(),
4942        ..with_candidate(200, vec![[address(7), address(8)]])
4943    })]
4944    fn diagnostic_probes_reject_invalid_shapes(#[case] probe: DiagnosticProbeParams) {
4945        assert!(probe.validate().is_err());
4946    }
4947
4948    #[rstest]
4949    #[case::without_pairs(diagnostic_probe(), serde_json::json!({
4950        "anchor": diagnostic_probe().anchor,
4951        "markets": [address(1).to_string(), address(2).to_string()],
4952        "usdValues": [100, 25_000],
4953        "label": "depth-0",
4954    }))]
4955    #[case::with_pairs(paired(1, vec![[address(7), address(8)]]), serde_json::json!({
4956        "anchor": diagnostic_probe().anchor,
4957        "markets": [address(1).to_string(), address(2).to_string()],
4958        "usdValues": [100, 25_000],
4959        "label": "depth-0",
4960        "pairs": [{
4961            "market": address(1).to_string(),
4962            "pairs": [[address(7).to_string(), address(8).to_string()]],
4963        }],
4964    }))]
4965    #[case::with_candidates(with_candidate(3, vec![[address(7), address(8)]]), serde_json::json!({
4966        "anchor": diagnostic_probe().anchor,
4967        "markets": [address(1).to_string(), address(2).to_string()],
4968        "usdValues": [100, 25_000],
4969        "label": "depth-0",
4970        "candidates": [{
4971            "market": address(3).to_string(),
4972            "owner": address(20).to_string(),
4973        }],
4974        "candidatePairs": [[address(7).to_string(), address(8).to_string()]],
4975    }))]
4976    fn a_diagnostic_probe_round_trips_its_wire_json(
4977        #[case] probe: DiagnosticProbeParams,
4978        #[case] wire: serde_json::Value,
4979    ) {
4980        assert_eq!(serde_json::to_value(&probe).unwrap(), wire);
4981        assert_eq!(
4982            serde_json::from_value::<DiagnosticProbeParams>(wire).unwrap(),
4983            probe
4984        );
4985    }
4986
4987    #[rstest]
4988    #[case::markets_only(diagnostic_probe())]
4989    #[case::paired(paired(1, vec![[address(7), address(8)]]))]
4990    #[case::candidates_only(DiagnosticProbeParams {
4991        markets: Vec::new(),
4992        ..with_candidate(3, vec![[address(7), address(8)]])
4993    })]
4994    #[case::after_slot(DiagnosticProbeParams {
4995        anchor: ActionAnchor::AfterSlot { slots: vec![1, 2] },
4996        ..diagnostic_probe()
4997    })]
4998    fn diagnostic_probes_accept_valid_shapes(#[case] probe: DiagnosticProbeParams) {
4999        assert!(probe.validate().is_ok());
5000    }
5001
5002    /// The shapes the rejections above are variations of.
5003    #[test]
5004    fn override_actions_accept_a_static_and_a_computed_shape() {
5005        assert!(decode_override_actions(&[valid()]).is_ok());
5006        // Transactions make the contribution computed rather than static — still valid,
5007        // just not resolvable until the action runs.
5008        assert!(
5009            decode_override_actions(&[ScheduledAction {
5010                transactions: vec!["dGVzdA==".to_string()],
5011                ..valid()
5012            }])
5013            .is_ok()
5014        );
5015    }
5016
5017    #[test]
5018    fn override_actions_merge_account_wise_later_wins() {
5019        let entry = |lamports| AccountData {
5020            lamports,
5021            ..override_entry(address(9), false)
5022        };
5023        let slot_action = |slots, account, lamports| {
5024            override_action(ActionAnchor::BeforeSlot { slots }, account, entry(lamports))
5025        };
5026        let actions = [
5027            slot_action(vec![5, 7], address(1), 1),
5028            slot_action(vec![5], address(2), 2),
5029            slot_action(vec![5], address(1), 3),
5030            ScheduledAction {
5031                anchor: ActionAnchor::AfterSlot { slots: vec![5] },
5032                kind: ActionKind::Simulate,
5033                feeds_reroute: false,
5034                transactions: vec!["dGVzdA==".to_string()],
5035                account_overrides: AccountModifications::default(),
5036                return_accounts: Vec::new(),
5037                label: None,
5038                resolve: None,
5039                within: None,
5040            },
5041        ];
5042        let schedule = decode_override_actions(&actions).unwrap();
5043        assert_eq!(schedule.slots().collect::<Vec<_>>(), vec![5, 7]);
5044        let lamports_at = |key, slot| {
5045            schedule
5046                .active_for(&key, slot)
5047                .map(|account| account.lamports())
5048        };
5049        assert_eq!(lamports_at(address(1), 5), Some(3));
5050        assert_eq!(lamports_at(address(2), 5), Some(2));
5051        assert_eq!(lamports_at(address(1), 7), Some(1));
5052    }
5053
5054    #[test]
5055    fn computed_override_resolution_preserves_action_order_and_failure() {
5056        let key = address(1);
5057        let static_action = |lamports| {
5058            override_action(
5059                ActionAnchor::BeforeSlot { slots: vec![5] },
5060                key,
5061                AccountData {
5062                    lamports,
5063                    ..override_entry(address(9), false)
5064                },
5065            )
5066        };
5067        let computed_action = || ScheduledAction {
5068            transactions: vec!["dGVzdA==".to_string()],
5069            ..static_action(2)
5070        };
5071
5072        let computed_last =
5073            decode_override_actions(&[static_action(1), computed_action()]).unwrap();
5074        computed_last
5075            .resolve(5, 1, Some(HashMap::from([(key, shared_account(2))])))
5076            .unwrap();
5077        assert_eq!(
5078            computed_last.active_for(&key, 5).map(|a| a.lamports()),
5079            Some(2)
5080        );
5081
5082        let static_last = decode_override_actions(&[computed_action(), static_action(3)]).unwrap();
5083        static_last
5084            .resolve(5, 0, Some(HashMap::from([(key, shared_account(2))])))
5085            .unwrap();
5086        assert_eq!(
5087            static_last.active_for(&key, 5).map(|a| a.lamports()),
5088            Some(3)
5089        );
5090
5091        let failed = decode_override_actions(&[static_action(1), computed_action()]).unwrap();
5092        failed.resolve(5, 1, None).unwrap();
5093        assert_eq!(failed.active_for(&key, 5).map(|a| a.lamports()), Some(1));
5094        assert!(failed.resolve(5, 1, None).is_err(), "resolving twice");
5095    }
5096
5097    fn shared_account(lamports: u64) -> AccountSharedData {
5098        AccountSharedData::from(solana_account::Account {
5099            lamports,
5100            data: vec![1],
5101            owner: address(9),
5102            executable: false,
5103            rent_epoch: 0,
5104        })
5105    }
5106
5107    fn carry_forward_schedule() -> (Address, Address, OverrideSchedule) {
5108        let (a, b) = (address(1), address(2));
5109        let schedule = OverrideSchedule::from(BTreeMap::from([
5110            (10, HashMap::from([(a, shared_account(1))])),
5111            (
5112                20,
5113                HashMap::from([(a, shared_account(2)), (b, shared_account(9))]),
5114            ),
5115        ]));
5116        (a, b, schedule)
5117    }
5118
5119    #[test]
5120    fn override_schedule_resolves_carry_forward_per_account() {
5121        let (a, b, schedule) = carry_forward_schedule();
5122
5123        assert!(schedule.active_for(&a, 9).is_none());
5124        let cases = [
5125            (9, None, None),
5126            (10, Some(1), None),
5127            (15, Some(1), None),
5128            (20, Some(2), Some(9)),
5129            (u64::MAX, Some(2), Some(9)),
5130        ];
5131        for (slot, want_a, want_b) in cases {
5132            assert_eq!(
5133                schedule
5134                    .active_for(&a, slot)
5135                    .map(|account| account.lamports()),
5136                want_a,
5137                "active_for a at {slot}"
5138            );
5139            let active = schedule.active_at(slot);
5140            assert_eq!(
5141                active.get(&a).map(ReadableAccount::lamports),
5142                want_a,
5143                "active_at a at {slot}"
5144            );
5145            assert_eq!(
5146                active.get(&b).map(ReadableAccount::lamports),
5147                want_b,
5148                "active_at b at {slot}"
5149            );
5150        }
5151    }
5152
5153    #[test]
5154    fn newly_active_yields_final_values_in_window() {
5155        let (a, b, schedule) = carry_forward_schedule();
5156
5157        let newly: HashMap<_, _> = schedule.newly_active(Some(10), 20).into_iter().collect();
5158        assert_eq!(newly.len(), 2);
5159        assert_eq!(newly[&a].lamports(), 2);
5160        assert_eq!(newly[&b].lamports(), 9);
5161        let spanning: HashMap<_, _> = schedule.newly_active(None, 20).into_iter().collect();
5162        assert_eq!(spanning[&a].lamports(), 2, "later slot wins");
5163        assert_eq!(schedule.newly_active(None, 15).len(), 1);
5164    }
5165
5166    #[test]
5167    fn reroute_filter_round_trips_camel_case() {
5168        let filter = RerouteFilter {
5169            pairs: BTreeSet::from([MintPair::new(address(1), address(2))]),
5170        };
5171        let json = serde_json::to_value(&filter).unwrap();
5172        assert!(
5173            json["pairs"][0][0].is_string() && json["pairs"][0][1].is_string(),
5174            "a pair serializes as two base58 strings: {json}"
5175        );
5176        let back: RerouteFilter = serde_json::from_value(json).unwrap();
5177        assert_eq!(back, filter);
5178    }
5179
5180    /// The set lookup is only direction-agnostic because construction normalizes, and
5181    /// values arriving over the wire have to be normalized on that path too.
5182    #[test]
5183    fn mint_pairs_are_normalized_however_they_are_built() {
5184        let (one, other) = (address(1), address(2));
5185        assert_eq!(MintPair::new(one, other), MintPair::new(other, one));
5186
5187        let reversed: MintPair =
5188            serde_json::from_value(serde_json::json!([other.to_string(), one.to_string()]))
5189                .unwrap();
5190        assert_eq!(reversed, MintPair::new(one, other));
5191    }
5192
5193    #[test]
5194    fn fail_fast_divergence_kind_str_round_trips() {
5195        for kind in [
5196            FailFastDivergenceKind::AnyNonBenign,
5197            FailFastDivergenceKind::Tracked,
5198        ] {
5199            assert_eq!(
5200                FailFastDivergenceKind::from_str_opt(kind.as_str()),
5201                Some(kind)
5202            );
5203        }
5204        assert_eq!(FailFastDivergenceKind::from_str_opt("nonsense"), None);
5205        assert_eq!(
5206            FailFastDivergenceKind::default(),
5207            FailFastDivergenceKind::AnyNonBenign
5208        );
5209    }
5210
5211    #[test]
5212    fn bundle_not_found_is_terminal_and_descriptive() {
5213        let error = BacktestError::BundleNotFound {
5214            start_slot: 100,
5215            end_slot: 600,
5216        };
5217
5218        assert!(error.is_terminal());
5219        assert_eq!(
5220            error.to_string(),
5221            "block bundle not found for start_slot=100, end_slot=600"
5222        );
5223    }
5224
5225    #[test]
5226    fn no_produced_blocks_is_terminal_and_descriptive() {
5227        let error = BacktestError::NoProducedBlocksInRange {
5228            start_slot: 100,
5229            end_slot: 100,
5230        };
5231
5232        assert!(error.is_terminal());
5233        // placement-e2e matches this phrase to classify the failure as
5234        // transient; keep it stable.
5235        assert_eq!(
5236            error.to_string(),
5237            "no produced blocks in requested range 100..=100; slot(s) may be skipped onchain"
5238        );
5239    }
5240
5241    #[test]
5242    fn session_name_taken_is_not_terminal_and_names_the_session() {
5243        let error = BacktestError::SessionNameTaken {
5244            session_name: "my-run".to_string(),
5245        };
5246
5247        assert!(!error.is_terminal());
5248        assert_eq!(error.to_string(), "session name 'my-run' is already in use");
5249    }
5250
5251    #[rstest]
5252    #[case::no_produced_blocks(BacktestError::NoProducedBlocksInRange { start_slot: 1, end_slot: 2 }, true)]
5253    #[case::programdata_not_deployed(BacktestError::ProgramdataNotDeployed { address: "x".into() }, true)]
5254    #[case::bundle_not_found(BacktestError::BundleNotFound { start_slot: 1, end_slot: 2 }, false)]
5255    #[case::internal(BacktestError::Internal { error: "x".into() }, false)]
5256    #[case::cut(BacktestError::Cut { slot: 1 }, false)]
5257    fn refusals_are_the_terminal_errors_a_fresh_session_meets_again(
5258        #[case] error: BacktestError,
5259        #[case] refusal: bool,
5260    ) {
5261        assert!(error.is_terminal());
5262        assert_eq!(error.is_refusal(), refusal);
5263    }
5264
5265    fn create_request(
5266        body: serde_json::Value,
5267    ) -> Result<CreateBacktestSessionRequestOptions, InvalidSessionName> {
5268        serde_json::from_value::<CreateBacktestSessionRequest>(body)
5269            .expect("decode create request")
5270            .try_into_request_options()
5271    }
5272
5273    #[test]
5274    fn create_requests_from_older_clients_decode_without_a_name() {
5275        let v0 = create_request(serde_json::json!({"startSlot": 1, "endSlot": 2})).expect("v0");
5276        assert!(!v0.parallel);
5277        assert_eq!(v0.name, None);
5278
5279        let v1 =
5280            create_request(serde_json::json!({"startSlot": 1, "endSlot": 2, "parallel": true}))
5281                .expect("v1");
5282        assert!(v1.parallel);
5283        assert_eq!(v1.name, None);
5284    }
5285
5286    #[test]
5287    fn named_create_request_without_parallel_keeps_its_name() {
5288        let options = create_request(serde_json::json!({
5289            "startSlot": 1,
5290            "endSlot": 2,
5291            "name": "my-run",
5292            "createToken": "token-1",
5293        }))
5294        .expect("valid name");
5295
5296        assert!(!options.parallel);
5297        assert_eq!(options.request.end_slot, 2);
5298        let requested = options.name.expect("name");
5299        assert_eq!(requested.name.as_str(), "my-run");
5300        assert_eq!(
5301            requested.create_token.as_ref().map(CreateToken::as_str),
5302            Some("token-1")
5303        );
5304    }
5305
5306    #[test]
5307    fn create_request_with_an_invalid_name_is_rejected() {
5308        let error = create_request(serde_json::json!({
5309            "startSlot": 1,
5310            "endSlot": 2,
5311            "name": "my run",
5312        }))
5313        .expect_err("invalid name");
5314        assert!(error.to_string().contains("'my run'"), "{error}");
5315    }
5316
5317    #[test]
5318    fn create_requests_without_a_name_serialize_as_before() {
5319        let params = CreateSessionParams::builder()
5320            .start_slot(1)
5321            .end_slot(2)
5322            .build();
5323        let params_json = serde_json::to_value(&params).expect("encode params");
5324
5325        let v0 = serde_json::to_value(CreateBacktestSessionRequest::from(params.clone()))
5326            .expect("encode v0");
5327        assert_eq!(v0, params_json);
5328
5329        let v1 = serde_json::to_value(CreateBacktestSessionRequest::from(
5330            CreateBacktestSessionRequestV1 {
5331                request: params,
5332                parallel: true,
5333                name: None,
5334                create_token: None,
5335            },
5336        ))
5337        .expect("encode v1");
5338        let mut expected = params_json;
5339        expected["parallel"] = true.into();
5340        assert_eq!(v1, expected);
5341    }
5342
5343    #[test]
5344    fn a_v0_request_becomes_a_v2_message_with_the_same_fields() {
5345        let params = CreateSessionParams::builder()
5346            .start_slot(1)
5347            .end_slot(2)
5348            .send_summary(true)
5349            .build();
5350        let v1 =
5351            CreateBacktestSessionRequestV1::from(CreateBacktestSessionRequest::V0(params.clone()));
5352        assert!(!v1.parallel);
5353        assert!(v1.name.is_none() && v1.create_token.is_none());
5354
5355        let message =
5356            serde_json::to_value(BacktestRequest::CreateBacktestSessionV2(v1)).expect("encode");
5357        let mut expected = serde_json::to_value(&params).expect("encode params");
5358        expected["parallel"] = false.into();
5359        assert_eq!(message["method"], "createBacktestSessionV2");
5360        assert_eq!(message["params"], expected);
5361    }
5362
5363    #[test]
5364    fn session_responses_omit_an_absent_name_and_decode_without_one() {
5365        let created = BacktestResponse::SessionCreated {
5366            session_id: SessionId::new(),
5367            rpc_endpoint: "/backtest/s".to_string(),
5368            task_id: None,
5369            session_name: None,
5370        };
5371        let json = serde_json::to_string(&created).expect("encode");
5372        assert!(!json.contains("session_name"), "{json}");
5373        let decoded: BacktestResponse = serde_json::from_str(&json).expect("decode");
5374        assert!(matches!(
5375            decoded,
5376            BacktestResponse::SessionCreated {
5377                session_name: None,
5378                ..
5379            }
5380        ));
5381
5382        let parallel = BacktestResponse::SessionsCreatedV2 {
5383            control_session_id: ControlSessionId::new(),
5384            control_session_name: None,
5385            session_ids: Vec::new(),
5386            task_ids: Vec::new(),
5387            start_slots: Vec::new(),
5388            end_slots: Vec::new(),
5389        };
5390        let json = serde_json::to_string(&parallel).expect("encode");
5391        assert!(!json.contains("control_session_name"), "{json}");
5392        let decoded: BacktestResponse = serde_json::from_str(&json).expect("decode");
5393        assert!(matches!(
5394            decoded,
5395            BacktestResponse::SessionsCreatedV2 {
5396                control_session_name: None,
5397                ..
5398            }
5399        ));
5400    }
5401
5402    #[test]
5403    fn bundle_build_request_optional_fields_default_to_none() {
5404        let req: BundleBuildRequest =
5405            serde_json::from_str(r#"{"start_slot":1,"end_slot":2}"#).expect("parse");
5406        assert_eq!((req.start_slot, req.end_slot), (1, 2));
5407        assert_eq!(req.bundle_size, None);
5408        assert_eq!(req.idempotency_key, None);
5409    }
5410
5411    #[test]
5412    fn bundle_build_request_parses_optional_fields() {
5413        let req: BundleBuildRequest = serde_json::from_str(
5414            r#"{"start_slot":1,"end_slot":2,"bundle_size":500,"idempotency_key":"abc"}"#,
5415        )
5416        .expect("parse");
5417        assert_eq!(req.bundle_size, Some(500));
5418        assert_eq!(req.idempotency_key.as_deref(), Some("abc"));
5419    }
5420
5421    #[test]
5422    fn bundle_build_status_serde_round_trips_with_snake_case() {
5423        let cases = [
5424            (BundleBuildStatus::Completed, "\"completed\""),
5425            (BundleBuildStatus::Failed, "\"failed\""),
5426            (BundleBuildStatus::InProgress, "\"in_progress\""),
5427            (
5428                BundleBuildStatus::NeedsInvestigation,
5429                "\"needs_investigation\"",
5430            ),
5431        ];
5432        for (status, expected) in cases {
5433            assert_eq!(serde_json::to_string(&status).unwrap(), expected);
5434            assert_eq!(
5435                serde_json::from_str::<BundleBuildStatus>(expected).unwrap(),
5436                status
5437            );
5438            assert_eq!(status.as_str(), expected.trim_matches('"'));
5439        }
5440        assert!(serde_json::from_str::<BundleBuildStatus>("\"queued\"").is_err());
5441    }
5442
5443    #[test]
5444    fn bundle_build_request_without_kind_deserializes_as_blocks() {
5445        // An old client's payload must keep meaning a plain block build.
5446        let request: BundleBuildRequest =
5447            serde_json::from_str(r#"{"start_slot":100,"end_slot":200}"#).unwrap();
5448        assert_eq!(request.kind, BundleKind::Blocks);
5449    }
5450
5451    #[test]
5452    fn bundle_kind_round_trips_over_serde_and_as_str() {
5453        for kind in [BundleKind::Blocks, BundleKind::AccountState] {
5454            let json = serde_json::to_string(&kind).unwrap();
5455            assert_eq!(json, format!("\"{}\"", kind.as_str()));
5456            assert_eq!(serde_json::from_str::<BundleKind>(&json).unwrap(), kind);
5457            // The store round-trips through `as_str`, not serde, so the two
5458            // maps have to agree for a stored kind to read back.
5459            assert_eq!(BundleKind::from_str_opt(kind.as_str()), Some(kind));
5460        }
5461        assert!(serde_json::from_str::<BundleKind>("\"accountState\"").is_err());
5462        assert_eq!(BundleKind::from_str_opt("accountState"), None);
5463    }
5464
5465    #[test]
5466    fn bundle_build_request_carries_kind_through_serde() {
5467        let request = BundleBuildRequest {
5468            start_slot: 100,
5469            end_slot: 200,
5470            kind: BundleKind::AccountState,
5471            ..Default::default()
5472        };
5473        let json = serde_json::to_string(&request).unwrap();
5474        assert!(json.contains(r#""kind":"account_state""#), "{json}");
5475        let parsed: BundleBuildRequest = serde_json::from_str(&json).unwrap();
5476        assert_eq!(parsed.kind, BundleKind::AccountState);
5477    }
5478
5479    #[test]
5480    fn bundle_build_status_response_serializes_request_and_status() {
5481        let response = BundleBuildStatusResponse {
5482            request_id: "r".to_string(),
5483            start_slot: 100,
5484            end_slot: 200,
5485            bundle_size: Some(50),
5486            status: BundleBuildStatus::InProgress,
5487            created_at_unix_ms: 0,
5488            kind: BundleKind::Blocks,
5489            eta_secs: Some(600),
5490        };
5491        let json = serde_json::to_value(&response).unwrap();
5492        assert_eq!(json["request_id"].as_str(), Some("r"));
5493        assert_eq!(json["start_slot"].as_u64(), Some(100));
5494        assert_eq!(json["bundle_size"].as_u64(), Some(50));
5495        assert_eq!(json["status"].as_str(), Some("in_progress"));
5496        assert_eq!(json["created_at_unix_ms"].as_u64(), Some(0));
5497        assert_eq!(json["eta_secs"].as_u64(), Some(600));
5498    }
5499
5500    #[test]
5501    fn an_empty_bundles_list_is_distinct_from_an_absent_one() {
5502        // A server that predates the section sends no `bundles` at all.
5503        let absent: BundleBuildListResponse = serde_json::from_str(r#"{"builds":[]}"#).unwrap();
5504        let empty: BundleBuildListResponse =
5505            serde_json::from_str(r#"{"builds":[],"bundles":[]}"#).unwrap();
5506        assert_eq!(absent.bundles, None);
5507        assert_eq!(empty.bundles, Some(Vec::new()));
5508    }
5509
5510    #[test]
5511    fn completed_bundle_round_trips() {
5512        let bundle = CompletedBundle {
5513            start_slot: 100,
5514            end_slot: 200,
5515            kind: BundleKind::AccountState,
5516            completed_at_unix_ms: Some(1_700_000_000_000),
5517            size_bytes: Some(4_096),
5518        };
5519        let json = serde_json::to_string(&bundle).unwrap();
5520        assert!(json.contains(r#""kind":"account_state""#), "{json}");
5521        assert_eq!(
5522            serde_json::from_str::<CompletedBundle>(&json).unwrap(),
5523            bundle
5524        );
5525
5526        let sparse = r#"{"start_slot":1,"end_slot":2,"kind":"blocks"}"#;
5527        let parsed: CompletedBundle = serde_json::from_str(sparse).unwrap();
5528        assert_eq!(parsed.completed_at_unix_ms, None);
5529        assert_eq!(parsed.size_bytes, None);
5530    }
5531
5532    #[test]
5533    fn available_range_reads_a_server_that_predates_kind_and_scope() {
5534        // Deploys are not atomic: a new client must not fail on the old shape.
5535        let json = r#"{
5536            "bundle_start_slot": 100,
5537            "bundle_start_slot_utc": null,
5538            "max_bundle_end_slot": 200,
5539            "max_bundle_end_slot_utc": null,
5540            "max_bundle_size": 101
5541        }"#;
5542        let parsed: AvailableRange = serde_json::from_str(json).unwrap();
5543        assert_eq!(parsed.bundle_start_slot, 100);
5544        assert_eq!(parsed.kind, None);
5545        assert_eq!(parsed.scope, None);
5546    }
5547
5548    #[test]
5549    fn available_range_ignores_fields_it_does_not_know() {
5550        // The other direction: an old client against a newer server.
5551        let json = r#"{"bundle_start_slot": 1, "some_future_field": "x"}"#;
5552        assert_eq!(
5553            serde_json::from_str::<AvailableRange>(json)
5554                .unwrap()
5555                .bundle_start_slot,
5556            1
5557        );
5558    }
5559
5560    #[test]
5561    fn available_range_labels_round_trip() {
5562        let range = AvailableRange {
5563            bundle_start_slot: 100,
5564            max_bundle_end_slot: Some(200),
5565            kind: Some(BundleKind::AccountState),
5566            scope: Some(RangeScope::User),
5567            ..Default::default()
5568        };
5569        let json = serde_json::to_string(&range).unwrap();
5570        assert!(json.contains(r#""kind":"account_state""#), "{json}");
5571        assert!(json.contains(r#""scope":"user""#), "{json}");
5572        let parsed: AvailableRange = serde_json::from_str(&json).unwrap();
5573        assert_eq!(parsed.kind, Some(BundleKind::AccountState));
5574        assert_eq!(parsed.scope, Some(RangeScope::User));
5575    }
5576
5577    #[test]
5578    fn a_modified_depth_selection_keeps_its_wire_shape() {
5579        let wire = serde_json::json!({
5580            "source": "onchain",
5581            "program_overrides": [{"program_id": address(7).to_string(), "elf": "f0VMRg=="}],
5582            "account_overrides": {
5583                address(8).to_string(): {
5584                    "data": {"data": "AQID", "encoding": "base64"},
5585                    "executable": false,
5586                    "lamports": 1,
5587                    "owner": address(9).to_string(),
5588                    "space": 3,
5589                },
5590            },
5591        });
5592        let selection: DepthSelection = serde_json::from_value(wire.clone()).expect("deserialize");
5593        assert_eq!(serde_json::to_value(&selection).expect("serialize"), wire);
5594    }
5595
5596    /// The manager hashes these bytes into the dataset's digest and the tool parses them back:
5597    /// both fields always present, in this order, each ELF keyed by its program id.
5598    #[rstest]
5599    #[case::accounts_only(BTreeMap::new(), r#"{"programs":{},"accounts":{}}"#.to_owned())]
5600    #[case::one_program(
5601        BTreeMap::from([(address(7), b"\x7fELF".to_vec())]),
5602        format!(r#"{{"programs":{{"{}":"f0VMRg=="}},"accounts":{{}}}}"#, address(7))
5603    )]
5604    fn a_depth_modifications_manifest_keeps_its_pinned_shape(
5605        #[case] programs: BTreeMap<Address, Vec<u8>>,
5606        #[case] expected: String,
5607    ) {
5608        let modifications = DepthModifications {
5609            programs,
5610            accounts: AccountModifications::default(),
5611        };
5612        assert_eq!(
5613            serde_json::to_string(&modifications).expect("serialize"),
5614            expected
5615        );
5616    }
5617
5618    fn range(start: u64, end: u64) -> AvailableRange {
5619        AvailableRange {
5620            bundle_start_slot: start,
5621            max_bundle_end_slot: Some(end),
5622            ..Default::default()
5623        }
5624    }
5625
5626    /// Each case lists the available bundles, the requested `[start, end]`, and
5627    /// the expected split — `Some(_)` for an accepted plan, `None` when the range
5628    /// is unservable and `split_range` must error.
5629    #[rstest::rstest]
5630    #[case::single(vec![range(100, 300)], 100, 300, Some(vec![(100, 300)]))]
5631    #[case::multi(
5632        vec![range(100, 200), range(201, 300), range(301, 400)],
5633        100, 300, Some(vec![(100, 200), (201, 300)])
5634    )]
5635    // Smaller bundles nested inside a larger one don't bridge the gap, but the
5636    // range is still coverable by riding the coarse series.
5637    #[case::nested(
5638        vec![range(100, 500), range(110, 150), range(150, 190), range(501, 900)],
5639        100, 900, Some(vec![(100, 500), (501, 900)])
5640    )]
5641    // A fine grid (1k bundles standing in for the 10k grid) overlapped by a
5642    // coarser, differently-aligned series: ride the fine grid, never landing on
5643    // the coarse bundle's drifted start.
5644    #[case::prefers_finer_grid(
5645        vec![range(1_000, 1_999), range(1_500, 3_400), range(2_000, 2_999), range(3_000, 3_999)],
5646        1_000, 3_999, Some(vec![(1_000, 1_999), (2_000, 2_999), (3_000, 3_999)])
5647    )]
5648    // A 50k snapshot bundle and the 10k bundles built on it share start 100: ride
5649    // the 10k grid instead of the coarse end, which would strand the cursor on a
5650    // slot no bundle starts at.
5651    #[case::shared_start_prefers_finer(
5652        vec![range(100, 150), range(100, 120), range(121, 140), range(141, 160)],
5653        100, 160, Some(vec![(100, 120), (121, 140), (141, 160)])
5654    )]
5655    // A coarse bundle (100, 200) overlaps a finer pair covering the same span:
5656    // split_range maximises parallelism, riding the fine pair (two sessions)
5657    // rather than merging onto the coarse max end (one session).
5658    #[case::coarse_overlap_prefers_finer_pair(
5659        vec![range(100, 200), range(100, 150), range(151, 160)],
5660        100, 160, Some(vec![(100, 150), (151, 160)])
5661    )]
5662    // The fine grid has a hole (nothing starts at 141), but a coarse bundle
5663    // sharing the start spans it: serve the request off the coarse bundle rather
5664    // than reporting an unsupported range.
5665    #[case::falls_back_to_coarse(
5666        vec![range(100, 160), range(100, 120), range(121, 140)],
5667        100, 160, Some(vec![(100, 160)])
5668    )]
5669    // The last bundle overshoots the requested end and is clamped.
5670    #[case::clamps_final_bundle(vec![range(100, 199), range(200, 999)], 100, 450, Some(vec![(100, 199), (200, 450)]))]
5671    // A request landing mid-bundle anchors to the covering bundle's start
5672    // (matching the server) instead of erroring as "not covered".
5673    #[case::anchors_mid_bundle(vec![range(150, 350)], 200, 300, Some(vec![(150, 300)]))]
5674    #[case::anchors_then_continues(
5675        vec![range(150, 350), range(351, 600)],
5676        200, 600, Some(vec![(150, 350), (351, 600)])
5677    )]
5678    #[case::start_inside_bundle_anchors(vec![range(200, 400)], 300, 400, Some(vec![(200, 400)]))]
5679    // Errors: a start before any bundle's coverage has no covering bundle...
5680    #[case::start_before_first_bundle(vec![range(200, 400)], 100, 400, None)]
5681    // ...the end must be reachable...
5682    #[case::end_not_covered(vec![range(100, 200)], 100, 300, None)]
5683    #[case::gap_in_coverage(vec![range(100, 200), range(210, 300)], 100, 300, None)]
5684    // Per-API-key isolation: a user's finer bundles and a coarse GLOBAL bundle
5685    // sharing a start are fed as SEPARATE entries (never merged on snapshot_slot,
5686    // which would keep only the max end). split_range set-unions the ends and
5687    // rides the finer user grid — a regression guard against re-merging.
5688    #[case::user_and_global_ranges_not_collapsed(
5689        vec![range(100, 200), range(100, 150), range(151, 200)],
5690        100, 200, Some(vec![(100, 150), (151, 200)])
5691    )]
5692    fn split_range_cases(
5693        #[case] ranges: Vec<AvailableRange>,
5694        #[case] start: u64,
5695        #[case] end: u64,
5696        #[case] expected: Option<Vec<(u64, u64)>>,
5697    ) {
5698        match expected {
5699            Some(expected) => assert_eq!(
5700                split_range(
5701                    &ranges,
5702                    SlotRange::new_unchecked(start, end),
5703                    BundleKind::Blocks
5704                )
5705                .unwrap(),
5706                expected
5707            ),
5708            None => assert!(
5709                split_range(
5710                    &ranges,
5711                    SlotRange::new_unchecked(start, end),
5712                    BundleKind::Blocks
5713                )
5714                .is_err()
5715            ),
5716        }
5717    }
5718
5719    /// Rides the coarsest series that still reaches the end.
5720    #[rstest]
5721    #[case::rides_a_coarse_bundle_over_a_finer_pair(
5722        vec![range(100, 200), range(100, 150), range(151, 160)],
5723        100, 160, vec![(100, 160)]
5724    )]
5725    #[case::never_strands_the_walk(
5726        vec![range(100, 150), range(100, 120), range(121, 140), range(141, 160)],
5727        100, 160, vec![(100, 120), (121, 140), (141, 160)]
5728    )]
5729    fn split_range_fewest_cases(
5730        #[case] ranges: Vec<AvailableRange>,
5731        #[case] start: u64,
5732        #[case] end: u64,
5733        #[case] expected: Vec<(u64, u64)>,
5734    ) {
5735        assert_eq!(
5736            split_range_fewest(
5737                &ranges,
5738                SlotRange::new_unchecked(start, end),
5739                BundleKind::Blocks
5740            ),
5741            Ok(expected)
5742        );
5743    }
5744
5745    fn account_state_range(start: u64, end: u64) -> AvailableRange {
5746        AvailableRange {
5747            kind: Some(BundleKind::AccountState),
5748            ..range(start, end)
5749        }
5750    }
5751
5752    #[test]
5753    fn a_replay_split_rides_the_recordings_not_a_finer_block_grid() {
5754        // The finer block grid wins on piece count, which is precisely what would
5755        // hand a replay run sub-ranges nothing ever recorded.
5756        let ranges = vec![
5757            range(100, 149),
5758            range(150, 199),
5759            account_state_range(100, 199),
5760        ];
5761        let requested = SlotRange::new_unchecked(100, 199);
5762
5763        assert_eq!(
5764            split_range(&ranges, requested, BundleKind::Blocks).unwrap(),
5765            [(100, 149), (150, 199)]
5766        );
5767        assert_eq!(
5768            split_range(&ranges, requested, BundleKind::AccountState).unwrap(),
5769            [(100, 199)]
5770        );
5771    }
5772
5773    #[test]
5774    fn a_replay_split_tiles_consecutive_recordings() {
5775        let ranges = vec![account_state_range(100, 199), account_state_range(200, 299)];
5776        assert_eq!(
5777            split_range(
5778                &ranges,
5779                SlotRange::new_unchecked(100, 299),
5780                BundleKind::AccountState
5781            )
5782            .unwrap(),
5783            [(100, 199), (200, 299)]
5784        );
5785    }
5786
5787    #[test]
5788    fn a_replay_split_ends_short_of_a_recording() {
5789        // A recording is read slot by slot, so a session stops wherever asked
5790        // inside it — the same as a block session does inside its bundle.
5791        let requested = SlotRange::new_unchecked(100, 150);
5792        assert_eq!(
5793            split_range(&[range(100, 199)], requested, BundleKind::Blocks).unwrap(),
5794            [(100, 150)]
5795        );
5796        assert_eq!(
5797            split_range(
5798                &[account_state_range(100, 199)],
5799                requested,
5800                BundleKind::AccountState
5801            )
5802            .unwrap(),
5803            [(100, 150)]
5804        );
5805    }
5806
5807    #[test]
5808    fn a_replay_split_ends_short_of_its_last_recording() {
5809        // Only the last sub-range may stop mid-recording; the ones before it
5810        // still have to hand over on the very next slot.
5811        let ranges = vec![account_state_range(100, 199), account_state_range(200, 299)];
5812        assert_eq!(
5813            split_range(
5814                &ranges,
5815                SlotRange::new_unchecked(100, 250),
5816                BundleKind::AccountState
5817            )
5818            .unwrap(),
5819            [(100, 199), (200, 250)]
5820        );
5821    }
5822
5823    #[test]
5824    fn a_replay_split_tiles_a_one_slot_recording() {
5825        // A series whose last split begins on the requested end records exactly
5826        // one slot.
5827        let ranges = vec![account_state_range(100, 249), account_state_range(250, 250)];
5828        assert_eq!(
5829            split_range(
5830                &ranges,
5831                SlotRange::new_unchecked(100, 250),
5832                BundleKind::AccountState
5833            )
5834            .unwrap(),
5835            [(100, 249), (250, 250)]
5836        );
5837    }
5838
5839    #[test]
5840    fn a_replay_split_anchors_a_mid_recording_start() {
5841        // A mid-bundle start anchors to the bundle covering it, whichever kind
5842        // the walk rides — the two differ in the bundles they read, not in the
5843        // ranges they admit.
5844        let requested = SlotRange::new_unchecked(150, 199);
5845        assert_eq!(
5846            split_range(&[range(100, 199)], requested, BundleKind::Blocks).unwrap(),
5847            [(100, 199)]
5848        );
5849        assert_eq!(
5850            split_range(
5851                &[account_state_range(100, 199)],
5852                requested,
5853                BundleKind::AccountState
5854            )
5855            .unwrap(),
5856            [(100, 199)]
5857        );
5858    }
5859
5860    #[test]
5861    fn a_replay_split_refuses_a_start_no_recording_covers() {
5862        let error = split_range(
5863            &[account_state_range(200, 299)],
5864            SlotRange::new_unchecked(100, 299),
5865            BundleKind::AccountState,
5866        )
5867        .expect_err("no recording covers 100");
5868        assert!(
5869            error.contains("is not covered by any available account-state bundle"),
5870            "{error}"
5871        );
5872    }
5873
5874    #[test]
5875    fn a_replay_split_ignores_block_ranges() {
5876        let error = split_range(
5877            &[range(100, 199)],
5878            SlotRange::new_unchecked(100, 199),
5879            BundleKind::AccountState,
5880        )
5881        .expect_err("owns no recordings");
5882        assert!(error.contains("account-state bundle"), "{error}");
5883    }
5884
5885    #[test]
5886    fn blocks_mode_admits_ranges_from_a_server_that_predates_kind() {
5887        // A server predating the field omits it, and those ranges must still
5888        // split exactly as they did before the kind was consulted.
5889        let unlabelled = range(100, 199);
5890        assert_eq!(unlabelled.kind, None);
5891        assert_eq!(
5892            split_range(
5893                &[unlabelled],
5894                SlotRange::new_unchecked(100, 150),
5895                BundleKind::Blocks
5896            )
5897            .unwrap(),
5898            [(100, 150)]
5899        );
5900    }
5901
5902    /// Servable end per bundle start, as `split_range` sees it — every advertised
5903    /// end at or past its start, keyed by start.
5904    fn ends_by_start(ranges: &[AvailableRange]) -> BTreeMap<u64, BTreeSet<u64>> {
5905        let mut ends: BTreeMap<u64, BTreeSet<u64>> = BTreeMap::new();
5906        for r in ranges {
5907            if let Some(end) = r.max_bundle_end_slot
5908                && end >= r.bundle_start_slot
5909            {
5910                ends.entry(r.bundle_start_slot).or_default().insert(end);
5911            }
5912        }
5913        ends
5914    }
5915
5916    /// Independent spec for the optimum: the sub-range count of every gap-free
5917    /// split of `[cursor, end]`, found by exhaustively trying every advertised end
5918    /// at each cursor. Empty when no split aligns with the bundle starts.
5919    fn split_lengths(
5920        ends: &BTreeMap<u64, BTreeSet<u64>>,
5921        cursor: u64,
5922        end: u64,
5923    ) -> BTreeSet<usize> {
5924        ends.get(&cursor)
5925            .into_iter()
5926            .flatten()
5927            .flat_map(|&bundle_end| {
5928                if bundle_end >= end {
5929                    BTreeSet::from([1])
5930                } else {
5931                    split_lengths(ends, bundle_end + 1, end)
5932                        .into_iter()
5933                        .map(|rest| rest + 1)
5934                        .collect()
5935                }
5936            })
5937            .collect()
5938    }
5939
5940    /// Structure-independent check that a split is one the server can serve: it
5941    /// tiles `[start, end]` gap-free, every start is a real bundle start, and
5942    /// every end is within that start's largest advertised end.
5943    fn is_valid_split(
5944        split: &[(u64, u64)],
5945        ends: &BTreeMap<u64, BTreeSet<u64>>,
5946        start: u64,
5947        end: u64,
5948    ) -> bool {
5949        split.first().is_some_and(|&(s, _)| s == start)
5950            && split.last().is_some_and(|&(_, e)| e == end)
5951            && split.windows(2).all(|w| w[1].0 == w[0].1 + 1)
5952            && split.iter().all(|&(s, e)| {
5953                e >= s
5954                    && ends
5955                        .get(&s)
5956                        .and_then(|bundle_ends| bundle_ends.iter().next_back())
5957                        .is_some_and(|&max_end| e <= max_end)
5958            })
5959    }
5960
5961    type SplitFn = fn(&[AvailableRange], SlotRange, BundleKind) -> Result<Vec<(u64, u64)>, String>;
5962    type OptimumFn = fn(&BTreeSet<usize>) -> Option<&usize>;
5963
5964    /// Property test: across many randomized bundle layouts, each walk must return
5965    /// a *valid* split with its *optimal* number of sub-ranges (the most for
5966    /// `split_range`, the fewest for `split_range_fewest`) whenever one exists, and
5967    /// error exactly when none does. Deterministic (fixed LCG seed) so a failure is
5968    /// reproducible.
5969    #[rstest]
5970    #[case::most(split_range as SplitFn, BTreeSet::last as OptimumFn)]
5971    #[case::fewest(split_range_fewest as SplitFn, BTreeSet::first as OptimumFn)]
5972    fn split_range_matches_reference(#[case] walk: SplitFn, #[case] optimum: OptimumFn) {
5973        let mut seed: u64 = 0x9E3779B97F4A7C15;
5974        let mut next = || {
5975            seed = seed
5976                .wrapping_mul(6364136223846793005)
5977                .wrapping_add(1442695040888963407);
5978            seed >> 33
5979        };
5980
5981        for _ in 0..50_000 {
5982            // A small slot universe makes shared starts, overlaps, nesting, and
5983            // gaps all common.
5984            let ranges: Vec<AvailableRange> = (0..next() % 6)
5985                .map(|_| {
5986                    let start = next() % 12;
5987                    range(start, start + next() % 6) // len 0 => filtered out
5988                })
5989                .collect();
5990            let start = next() % 12;
5991            let end = start + next() % 6; // sometimes start == end, sometimes unservable
5992
5993            let got = walk(
5994                &ranges,
5995                SlotRange::new_unchecked(start, end),
5996                BundleKind::Blocks,
5997            );
5998            let ends = ends_by_start(&ranges);
5999            // split_range anchors a mid-bundle start to the covering bundle's
6000            // start, so the reference must walk from the same anchor.
6001            let anchor = ends
6002                .range(..=start)
6003                .rfind(|(_, e)| e.iter().next_back().is_some_and(|&x| x >= start))
6004                .map(|(&s, _)| s);
6005            let reference = anchor.and_then(|a| optimum(&split_lengths(&ends, a, end)).copied());
6006
6007            let layout: Vec<_> = ranges
6008                .iter()
6009                .map(|r| (r.bundle_start_slot, r.max_bundle_end_slot))
6010                .collect();
6011            match (&got, reference) {
6012                (Ok(split), Some(best)) => {
6013                    assert!(
6014                        is_valid_split(split, &ends, anchor.unwrap(), end),
6015                        "invalid split {split:?} for {layout:?} [{start},{end}]"
6016                    );
6017                    assert_eq!(
6018                        split.len(),
6019                        best,
6020                        "suboptimal split {split:?} vs {best} sub-ranges for {layout:?} [{start},{end}]"
6021                    );
6022                }
6023                (Err(_), None) => {}
6024                _ => panic!(
6025                    "disagreement: walk={got:?}, reference={reference:?} sub-ranges for {layout:?} [{start},{end}]"
6026                ),
6027            }
6028        }
6029    }
6030
6031    #[test]
6032    fn a_reroute_without_templates_omits_venue() {
6033        let json = serde_json::to_value(RerouteParams::default()).expect("serialize");
6034        assert!(json.get("directFill").is_none(), "{json}");
6035    }
6036
6037    #[test]
6038    fn venue_fields_keep_their_venue_wire_names() {
6039        let reroute = RerouteParams {
6040            venue_templates: vec![template("t")],
6041            ..Default::default()
6042        };
6043        let json = serde_json::to_value(&reroute).expect("serialize");
6044        assert_eq!(json["directFill"][0]["label"], "t", "{json}");
6045
6046        let json = serde_json::to_value(RerouteStatsReport::default()).expect("serialize");
6047        for key in [
6048            "directFillMatched",
6049            "directFillOutcomes",
6050            "directFillScored",
6051            "directFillBpsTotal",
6052            "directFillTemplates",
6053        ] {
6054            assert!(json.get(key).is_some(), "{key} missing from {json}");
6055        }
6056    }
6057
6058    #[test]
6059    fn extra_markets_cross_the_wire_as_base58() {
6060        let json = serde_json::to_value(RerouteParams::default()).expect("serialize");
6061        assert!(json.get("extraMarkets").is_none(), "{json}");
6062
6063        let reroute = RerouteParams {
6064            extra_markets: BTreeSet::from([address(7)]),
6065            ..Default::default()
6066        };
6067        let json = serde_json::to_value(&reroute).expect("serialize");
6068        assert_eq!(
6069            json["extraMarkets"],
6070            serde_json::json!([address(7).to_string()])
6071        );
6072        assert_eq!(
6073            serde_json::from_value::<RerouteParams>(json).expect("deserialize"),
6074            reroute
6075        );
6076
6077        serde_json::from_value::<RerouteParams>(serde_json::json!({
6078            "extraMarkets": ["not-an-address"]
6079        }))
6080        .expect_err("an invalid address is rejected");
6081    }
6082
6083    /// A valid template, spelled out rather than parsed: the wire twins are their own test.
6084    fn template(label: &str) -> VenueTemplate {
6085        let placeholder = Address::default();
6086        VenueTemplate {
6087            label: label.to_owned(),
6088            mode: SwapMode::ExactIn,
6089            input_mint: mints::SOL,
6090            output_mint: mints::USDC,
6091            instruction: TemplateInstruction {
6092                program_id: address(7),
6093                accounts: vec![
6094                    TemplateAccount {
6095                        address: placeholder,
6096                        writable: true,
6097                        signer: true,
6098                    },
6099                    TemplateAccount {
6100                        address: placeholder,
6101                        writable: true,
6102                        signer: false,
6103                    },
6104                    TemplateAccount {
6105                        address: placeholder,
6106                        writable: true,
6107                        signer: false,
6108                    },
6109                    TemplateAccount {
6110                        address: address(8),
6111                        writable: false,
6112                        signer: false,
6113                    },
6114                ],
6115                data: vec![0; 16],
6116            },
6117            amount_offset: 2,
6118            taker: TakerSlots {
6119                user: vec![0],
6120                input_token_account: vec![1],
6121                output_token_account: vec![2],
6122                derived: Vec::new(),
6123            },
6124            resolve: None,
6125        }
6126    }
6127
6128    /// Presence of templates is the switch, exactly as `requote` is.
6129    #[rstest]
6130    #[case::requote_alone(true, 0, false)]
6131    #[case::templates_alone(false, 1, false)]
6132    #[case::both(true, 2, false)]
6133    #[case::neither(false, 0, true)]
6134    fn a_reroute_is_a_noop_only_with_nothing_to_ask(
6135        #[case] requote: bool,
6136        #[case] templates: usize,
6137        #[case] noop: bool,
6138    ) {
6139        let reroute = RerouteParams {
6140            requote,
6141            venue_templates: (0..templates).map(|i| template(&format!("t{i}"))).collect(),
6142            ..Default::default()
6143        };
6144        assert_eq!(reroute.is_noop(), noop);
6145    }
6146
6147    /// A template-only run warms the universe its probes trade through, sidecar or not.
6148    #[rstest]
6149    #[case::templates_without_requote(false, 1, true)]
6150    #[case::requote_without_templates(true, 0, true)]
6151    #[case::nothing(false, 0, false)]
6152    fn the_account_universe_warms_for_templates_as_for_requoting(
6153        #[case] requote: bool,
6154        #[case] templates: usize,
6155        #[case] warms: bool,
6156    ) {
6157        let params = CreateSessionParams::builder()
6158            .start_slot(1)
6159            .end_slot(2)
6160            .reroute(RerouteParams {
6161                requote,
6162                venue_templates: (0..templates).map(|i| template(&format!("t{i}"))).collect(),
6163                ..Default::default()
6164            })
6165            .build();
6166        assert_eq!(params.warms_account_universe(), warms);
6167    }
6168
6169    #[rstest]
6170    #[case::a_requoted_template_without_requote(false, Some(TemplateResolver::Requote), true)]
6171    #[case::an_array_template_without_requote(
6172        false,
6173        Some(TemplateResolver::LiquidityArrays),
6174        false
6175    )]
6176    #[case::a_fixed_template_without_requote(false, None, false)]
6177    #[case::requote(true, None, true)]
6178    fn only_requoting_or_a_requoted_template_needs_the_sidecar(
6179        #[case] requote: bool,
6180        #[case] resolve: Option<TemplateResolver>,
6181        #[case] needs: bool,
6182    ) {
6183        let params = CreateSessionParams::builder()
6184            .start_slot(1)
6185            .end_slot(2)
6186            .reroute(RerouteParams {
6187                requote,
6188                venue_templates: vec![VenueTemplate {
6189                    resolve,
6190                    ..template("t")
6191                }],
6192                ..Default::default()
6193            })
6194            .build();
6195        assert_eq!(params.requires_sidecar(), needs);
6196    }
6197
6198    /// A busy create arrives as `Internal`; a bad request must never look retryable.
6199    #[rstest]
6200    #[case::capacity(BacktestError::Internal { error: "unable to start session: insufficient capacity".into() }, true)]
6201    #[case::clerk(BacktestError::ClerkError { error: "timeout".into() }, true)]
6202    #[case::ownership_busy(BacktestError::SessionOwnershipBusy { reason: "draining".into() }, true)]
6203    #[case::invalid_request(BacktestError::InvalidRequest { error: "bad range".into() }, false)]
6204    #[case::bundle_not_found(BacktestError::BundleNotFound { start_slot: 1, end_slot: 2 }, false)]
6205    #[case::name_taken(BacktestError::SessionNameTaken { session_name: "a".into() }, false)]
6206    #[case::no_more_blocks(BacktestError::NoMoreBlocks, false)]
6207    fn only_server_side_failures_are_retryable(
6208        #[case] error: BacktestError,
6209        #[case] retryable: bool,
6210    ) {
6211        assert_eq!(error.is_retryable(), retryable);
6212    }
6213}