checkpointkit 0.1.2

Crash-resume checkpoint persistence with atomic writes and progress tracking
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
//! Input/Output operations for saving and loading checkpoints.

use crate::error::CheckpointError;
use serde::{de::DeserializeOwned, Serialize};
use std::fs::{self, File, OpenOptions};
use std::io::{BufReader, BufWriter, Write};
use std::path::{Component, Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
#[cfg(unix)]
use libc::O_NOFOLLOW;

/// Guard that cleans up a temp file unless explicitly committed.
///
/// `Drop` attempts [`std::fs::remove_file`]; failures cannot be reported because `Drop` has no
/// `Result` channel - callers rely on atomic `rename` for durability, not on temp deletion.
struct TempFileGuard {
    path: PathBuf,
    committed: bool,
}

impl TempFileGuard {
    fn new(path: PathBuf) -> Self {
        Self {
            path,
            committed: false,
        }
    }

    fn commit(mut self) -> PathBuf {
        self.committed = true;
        std::mem::take(&mut self.path)
    }
}

impl Drop for TempFileGuard {
    fn drop(&mut self) {
        if !self.committed && !self.path.as_os_str().is_empty() && fs::remove_file(&self.path).is_err() {
            // Best-effort cleanup; `Drop` cannot report I/O failures to the caller.
        }
    }
}

static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);

/// Nanoseconds of `now` relative to the Unix epoch, as an entropy input.
///
/// Uniqueness of a temp-file suffix does NOT depend on this value: the
/// process-global `TEMP_COUNTER` (a `SeqCst` `fetch_add`) is the real
/// guarantee that two suffixes from the same process differ, and PID + thread
/// id separate concurrent processes/threads. The timestamp only adds entropy.
///
/// For a normal clock this is the forward distance from the epoch. For a clock
/// set before 1970 (`duration_since` errors), we use the *absolute* distance
/// via [`std::time::SystemTimeError::duration`] rather than the old
/// `unwrap_or_default()` (which collapsed every pre-1970 clock to `0`,
/// discarding all timestamp entropy). The absolute offset keeps a pre-1970
/// clock contributing a distinct, non-zero value.
fn epoch_nanos(now: std::time::SystemTime) -> u128 {
    now.duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_else(|before_epoch| before_epoch.duration())
        .as_nanos()
}

fn generate_unique_suffix() -> u64 {
    use std::hash::{Hash, Hasher};

    let mut hasher = std::collections::hash_map::DefaultHasher::new();

    std::process::id().hash(&mut hasher);
    std::thread::current().id().hash(&mut hasher);
    TEMP_COUNTER
        .fetch_add(1, Ordering::SeqCst)
        .hash(&mut hasher);
    epoch_nanos(std::time::SystemTime::now()).hash(&mut hasher);

    hasher.finish()
}

fn temporary_path(path: &Path) -> PathBuf {
    let unique = generate_unique_suffix();
    let mut temp_name = path
        .file_name()
        .map_or_else(|| "checkpoint".into(), std::ffi::OsStr::to_os_string);
    temp_name.push(format!(".tmp.{unique:016x}"));
    path.with_file_name(temp_name)
}

fn resolve_and_guard_path(path: &Path) -> Result<(), CheckpointError> {
    // The caller already rejects literal `..` components. This function defends
    // against pre-existing symlinks that would cause reads/writes to escape the
    // requested parent directory.
    let Some(parent) = path.parent() else { return Ok(()) };
    if parent.as_os_str().is_empty() {
        return Ok(());
    }

    let Ok(canonical_parent) = fs::canonicalize(parent) else {
        // Parent does not exist yet (load on missing checkpoint) or is inaccessible.
        // Let the later I/O operation surface that error.
        return Ok(());
    };

    if let Ok(meta) = fs::symlink_metadata(path) {
        if meta.file_type().is_symlink() {
            let target = fs::read_link(path)
                .map_err(|source| CheckpointError::from_io_error(path.to_path_buf(), source))?;
            let target = if target.is_relative() {
                parent.join(target)
            } else {
                target
            };
            let resolved = fs::canonicalize(&target)
                .map_err(|_| CheckpointError::PathTraversal(path.to_path_buf()))?;
            let Some(resolved_parent) = resolved.parent() else {
                return Err(CheckpointError::PathTraversal(path.to_path_buf()));
            };
            if resolved_parent != canonical_parent {
                return Err(CheckpointError::PathTraversal(path.to_path_buf()));
            }
        }
    }

    Ok(())
}

fn create_file_no_follow(path: &Path) -> Result<File, std::io::Error> {
    let mut opts = OpenOptions::new();
    opts.create(true).write(true).truncate(true);
    #[cfg(unix)]
    opts.custom_flags(O_NOFOLLOW);
    opts.open(path)
}

fn open_file_no_follow(path: &Path) -> Result<File, std::io::Error> {
    let mut opts = OpenOptions::new();
    opts.read(true);
    #[cfg(unix)]
    opts.custom_flags(O_NOFOLLOW);
    opts.open(path)
}

