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