sqlitegraph 2.0.7

Embedded graph database with full ACID transactions, HNSW vector search, dual backend support, and comprehensive graph algorithms library
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
//! V2 Invariant Validation
//!
//! This module provides V2-specific invariant validation for checkpoint operations.
//! It validates V2 graph file format invariants, cluster alignment, block sizes,
//! and other V2-specific requirements to ensure compatibility and correctness.

use crate::backend::native::v2::wal::V2WALConfig;
use crate::backend::native::v2::wal::checkpoint::constants::*;
use crate::backend::native::v2::wal::checkpoint::core::{
    CheckpointManagerState, CheckpointState, DirtyBlockTracker,
};
use crate::backend::native::v2::wal::checkpoint::errors::{CheckpointError, CheckpointResult};
use std::fs;
use std::time::SystemTime;

/// V2-specific invariant validation result
#[derive(Debug, Clone, serde::Serialize)]
pub struct V2InvariantResult {
    /// Overall invariant validation result
    pub invariants_held: bool,
    /// Invariant violations found
    pub violations: Vec<V2InvariantViolation>,
    /// Validation timestamp
    pub validation_timestamp: SystemTime,
    /// V2 version validated
    pub v2_version: Option<u32>,
}

/// V2 invariant violation details
#[derive(Debug, Clone, serde::Serialize)]
pub struct V2InvariantViolation {
    /// Violation type
    pub violation_type: V2InvariantViolationType,
    /// Violation description
    pub description: String,
    /// Expected value
    pub expected: Option<String>,
    /// Actual value found
    pub actual: Option<String>,
    /// Whether this is a critical invariant violation
    pub critical: bool,
}

/// Types of V2 invariant violations
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub enum V2InvariantViolationType {
    /// Invalid V2 version
    InvalidV2Version,
    /// V2 block size mismatch
    V2BlockSizeMismatch,
    /// V2 cluster alignment mismatch
    V2ClusterAlignmentMismatch,
    /// V2 metadata corruption
    V2MetadataCorruption,
    /// Cluster boundary violation
    ClusterBoundaryViolation,
    /// Block alignment violation
    BlockAlignmentViolation,
    /// V2 string table invariant violation
    V2StringTableViolation,
    /// V2 free space invariant violation
    V2FreeSpaceViolation,
    /// Clustered edge format violation
    ClusteredEdgeFormatViolation,
    /// Node record version mismatch
    NodeRecordVersionMismatch,
}

/// V2 invariant validator for checkpoint operations
pub struct V2InvariantValidator {
    config: V2WALConfig,
}

impl V2InvariantValidator {
    /// Create a new V2 invariant validator
    pub fn new(config: V2WALConfig) -> Self {
        Self { config }
    }

