# checkpointkit - Specification
## Overview
`checkpointkit` persists serializable Rust state to disk atomically and provides a resumable progress tracker for long-running operations. It serializes state as JSON and uses a temp-file-plus-rename pattern so readers always see a complete old or new file, never a partial write.
## Architecture
The crate has three internal modules:
- **`io`** - `save` and `load`.
- **`progress`** - `ProgressTracker` and its internal `ProgressState`.
- **`error`** - `CheckpointError`.
**Write path (`save`):**
1. Path validation - rejects paths containing `..` (`Component::ParentDir`).
2. Parent directory creation via `fs::create_dir_all`.
3. Temp file allocation in the same directory with a unique 64-bit suffix (derived from PID, thread ID hash, atomic counter, and nanosecond timestamp).
4. `TempFileGuard` wraps the temp path; on drop it deletes the temp file unless `commit()` was called after a successful rename.
5. Buffered JSON serialization via `BufWriter`.
6. `sync_all` on the temp file, atomic `fs::rename` to the final path, then `sync_all` on the parent directory.
**Read path (`load`):**
1. Path validation - same traversal check.
2. Returns `Ok(None)` if the file is missing or has zero length.
3. Deserializes via `BufReader` and `serde_json`.
**Progress tracker:**
`ProgressTracker` holds `total`, in-memory `current`, checkpoint `path`, auto-save `interval`, and `last_save` timestamp. On construction it loads any existing `ProgressState` and clamps it to `total`. `increment(n)` saturates `current`, caps it at `total`, and auto-persists when the interval has elapsed or progress is complete. `flush()` forces an immediate persist. `Drop` attempts a best-effort final persist (errors are silently ignored).
## Guarantees
- **Atomic visibility:** Temp-file + `fs::rename` ensures the final path is replaced atomically.
- **Durability on success:** `sync_all` on the file before rename and on the parent directory after rename.
- **Concurrent safety:** Unique temp-file suffixes prevent collisions when multiple writers target the same path.
- **No orphan temp files on success:** `TempFileGuard` cleans up on failure or panic.
- **Graceful missing checkpoint:** `load` returns `None` for non-existent or empty files.
- **Progress monotonicity:** `ProgressTracker` saturates on increment and clamps resumed values to `total`.
## Public API
```rust
pub fn save(path: impl AsRef<Path>, state: &impl Serialize) -> Result<(), CheckpointError>;
pub fn load<T: DeserializeOwned>(path: impl AsRef<Path>) -> Result<Option<T>, CheckpointError>;
```
```rust
impl ProgressTracker {
pub fn new(total: u64, path: impl AsRef<Path>, interval: Duration) -> Result<Self, CheckpointError>;
pub fn increment(&mut self, n: u64) -> Result<u64, CheckpointError>;
pub fn resume(&self) -> Result<u64, CheckpointError>;
pub const fn current(&self) -> u64;
pub const fn total(&self) -> u64;
pub fn flush(&mut self) -> Result<(), CheckpointError>;
}
```
```rust
#[non_exhaustive]
pub enum CheckpointError {
Serialize(serde_json::Error),
Io { path: PathBuf, source: std::io::Error },
DiskFull { path: PathBuf, source: std::io::Error },
PathTraversal(PathBuf),
}
impl CheckpointError {
pub const fn is_disk_full(&self) -> bool;
}
```
## Error handling
All fallible operations return `CheckpointError`, which is `#[non_exhaustive]`.
- **`Serialize`** - `serde_json` cannot serialize the state or deserialize the file (schema mismatch, corrupted JSON).
- **`Io`** - General filesystem failure (permission denied, read-only directory, broken pipe, etc.).
- **`DiskFull`** - Specialized variant detected from `ErrorKind::StorageFull` or `ENOSPC` on Unix. Use `is_disk_full()` to identify it.
- **`PathTraversal`** - The supplied path contains `..` parent-directory references.
## Performance characteristics
- `save` is **O(N)** in serialized size, dominated by JSON serialization and `fsync`. Memory usage is bounded by the `BufWriter` buffer (default 8 KiB) plus the source state.
- `load` is **O(N)** in file size, with similar buffered memory usage.
- `ProgressTracker::increment` is **O(1)** amortized; I/O occurs only when the auto-save interval elapses or at completion.
- Unique suffix generation is **O(1)**.
## Limitations
- JSON only; no support for binary formats or compression.
- No schema migration support for checkpointed data.
- No encryption.
- No distributed consensus or locking beyond filesystem atomicity.
- `Drop`-based persists are best-effort and cannot return errors to the caller.
- Path traversal detection now canonicalizes parent directories and rejects final-path symlinks that resolve outside the canonical parent; `O_NOFOLLOW` is used on Unix to prevent races.
- Durability is limited by the host filesystem's `fsync` semantics.