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