    /// Validate V2-specific metadata in checkpoint file
    pub fn validate_v2_metadata(
        &self,
        checkpoint_path: &std::path::Path,
    ) -> CheckpointResult<V2InvariantResult> {
        let mut violations = Vec::new();
        let start_time = SystemTime::now();

        let mut file = fs::File::open(checkpoint_path).map_err(|e| {
            CheckpointError::validation(format!("Failed to open checkpoint file: {}", e))
        })?;

        use std::io::{Read, Seek, SeekFrom};

        // Seek past LSN range (16 bytes) and timestamp (8 bytes) and block count (8 bytes)
        file.seek(SeekFrom::Start(36)).map_err(|e| {
            CheckpointError::validation(format!("Failed to seek to V2 metadata: {}", e))
        })?;

        // Read and validate V2 version
        let mut v2_version_bytes = [0u8; 4];
        file.read_exact(&mut v2_version_bytes).map_err(|e| {
            CheckpointError::validation(format!("Failed to read V2 version: {}", e))
        })?;

        let v2_version = u32::from_le_bytes(v2_version_bytes);
        if v2_version != 2 {
            violations.push(V2InvariantViolation {
                violation_type: V2InvariantViolationType::InvalidV2Version,
                description: format!(
                    "Unsupported V2 checkpoint version: {} (expected: 2)",
                    v2_version
                ),
                expected: Some("2".to_string()),
                actual: Some(v2_version.to_string()),
                critical: true,
            });
        }

        // Read and validate V2 block size
        let mut block_size_bytes = [0u8; 8];
        file.read_exact(&mut block_size_bytes).map_err(|e| {
            CheckpointError::validation(format!("Failed to read V2 block size: {}", e))
        })?;

        let block_size = u64::from_le_bytes(block_size_bytes);
        if block_size != v2::V2_GRAPH_BLOCK_SIZE {
            violations.push(V2InvariantViolation {
                violation_type: V2InvariantViolationType::V2BlockSizeMismatch,
                description: format!(
                    "Invalid V2 block size: {} (expected: {})",
                    block_size,
                    v2::V2_GRAPH_BLOCK_SIZE
                ),
                expected: Some(v2::V2_GRAPH_BLOCK_SIZE.to_string()),
                actual: Some(block_size.to_string()),
                critical: true,
            });
        }

        // Read and validate cluster alignment
        let mut alignment_bytes = [0u8; 8];
        file.read_exact(&mut alignment_bytes).map_err(|e| {
            CheckpointError::validation(format!("Failed to read V2 cluster alignment: {}", e))
        })?;

        let alignment = u64::from_le_bytes(alignment_bytes);
        if alignment != v2::V2_CLUSTER_ALIGNMENT {
            violations.push(V2InvariantViolation {
                violation_type: V2InvariantViolationType::V2ClusterAlignmentMismatch,
                description: format!(
                    "Invalid V2 cluster alignment: {} (expected: {})",
                    alignment,
                    v2::V2_CLUSTER_ALIGNMENT
                ),
                expected: Some(v2::V2_CLUSTER_ALIGNMENT.to_string()),
                actual: Some(alignment.to_string()),
                critical: true,
            });
        }

        let invariants_held = violations
            .iter()
            .all(|v: &V2InvariantViolation| !v.critical);

        Ok(V2InvariantResult {
            invariants_held,
            violations,
            validation_timestamp: start_time,
            v2_version: Some(v2_version),
        })
    }

    /// Validate V2 cluster alignment invariants
    pub fn validate_cluster_alignment_invariants(
        &self,
        _dirty_blocks: &DirtyBlockTracker,
    ) -> CheckpointResult<V2InvariantResult> {
        let violations = Vec::new();
        let start_time = SystemTime::now();

        // Check that all dirty block offsets are properly aligned
        let _alignment = v2::V2_CLUSTER_ALIGNMENT;

        // Block alignment checks commented out - no public API available for DirtyBlockTracker fields
        // for &block_offset in &dirty_blocks.global_dirty_blocks {
        //     if block_offset % alignment != 0 {
        //         violations.push(V2InvariantViolation {
        //             violation_type: V2InvariantViolationType::BlockAlignmentViolation,
        //             description: format!(
        //                 "Global dirty block {} not aligned to {}",
        //                 block_offset, alignment
        //             ),
        //             expected: Some(format!("offset % {} = 0", alignment)),
        //             actual: Some(format!("{}", block_offset % alignment)),
        //             critical: false,
        //         });
        //     }
        // }

        // // Check cluster-specific block alignments
        // for (cluster_key, cluster_blocks) in &dirty_blocks.cluster_dirty_blocks {
        //     for &block_offset in cluster_blocks {
        //         if block_offset % alignment != 0 {
        //             violations.push(V2InvariantViolation {
        //                 violation_type: V2InvariantViolationType::ClusterBoundaryViolation,
        //                 description: format!(
        //                     "Cluster {} dirty block {} not aligned to {}",
        //                     cluster_key, block_offset, alignment
        //                 ),
        //                 expected: Some(format!("offset % {} = 0", alignment)),
        //                 actual: Some(format!("{}", block_offset % alignment)),
        //                 critical: false,
        //             });
        //         }
        //     }
        // }

        let invariants_held = violations
            .iter()
            .all(|v: &V2InvariantViolation| !v.critical);

        Ok(V2InvariantResult {
            invariants_held,
            violations,
            validation_timestamp: start_time,
            v2_version: None,
        })
    }

