Skip to main content

feldera_types/
checkpoint.rs

1use std::{collections::BTreeSet, time::Duration};
2
3use chrono::{DateTime, Utc};
4use serde::{Deserialize, Serialize};
5use utoipa::ToSchema;
6use uuid::Uuid;
7
8use crate::suspend::TemporarySuspendError;
9
10/// Checkpoint status returned by the `/checkpoint_status` endpoint.
11#[derive(Clone, Debug, Default, Serialize, Deserialize, ToSchema)]
12pub struct CheckpointStatus {
13    /// Most recently successful checkpoint.
14    pub success: Option<u64>,
15
16    /// Most recently failed checkpoint, and the associated error.
17    ///
18    /// This tracks transient checkpoint failures (e.g. I/O errors during
19    /// writing).  A subsequent successful checkpoint will not clear this
20    /// field — it always reflects the *last* failure that occurred.
21    pub failure: Option<CheckpointFailure>,
22}
23
24/// Current checkpoint activity state.
25#[derive(Clone, Debug, Default, Serialize, Deserialize, ToSchema)]
26#[serde(tag = "status", rename_all = "snake_case")]
27pub enum CheckpointActivity {
28    /// No checkpoint is pending or in progress.
29    #[default]
30    Idle,
31
32    /// A checkpoint has been requested but is delayed for temporary reasons
33    /// (e.g. replaying, bootstrapping, transaction in progress, or input
34    /// endpoint barriers that require the coordinator to run steps).
35    Delayed {
36        /// Why the checkpoint cannot proceed yet.
37        reasons: Vec<TemporarySuspendError>,
38        /// When the delay started (serialized as ISO 8601).
39        delayed_since: DateTime<Utc>,
40    },
41
42    /// A checkpoint is currently being written to storage.
43    InProgress {
44        /// When the checkpoint write started (serialized as ISO 8601).
45        started_at: DateTime<Utc>,
46    },
47}
48
49/// Information about a failed checkpoint.
50#[derive(Clone, Debug, Default, Serialize, Deserialize, ToSchema)]
51pub struct CheckpointFailure {
52    /// Sequence number of the failed checkpoint.
53    pub sequence_number: u64,
54
55    /// Error message associated with the failure.
56    pub error: String,
57
58    /// When the failure occurred (serialized as ISO 8601).
59    pub failed_at: DateTime<Utc>,
60}
61
62/// Response to a checkpoint request.
63#[derive(Clone, Debug, Default, Serialize, Deserialize, ToSchema)]
64pub struct CheckpointResponse {
65    pub checkpoint_sequence_number: u64,
66
67    /// Pass back to `/checkpoint_status` to detect pipeline restarts.
68    ///
69    /// Only `None` if sent by an older pipeline.
70    pub incarnation_uuid: Option<Uuid>,
71}
72
73impl CheckpointResponse {
74    pub fn new(checkpoint_sequence_number: u64, incarnation_uuid: Uuid) -> Self {
75        Self {
76            checkpoint_sequence_number,
77            incarnation_uuid: Some(incarnation_uuid),
78        }
79    }
80}
81
82/// Response to a sync checkpoint request.
83#[derive(Clone, Debug, Default, Serialize, Deserialize, ToSchema)]
84pub struct CheckpointSyncResponse {
85    pub checkpoint_uuid: Uuid,
86
87    /// Pass back to `/checkpoint/sync_status` to detect pipeline restarts.
88    ///
89    /// Only `None` if sent by an older pipeline.
90    pub incarnation_uuid: Option<Uuid>,
91}
92
93impl CheckpointSyncResponse {
94    pub fn new(checkpoint_uuid: Uuid, incarnation_uuid: Uuid) -> Self {
95        Self {
96            checkpoint_uuid,
97            incarnation_uuid: Some(incarnation_uuid),
98        }
99    }
100}
101
102/// Query parameters for `/checkpoint_status` and `/checkpoint/sync_status`.
103#[derive(Clone, Debug, Default, Serialize, Deserialize)]
104pub struct CheckpointStatusQuery {
105    /// Pass the value from the initial response, to detect pipeline restarts.
106    ///
107    /// Optional to allow older clients to continue working.
108    pub incarnation_uuid: Option<Uuid>,
109}
110
111/// Checkpoint status returned by the `/checkpoint/sync_status` endpoint.
112#[derive(Clone, Debug, Default, Serialize, Deserialize, ToSchema)]
113#[serde(default)]
114pub struct CheckpointSyncStatus {
115    /// Most recently successful checkpoint sync.
116    ///
117    /// If `success` and `failure` would otherwise name the same UUID, then the
118    /// most recent result is set and the other is cleared.
119    pub success: Option<Uuid>,
120
121    /// Most recently failed checkpoint sync, and the associated error.
122    pub failure: Option<CheckpointSyncFailure>,
123
124    /// Most recently successful automated periodic checkpoint sync.
125    pub periodic: Option<Uuid>,
126
127    /// Checkpoint syncs running right now.
128    ///
129    /// A UUID leaves `running` and lands in `success` or `failure` at the same
130    /// moment.
131    ///
132    /// Periodic syncs do not appear here.
133    pub running: BTreeSet<Uuid>,
134}
135
136/// Information about a failed checkpoint sync.
137#[derive(Clone, Debug, Default, Serialize, Deserialize, ToSchema)]
138pub struct CheckpointSyncFailure {
139    /// UUID of the failed checkpoint.
140    pub uuid: Uuid,
141
142    /// Error message associated with the failure.
143    pub error: String,
144}
145
146/// Holds meta-data about a checkpoint that was taken for persistent storage
147/// and recovery of a circuit's state.
148#[derive(Debug, Clone, Default, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
149pub struct CheckpointMetadata {
150    /// A unique identifier for the given checkpoint.
151    ///
152    /// This is used to identify the checkpoint in the file-system hierarchy.
153    pub uuid: Uuid,
154    /// An optional name for the checkpoint.
155    pub identifier: Option<String>,
156    /// Fingerprint of the circuit at the time of the checkpoint.
157    // Uses the full 64-bit range.
158    #[schema(format = "uint64")]
159    pub fingerprint: u64,
160    /// Total size of the checkpoint files in bytes.
161    pub size: Option<u64>,
162    /// Total number of steps made.
163    pub steps: Option<u64>,
164    /// Total number of records processed.
165    pub processed_records: Option<u64>,
166}
167
168/// Identifies a host within a multihost pipeline.
169///
170/// Used to scope checkpoint sync operations (push/pull) to the correct
171/// remote subdirectory.
172#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
173pub struct HostInfo {
174    /// Zero-based index of this host in the pipeline layout.
175    pub host_idx: usize,
176    /// Total number of hosts in the pipeline layout.
177    pub n_hosts: usize,
178}
179
180impl HostInfo {
181    /// Returns the remote storage subdirectory prefix for this host,
182    /// e.g. `"host0"` for index 0.
183    pub fn prefix(&self) -> String {
184        if self.host_idx >= self.n_hosts {
185            log::warn!(
186                "HostInfo::prefix: host_idx {} >= n_hosts {}",
187                self.host_idx,
188                self.n_hosts
189            );
190        }
191        format!("host{}", self.host_idx)
192    }
193}
194
195/// Format of `pspine-batches-*.dat` in storage.
196///
197/// These files exist to be a simple format for higher-level code and outside
198/// tools to parse.  The spine itself writes them for that purpose, but it does
199/// not read them.
200#[derive(Debug, Serialize, Deserialize)]
201pub struct PSpineBatches {
202    pub files: Vec<String>,
203}
204
205/// Serialized form of `dependencies.json` on disk.
206///
207/// Two formats. New checkpoints write the struct form (`V2`) carrying both
208/// the batch list referenced at the storage root *and* the list of per-operator
209/// state files inside the checkpoint dir. Old checkpoints stored only the
210/// batch-filename array (`V1`); they remain readable so a rolling upgrade
211/// across in-flight checkpoints is safe.
212#[derive(Debug, Deserialize)]
213#[serde(untagged)]
214pub enum CheckpointDependencies {
215    V2 {
216        /// Batch filenames at the storage root (`w*.feldera`) that the
217        /// checkpoint references for GC retention.
218        batches: Vec<String>,
219        /// Per-operator state filenames inside the checkpoint dir
220        /// (e.g. `pspine-*.dat`, `z1-*.dat`, `CHECKPOINT`). Consumed by
221        /// restore-time verification. Defaulted to empty for forward compat.
222        #[serde(default)]
223        state_files: Vec<String>,
224    },
225    /// Legacy form: JSON array of batch filenames at the storage root
226    /// (`w*.feldera`). No state-file manifest.
227    V1(Vec<String>),
228}
229
230impl CheckpointDependencies {
231    /// Batch files the checkpoint references at the storage root
232    /// (`w*.feldera`). Present in both V1 and V2 checkpoints.
233    pub fn batches(&self) -> &[String] {
234        match self {
235            CheckpointDependencies::V2 { batches, .. } => batches,
236            CheckpointDependencies::V1(batches) => batches,
237        }
238    }
239
240    /// Per-operator state files the checkpoint owned at commit time. These
241    /// live inside the checkpoint dir (e.g. `pspine-*.dat`, `z1-*.dat`).
242    /// Empty for V1 checkpoints, which predate the state-file manifest.
243    pub fn state_files(&self) -> &[String] {
244        match self {
245            CheckpointDependencies::V2 { state_files, .. } => state_files,
246            CheckpointDependencies::V1(_) => &[],
247        }
248    }
249}
250
251/// Serialized form written to `dependencies.json`.  Always emits V2.
252#[derive(Debug, Serialize)]
253pub struct CheckpointDependenciesWrite<'a> {
254    pub batches: &'a [String],
255    pub state_files: &'a [String],
256}
257
258/// A checkpoint that exists in remote object storage.
259#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
260pub struct RemoteCheckpoint {
261    /// UUID of the checkpoint.
262    pub uuid: Uuid,
263}
264
265#[derive(Debug)]
266pub struct CheckpointSyncMetrics {
267    pub duration: Duration,
268    pub speed: u64,
269    pub bytes: u64,
270}
271
272/// Status of a `POST /coordination/checkpoint/pull` operation.
273///
274/// Returned by `GET /coordination/checkpoint/pull_status`.
275#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
276#[serde(tag = "status", rename_all = "snake_case")]
277pub enum CheckpointPullStatus {
278    /// No pull has been requested yet.
279    #[default]
280    NotRequested,
281    /// A pull is currently in progress.
282    InProgress,
283    /// The pull completed successfully.
284    Ok,
285    /// The pull failed.
286    Error { error: String },
287}
288
289#[cfg(test)]
290mod tests {
291    use super::*;
292
293    /// A newer client's `CheckpointResponse`/`CheckpointSyncResponse` must
294    /// still parse a response from an older pipeline that predates the
295    /// `incarnation_uuid` field, yielding `None` rather than a
296    /// deserialization error.
297    #[test]
298    fn deserialize_response_missing_incarnation_uuid() {
299        let resp: CheckpointResponse =
300            serde_json::from_str(r#"{"checkpoint_sequence_number": 3}"#).unwrap();
301        assert_eq!(resp.checkpoint_sequence_number, 3);
302        assert_eq!(resp.incarnation_uuid, None);
303
304        let sync_resp: CheckpointSyncResponse =
305            serde_json::from_str(r#"{"checkpoint_uuid": "00000000-0000-0000-0000-000000000001"}"#)
306                .unwrap();
307        assert_eq!(sync_resp.incarnation_uuid, None);
308    }
309
310    /// Legacy bare-array dependencies.json from older checkpoints must still
311    /// parse, yielding an empty state-file list (no manifest verification).
312    #[test]
313    fn deserialize_v1_legacy_array() {
314        let raw = r#"["w0-aaa.feldera", "w1-bbb.feldera"]"#;
315        let deps: CheckpointDependencies = serde_json::from_str(raw).unwrap();
316        assert!(deps.state_files().is_empty());
317        assert_eq!(deps.batches(), &["w0-aaa.feldera", "w1-bbb.feldera"]);
318    }
319
320    /// Current struct form carries both lists.
321    #[test]
322    fn deserialize_v2_struct() {
323        let raw = r#"{
324            "batches": ["w0-aaa.feldera"],
325            "state_files": ["pspine-0-zzz.dat", "CHECKPOINT"]
326        }"#;
327        let deps: CheckpointDependencies = serde_json::from_str(raw).unwrap();
328        assert_eq!(deps.state_files(), &["pspine-0-zzz.dat", "CHECKPOINT"]);
329        assert_eq!(deps.batches(), &["w0-aaa.feldera"]);
330    }
331
332    /// V2 without `state_files` (partial writer, partial migration)
333    /// deserializes with an empty state-file list rather than failing.
334    #[test]
335    fn deserialize_v2_missing_state_files_defaults_to_empty() {
336        let raw = r#"{"batches": ["w0-aaa.feldera"]}"#;
337        let deps: CheckpointDependencies = serde_json::from_str(raw).unwrap();
338        assert!(deps.state_files().is_empty());
339        assert_eq!(deps.batches(), &["w0-aaa.feldera"]);
340    }
341
342    /// Writes emit V2 and round-trip back to the same content.
343    #[test]
344    fn write_v2_round_trips() {
345        let batches = vec!["w0-x.feldera".to_string()];
346        let state_files = vec!["pspine-0-y.dat".to_string()];
347        let json = serde_json::to_string(&CheckpointDependenciesWrite {
348            batches: &batches,
349            state_files: &state_files,
350        })
351        .unwrap();
352        let deps: CheckpointDependencies = serde_json::from_str(&json).unwrap();
353        assert_eq!(deps.state_files(), state_files.as_slice());
354        assert_eq!(deps.batches(), batches.as_slice());
355    }
356
357    #[test]
358    fn host_info_prefix_formats_index() {
359        assert_eq!(
360            HostInfo {
361                host_idx: 0,
362                n_hosts: 2
363            }
364            .prefix(),
365            "host0"
366        );
367        assert_eq!(
368            HostInfo {
369                host_idx: 1,
370                n_hosts: 2
371            }
372            .prefix(),
373            "host1"
374        );
375        assert_eq!(
376            HostInfo {
377                host_idx: 42,
378                n_hosts: 100
379            }
380            .prefix(),
381            "host42"
382        );
383    }
384}