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
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
534
535
536
537
538
539
540
541
use checkpointkit::{load, save, CheckpointError, ProgressTracker};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::Path;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use tempfile::tempdir;

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Version1State {
    value: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Version2State {
    value: String,
    new_field: Option<i32>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct LargeScanState {
    items_processed: u64,
    data: Vec<u64>,
}

// 1. Checkpoint save/restore correctness after crash simulation
#[test]
fn test_break_crash_during_rename() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("crash1.json");
    save(&path, &"initial").unwrap();
    
    // Simulate crash by creating a tmp file that never got renamed
    let tmp_path = dir.path().join("crash1.json.tmp.123");
    fs::write(&tmp_path, b"\"corrupt_tmp_data\"").unwrap();
    
    // Original should load fine
    let loaded: Option<String> = load(&path).unwrap();
    assert_eq!(loaded, Some("initial".to_string()));
}

#[test]
fn test_break_crash_leaves_empty_file() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("crash2.json");
    fs::write(&path, b"").unwrap(); // Empty file
    
    // An existing 0-byte checkpoint is corruption, not absence: `load` fails
    // closed with CorruptCheckpoint instead of silently restarting.
    let loaded: Result<Option<String>, _> = load(&path);
    assert!(
        matches!(&loaded, Err(CheckpointError::CorruptCheckpoint(p)) if p == &path),
        "expected CorruptCheckpoint for crash-truncated file, got {loaded:?}"
    );
}

#[test]
fn test_break_crash_leaves_partial_json() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("crash3.json");
    fs::write(&path, b"{\"value\":").unwrap();
    
    let loaded: Result<Option<Version1State>, _> = load(&path);
    assert!(matches!(loaded, Err(CheckpointError::Serialize(_))));
}

#[test]
fn test_break_crash_leaves_null_bytes() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("crash4.json");
    fs::write(&path, b"\0\0\0\0").unwrap();
    
    let loaded: Result<Option<Version1State>, _> = load(&path);
    assert!(matches!(loaded, Err(CheckpointError::Serialize(_))));
}

#[test]
fn test_break_crash_tmp_file_cleaned_on_next_save() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("crash5.json");
    let tmp_path = dir.path().join("crash5.json.tmp.999");
    fs::write(&tmp_path, b"junk").unwrap();
    
    // The next save doesn't explicitly delete old tmp files, it just ignores them or creates a new unique one
    save(&path, &"new").unwrap();
    
    let loaded: Option<String> = load(&path).unwrap();
    assert_eq!(loaded, Some("new".to_string()));
}

// 2. Checkpoint with zero progress
#[test]
fn test_break_zero_progress_tracker() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("zero1.json");
    
    let mut tracker = ProgressTracker::new(100, &path, Duration::ZERO).unwrap();
    tracker.increment(0).unwrap(); // Explicit zero progress increment
    
    let resumed = ProgressTracker::new(100, &path, Duration::ZERO).unwrap();
    assert_eq!(resumed.current(), 0);
}

#[test]
fn test_break_zero_progress_resume() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("zero2.json");
    
    let tracker = ProgressTracker::new(100, &path, Duration::ZERO).unwrap();
    assert_eq!(tracker.resume().unwrap(), 0);
}

#[test]
fn test_break_zero_progress_file_content() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("zero3.json");

    let mut tracker = ProgressTracker::new(100, &path, Duration::ZERO).unwrap();
    // Force a save of the initial (zero) progress state.
    tracker.flush().unwrap();

    // Read the file directly to verify it wrote {total: 100, progress: 0}
    let content = fs::read_to_string(&path).unwrap();
    assert!(content.contains("\"progress\":0"));
}

#[test]
fn test_break_zero_total_progress() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("zero4.json");
    
    let mut tracker = ProgressTracker::new(0, &path, Duration::ZERO).unwrap();
    tracker.increment(10).unwrap(); // Increment past total
    
    assert_eq!(tracker.current(), 0); // Should be capped at 0
}

// 3. Checkpoint at exact completion
#[test]
fn test_break_exact_completion_increment() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("comp1.json");
    
    let mut tracker = ProgressTracker::new(50, &path, Duration::from_secs(100)).unwrap();
    tracker.increment(50).unwrap();
    
    let resumed = ProgressTracker::new(50, &path, Duration::ZERO).unwrap();
    assert_eq!(resumed.current(), 50);
}

#[test]
fn test_break_exact_completion_multiple_steps() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("comp2.json");
    
    let mut tracker = ProgressTracker::new(10, &path, Duration::ZERO).unwrap();
    for _ in 0..10 {
        tracker.increment(1).unwrap();
    }
    
    assert_eq!(tracker.resume().unwrap(), 10);
}

#[test]
fn test_break_past_completion_capped() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("comp3.json");
    
    let mut tracker = ProgressTracker::new(10, &path, Duration::ZERO).unwrap();
    tracker.increment(100).unwrap();
    
    assert_eq!(tracker.current(), 10);
    assert_eq!(tracker.resume().unwrap(), 10);
}