    /// Validate V2 checkpoint state invariants
    ///
    /// Validates checkpoint state machine transitions and metadata consistency.
    /// Takes both the CheckpointState enum and CheckpointManagerState struct
    /// to properly validate state transitions and associated metadata.
    ///
    /// # Valid State Transitions
    ///
    /// The checkpoint state machine follows these valid transitions:
    /// - Idle -> Initializing
    /// - Initializing -> Collecting
    /// - Collecting -> Processing
    /// - Processing -> Flushing
    /// - Flushing -> Validating
    /// - Validating -> Complete
    /// - Any state -> Failed
    /// - Complete -> Idle (for next checkpoint)
    /// - Failed -> Idle (for retry)
    pub fn validate_checkpoint_state_invariants(
        &self,
        state: &CheckpointState,
        manager_state: &CheckpointManagerState,
    ) -> CheckpointResult<V2InvariantResult> {
        let mut violations = Vec::new();
        let start_time = SystemTime::now();

        // Validate state consistency with manager metadata
        // If manager_state.in_progress is true, state should NOT be Idle
        if manager_state.in_progress && matches!(state, CheckpointState::Idle) {
            violations.push(V2InvariantViolation {
                violation_type: V2InvariantViolationType::V2MetadataCorruption,
                description: "Checkpoint marked as in_progress but state is Idle".to_string(),
                expected: Some("state != Idle when in_progress is true".to_string()),
                actual: Some(format!("state = {:?}, in_progress = true", state)),
                critical: true,
            });
        }

        // If state is an active state, in_progress should be true
        if !manager_state.in_progress
            && (matches!(state, CheckpointState::Initializing)
                || matches!(state, CheckpointState::Collecting)
                || matches!(state, CheckpointState::Processing)
                || matches!(state, CheckpointState::Flushing)
                || matches!(state, CheckpointState::Validating))
        {
            violations.push(V2InvariantViolation {
                violation_type: V2InvariantViolationType::V2MetadataCorruption,
                description: format!(
                    "Checkpoint state {:?} indicates active work but in_progress is false",
                    state
                ),
                expected: Some("in_progress = true for active states".to_string()),
                actual: Some("in_progress = false".to_string()),
                critical: true,
            });
        }

        // If checkpoint_start_time is Some, state should be past Initializing
        if manager_state.checkpoint_start_time.is_some() {
            if matches!(state, CheckpointState::Idle) {
                violations.push(V2InvariantViolation {
                    violation_type: V2InvariantViolationType::V2MetadataCorruption,
                    description: "Checkpoint has start_time but state is Idle".to_string(),
                    expected: Some("state != Idle when start_time is Some".to_string()),
                    actual: Some(format!("state = {:?}, start_time = Some", state)),
                    critical: false,
                });
            }
        }

        // If state is Complete, completed_checkpoints should reflect the completed work
        if matches!(state, CheckpointState::Complete) {
            if manager_state.completed_checkpoints == 0 && manager_state.current_operation_id == 0 {
                // This is only a violation if we've performed an operation
                // (operation_id > 0 indicates a checkpoint was started)
                violations.push(V2InvariantViolation {
                    violation_type: V2InvariantViolationType::V2MetadataCorruption,
                    description: "Checkpoint state is Complete but no checkpoints recorded"
                        .to_string(),
                    expected: Some("completed_checkpoints > 0 when state is Complete".to_string()),
                    actual: Some("completed_checkpoints = 0, state = Complete".to_string()),
                    critical: false,
                });
            }
        }

        // Validate that in_progress flag is consistent with current_state
        if manager_state.current_state != *state {
            violations.push(V2InvariantViolation {
                violation_type: V2InvariantViolationType::V2MetadataCorruption,
                description: format!(
                    "Checkpoint state mismatch: state parameter {:?} != manager_state.current_state {:?}",
                    state, manager_state.current_state
                ),
                expected: Some("state == manager_state.current_state".to_string()),
                actual: Some(format!("state ({:?}) != current_state ({:?})", state, manager_state.current_state)),
                critical: true,
            });
        }

        let invariants_held = violations
            .iter()
            .all(|v: &V2InvariantViolation| !v.critical);

        Ok(V2InvariantResult {
            invariants_held,
            violations,
            validation_timestamp: start_time,
            v2_version: None,
        })
    }

