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