#[test]
fn test_break_completion_resume_from_file() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("comp4.json");
    
    fs::write(&path, r#"{"total":10,"progress":10}"#).unwrap();
    
    let tracker = ProgressTracker::new(10, &path, Duration::ZERO).unwrap();
    assert_eq!(tracker.current(), 10);
}

// 4. Concurrent checkpoint writes
#[test]
fn test_break_concurrent_writers_progress() {
    let dir = tempdir().unwrap();
    let path = Arc::new(dir.path().join("conc1.json"));
    
    let mut handles = vec![];
    for _ in 0..10 {
        let path = Arc::clone(&path);
        handles.push(thread::spawn(move || {
            let mut tracker = ProgressTracker::new(1000, &*path, Duration::ZERO).unwrap();
            tracker.increment(10).unwrap();
        }));
    }
    
    for h in handles {
        h.join().unwrap();
    }
    
    // It should parse correctly, no corruption
    let tracker = ProgressTracker::new(1000, &*path, Duration::ZERO).unwrap();
    assert!(tracker.current() >= 10);
}

#[test]
fn test_break_concurrent_readers_and_writers() {
    let dir = tempdir().unwrap();
    let path = Arc::new(dir.path().join("conc2.json"));
    
    save(&*path, &0).unwrap();
    
    let mut handles = vec![];
    for i in 0..20 {
        let path = Arc::clone(&path);
        if i % 2 == 0 {
            handles.push(thread::spawn(move || {
                let _ = save(&*path, &i);
            }));
        } else {
            handles.push(thread::spawn(move || {
                let _loaded: Option<i32> = load(&*path).unwrap();
            }));
        }
    }
    
    for h in handles {
        h.join().unwrap();
    }
    
    let final_val: Option<i32> = load(&*path).unwrap();
    assert!(final_val.is_some());
}

#[test]
fn test_break_concurrent_saves_same_value() {
    let dir = tempdir().unwrap();
    let path = Arc::new(dir.path().join("conc3.json"));
    
    let mut handles = vec![];
    for _ in 0..10 {
        let path = Arc::clone(&path);
        handles.push(thread::spawn(move || {
            save(&*path, &42).unwrap();
        }));
    }
    
    for h in handles {
        h.join().unwrap();
    }
    
    let loaded: Option<i32> = load(&*path).unwrap();
    assert_eq!(loaded, Some(42));
}

#[test]
fn test_break_concurrent_rapid_updates() {
    let dir = tempdir().unwrap();
    let path = Arc::new(dir.path().join("conc4.json"));
    
    let mut handles = vec![];
    for i in 0..5 {
        let path = Arc::clone(&path);
        handles.push(thread::spawn(move || {
            for j in 0..50 {
                save(&*path, &(i * 100 + j)).unwrap();
            }
        }));
    }
    
    for h in handles {
        h.join().unwrap();
    }
    
    let loaded: Option<i32> = load(&*path).unwrap();
    assert!(loaded.is_some());
}

// 5. Corrupt checkpoint file recovery
#[test]
fn test_break_corrupt_recovery_overwrite() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("corr1.json");
    
    fs::write(&path, b"invalid_json").unwrap();
    
    // Load fails
    assert!(matches!(load::<i32>(&path), Err(CheckpointError::Serialize(_))));
    
    // Save overwrites it atomically
    save(&path, &99).unwrap();
    
    // Load succeeds now
    let loaded: Option<i32> = load(&path).unwrap();
    assert_eq!(loaded, Some(99));
}

#[test]
fn test_break_corrupt_recovery_progress_tracker() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("corr2.json");
    
    fs::write(&path, b"invalid").unwrap();
    
    // Tracker fails to initialize
    let res = ProgressTracker::new(100, &path, Duration::ZERO);
    assert!(matches!(res, Err(CheckpointError::Serialize(_))));
}

#[test]
fn test_break_corrupt_type_mismatch() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("corr3.json");
    
    save(&path, &"string_value").unwrap();
    
    // Try loading as int
    let res: Result<Option<i32>, _> = load(&path);
    assert!(matches!(res, Err(CheckpointError::Serialize(_))));
}

#[test]
fn test_break_corrupt_array_for_object() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("corr4.json");
    
    fs::write(&path, b"[1, 2, 3]").unwrap();
    
    let res: Result<Option<Version1State>, _> = load(&path);
    assert!(matches!(res, Err(CheckpointError::Serialize(_))));
}

#[test]
fn test_break_corrupt_whitespace_only() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("corr5.json");
    
    fs::write(&path, b"   \n  \t  ").unwrap();
    
    let res: Result<Option<i32>, _> = load(&path);
    assert!(matches!(res, Err(CheckpointError::Serialize(_))));
}

// 6. Checkpoint resume from middle of large scan
#[test]
fn test_break_large_scan_resume() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("scan1.json");
    
    let state = LargeScanState {
        items_processed: 500_000,
        data: vec![1, 2, 3, 4, 5],
    };
    save(&path, &state).unwrap();
    
    // Resume
    let loaded: LargeScanState = load(&path).unwrap().unwrap();
    assert_eq!(loaded.items_processed, 500_000);
    assert_eq!(loaded.data, vec![1, 2, 3, 4, 5]);
}