    /// Validate V2 format compatibility invariants
    pub fn validate_v2_format_compatibility(
        &self,
        checkpoint_path: &std::path::Path,
    ) -> CheckpointResult<V2InvariantResult> {
        let mut violations = Vec::new();
        let start_time = SystemTime::now();

        // Read checkpoint file to validate format
        let mut file = fs::File::open(checkpoint_path).map_err(|e| {
            CheckpointError::validation(format!("Failed to open checkpoint file: {}", e))
        })?;

        use std::io::Read;

        // Read magic number
        let mut magic = [0u8; 4];
        file.read_exact(&mut magic).map_err(|e| {
            CheckpointError::validation(format!("Failed to read checkpoint magic: {}", e))
        })?;

        if magic != *CHECKPOINT_MAGIC {
            violations.push(V2InvariantViolation {
                violation_type: V2InvariantViolationType::V2MetadataCorruption,
                description: "Invalid checkpoint magic number".to_string(),
                expected: Some(format!("{:?}", CHECKPOINT_MAGIC)),
                actual: Some(format!("{:?}", magic)),
                critical: true,
            });
        }

        // Read version
        let mut version_bytes = [0u8; 4];
        file.read_exact(&mut version_bytes).map_err(|e| {
            CheckpointError::validation(format!("Failed to read checkpoint version: {}", e))
        })?;

        let version = u32::from_le_bytes(version_bytes);
        if version != CHECKPOINT_VERSION {
            violations.push(V2InvariantViolation {
                violation_type: V2InvariantViolationType::NodeRecordVersionMismatch,
                description: format!("Unsupported checkpoint version: {}", version),
                expected: Some(CHECKPOINT_VERSION.to_string()),
                actual: Some(version.to_string()),
                critical: true,
            });
        }

        // Verify file size is reasonable for V2 format
        let metadata = fs::metadata(checkpoint_path).map_err(|e| {
            CheckpointError::validation(format!("Failed to read checkpoint metadata: {}", e))
        })?;

        if metadata.len() < MIN_CHECKPOINT_SIZE {
            violations.push(V2InvariantViolation {
                violation_type: V2InvariantViolationType::V2MetadataCorruption,
                description: format!(
                    "Checkpoint file too small for V2 format: {} bytes (minimum: {})",
                    metadata.len(),
                    MIN_CHECKPOINT_SIZE
                ),
                expected: Some(format!(">= {} bytes", MIN_CHECKPOINT_SIZE)),
                actual: Some(format!("{} bytes", metadata.len())),
                critical: true,
            });
        }

        let invariants_held = violations
            .iter()
            .all(|v: &V2InvariantViolation| !v.critical);

        Ok(V2InvariantResult {
            invariants_held,
            violations,
            validation_timestamp: start_time,
            v2_version: Some(version),
        })
    }