/// Saves serializable state to `path` using unique temp file + rename for atomic replacement.
///
/// This operation is safe for concurrent use - multiple threads/processes can
/// save to the same path simultaneously without data corruption.
///
/// On error, any temporary files are automatically cleaned up.
///
/// # Examples
///
/// ```rust
/// use checkpointkit::save;
///
/// let path = tempfile::tempdir().unwrap().path().join("state.json");
/// save(&path, &42).unwrap();
/// ```
///
/// # Errors
///
/// Returns an error when the parent directory cannot be created, when the state
/// cannot be serialized to JSON, when the disk is full, or when the checkpoint
/// file cannot be written and atomically renamed into place.
pub fn save(path: impl AsRef<Path>, state: &impl Serialize) -> Result<(), CheckpointError> {
    let bytes = serde_json::to_vec(state).map_err(CheckpointError::Serialize)?;
    atomic_write(path, &bytes)
}

/// Atomically writes raw bytes to `path` using a unique temp file + rename.
///
/// This is the durability primitive underneath [`save`] (which is simply
/// `serialize` + `atomic_write`), exposed for callers that serialize their own
/// payload — e.g. a checkpoint format that is not plain compact JSON, or a
/// caller that layers additional locking/backup on top. Guarantees are
/// identical to [`save`]: `..` and symlink path-traversal guards, `O_NOFOLLOW`
/// temp creation, fsync of both the file and its parent directory, atomic
/// rename into place, and automatic temp-file cleanup on any error.
///
/// Safe for concurrent use: the temp file name is process/thread/counter
/// unique, so multiple writers to the same `path` never corrupt each other.
///
/// # Errors
///
/// Returns an error when `path` contains a `..` component or resolves through a
/// symlink escaping its parent, when the parent directory cannot be created,
/// when the disk is full, or when the temp file cannot be written and
/// atomically renamed into place.
pub fn atomic_write(path: impl AsRef<Path>, bytes: &[u8]) -> Result<(), CheckpointError> {
    let path = path.as_ref();

    if path.components().any(|c| matches!(c, Component::ParentDir)) {
        return Err(CheckpointError::PathTraversal(path.to_path_buf()));
    }

    if let Some(parent) = path.parent() {
        if !parent.as_os_str().is_empty() {
            fs::create_dir_all(parent)
                .map_err(|source| CheckpointError::from_io_error(parent.to_path_buf(), source))?;
        }
    }

    resolve_and_guard_path(path)?;

    let temp_path = temporary_path(path);
    let guard = TempFileGuard::new(temp_path.clone());

    let file = create_file_no_follow(&temp_path)
        .map_err(|source| CheckpointError::from_io_error(temp_path.clone(), source))?;

    let mut writer = BufWriter::new(file);

    writer
        .write_all(bytes)
        .map_err(|source| CheckpointError::from_io_error(temp_path.clone(), source))?;

    let file = writer
        .into_inner()
        .map_err(|e| CheckpointError::from_io_error(temp_path.clone(), e.into_error()))?;

    file.sync_all()
        .map_err(|source| CheckpointError::from_io_error(temp_path.clone(), source))?;

    drop(file);

    fs::rename(&temp_path, path)
        .map_err(|source| CheckpointError::from_io_error(path.to_path_buf(), source))?;

    sync_parent_dir(path)?;

    let _committed_path = guard.commit();

    Ok(())
}

fn sync_parent_dir(path: &Path) -> Result<(), CheckpointError> {
    if let Some(parent) = path.parent() {
        if parent.as_os_str().is_empty() {
            return Ok(());
        }

        #[cfg(not(windows))]
        {
            let dir_file = File::open(parent)
                .map_err(|source| CheckpointError::from_io_error(parent.to_path_buf(), source))?;
            dir_file
                .sync_all()
                .map_err(|source| CheckpointError::from_io_error(parent.to_path_buf(), source))?;
        }
    }
    Ok(())
}

