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