    /// Validate V2-specific graph file invariants
    pub fn validate_v2_graph_file_invariants(
        &self,
        _graph_file_path: &std::path::Path,
    ) -> CheckpointResult<V2InvariantResult> {
        let violations = Vec::new();
        let start_time = SystemTime::now();

        // Note: This is a placeholder for V2 graph file invariant validation
        // In a full implementation, this would validate:
        // - V2 NodeRecord format invariants
        // - EdgeCluster alignment invariants
        // - String table invariants
        // - Free space management invariants
        // - Cluster boundary invariants

        // For now, we just return a successful result
        let invariants_held = true;

        Ok(V2InvariantResult {
            invariants_held,
            violations,
            validation_timestamp: start_time,
            v2_version: None,
        })
    }

    /// Perform comprehensive V2 invariant validation
    ///
    /// This method orchestrates all V2 invariant checks including metadata validation,
    /// cluster alignment, checkpoint state invariants, and format compatibility.
    pub fn validate_comprehensive_v2_invariants(
        &self,
        checkpoint_path: &std::path::Path,
        dirty_blocks: &DirtyBlockTracker,
        checkpoint_state: &CheckpointState,
        manager_state: &CheckpointManagerState,
    ) -> CheckpointResult<V2InvariantResult> {
        let mut all_violations = Vec::new();
        #[allow(unused_assignments)]
        let mut v2_version = None;

        // Validate V2 metadata
        let metadata_result = self.validate_v2_metadata(checkpoint_path)?;
        v2_version = metadata_result.v2_version;
        all_violations.extend(metadata_result.violations);

        // Validate cluster alignment invariants
        let alignment_result = self.validate_cluster_alignment_invariants(dirty_blocks)?;
        all_violations.extend(alignment_result.violations);

        // Validate checkpoint state invariants (now with manager_state)
        let state_result =
            self.validate_checkpoint_state_invariants(checkpoint_state, manager_state)?;
        all_violations.extend(state_result.violations);

        // Validate format compatibility
        let format_result = self.validate_v2_format_compatibility(checkpoint_path)?;
        all_violations.extend(format_result.violations);

        let invariants_held = all_violations.iter().all(|v| !v.critical);

        Ok(V2InvariantResult {
            invariants_held,
            violations: all_violations,
            validation_timestamp: SystemTime::now(),
            v2_version,
        })
    }
}

/// V2 invariant validation utilities
pub struct V2InvariantUtils;

impl V2InvariantUtils {
    /// Check if invariant violation is critical
    pub fn is_critical_violation(violation: &V2InvariantViolation) -> bool {
        violation.critical
            || match violation.violation_type {
                V2InvariantViolationType::InvalidV2Version => true,
                V2InvariantViolationType::V2BlockSizeMismatch => true,
                V2InvariantViolationType::V2ClusterAlignmentMismatch => true,
                V2InvariantViolationType::V2MetadataCorruption => true,
                V2InvariantViolationType::NodeRecordVersionMismatch => true,
                _ => false,
            }
    }

    /// Get invariant violation severity level
    pub fn get_violation_severity(violation: &V2InvariantViolation) -> V2InvariantSeverity {
        if Self::is_critical_violation(violation) {
            V2InvariantSeverity::Critical
        } else {
            match violation.violation_type {
                V2InvariantViolationType::ClusterBoundaryViolation => V2InvariantSeverity::Error,
                V2InvariantViolationType::BlockAlignmentViolation => V2InvariantSeverity::Warning,
                V2InvariantViolationType::ClusteredEdgeFormatViolation => {
                    V2InvariantSeverity::Error
                }
                V2InvariantViolationType::V2StringTableViolation => V2InvariantSeverity::Warning,
                V2InvariantViolationType::V2FreeSpaceViolation => V2InvariantSeverity::Warning,
                _ => V2InvariantSeverity::Error,
            }
        }
    }

    /// Calculate invariant compliance score
    pub fn calculate_compliance_score(violations: &[V2InvariantViolation]) -> f64 {
        if violations.is_empty() {
            return 1.0;
        }

        let critical_count = violations
            .iter()
            .filter(|v| Self::is_critical_violation(v))
            .count();
        let total_count = violations.len();

        if critical_count > 0 {
            return 0.0; // Any critical violation means failed compliance
        }

        // Score based on non-critical violations
        1.0 - (total_count as f64 * 0.1).max(0.0).min(1.0)
    }

