Skip to main content

simulator_api/
dataset_jobs.rs

1//! Start, follow and cancel dataset jobs: `POST`, `GET` and `DELETE /dataset-jobs[/{job_id}]`.
2
3use std::{collections::BTreeSet, fmt, num::NonZeroU64};
4
5use serde::{Deserialize, Serialize};
6
7use crate::{DepthSelection, SlotRange};
8
9/// Request body of `POST /dataset-jobs`. Resubmitting it answers with the same job, re-running
10/// it if it failed or was cancelled.
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
12pub struct DatasetJobRequest {
13    /// Inclusive; sent as `start_slot` and `end_slot`.
14    #[serde(flatten, with = "crate::slot_range::slot_bounds")]
15    pub slots: SlotRange,
16    /// Which dataset to build.
17    #[serde(flatten)]
18    pub dataset: DatasetJobSpec,
19}
20
21/// The dataset a job builds, tagged by `kind` on the wire.
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23#[serde(tag = "kind", rename_all = "snake_case")]
24pub enum DatasetJobSpec {
25    /// Probes the current curated template set.
26    EstimatedFills,
27    /// World BTC 5-minute prediction-market tables.
28    Predict {
29        /// At least one table.
30        tables: BTreeSet<PredictTable>,
31    },
32    /// What each venue's liquidity would have filled, or the router quoted, at each size across the
33    /// range.
34    Depth(DepthSelection),
35}
36
37impl DatasetJobSpec {
38    /// The wire value of `kind`.
39    pub fn kind(&self) -> &'static str {
40        match self {
41            Self::EstimatedFills => "estimated_fills",
42            Self::Predict { .. } => "predict",
43            Self::Depth(_) => "depth",
44        }
45    }
46}
47
48/// A predict table a dataset job produces.
49#[derive(
50    Debug,
51    Clone,
52    Copy,
53    PartialEq,
54    Eq,
55    PartialOrd,
56    Ord,
57    Hash,
58    Serialize,
59    Deserialize,
60    strum::IntoStaticStr,
61)]
62#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
63#[serde(rename_all = "snake_case")]
64#[strum(serialize_all = "snake_case")]
65pub enum PredictTable {
66    /// The markets the makers quote.
67    Markets,
68    /// The writes to the makers' accounts.
69    Writes,
70    /// Maker quote ladders, per batch that changed a market account.
71    Depth,
72    /// An order per row, with each maker's quote.
73    Orders,
74}
75
76impl PredictTable {
77    /// The table's wire name.
78    pub fn as_str(self) -> &'static str {
79        self.into()
80    }
81}
82
83/// A job's request, resolved range, phase and outputs, as `GET /dataset-jobs/{job_id}` answers.
84#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
85pub struct DatasetJobStatusResponse {
86    /// The id the job is followed and cancelled by.
87    pub job_id: String,
88    /// First slot requested.
89    pub start_slot: u64,
90    /// Last slot requested.
91    pub end_slot: u64,
92    /// The requested range widened to whole bundles.
93    pub capture: SlotRange,
94    /// The dataset the job builds.
95    #[serde(flatten)]
96    pub dataset: DatasetJobSpec,
97    /// Where the job is.
98    #[serde(flatten)]
99    pub phase: DatasetJobPhase,
100    /// Where the job's datasets land; filled in as they are written.
101    pub outputs: Vec<DatasetLocation>,
102    /// When the job was created, in Unix milliseconds.
103    pub created_at_unix_ms: u64,
104}
105
106/// Where a job is, tagged by `phase` on the wire.
107#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
108#[serde(tag = "phase", rename_all = "snake_case")]
109pub enum DatasetJobPhase {
110    /// Building the bundles the range needs.
111    Building {
112        /// Bundles built so far.
113        bundles: Progress,
114    },
115    /// `sessions` is absent when they cannot be counted.
116    Running {
117        /// Sessions finished so far.
118        #[serde(default, skip_serializing_if = "Option::is_none")]
119        sessions: Option<Progress>,
120        /// Slots the job's sessions have replayed, out of the slots they must replay. It drops when a
121        /// failed session is run again. Absent when the job cannot count them yet.
122        #[serde(default, skip_serializing_if = "Option::is_none")]
123        slots: Option<SlotProgress>,
124        /// The job this one waits on before it measures.
125        #[serde(default, skip_serializing_if = "Option::is_none")]
126        waiting_for: Option<String>,
127    },
128    /// Every output is written.
129    Completed,
130    /// The job stopped without finishing.
131    Failed {
132        /// Why it stopped.
133        reason: String,
134    },
135    /// Rows already written stay.
136    Cancelled,
137}
138
139impl DatasetJobPhase {
140    /// The wire value of `phase`.
141    pub fn as_str(&self) -> &'static str {
142        match self {
143            Self::Building { .. } => "building",
144            Self::Running { .. } => "running",
145            Self::Completed => "completed",
146            Self::Failed { .. } => "failed",
147            Self::Cancelled => "cancelled",
148        }
149    }
150
151    /// Whether the job has stopped for good.
152    pub fn is_terminal(&self) -> bool {
153        match self {
154            Self::Building { .. } | Self::Running { .. } => false,
155            Self::Completed | Self::Failed { .. } | Self::Cancelled => true,
156        }
157    }
158}
159
160/// A count of finished units out of the total.
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
162pub struct Progress {
163    /// Units finished.
164    pub done: usize,
165    /// Units the job needs.
166    pub total: usize,
167}
168
169/// Slots a running job's sessions have replayed, out of the slots it owes.
170#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
171pub struct SlotProgress {
172    /// Slots replayed.
173    pub done: u64,
174    /// Slots the job owes.
175    pub total: NonZeroU64,
176}
177
178impl SlotProgress {
179    /// Whole percent, rounded down, at most 100.
180    pub fn percent(&self) -> u64 {
181        self.done.min(self.total.get()).saturating_mul(100) / self.total
182    }
183}
184
185/// A dataset under the `user_s3_uri` that `POST /datasets/credentials` returns, at
186/// `<name>/v<version>/`.
187#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
188pub struct DatasetLocation {
189    /// The dataset's name.
190    pub name: String,
191    /// The dataset's schema version.
192    pub version: u16,
193}
194
195impl fmt::Display for DatasetLocation {
196    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197        write!(f, "{}/v{}/", self.name, self.version)
198    }
199}
200
201/// The caller's jobs, as `GET /dataset-jobs` answers.
202#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
203pub struct DatasetJobListResponse {
204    /// Newest first.
205    pub jobs: Vec<DatasetJobStatusResponse>,
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211    use crate::{DepthGranularity, DepthSource};
212
213    #[rstest::rstest]
214    #[case::none(0, 8, 0)]
215    #[case::rounded_down(3, 8, 37)]
216    #[case::all(8, 8, 100)]
217    #[case::past_the_total(9, 8, 100)]
218    fn the_share_is_a_whole_percent_rounded_down_and_never_over_100(
219        #[case] done: u64,
220        #[case] total: u64,
221        #[case] percent: u64,
222    ) {
223        let progress = SlotProgress {
224            done,
225            total: NonZeroU64::new(total).unwrap(),
226        };
227        assert_eq!(progress.percent(), percent);
228    }
229
230    #[test]
231    fn a_status_carries_its_kind_and_phase_beside_its_fields() {
232        let status = DatasetJobStatusResponse {
233            job_id: "j".to_owned(),
234            start_slot: 100,
235            end_slot: 199,
236            capture: SlotRange::new_unchecked(90, 210),
237            dataset: DatasetJobSpec::EstimatedFills,
238            phase: DatasetJobPhase::Running {
239                sessions: Some(Progress { done: 1, total: 3 }),
240                slots: None,
241                waiting_for: None,
242            },
243            outputs: vec![DatasetLocation {
244                name: "estimated-fills".to_owned(),
245                version: 2,
246            }],
247            created_at_unix_ms: 7,
248        };
249        let wire = serde_json::json!({
250            "job_id": "j",
251            "start_slot": 100,
252            "end_slot": 199,
253            "capture": {"start": 90, "end": 210},
254            "kind": "estimated_fills",
255            "phase": "running",
256            "sessions": {"done": 1, "total": 3},
257            "outputs": [{"name": "estimated-fills", "version": 2}],
258            "created_at_unix_ms": 7,
259        });
260        assert_eq!(serde_json::to_value(&status).unwrap(), wire);
261        assert_eq!(
262            serde_json::from_value::<DatasetJobStatusResponse>(wire).unwrap(),
263            status
264        );
265    }
266
267    #[rstest::rstest]
268    #[case::without_a_count(
269        serde_json::json!({"phase": "running"}),
270        DatasetJobPhase::Running { sessions: None, slots: None, waiting_for: None }
271    )]
272    #[case::with_the_counts(
273        serde_json::json!({
274            "phase": "running",
275            "sessions": {"done": 1, "total": 3},
276            "slots": {"done": 1_400, "total": 3_000},
277        }),
278        DatasetJobPhase::Running {
279            sessions: Some(Progress { done: 1, total: 3 }),
280            slots: Some(SlotProgress { done: 1_400, total: NonZeroU64::new(3_000).unwrap() }),
281            waiting_for: None,
282        }
283    )]
284    fn a_running_phase_leaves_out_the_counts_it_lacks(
285        #[case] wire: serde_json::Value,
286        #[case] phase: DatasetJobPhase,
287    ) {
288        assert_eq!(serde_json::to_value(&phase).unwrap(), wire);
289        assert_eq!(
290            serde_json::from_value::<DatasetJobPhase>(wire).unwrap(),
291            phase
292        );
293    }
294
295    #[test]
296    fn a_slot_total_of_zero_fails_to_decode() {
297        let wire = serde_json::json!({"done": 0, "total": 0});
298        assert!(serde_json::from_value::<SlotProgress>(wire).is_err());
299    }
300
301    #[test]
302    fn a_waiting_job_names_the_job_it_waits_for() {
303        let phase = DatasetJobPhase::Running {
304            sessions: None,
305            slots: None,
306            waiting_for: Some("j2".to_owned()),
307        };
308        let wire = serde_json::json!({"phase": "running", "waiting_for": "j2"});
309        assert_eq!(serde_json::to_value(&phase).unwrap(), wire);
310        assert_eq!(
311            serde_json::from_value::<DatasetJobPhase>(wire).unwrap(),
312            phase
313        );
314    }
315
316    /// The Prefect `dispatch-dataset-jobs` flow reads this file and must send exactly it.
317    #[test]
318    fn the_prefect_dispatch_bodies_round_trip() {
319        let golden: serde_json::Value =
320            serde_json::from_str(include_str!("../tests/data/dataset_job_requests.json")).unwrap();
321        let requests: Vec<DatasetJobRequest> = serde_json::from_value(golden.clone()).unwrap();
322        assert_eq!(serde_json::to_value(requests).unwrap(), golden);
323    }
324
325    #[test]
326    fn a_request_names_its_kind_and_range() {
327        let request: DatasetJobRequest = serde_json::from_value(serde_json::json!({
328            "start_slot": 1,
329            "end_slot": 2,
330            "kind": "estimated_fills",
331        }))
332        .unwrap();
333        assert_eq!(request.dataset, DatasetJobSpec::EstimatedFills);
334        assert_eq!(request.slots, SlotRange::new_unchecked(1, 2));
335    }
336
337    #[test]
338    fn a_request_with_an_inverted_range_is_refused_as_it_is_read() {
339        let request = serde_json::from_value::<DatasetJobRequest>(serde_json::json!({
340            "start_slot": 2,
341            "end_slot": 1,
342            "kind": "estimated_fills",
343        }));
344
345        assert!(request.is_err());
346    }
347
348    #[test]
349    fn a_request_writes_its_range_as_start_and_end_slots() {
350        let request = DatasetJobRequest {
351            slots: SlotRange::new_unchecked(5, 9),
352            dataset: DatasetJobSpec::EstimatedFills,
353        };
354
355        assert_eq!(
356            serde_json::to_value(&request).unwrap(),
357            serde_json::json!({"start_slot": 5, "end_slot": 9, "kind": "estimated_fills"})
358        );
359    }
360
361    #[test]
362    fn a_predict_request_names_its_tables() {
363        let request = DatasetJobRequest {
364            slots: SlotRange::new_unchecked(1, 2),
365            dataset: DatasetJobSpec::Predict {
366                tables: BTreeSet::from([
367                    PredictTable::Orders,
368                    PredictTable::Depth,
369                    PredictTable::Markets,
370                ]),
371            },
372        };
373        let wire = serde_json::json!({
374            "start_slot": 1,
375            "end_slot": 2,
376            "kind": "predict",
377            "tables": ["markets", "depth", "orders"],
378        });
379        assert_eq!(serde_json::to_value(&request).unwrap(), wire);
380        assert_eq!(
381            serde_json::from_value::<DatasetJobRequest>(wire).unwrap(),
382            request
383        );
384    }
385
386    #[test]
387    fn a_depth_request_spells_its_options_beside_its_slots() {
388        let request = DatasetJobRequest {
389            slots: SlotRange::new_unchecked(1, 2),
390            dataset: DatasetJobSpec::Depth(DepthSelection {
391                source: DepthSource::Onchain,
392                granularity: DepthGranularity::Oracle,
393                markets: vec!["SOL-USDC".to_owned()],
394                ..DepthSelection::default()
395            }),
396        };
397        let wire = serde_json::json!({
398            "start_slot": 1,
399            "end_slot": 2,
400            "kind": "depth",
401            "source": "onchain",
402            "granularity": "oracle",
403            "markets": ["SOL-USDC"],
404        });
405        assert_eq!(serde_json::to_value(&request).unwrap(), wire);
406        assert_eq!(
407            serde_json::from_value::<DatasetJobRequest>(wire).unwrap(),
408            request
409        );
410    }
411
412    #[test]
413    fn a_depth_request_naming_only_its_kind_measures_every_onchain_market_by_slot() {
414        let request: DatasetJobRequest = serde_json::from_value(serde_json::json!({
415            "start_slot": 1,
416            "end_slot": 2,
417            "kind": "depth",
418        }))
419        .unwrap();
420        assert_eq!(
421            request.dataset,
422            DatasetJobSpec::Depth(DepthSelection::default())
423        );
424    }
425}