laminar-storage 0.18.13

Storage layer for LaminarDB - WAL, checkpointing, and lakehouse integration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
//! Async checkpoint persistence via object stores.
//!
//! `ObjectStoreCheckpointer` writes checkpoint artifacts to any
//! `object_store::ObjectStore` backend with:
//! - Concurrent partition uploads via `JoinSet`
//! - SHA-256 integrity digests
//! - Exponential backoff retry on transient errors

use std::sync::Arc;

use bytes::Bytes;
use futures::StreamExt;
use object_store::path::Path;
use object_store::{GetOptions, ObjectStore, PutOptions, PutPayload};
use sha2::{Digest, Sha256};
use tokio::task::JoinSet;

use super::layout::{CheckpointId, CheckpointManifestV2, CheckpointPaths, PartitionSnapshotEntry};

/// Errors from checkpoint persistence operations.
#[derive(Debug, thiserror::Error)]
pub enum CheckpointerError {
    /// Object store I/O error.
    #[error("object store error: {0}")]
    ObjectStore(#[from] object_store::Error),

    /// JSON serialization/deserialization error.
    #[error("serialization error: {0}")]
    Serialization(#[from] serde_json::Error),

    /// SHA-256 integrity check failed.
    #[error("integrity check failed for {path}: expected {expected}, got {actual}")]
    IntegrityMismatch {
        /// Object path.
        path: String,
        /// Expected SHA-256 hex digest.
        expected: String,
        /// Actual SHA-256 hex digest.
        actual: String,
    },

    /// A concurrent upload task failed.
    #[error("upload task failed: {0}")]
    JoinError(#[from] tokio::task::JoinError),
}

/// Checkpoint persister backed by an [`ObjectStore`].
///
/// Supports concurrent partition uploads and SHA-256 integrity verification.
pub struct ObjectStoreCheckpointer {
    /// The underlying object store.
    store: Arc<dyn ObjectStore>,
    /// Path generator for checkpoint artifacts.
    paths: CheckpointPaths,
    /// Maximum number of concurrent uploads.
    max_concurrent_uploads: usize,
}

impl ObjectStoreCheckpointer {
    /// Create a new checkpointer.
    #[must_use]
    pub fn new(
        store: Arc<dyn ObjectStore>,
        paths: CheckpointPaths,
        max_concurrent_uploads: usize,
    ) -> Self {
        Self {
            store,
            paths,
            max_concurrent_uploads,
        }
    }

    /// Write data to a path with exponential backoff retry.
    async fn put_with_retry(
        store: &dyn ObjectStore,
        path: &Path,
        data: PutPayload,
    ) -> Result<(), CheckpointerError> {
        let op = || async {
            store
                .put_opts(path, data.clone(), PutOptions::default())
                .await
                .map_err(|e| match &e {
                    object_store::Error::Generic { .. } => {
                        backoff::Error::transient(CheckpointerError::ObjectStore(e))
                    }
                    _ => backoff::Error::permanent(CheckpointerError::ObjectStore(e)),
                })?;
            Ok(())
        };

        let backoff = backoff::ExponentialBackoffBuilder::new()
            .with_max_elapsed_time(Some(std::time::Duration::from_secs(30)))
            .build();

        backoff::future::retry(backoff, op).await
    }

    /// Compute SHA-256 hex digest of data.
    fn sha256_hex(data: &[u8]) -> String {
        let mut hasher = Sha256::new();
        hasher.update(data);
        format!("{:x}", hasher.finalize())
    }

    /// Write data to a path and return its SHA-256 digest.
    async fn write_with_digest(
        &self,
        path_str: &str,
        data: Bytes,
    ) -> Result<String, CheckpointerError> {
        let digest = Self::sha256_hex(&data);
        let path = Path::from(path_str);
        let payload = PutPayload::from_bytes(data);
        Self::put_with_retry(self.store.as_ref(), &path, payload).await?;
        Ok(digest)
    }

    /// Save multiple operator partition snapshots concurrently.
    ///
    /// Returns a map of `(operator, partition) -> PartitionSnapshotEntry`.
    ///
    /// # Errors
    ///
    /// Returns [`CheckpointerError`] if any upload or join fails.
    pub async fn save_partitions_concurrent(
        &self,
        id: &CheckpointId,
        snapshots: Vec<(String, u32, bool, Bytes)>,
    ) -> Result<Vec<(String, PartitionSnapshotEntry)>, CheckpointerError> {
        let mut join_set = JoinSet::new();
        let store = Arc::clone(&self.store);

        for (operator, partition, is_delta, data) in snapshots {
            let path_str = if is_delta {
                self.paths.delta(id, &operator, partition)
            } else {
                self.paths.snapshot(id, &operator, partition)
            };

            let store = Arc::clone(&store);
            let data_len = data.len() as u64;

            // Limit concurrency by awaiting when at max
            if join_set.len() >= self.max_concurrent_uploads {
                if let Some(result) = join_set.join_next().await {
                    result??;
                }
            }

            join_set.spawn(async move {
                let digest = {
                    let mut hasher = Sha256::new();
                    hasher.update(&data);
                    format!("{:x}", hasher.finalize())
                };
                let path = Path::from(path_str.as_str());
                let payload = PutPayload::from_bytes(data);
                Self::put_with_retry(store.as_ref(), &path, payload).await?;

                Ok::<_, CheckpointerError>((
                    operator,
                    PartitionSnapshotEntry {
                        partition_id: partition,
                        is_delta,
                        path: path_str,
                        size_bytes: data_len,
                        sha256: Some(digest),
                    },
                ))
            });
        }

        // Collect remaining results
        let mut entries = Vec::new();
        while let Some(result) = join_set.join_next().await {
            entries.push(result??);
        }

        Ok(entries)
    }

    /// Write a manifest to the checkpoint store.
    ///
    /// # Errors
    ///
    /// Returns [`CheckpointerError`] on I/O or serialization failure.
    pub async fn save_manifest(
        &self,
        manifest: &CheckpointManifestV2,
    ) -> Result<(), CheckpointerError> {
        let json = serde_json::to_vec_pretty(manifest)?;
        let path_str = self.paths.manifest(&manifest.checkpoint_id);
        let path = Path::from(path_str.as_str());
        let payload = PutPayload::from_bytes(Bytes::from(json));
        Self::put_with_retry(self.store.as_ref(), &path, payload).await
    }

    /// Load a manifest by checkpoint ID.
    ///
    /// # Errors
    ///
    /// Returns [`CheckpointerError`] on I/O or deserialization failure.
    pub async fn load_manifest(
        &self,
        id: &CheckpointId,
    ) -> Result<CheckpointManifestV2, CheckpointerError> {
        let path_str = self.paths.manifest(id);
        let path = Path::from(path_str.as_str());
        let result = self.store.get_opts(&path, GetOptions::default()).await?;
        let data = result.bytes().await?;
        let manifest: CheckpointManifestV2 = serde_json::from_slice(&data)?;
        Ok(manifest)
    }

    /// Write a state snapshot for a single operator partition.
    ///
    /// Returns the SHA-256 hex digest of the written data.
    ///
    /// # Errors
    ///
    /// Returns [`CheckpointerError`] on I/O failure.
    pub async fn save_snapshot(
        &self,
        id: &CheckpointId,
        operator: &str,
        partition: u32,
        data: Bytes,
    ) -> Result<String, CheckpointerError> {
        let path_str = self.paths.snapshot(id, operator, partition);
        self.write_with_digest(&path_str, data).await
    }

    /// Write an incremental delta for a single operator partition.
    ///
    /// Returns the SHA-256 hex digest of the written data.
    ///
    /// # Errors
    ///
    /// Returns [`CheckpointerError`] on I/O failure.
    pub async fn save_delta(
        &self,
        id: &CheckpointId,
        operator: &str,
        partition: u32,
        data: Bytes,
    ) -> Result<String, CheckpointerError> {
        let path_str = self.paths.delta(id, operator, partition);
        self.write_with_digest(&path_str, data).await
    }

    /// Load a snapshot or delta by path.
    ///
    /// # Errors
    ///
    /// Returns [`CheckpointerError`] on I/O failure.
    pub async fn load_artifact(&self, path_str: &str) -> Result<Bytes, CheckpointerError> {
        let path = Path::from(path_str);
        let result = self.store.get_opts(&path, GetOptions::default()).await?;
        let data = result.bytes().await?;
        Ok(data)
    }

    /// Update the `_latest` pointer to the given checkpoint.
    ///
    /// # Errors
    ///
    /// Returns [`CheckpointerError`] on I/O failure.
    pub async fn update_latest(&self, id: &CheckpointId) -> Result<(), CheckpointerError> {
        let path_str = self.paths.latest_pointer();
        let path = Path::from(path_str.as_str());
        let payload = PutPayload::from_bytes(Bytes::from(id.to_string_id()));
        Self::put_with_retry(self.store.as_ref(), &path, payload).await
    }

    /// Read the `_latest` pointer to find the most recent checkpoint.
    ///
    /// # Errors
    ///
    /// Returns [`CheckpointerError`] on I/O failure.
    pub async fn read_latest(&self) -> Result<Option<CheckpointId>, CheckpointerError> {
        let path_str = self.paths.latest_pointer();
        let path = Path::from(path_str.as_str());
        match self.store.get_opts(&path, GetOptions::default()).await {
            Ok(result) => {
                let data = result.bytes().await?;
                let id_str =
                    std::str::from_utf8(&data).map_err(|e| object_store::Error::Generic {
                        store: "checkpointer",
                        source: Box::new(e),
                    })?;
                let uuid =
                    uuid::Uuid::parse_str(id_str).map_err(|e| object_store::Error::Generic {
                        store: "checkpointer",
                        source: Box::new(e),
                    })?;
                Ok(Some(CheckpointId::from_uuid(uuid)))
            }
            Err(object_store::Error::NotFound { .. }) => Ok(None),
            Err(e) => Err(CheckpointerError::ObjectStore(e)),
        }
    }

    /// List all checkpoint IDs (sorted chronologically, oldest first).
    ///
    /// # Errors
    ///
    /// Returns [`CheckpointerError`] on I/O failure.
    pub async fn list_checkpoints(&self) -> Result<Vec<CheckpointId>, CheckpointerError> {
        // List objects at the base prefix — each checkpoint is a directory.
        // We look for manifest.json files to identify checkpoints.
        //
        // Manifest path format: {base_prefix}{UUID}manifest.json
        // (no slash between UUID and "manifest.json", see layout.rs:114)
        let prefix = Path::from(self.paths.latest_pointer().trim_end_matches("_latest"));
        let base_prefix = &self.paths.base_prefix;
        let mut ids = Vec::new();

        let mut stream = self.store.list(Some(&prefix));
        while let Some(meta) = stream.next().await {
            let meta = meta?;
            let path_str = meta.location.to_string();
            if path_str.ends_with("manifest.json") {
                // Extract checkpoint ID: strip suffix then strip base prefix.
                // Path is "{base_prefix}{UUID}manifest.json".
                // After stripping suffix: "{base_prefix}{UUID}".
                // After stripping prefix: "{UUID}".
                if let Some(remainder) = path_str.strip_suffix("manifest.json") {
                    let id_str = remainder
                        .strip_prefix(base_prefix.as_str())
                        .unwrap_or(remainder);
                    let id_str = id_str.trim_end_matches('/');
                    if !id_str.is_empty() {
                        if let Ok(uuid) = uuid::Uuid::parse_str(id_str) {
                            ids.push(CheckpointId::from_uuid(uuid));
                        }
                    }
                }
            }
        }

        ids.sort();
        Ok(ids)
    }

    /// Delete a checkpoint and all its artifacts.
    ///
    /// # Errors
    ///
    /// Returns [`CheckpointerError`] on I/O failure.
    pub async fn delete_checkpoint(&self, id: &CheckpointId) -> Result<(), CheckpointerError> {
        // List all objects under this checkpoint's directory and delete them
        let dir = self.paths.checkpoint_dir(id);
        let prefix = Path::from(dir.as_str());

        let mut paths_to_delete = Vec::new();
        let mut stream = self.store.list(Some(&prefix));
        while let Some(meta) = stream.next().await {
            let meta = meta?;
            paths_to_delete.push(meta.location);
        }

        // Delete using delete_stream (object-safe, no ObjectStoreExt needed)
        let locations_stream = futures::stream::iter(paths_to_delete.into_iter().map(Ok)).boxed();
        let mut results = self.store.delete_stream(locations_stream);
        while let Some(result) = results.next().await {
            result?;
        }

        Ok(())
    }
}

/// Verify a loaded artifact against its expected SHA-256 digest.
///
/// # Errors
///
/// Returns [`CheckpointerError::IntegrityMismatch`] if the digest doesn't match.
pub fn verify_integrity(
    path: &str,
    data: &[u8],
    expected_sha256: &str,
) -> Result<(), CheckpointerError> {
    let actual = ObjectStoreCheckpointer::sha256_hex(data);
    if actual != expected_sha256 {
        return Err(CheckpointerError::IntegrityMismatch {
            path: path.to_string(),
            expected: expected_sha256.to_string(),
            actual,
        });
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::super::layout::OperatorSnapshotEntry;
    use super::*;
    use object_store::memory::InMemory;

    fn make_checkpointer() -> ObjectStoreCheckpointer {
        let store = Arc::new(InMemory::new());
        let paths = CheckpointPaths::default();
        ObjectStoreCheckpointer::new(store, paths, 4)
    }

    #[tokio::test]
    async fn test_save_and_load_manifest() {
        let ckpt = make_checkpointer();
        let id = CheckpointId::now();
        let manifest = CheckpointManifestV2::new(id, 1);

        ckpt.save_manifest(&manifest).await.unwrap();
        let loaded = ckpt.load_manifest(&id).await.unwrap();

        assert_eq!(loaded.checkpoint_id, id);
        assert_eq!(loaded.epoch, 1);
    }

    #[tokio::test]
    async fn test_save_snapshot_with_digest() {
        let ckpt = make_checkpointer();
        let id = CheckpointId::now();
        let data = Bytes::from_static(b"hello world");

        let digest = ckpt
            .save_snapshot(&id, "window-agg", 0, data.clone())
            .await
            .unwrap();

        // Verify digest
        assert!(!digest.is_empty());
        verify_integrity("test", &data, &digest).unwrap();
    }

    #[tokio::test]
    async fn test_load_artifact() {
        let ckpt = make_checkpointer();
        let id = CheckpointId::now();
        let data = Bytes::from_static(b"partition state");

        ckpt.save_snapshot(&id, "op1", 0, data.clone())
            .await
            .unwrap();

        let path = ckpt.paths.snapshot(&id, "op1", 0);
        let loaded = ckpt.load_artifact(&path).await.unwrap();
        assert_eq!(loaded, data);
    }

    #[tokio::test]
    async fn test_latest_pointer() {
        let ckpt = make_checkpointer();

        // No latest yet
        assert!(ckpt.read_latest().await.unwrap().is_none());

        let id = CheckpointId::now();
        ckpt.update_latest(&id).await.unwrap();

        let latest = ckpt.read_latest().await.unwrap().unwrap();
        assert_eq!(latest, id);
    }

    #[tokio::test]
    async fn test_concurrent_partition_uploads() {
        let ckpt = make_checkpointer();
        let id = CheckpointId::now();

        let snapshots = vec![
            ("op1".into(), 0, false, Bytes::from_static(b"part0")),
            ("op1".into(), 1, false, Bytes::from_static(b"part1")),
            ("op1".into(), 2, true, Bytes::from_static(b"delta2")),
        ];

        let entries = ckpt
            .save_partitions_concurrent(&id, snapshots)
            .await
            .unwrap();

        assert_eq!(entries.len(), 3);
        for (_, entry) in &entries {
            assert!(entry.sha256.is_some());
        }
    }

    #[tokio::test]
    async fn test_integrity_mismatch() {
        let result = verify_integrity("test.snap", b"data", "wrong_hash");
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            CheckpointerError::IntegrityMismatch { .. }
        ));
    }

    #[tokio::test]
    async fn test_save_and_build_manifest() {
        let ckpt = make_checkpointer();
        let id = CheckpointId::now();

        // Save partitions
        let snapshots = vec![
            ("op1".into(), 0, false, Bytes::from_static(b"state0")),
            ("op1".into(), 1, false, Bytes::from_static(b"state1")),
        ];
        let entries = ckpt
            .save_partitions_concurrent(&id, snapshots)
            .await
            .unwrap();

        // Build manifest from entries
        let mut manifest = CheckpointManifestV2::new(id, 5);
        let mut op_entry = OperatorSnapshotEntry {
            partitions: Vec::new(),
            total_bytes: 0,
        };
        for (_, part) in entries {
            op_entry.total_bytes += part.size_bytes;
            op_entry.partitions.push(part);
        }
        manifest.operators.insert("op1".into(), op_entry);

        ckpt.save_manifest(&manifest).await.unwrap();
        ckpt.update_latest(&id).await.unwrap();

        // Verify round-trip
        let loaded = ckpt.load_manifest(&id).await.unwrap();
        assert_eq!(loaded.operators.len(), 1);
        assert_eq!(loaded.operators["op1"].partitions.len(), 2);
    }
}