/// Loads serializable state from `path`, returning `Ok(None)` when no checkpoint exists.
///
/// # Examples
///
/// ```rust
/// use checkpointkit::{save, load};
///
/// let path = tempfile::tempdir().unwrap().path().join("state.json");
/// save(&path, &42).unwrap();
/// let value: i32 = load(&path).unwrap().unwrap();
/// assert_eq!(value, 42);
/// ```
///
/// # Errors
///
/// Returns an error when an existing checkpoint cannot be read, when it is
/// empty/truncated ([`CheckpointError::CorruptCheckpoint`]), or when the
/// checkpoint contents are not valid JSON for `T`. Absence (the file does not
/// exist) is reported as `Ok(None)`, never as an error.
pub fn load<T: DeserializeOwned>(path: impl AsRef<Path>) -> Result<Option<T>, CheckpointError> {
    let path = path.as_ref();

    if path.components().any(|c| matches!(c, Component::ParentDir)) {
        return Err(CheckpointError::PathTraversal(path.to_path_buf()));
    }

    resolve_and_guard_path(path)?;

    match open_file_no_follow(path) {
        Ok(file) => {
            // An existing but empty (0-byte) file is NOT "no checkpoint". `save`
            // writes JSON via an atomic rename and JSON is never 0 bytes (even
            // `null` is 4), so a 0-byte final file means the checkpoint was
            // truncated or externally clobbered. Fail CLOSED here instead of the
            // old `Ok(None)`, which silently restarted from scratch and would
            // discard a corrupt checkpoint with no operator signal (Law-10).
            match file.metadata() {
                Ok(meta) if meta.len() == 0 => {
                    return Err(CheckpointError::CorruptCheckpoint(path.to_path_buf()));
                }
                Ok(_) => {}
                // A metadata failure on an already-open handle is a real I/O
                // fault - surface it rather than assuming the file is non-empty
                // and blindly parsing (the old `is_ok_and` swallowed this).
                Err(source) => {
                    return Err(CheckpointError::from_io_error(path.to_path_buf(), source));
                }
            }
            let reader = BufReader::new(file);
            Ok(Some(serde_json::from_reader::<_, T>(reader)?))
        }
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(source) => Err(CheckpointError::from_io_error(path.to_path_buf(), source)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn generate_unique_suffix_produces_different_values() {
        let v1 = generate_unique_suffix();
        let v2 = generate_unique_suffix();
        let v3 = generate_unique_suffix();

        assert_ne!(v1, v2, "unique suffixes should be different");
        assert_ne!(v2, v3, "unique suffixes should be different");
    }

    #[test]
    fn temporary_path_includes_unique_suffix() {
        let path = Path::new("/tmp/checkpoint.json");
        let temp1 = temporary_path(path);
        let temp2 = temporary_path(path);

        assert_ne!(temp1, temp2, "temporary paths should be unique");
        assert!(
            temp1.to_string_lossy().contains(".tmp."),
            "temp path should contain .tmp. suffix"
        );
    }

    #[test]
    fn epoch_nanos_preserves_pre_1970_clock_entropy_instead_of_zero() {
        use std::time::{Duration, UNIX_EPOCH};

        // A clock set 5 seconds before the epoch used to collapse to 0 via
        // `unwrap_or_default()`, throwing away all timestamp entropy. The
        // documented fallback now yields the ABSOLUTE offset (5s in nanos), a
        // distinct non-zero value.
        let before_epoch = UNIX_EPOCH - Duration::from_secs(5);
        assert_eq!(
            epoch_nanos(before_epoch),
            5_000_000_000,
            "pre-1970 clock must contribute its absolute offset, not 0"
        );

        // The epoch itself is exactly 0 (boundary), and a normal forward time is
        // its forward distance.
        assert_eq!(epoch_nanos(UNIX_EPOCH), 0);
        assert_eq!(
            epoch_nanos(UNIX_EPOCH + Duration::from_nanos(1_234)),
            1_234,
            "a normal clock contributes its forward distance from the epoch"
        );

        // The two 5-second offsets (before vs after) must NOT hash to the same
        // input the old code produced (0 for before, 5e9 for after): entropy is
        // preserved on both sides.
        let after_epoch = UNIX_EPOCH + Duration::from_secs(5);
        assert_ne!(
            epoch_nanos(before_epoch),
            0,
            "the pre-1970 fallback must not degenerate to the old 0"
        );
        assert_eq!(epoch_nanos(before_epoch), epoch_nanos(after_epoch));
    }

    #[test]
    fn load_rejects_empty_checkpoint_file_instead_of_restarting() {
        // An existing 0-byte checkpoint is corruption, not absence. `load` must
        // fail closed with CorruptCheckpoint rather than silently returning
        // Ok(None) (which would discard the truncated checkpoint and restart).
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("state.json");
        std::fs::write(&path, b"").expect("write empty checkpoint");

        let result: Result<Option<u64>, _> = load(&path);
        assert!(
            matches!(&result, Err(CheckpointError::CorruptCheckpoint(p)) if p == &path),
            "empty checkpoint must fail closed as CorruptCheckpoint, got {result:?}"
        );
    }

    #[test]
    fn load_reports_absent_checkpoint_as_none_not_error() {
        // Genuine absence (file never created) must still be Ok(None) - only an
        // EXISTING empty file is an error.
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("missing.json");

        let result: Result<Option<u64>, _> = load(&path);
        assert!(
            matches!(result, Ok(None)),
            "an absent checkpoint must be Ok(None), got {result:?}"
        );
    }

    #[test]
    fn load_reads_back_a_real_checkpoint() {
        // Guard the fail-closed change against over-rejection: a normal non-empty
        // checkpoint round-trips to the exact saved value.
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("state.json");
        save(&path, &4_242_u64).expect("save");

        let value: u64 = load(&path).expect("load ok").expect("some value");
        assert_eq!(value, 4_242, "checkpoint must round-trip to the exact value");
    }
}