checkpointkit 0.1.4

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

use checkpointkit::{load, save, CheckpointError, ProgressTracker};
use serde::{Deserialize, Serialize};
use std::fs;
use std::time::Duration;
use tempfile::tempdir;

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

/// Simulate a completely garbled JSON file (e.g. from bit flips).
/// Verification: load() should return CheckpointError::Serialize.
#[test]
fn corruption_garbled_json_returns_error() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("corrupt1.json");

    fs::write(&path, b"{ \x00\x01\x02 garbled \xff }").unwrap();

    let result = load::<CorruptionState>(&path);
    assert!(
        matches!(result, Err(CheckpointError::Serialize(_))),
        "Expected Serialize error for garbled JSON, got {:?}",
        result
    );
}

/// Simulate a file that is valid JSON but the wrong schema entirely.
/// Verification: load() should return CheckpointError::Serialize.
#[test]
fn corruption_wrong_schema_returns_error() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("corrupt2.json");

    // Write a valid JSON array instead of the expected struct
    fs::write(&path, b"[\"some\", \"array\"]").unwrap();

    let result = load::<CorruptionState>(&path);
    assert!(
        matches!(result, Err(CheckpointError::Serialize(_))),
        "Expected Serialize error for wrong schema, got {:?}",
        result
    );
}

/// Simulate a file that has valid schema, but numeric fields are strings.
#[test]
fn corruption_wrong_types_in_schema_returns_error() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("corrupt3.json");

    // metadata should be u64, but is string here
    fs::write(&path, b"{\"value\": \"test\", \"metadata\": \"not_a_number\"}").unwrap();

    let result = load::<CorruptionState>(&path);
    assert!(
        matches!(result, Err(CheckpointError::Serialize(_))),
        "Expected Serialize error for wrong field types, got {:?}",
        result
    );
}

/// Simulate an empty file.
/// Verification: load() must fail closed with CorruptCheckpoint. An existing
/// 0-byte file is a truncated/corrupt checkpoint, not absence: JSON is never
/// 0 bytes and `save` renames only fully written files, so treating it as
/// `Ok(None)` would silently discard corruption and restart from scratch.
#[test]
fn corruption_empty_file_returns_none() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("corrupt4.json");

    fs::File::create(&path).unwrap(); // create empty file

    let result = load::<CorruptionState>(&path);
    assert!(
        matches!(&result, Err(CheckpointError::CorruptCheckpoint(p)) if p == &path),
        "Expected CorruptCheckpoint for empty file, got {:?}",
        result
    );
}

/// ProgressTracker corruption tests.
/// Check what happens when a progress tracker file gets corrupted.
#[test]
fn corruption_progress_tracker_returns_error() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("corrupt_tracker.json");

    // Write valid progress state first.
    let mut tracker = ProgressTracker::new(100, &path, Duration::ZERO).unwrap();
    tracker.increment(10).unwrap();
    drop(tracker);

    // Corrupt it.
    fs::write(&path, b"{\"total\": 100, \"progress\": ").unwrap(); // truncated JSON

    // Instantiating a new tracker on corrupted file should bubble up the error.
    let result = ProgressTracker::new(100, &path, Duration::ZERO);
    assert!(
        matches!(result, Err(CheckpointError::Serialize(_))),
        "Expected Serialize error for corrupted progress tracker, got {:?}",
        result
    );
}

/// Test that we can overwrite a corrupted file with a valid one via `save`.
/// The atomic rename should transparently replace the corrupted file.
#[test]
fn corruption_overwrite_corrupted_file_succeeds() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("corrupt5.json");

    // Start with corrupted file
    fs::write(&path, b"[[[garbage]]]").unwrap();
    assert!(load::<CorruptionState>(&path).is_err());

    // Overwrite with save
    let valid_state = CorruptionState {
        value: "recovered".to_string(),
        metadata: 42,
    };
    save(&path, &valid_state).unwrap();

    // Ensure it's now valid
    let loaded: CorruptionState = load(&path).unwrap().unwrap();
    assert_eq!(loaded, valid_state);
}

/// Truncated file simulating an incomplete write that somehow bypassed atomic rename.
#[test]
fn corruption_truncated_json_returns_error() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("corrupt6.json");

    // Valid JSON up to a point, then EOF
    fs::write(&path, b"{\"value\": \"test\", \"meta").unwrap();

    let result = load::<CorruptionState>(&path);
    assert!(
        matches!(result, Err(CheckpointError::Serialize(_))),
        "Expected Serialize error for truncated JSON, got {:?}",
        result
    );
}

/// A huge JSON payload where a single byte deep inside a string is flipped.
#[test]
fn corruption_single_bit_flip_in_large_payload() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("corrupt7.json");

    let state = CorruptionState {
        value: "a".repeat(1024 * 1024),
        metadata: 0,
    };
    save(&path, &state).unwrap();

    // Flip a bit in the middle of the JSON file
    let mut bytes = fs::read(&path).unwrap();
    let mid = bytes.len() / 2;
    bytes[mid] ^= 0x01;
    fs::write(&path, &bytes).unwrap();

    let result = load::<CorruptionState>(&path);
    
    // Depending on what we flipped, it might still parse (if it flipped an 'a' to a 'c' inside a string),
    // or it might error if it hit a structural character or escape sequence.
    // If it succeeds, the value MUST NOT equal the original state.
    match result {
        Ok(Some(loaded)) => {
            assert_ne!(loaded, state, "Bit flip did not change the loaded data!");
        }
        Ok(None) => panic!("Should not be None"),
        Err(_) => {
            // Error is perfectly fine (e.g. invalid UTF-8 in string or structural corruption)
        }
    }
}