#[test]
fn test_break_large_scan_huge_data() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("scan2.json");
    
    let state = LargeScanState {
        items_processed: 100,
        data: vec![42; 100_000],
    };
    save(&path, &state).unwrap();
    
    let loaded: LargeScanState = load(&path).unwrap().unwrap();
    assert_eq!(loaded.data.len(), 100_000);
}

#[test]
fn test_break_large_scan_progress_tracker() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("scan3.json");
    
    // Middle of scan
    fs::write(&path, r#"{"total":1000000,"progress":500000}"#).unwrap();
    
    let mut tracker = ProgressTracker::new(1_000_000, &path, Duration::ZERO).unwrap();
    assert_eq!(tracker.current(), 500_000);
    
    tracker.increment(1).unwrap();
    assert_eq!(tracker.current(), 500_001);
}

#[test]
fn test_break_large_scan_progress_tracker_change_total() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("scan4.json");
    
    fs::write(&path, r#"{"total":1000000,"progress":500000}"#).unwrap();
    
    // New total is smaller than current progress
    let tracker = ProgressTracker::new(100_000, &path, Duration::ZERO).unwrap();
    assert_eq!(tracker.current(), 100_000); // Should be capped at new total
}

#[test]
fn test_break_large_scan_zero_progress_resume() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("scan5.json");
    
    let state = LargeScanState {
        items_processed: 0,
        data: vec![],
    };
    save(&path, &state).unwrap();
    
    let loaded: LargeScanState = load(&path).unwrap().unwrap();
    assert_eq!(loaded.items_processed, 0);
}

// 7. Checkpoint versioning across binary updates
#[test]
fn test_break_version_upgrade_forward_compatible() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("vers1.json");
    
    let v1 = Version1State { value: "test".to_string() };
    save(&path, &v1).unwrap();
    
    // Load as v2, missing field should become None (because Option is used)
    let v2: Version2State = load(&path).unwrap().unwrap();
    assert_eq!(v2.value, "test");
    assert_eq!(v2.new_field, None);
}

#[test]
fn test_break_version_downgrade_backward_compatible() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("vers2.json");
    
    let v2 = Version2State { value: "test".to_string(), new_field: Some(42) };
    save(&path, &v2).unwrap();
    
    // Load as v1, extra field is ignored by serde
    let v1: Version1State = load(&path).unwrap().unwrap();
    assert_eq!(v1.value, "test");
}

#[test]
fn test_break_version_upgrade_missing_required_field() {
    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    struct Version3State {
        value: String,
        required_field: i32,
    }

    let dir = tempdir().unwrap();
    let path = dir.path().join("vers3.json");
    
    let v1 = Version1State { value: "test".to_string() };
    save(&path, &v1).unwrap();
    
    // Load as v3, missing required field fails
    let res: Result<Option<Version3State>, _> = load(&path);
    assert!(matches!(res, Err(CheckpointError::Serialize(_))));
}

#[test]
fn test_break_version_type_change() {
    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    struct Version4State {
        value: i32, // Changed from String
    }

    let dir = tempdir().unwrap();
    let path = dir.path().join("vers4.json");
    
    let v1 = Version1State { value: "123".to_string() };
    save(&path, &v1).unwrap();
    
    // Type mismatch fails
    let res: Result<Option<Version4State>, _> = load(&path);
    assert!(matches!(res, Err(CheckpointError::Serialize(_))));
}

#[test]
fn test_break_version_enum_variants() {
    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    enum V1Enum { A, B }
    
    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    enum V2Enum { A, B, C }

    let dir = tempdir().unwrap();
    let path = dir.path().join("vers5.json");
    
    // Save V1 as B
    save(&path, &V1Enum::B).unwrap();
    
    // Load as V2, matches
    let loaded: V2Enum = load(&path).unwrap().unwrap();
    assert_eq!(loaded, V2Enum::B);
    
    // Save V2 as C
    save(&path, &V2Enum::C).unwrap();
    
    // Load as V1, fails
    let res: Result<Option<V1Enum>, _> = load(&path);
    assert!(matches!(res, Err(CheckpointError::Serialize(_))));
}

// Ensure 33+ tests
#[test]
fn test_break_progress_tracker_interval_not_elapsed() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("extra1.json");
    
    let mut tracker = ProgressTracker::new(100, &path, Duration::from_secs(1000)).unwrap();
    tracker.increment(1).unwrap();
    
    // Should not have saved because interval hasn't elapsed
    let file_exists = path.exists();
    assert!(!file_exists);
}

#[test]
fn test_break_progress_tracker_persist_error_propagation() {
    let dir = tempdir().unwrap();
    let _path = dir.path().join("readonly").join("extra2.json");
    
    // Directory doesn't exist, and parent is inaccessible... actually create_dir_all handles missing dirs.
    // Let's pass a null byte path instead.
    let path = Path::new("null\0dir/progress.json");
    let res = ProgressTracker::new(100, path, Duration::ZERO);
    assert!(matches!(res, Err(CheckpointError::Io { .. })));
}