    /// Get invariant violation summary
    pub fn get_violation_summary(violations: &[V2InvariantViolation]) -> V2InvariantSummary {
        let mut summary = V2InvariantSummary::default();

        for violation in violations {
            summary.total_violations += 1;

            match Self::get_violation_severity(violation) {
                V2InvariantSeverity::Critical => summary.critical_violations += 1,
                V2InvariantSeverity::Error => summary.error_violations += 1,
                V2InvariantSeverity::Warning => summary.warning_violations += 1,
                V2InvariantSeverity::Info => summary.info_violations += 1,
            }
        }

        summary.compliance_score = Self::calculate_compliance_score(violations);
        summary
    }
}

/// V2 invariant severity levels
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum V2InvariantSeverity {
    /// Informational level
    Info = 0,
    /// Warning level (non-critical)
    Warning = 1,
    /// Error level (may affect operation)
    Error = 2,
    /// Critical level (must be fixed)
    Critical = 3,
}

/// V2 invariant violation summary
#[derive(Debug, Clone, Default)]
pub struct V2InvariantSummary {
    /// Total number of violations
    pub total_violations: usize,
    /// Critical violations
    pub critical_violations: usize,
    /// Error violations
    pub error_violations: usize,
    /// Warning violations
    pub warning_violations: usize,
    /// Info violations
    pub info_violations: usize,
    /// Compliance score (0.0 to 1.0)
    pub compliance_score: f64,
}

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

    #[test]
    fn test_v2_invariant_validator_creation() {
        let temp_dir = tempdir().unwrap();
        let config = V2WALConfig {
            wal_path: temp_dir.path().join("test.wal"),
            checkpoint_path: temp_dir.path().join("test.checkpoint"),
            ..Default::default()
        };

        let validator = V2InvariantValidator::new(config);
        assert!(true, "V2 invariant validator created successfully");
    }

    #[test]
    fn test_cluster_alignment_invariants() {
        let temp_dir = tempdir().unwrap();
        let config = V2WALConfig {
            wal_path: temp_dir.path().join("test.wal"),
            checkpoint_path: temp_dir.path().join("test.checkpoint"),
            ..Default::default()
        };

        let validator = V2InvariantValidator::new(config);
        let dirty_blocks = DirtyBlockTracker::new(100, 100);

        let result = validator.validate_cluster_alignment_invariants(&dirty_blocks);
        assert!(result.is_ok());
        let invariant_result = result.unwrap();
        assert!(invariant_result.invariants_held);
        assert!(invariant_result.violations.is_empty());
    }

    #[test]
    fn test_checkpoint_state_invariants() {
        let temp_dir = tempdir().unwrap();
        let config = V2WALConfig {
            wal_path: temp_dir.path().join("test.wal"),
            checkpoint_path: temp_dir.path().join("test.checkpoint"),
            ..Default::default()
        };

        let validator = V2InvariantValidator::new(config);
        let state = CheckpointState::default();
        let manager_state = CheckpointManagerState::default();

        let result = validator.validate_checkpoint_state_invariants(&state, &manager_state);
        assert!(result.is_ok());
        let invariant_result = result.unwrap();
        assert!(invariant_result.invariants_held);
    }

    #[test]
    fn test_valid_state_transitions() {
        let temp_dir = tempdir().unwrap();
        let config = V2WALConfig {
            wal_path: temp_dir.path().join("test.wal"),
            checkpoint_path: temp_dir.path().join("test.checkpoint"),
            ..Default::default()
        };

        let validator = V2InvariantValidator::new(config);

        // Test valid state transition: Idle with no in-progress
        let state = CheckpointState::Idle;
        let mut manager_state = CheckpointManagerState::default();
        manager_state.in_progress = false;

        let result = validator.validate_checkpoint_state_invariants(&state, &manager_state);
        assert!(result.is_ok());
        let invariant_result = result.unwrap();
        assert!(invariant_result.invariants_held);
        assert!(invariant_result.violations.is_empty());

        // Test valid state: Collecting with in_progress=true
        let state = CheckpointState::Collecting;
        manager_state.current_state = CheckpointState::Collecting;
        manager_state.in_progress = true;
        manager_state.checkpoint_start_time = Some(std::time::Instant::now());

        let result = validator.validate_checkpoint_state_invariants(&state, &manager_state);
        assert!(result.is_ok());
        let invariant_result = result.unwrap();
        assert!(invariant_result.invariants_held);
        assert!(invariant_result.violations.is_empty());

        // Test valid state: Complete with completed_checkpoints > 0
        let state = CheckpointState::Complete;
        manager_state.current_state = CheckpointState::Complete;
        manager_state.in_progress = false;
        manager_state.completed_checkpoints = 1;

        let result = validator.validate_checkpoint_state_invariants(&state, &manager_state);
        assert!(result.is_ok());
        let invariant_result = result.unwrap();
        assert!(invariant_result.invariants_held);
        assert!(invariant_result.violations.is_empty());
    }

    #[test]
    fn test_invalid_state_transition_idle_with_in_progress() {
        let temp_dir = tempdir().unwrap();
        let config = V2WALConfig {
            wal_path: temp_dir.path().join("test.wal"),
            checkpoint_path: temp_dir.path().join("test.checkpoint"),
            ..Default::default()
        };

        let validator = V2InvariantValidator::new(config);

        // Test invalid: Idle state with in_progress=true
        let state = CheckpointState::Idle;
        let mut manager_state = CheckpointManagerState::default();
        manager_state.current_state = CheckpointState::Idle;
        manager_state.in_progress = true;

        let result = validator.validate_checkpoint_state_invariants(&state, &manager_state);
        assert!(result.is_ok());
        let invariant_result = result.unwrap();
        // Should have violation for Idle with in_progress=true
        assert!(!invariant_result.invariants_held);
        assert!(!invariant_result.violations.is_empty());
        assert!(invariant_result.violations.iter().any(|v| v.critical
            && matches!(
                v.violation_type,
                V2InvariantViolationType::V2MetadataCorruption
            )));
    }

    #[test]
    fn test_invalid_state_active_without_in_progress() {
        let temp_dir = tempdir().unwrap();
        let config = V2WALConfig {
            wal_path: temp_dir.path().join("test.wal"),
            checkpoint_path: temp_dir.path().join("test.checkpoint"),
            ..Default::default()
        };

        let validator = V2InvariantValidator::new(config);

        // Test invalid: Processing state with in_progress=false
        let state = CheckpointState::Processing;
        let mut manager_state = CheckpointManagerState::default();
        manager_state.current_state = CheckpointState::Processing;
        manager_state.in_progress = false;

        let result = validator.validate_checkpoint_state_invariants(&state, &manager_state);
        assert!(result.is_ok());
        let invariant_result = result.unwrap();
        // Should have violation for active state with in_progress=false
        assert!(!invariant_result.invariants_held);
        assert!(!invariant_result.violations.is_empty());
    }

    #[test]
    fn test_failed_state_from_any() {
        let temp_dir = tempdir().unwrap();
        let config = V2WALConfig {
            wal_path: temp_dir.path().join("test.wal"),
            checkpoint_path: temp_dir.path().join("test.checkpoint"),
            ..Default::default()
        };

        let validator = V2InvariantValidator::new(config);

        // Test valid transition to Failed from any state
        let state = CheckpointState::Failed;
        let mut manager_state = CheckpointManagerState::default();
        manager_state.current_state = CheckpointState::Failed;
        manager_state.in_progress = false;
        manager_state.failed_attempts = 1;

        let result = validator.validate_checkpoint_state_invariants(&state, &manager_state);
        assert!(result.is_ok());
        let invariant_result = result.unwrap();
        assert!(invariant_result.invariants_held);
        assert!(invariant_result.violations.is_empty());
    }

    #[test]
    fn test_v2_invariant_utils_severity() {
        let critical_violation = V2InvariantViolation {
            violation_type: V2InvariantViolationType::InvalidV2Version,
            description: "Invalid version".to_string(),
            expected: Some("2".to_string()),
            actual: Some("1".to_string()),
            critical: true,
        };

        assert!(V2InvariantUtils::is_critical_violation(&critical_violation));
        assert_eq!(
            V2InvariantUtils::get_violation_severity(&critical_violation),
            V2InvariantSeverity::Critical
        );

        let warning_violation = V2InvariantViolation {
            violation_type: V2InvariantViolationType::BlockAlignmentViolation,
            description: "Block not aligned".to_string(),
            expected: None,
            actual: None,
            critical: false,
        };

        assert!(!V2InvariantUtils::is_critical_violation(&warning_violation));
        assert_eq!(
            V2InvariantUtils::get_violation_severity(&warning_violation),
            V2InvariantSeverity::Warning
        );
    }

    #[test]
    fn test_v2_invariant_utils_compliance_score() {
        let violations = vec![V2InvariantViolation {
            violation_type: V2InvariantViolationType::BlockAlignmentViolation,
            description: "Warning violation".to_string(),
            expected: None,
            actual: None,
            critical: false,
        }];

        let score = V2InvariantUtils::calculate_compliance_score(&violations);
        assert!(score < 1.0);
        assert!(score > 0.0);

        // Critical violations should result in zero compliance
        let critical_violations = vec![V2InvariantViolation {
            violation_type: V2InvariantViolationType::InvalidV2Version,
            description: "Critical violation".to_string(),
            expected: None,
            actual: None,
            critical: true,
        }];

        let critical_score = V2InvariantUtils::calculate_compliance_score(&critical_violations);
        assert_eq!(critical_score, 0.0);
    }

    #[test]
    fn test_v2_invariant_summary() {
        let violations = vec![
            V2InvariantViolation {
                violation_type: V2InvariantViolationType::InvalidV2Version,
                description: "Critical violation".to_string(),
                expected: None,
                actual: None,
                critical: true,
            },
            V2InvariantViolation {
                violation_type: V2InvariantViolationType::BlockAlignmentViolation,
                description: "Warning violation".to_string(),
                expected: None,
                actual: None,
                critical: false,
            },
        ];

        let summary = V2InvariantUtils::get_violation_summary(&violations);
        assert_eq!(summary.total_violations, 2);
        assert_eq!(summary.critical_violations, 1);
        assert_eq!(summary.compliance_score, 0.0); // Critical violations break compliance
    }

    #[test]
    fn test_v2_invariant_severity_ordering() {
        assert!(V2InvariantSeverity::Info < V2InvariantSeverity::Warning);
        assert!(V2InvariantSeverity::Warning < V2InvariantSeverity::Error);
        assert!(V2InvariantSeverity::Error < V2InvariantSeverity::Critical);
    }

    #[test]
    fn test_v2_graph_file_invariants() {
        let temp_dir = tempdir().unwrap();
        let config = V2WALConfig {
            wal_path: temp_dir.path().join("test.wal"),
            checkpoint_path: temp_dir.path().join("test.checkpoint"),
            ..Default::default()
        };

        let validator = V2InvariantValidator::new(config);
        let graph_file_path = temp_dir.path().join("test.graph");

        let result = validator.validate_v2_graph_file_invariants(&graph_file_path);
        assert!(result.is_ok());
        let invariant_result = result.unwrap();
        assert!(invariant_result.invariants_held);
        assert!(invariant_result.violations.is_empty());
    }
}