checkpointkit 0.1.2

Crash-resume checkpoint persistence with atomic writes and progress tracking
Documentation
//! Adversarial audit tests for checkpointkit.

use checkpointkit::{load, save, CheckpointError, ProgressTracker};
use std::fs;
use std::io;
use std::path::Path;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use tempfile::tempdir;

#[test]
fn audit_corrupt_checkpoint_file() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("corrupt.json");
    fs::write(&path, vec![0xFF, 0x00, 0xFE, 0x77]).unwrap();
    let result: Result<Option<i32>, _> = load(&path);
    assert!(
        matches!(result, Err(CheckpointError::Serialize(_))),
        "Expected serialization error for corrupt binary file"
    );
}

#[test]
fn audit_power_loss_simulation_partial_write() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("power_loss.json");
    // Simulate a partial tmp file left behind by a crash
    let tmp_path = dir.path().join("power_loss.json.tmp.abcdef0123456789");
    fs::write(&tmp_path, r#"{"partial":"#).unwrap();

    // Since the actual file doesn't exist, load should return Ok(None)
    let result: Result<Option<i32>, _> = load(&path);
    assert_eq!(result.unwrap(), None, "Partial temp file should not affect loading the non-existent main file");
}

#[test]
fn audit_power_loss_simulation_partial_write_over_existing() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("power_loss2.json");
    save(&path, &42).unwrap();

    let tmp_path = dir.path().join("power_loss2.json.tmp.abcdef0123456789");
    fs::write(&tmp_path, r#"{"partial":"#).unwrap();

    // The existing file should still be readable
    let result: Result<Option<i32>, _> = load(&path);
    assert_eq!(result.unwrap(), Some(42), "Partial temp file should not corrupt existing valid checkpoint");
}

#[test]
fn audit_concurrent_save_load() {
    let dir = tempdir().unwrap();
    let path = Arc::new(dir.path().join("concurrent.json"));
    let mut handles = vec![];
    
    // Seed the file
    save(path.as_ref(), &0).unwrap();

    for i in 1..=50 {
        let p = Arc::clone(&path);
        handles.push(thread::spawn(move || {
            let _ = save(p.as_ref(), &i);
            let result: Result<Option<i32>, _> = load(p.as_ref());
            assert!(result.is_ok(), "Concurrent load should always succeed without torn reads");
        }));
    }

    for h in handles {
        h.join().unwrap();
    }
}

#[test]
fn audit_checkpoint_larger_than_disk_enospc_error() {
    // We simulate disk full by creating an error that matches ENOSPC and verifying CheckpointError::DiskFull
    let raw_error = io::Error::from_raw_os_error(libc::ENOSPC);
    let checkpoint_error = CheckpointError::from_io_error(Path::new("dummy").to_path_buf(), raw_error);
    assert!(checkpoint_error.is_disk_full(), "ENOSPC should map to DiskFull error");
    
    let kind_error = io::Error::new(io::ErrorKind::StorageFull, "no space left on device");
    let checkpoint_error_kind = CheckpointError::from_io_error(Path::new("dummy").to_path_buf(), kind_error);
    assert!(checkpoint_error_kind.is_disk_full(), "StorageFull kind should map to DiskFull error");
}

#[test]
fn audit_invalid_json() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("invalid.json");
    fs::write(&path, r#"{"not_closed": 42"#).unwrap();
    let result: Result<Option<i32>, _> = load(&path);
    assert!(
        matches!(result, Err(CheckpointError::Serialize(_))),
        "Invalid JSON should return a serialization error"
    );
}

#[test]
fn audit_zero_byte_checkpoint() {
    // An existing 0-byte checkpoint is corruption, not absence: `load` must
    // fail closed with CorruptCheckpoint. Treating it as `Ok(None)` would
    // silently discard a truncated checkpoint and restart from scratch.
    let dir = tempdir().unwrap();
    let path = dir.path().join("zerobyte.json");
    fs::write(&path, "").unwrap();

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

#[test]
fn audit_checkpoint_with_null_bytes_in_path() {
    let path = Path::new("test\0null.json");
    let result: Result<Option<i32>, _> = load(path);
    assert!(result.is_err(), "Loading from path with null bytes should error");
    
    let save_result = save(path, &42);
    assert!(save_result.is_err(), "Saving to path with null bytes should error");
}

#[test]
fn audit_read_only_directory() {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempdir().unwrap();
        let ro_dir = dir.path().join("ro");
        fs::create_dir(&ro_dir).unwrap();
        
        let mut perms = fs::metadata(&ro_dir).unwrap().permissions();
        perms.set_mode(0o555); // Read and execute only
        fs::set_permissions(&ro_dir, perms).unwrap();
        
        let path = ro_dir.join("test.json");
        let result = save(&path, &42);
        
        // Restore permissions so tempdir cleanup works
        let mut perms = fs::metadata(&ro_dir).unwrap().permissions();
        perms.set_mode(0o777);
        fs::set_permissions(&ro_dir, perms).unwrap();
        
        assert!(matches!(result, Err(CheckpointError::Io { .. })), "Saving to RO dir should return IO error");
    }
}

#[test]
fn audit_very_large_state() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("large.json");
    let large_state = vec![42; 100_000]; // 100k integers
    
    save(&path, &large_state).unwrap();
    let loaded: Vec<i32> = load(&path).unwrap().unwrap();
    assert_eq!(loaded, large_state, "Large state should load correctly");
}

#[test]
fn audit_progress_tracker_boundary_overflow() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("overflow.json");
    let mut tracker = ProgressTracker::new(u64::MAX, &path, Duration::ZERO).unwrap();
    
    tracker.increment(10).unwrap();
    assert_eq!(tracker.current(), 10);
    
    // Incrementing by u64::MAX should cap at total
    tracker.increment(u64::MAX).unwrap();
    assert_eq!(tracker.current(), u64::MAX);
    
    // Further increments should stay at u64::MAX
    tracker.increment(1).unwrap();
    assert_eq!(tracker.current(), u64::MAX);
}

#[cfg(unix)]
#[test]
fn audit_load_zero_permissions_returns_io_error() {
    use std::fs::{self, Permissions};
    use std::os::unix::fs::PermissionsExt;

    let dir = tempdir().unwrap();
    let path = dir.path().join("readonly.json");
    fs::write(&path, br#"42"#).unwrap();

    let original = fs::metadata(&path).unwrap().permissions().mode();
    fs::set_permissions(&path, Permissions::from_mode(0o000)).unwrap();

    let result: Result<Option<i32>, _> = load(&path);

    // Restore permissions so the temp directory can be cleaned up.
    let _ = fs::set_permissions(&path, Permissions::from_mode(original));

    assert!(
        matches!(result, Err(CheckpointError::Io { .. })),
        "loading a file with 000 permissions should yield an Io error: {result:?}"
    );
}