Skip to main content

feldera_types/
checkpoint.rs

1use std::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
68impl CheckpointResponse {
69    pub fn new(checkpoint_sequence_number: u64) -> Self {
70        Self {
71            checkpoint_sequence_number,
72        }
73    }
74}
75
76/// Response to a sync checkpoint request.
77#[derive(Clone, Debug, Default, Serialize, Deserialize, ToSchema)]
78pub struct CheckpointSyncResponse {
79    pub checkpoint_uuid: Uuid,
80}
81
82impl CheckpointSyncResponse {
83    pub fn new(checkpoint_uuid: Uuid) -> Self {
84        Self { checkpoint_uuid }
85    }
86}
87
88/// Checkpoint status returned by the `/checkpoint/sync_status` endpoint.
89#[derive(Clone, Debug, Default, Serialize, Deserialize, ToSchema)]
90pub struct CheckpointSyncStatus {
91    /// Most recently successful checkpoint sync.
92    pub success: Option<Uuid>,
93
94    /// Most recently failed checkpoint sync, and the associated error.
95    pub failure: Option<CheckpointSyncFailure>,
96
97    /// Most recently successful automated periodic checkpoint sync.
98    pub periodic: Option<Uuid>,
99}
100
101/// Information about a failed checkpoint sync.
102#[derive(Clone, Debug, Default, Serialize, Deserialize, ToSchema)]
103pub struct CheckpointSyncFailure {
104    /// UUID of the failed checkpoint.
105    pub uuid: Uuid,
106
107    /// Error message associated with the failure.
108    pub error: String,
109}
110
111/// Holds meta-data about a checkpoint that was taken for persistent storage
112/// and recovery of a circuit's state.
113#[derive(Debug, Clone, Default, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
114pub struct CheckpointMetadata {
115    /// A unique identifier for the given checkpoint.
116    ///
117    /// This is used to identify the checkpoint in the file-system hierarchy.
118    pub uuid: Uuid,
119    /// An optional name for the checkpoint.
120    pub identifier: Option<String>,
121    /// Fingerprint of the circuit at the time of the checkpoint.
122    pub fingerprint: u64,
123    /// Total size of the checkpoint files in bytes.
124    pub size: Option<u64>,
125    /// Total number of steps made.
126    pub steps: Option<u64>,
127    /// Total number of records processed.
128    pub processed_records: Option<u64>,
129}
130
131/// Identifies a host within a multihost pipeline.
132///
133/// Used to scope checkpoint sync operations (push/pull) to the correct
134/// remote subdirectory.
135#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
136pub struct HostInfo {
137    /// Zero-based index of this host in the pipeline layout.
138    pub host_idx: usize,
139    /// Total number of hosts in the pipeline layout.
140    pub n_hosts: usize,
141}
142
143impl HostInfo {
144    /// Returns the remote storage subdirectory prefix for this host,
145    /// e.g. `"host0"` for index 0.
146    pub fn prefix(&self) -> String {
147        if self.host_idx >= self.n_hosts {
148            log::warn!(
149                "HostInfo::prefix: host_idx {} >= n_hosts {}",
150                self.host_idx,
151                self.n_hosts
152            );
153        }
154        format!("host{}", self.host_idx)
155    }
156}
157
158/// Format of `pspine-batches-*.dat` in storage.
159///
160/// These files exist to be a simple format for higher-level code and outside
161/// tools to parse.  The spine itself writes them for that purpose, but it does
162/// not read them.
163#[derive(Debug, Serialize, Deserialize)]
164pub struct PSpineBatches {
165    pub files: Vec<String>,
166}
167
168/// Serialized form of `dependencies.json` on disk.
169///
170/// Two formats. New checkpoints write the struct form (`V2`) carrying both
171/// the batch list referenced at the storage root *and* the list of per-operator
172/// state files inside the checkpoint dir. Old checkpoints stored only the
173/// batch-filename array (`V1`); they remain readable so a rolling upgrade
174/// across in-flight checkpoints is safe.
175#[derive(Debug, Deserialize)]
176#[serde(untagged)]
177pub enum CheckpointDependencies {
178    V2 {
179        /// Batch filenames at the storage root (`w*.feldera`) that the
180        /// checkpoint references for GC retention.
181        batches: Vec<String>,
182        /// Per-operator state filenames inside the checkpoint dir
183        /// (e.g. `pspine-*.dat`, `z1-*.dat`, `CHECKPOINT`). Consumed by
184        /// restore-time verification. Defaulted to empty for forward compat.
185        #[serde(default)]
186        state_files: Vec<String>,
187    },
188    /// Legacy form: JSON array of batch filenames at the storage root
189    /// (`w*.feldera`). No state-file manifest.
190    V1(Vec<String>),
191}
192
193impl CheckpointDependencies {
194    /// Batch files the checkpoint references at the storage root
195    /// (`w*.feldera`). Present in both V1 and V2 checkpoints.
196    pub fn batches(&self) -> &[String] {
197        match self {
198            CheckpointDependencies::V2 { batches, .. } => batches,
199            CheckpointDependencies::V1(batches) => batches,
200        }
201    }
202
203    /// Per-operator state files the checkpoint owned at commit time. These
204    /// live inside the checkpoint dir (e.g. `pspine-*.dat`, `z1-*.dat`).
205    /// Empty for V1 checkpoints, which predate the state-file manifest.
206    pub fn state_files(&self) -> &[String] {
207        match self {
208            CheckpointDependencies::V2 { state_files, .. } => state_files,
209            CheckpointDependencies::V1(_) => &[],
210        }
211    }
212}
213
214/// Serialized form written to `dependencies.json`.  Always emits V2.
215#[derive(Debug, Serialize)]
216pub struct CheckpointDependenciesWrite<'a> {
217    pub batches: &'a [String],
218    pub state_files: &'a [String],
219}
220
221/// A checkpoint that exists in remote object storage.
222#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
223pub struct RemoteCheckpoint {
224    /// UUID of the checkpoint.
225    pub uuid: Uuid,
226}
227
228#[derive(Debug)]
229pub struct CheckpointSyncMetrics {
230    pub duration: Duration,
231    pub speed: u64,
232    pub bytes: u64,
233}
234
235/// Status of a `POST /coordination/checkpoint/pull` operation.
236///
237/// Returned by `GET /coordination/checkpoint/pull_status`.
238#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
239#[serde(tag = "status", rename_all = "snake_case")]
240pub enum CheckpointPullStatus {
241    /// No pull has been requested yet.
242    #[default]
243    NotRequested,
244    /// A pull is currently in progress.
245    InProgress,
246    /// The pull completed successfully.
247    Ok,
248    /// The pull failed.
249    Error { error: String },
250}
251
252#[cfg(test)]
253mod tests {
254    use super::*;
255
256    /// Legacy bare-array dependencies.json from older checkpoints must still
257    /// parse, yielding an empty state-file list (no manifest verification).
258    #[test]
259    fn deserialize_v1_legacy_array() {
260        let raw = r#"["w0-aaa.feldera", "w1-bbb.feldera"]"#;
261        let deps: CheckpointDependencies = serde_json::from_str(raw).unwrap();
262        assert!(deps.state_files().is_empty());
263        assert_eq!(deps.batches(), &["w0-aaa.feldera", "w1-bbb.feldera"]);
264    }
265
266    /// Current struct form carries both lists.
267    #[test]
268    fn deserialize_v2_struct() {
269        let raw = r#"{
270            "batches": ["w0-aaa.feldera"],
271            "state_files": ["pspine-0-zzz.dat", "CHECKPOINT"]
272        }"#;
273        let deps: CheckpointDependencies = serde_json::from_str(raw).unwrap();
274        assert_eq!(deps.state_files(), &["pspine-0-zzz.dat", "CHECKPOINT"]);
275        assert_eq!(deps.batches(), &["w0-aaa.feldera"]);
276    }
277
278    /// V2 without `state_files` (partial writer, partial migration)
279    /// deserializes with an empty state-file list rather than failing.
280    #[test]
281    fn deserialize_v2_missing_state_files_defaults_to_empty() {
282        let raw = r#"{"batches": ["w0-aaa.feldera"]}"#;
283        let deps: CheckpointDependencies = serde_json::from_str(raw).unwrap();
284        assert!(deps.state_files().is_empty());
285        assert_eq!(deps.batches(), &["w0-aaa.feldera"]);
286    }
287
288    /// Writes emit V2 and round-trip back to the same content.
289    #[test]
290    fn write_v2_round_trips() {
291        let batches = vec!["w0-x.feldera".to_string()];
292        let state_files = vec!["pspine-0-y.dat".to_string()];
293        let json = serde_json::to_string(&CheckpointDependenciesWrite {
294            batches: &batches,
295            state_files: &state_files,
296        })
297        .unwrap();
298        let deps: CheckpointDependencies = serde_json::from_str(&json).unwrap();
299        assert_eq!(deps.state_files(), state_files.as_slice());
300        assert_eq!(deps.batches(), batches.as_slice());
301    }
302
303    #[test]
304    fn host_info_prefix_formats_index() {
305        assert_eq!(
306            HostInfo {
307                host_idx: 0,
308                n_hosts: 2
309            }
310            .prefix(),
311            "host0"
312        );
313        assert_eq!(
314            HostInfo {
315                host_idx: 1,
316                n_hosts: 2
317            }
318            .prefix(),
319            "host1"
320        );
321        assert_eq!(
322            HostInfo {
323                host_idx: 42,
324                n_hosts: 100
325            }
326            .prefix(),
327            "host42"
328        );
329    }
330}