globalsearch 0.5.0

A multistart framework for global optimization with scatter search and local NLP solvers written in Rust
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
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
//! # Checkpointing Module
//!
//! This module provides robust checkpointing functionality for OQNLP optimizations,
//! enabling users to save and resume long-running optimization processes. This is
//! particularly valuable for expensive function evaluations or time-constrained environments.
//!
//! ## Features
//!
//! ### Automatic State Persistence
//! - **Complete State Capture**: Saves all algorithm state including reference sets,
//!   filter parameters, iteration counters, and random number generator state
//! - **Configurable Frequency**: Control how often checkpoints are saved
//! - **Binary Format**: Efficient serialization using bincode for fast I/O
//!
//! ### Flexible Resume Options
//! - **Exact Resume**: Continue optimization with identical parameters
//! - **Modified Resume**: Restart with updated parameters (e.g., more iterations)
//! - **Auto-Resume**: Automatically detect and load existing checkpoints
//!
//! ### Checkpoint Management
//! - **Multiple Strategies**: Keep all checkpoints or maintain only the latest
//! - **Custom Naming**: User-defined checkpoint file naming schemes
//! - **Directory Organization**: Configurable checkpoint storage locations
//! - **Cleanup Utilities**: Automatic management of old checkpoint files
//!
//! ## Usage Patterns
//!
//! ### Basic Checkpointing
//! ```rust
//! use globalsearch::checkpoint::CheckpointManager;
//! use globalsearch::types::CheckpointConfig;
//! use std::path::PathBuf;
//!
//! let config = CheckpointConfig {
//!     checkpoint_dir: PathBuf::from("./checkpoints"),
//!     checkpoint_name: "optimization".to_string(),
//!     save_frequency: 50,  // Save every 50 iterations
//!     keep_all: false,     // Keep only latest checkpoint
//!     auto_resume: true,   // Auto-resume if checkpoint exists
//! };
//!
//! let manager = CheckpointManager::new(config)?;
//! # Ok::<(), globalsearch::checkpoint::CheckpointError>(())
//! ```
//!
//! ### Long-Running Optimizations
//! Ideal for scenarios where:
//! - Function evaluations are expensive (minutes to hours per evaluation)
//! - Optimization runs for days or weeks
//! - System reliability is a concern
//! - Parameter tuning requires multiple restart attempts
//!
//! ## Error Handling
//!
//! The module provides comprehensive error handling for:
//! - File system I/O failures
//! - Serialization/deserialization errors
//! - Missing or corrupted checkpoint files
//! - Invalid checkpoint data

use crate::types::{CheckpointConfig, OQNLPCheckpoint};
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use thiserror::Error;

/// Wrapper for bincode v2 errors that can occur during encoding or decoding
#[derive(Debug, Error)]
pub enum BincodeError {
    /// Encoding error
    #[error("Encode error: {0}")]
    EncodeError(#[from] bincode::error::EncodeError),

    /// Decoding error
    #[error("Decode error: {0}")]
    DecodeError(#[from] bincode::error::DecodeError),
}

#[derive(Debug, Error)]
/// Errors that can occur during checkpointing operations.
///
/// This enum covers all possible failure modes when working with checkpoint
/// files, providing detailed error information for debugging and error handling.
///
/// ## Error Categories
///
/// ### I/O Errors
/// File system operations can fail due to:
/// - Insufficient disk space
/// - Permission issues
/// - Network storage problems
/// - Directory creation failures
///
/// ### Serialization Errors
/// Data encoding/decoding failures from:
/// - Corrupted checkpoint files
/// - Version incompatibilities
/// - Incomplete file writes
/// - Memory allocation issues
///
/// ### Missing Checkpoints
/// Occurs when trying to load non-existent checkpoints:
/// - File was deleted or moved
/// - Incorrect file path specification
/// - First run without existing checkpoints
///
/// ### Invalid Data
/// Checkpoint files that cannot be processed:
/// - Wrong file format
/// - Truncated or corrupted data
/// - Incompatible algorithm versions
pub enum CheckpointError {
    /// IO error when reading/writing checkpoint files
    ///
    /// Includes the operation being performed and the file path
    #[error("IO error during {operation} on '{path}': {source}")]
    IoError {
        operation: String,
        path: PathBuf,
        #[source]
        source: io::Error,
    },

    /// Serialization/deserialization error
    ///
    /// Includes whether it's encoding or decoding and the file involved
    #[error("Serialization error during {operation} of '{path}': {source}")]
    SerializationError {
        operation: String,
        path: PathBuf,
        #[source]
        source: BincodeError,
    },

    /// Checkpoint file not found
    ///
    /// Includes search path
    #[error("Checkpoint file not found at: {path}")]
    CheckpointNotFound { path: PathBuf },

    /// Invalid checkpoint data
    ///
    /// Includes file path and reason
    #[error("Invalid checkpoint data in '{path}': {reason}")]
    InvalidCheckpoint { path: PathBuf, reason: String },

    /// Directory creation failed
    ///
    /// Includes the directory path and reason for failure
    #[error("Failed to create checkpoint directory '{path}': {reason}")]
    DirectoryCreationFailed { path: PathBuf, reason: String },
}

/// Manages checkpoint creation, storage, and retrieval for OQNLP optimizations.
///
/// The `CheckpointManager` handles all aspects of optimization state persistence,
/// from initial configuration to final cleanup. It abstracts away the complexity
/// of file management and serialization.
///
/// ## Core Responsibilities
///
/// - **Configuration Management**: Handle checkpoint directory and naming settings
/// - **State Serialization**: Convert optimization state to/from binary format
/// - **File Operations**: Manage checkpoint file creation, reading, and cleanup
/// - **Error Handling**: Provide detailed error information for troubleshooting
///
/// ## Checkpoint Strategies
///
/// ### Single Checkpoint Mode (`keep_all = false`)
/// - Maintains only the most recent checkpoint
/// - Overwrites previous checkpoint on each save
/// - Minimal disk space usage
/// - Best for routine checkpointing
///
/// ### Archive Mode (`keep_all = true`)
/// - Preserves all checkpoint files with iteration numbers
/// - Enables rollback to any previous state
/// - Higher disk space requirements
/// - Best for experimental optimization
///
/// ## Example Usage
///
/// ```rust
/// use globalsearch::checkpoint::CheckpointManager;
/// use globalsearch::types::{CheckpointConfig, OQNLPCheckpoint};
/// use std::path::PathBuf;
///
/// // Configure checkpoint management
/// let config = CheckpointConfig {
///     checkpoint_dir: PathBuf::from("./my_optimization_checkpoints"),
///     checkpoint_name: "expensive_problem".to_string(),
///     save_frequency: 25,
///     keep_all: true,  // Archive all checkpoints
///     auto_resume: false,
/// };
///
/// let manager = CheckpointManager::new(config)?;
///
/// // Check if previous optimization exists
/// if manager.checkpoint_exists() {
///     println!("Found existing checkpoint, resuming optimization...");
///     let checkpoint = manager.load_latest_checkpoint()?;
///     // Resume optimization from checkpoint
/// } else {
///     println!("Starting fresh optimization...");
///     // Start new optimization
/// }
/// # Ok::<(), globalsearch::checkpoint::CheckpointError>(())
/// ```
pub struct CheckpointManager {
    config: CheckpointConfig,
}

impl CheckpointManager {
    /// Create a new checkpoint manager with the given configuration
    pub fn new(config: CheckpointConfig) -> Result<Self, CheckpointError> {
        if !config.checkpoint_dir.exists() {
            fs::create_dir_all(&config.checkpoint_dir).map_err(|e| CheckpointError::IoError {
                operation: "create_directory".to_string(),
                path: config.checkpoint_dir.clone(),
                source: e,
            })?;
        }

        Ok(Self { config })
    }

    /// Save a checkpoint to disk
    pub fn save_checkpoint(
        &self,
        checkpoint: &OQNLPCheckpoint,
        iteration: usize,
    ) -> Result<PathBuf, CheckpointError> {
        let filename = if self.config.keep_all {
            format!("{}_{:06}.bin", self.config.checkpoint_name, iteration)
        } else {
            format!("{}.bin", self.config.checkpoint_name)
        };

        let filepath = self.config.checkpoint_dir.join(filename);
        let encoded = bincode::serde::encode_to_vec(checkpoint, bincode::config::legacy())
            .map_err(BincodeError::EncodeError)
            .map_err(|e| CheckpointError::SerializationError {
                operation: "encode".to_string(),
                path: filepath.clone(),
                source: e,
            })?;
        fs::write(&filepath, encoded).map_err(|e| CheckpointError::IoError {
            operation: "write".to_string(),
            path: filepath.clone(),
            source: e,
        })?;

        Ok(filepath)
    }

    /// Load the latest checkpoint from disk
    pub fn load_latest_checkpoint(&self) -> Result<OQNLPCheckpoint, CheckpointError> {
        let checkpoint_path = if self.config.keep_all {
            self.find_latest_checkpoint()?
        } else {
            let filename = format!("{}.bin", self.config.checkpoint_name);
            self.config.checkpoint_dir.join(filename)
        };

        self.load_checkpoint_from_path(&checkpoint_path)
    }

    /// Load a specific checkpoint from a file path
    pub fn load_checkpoint_from_path(
        &self,
        path: &Path,
    ) -> Result<OQNLPCheckpoint, CheckpointError> {
        if !path.exists() {
            return Err(CheckpointError::CheckpointNotFound { path: path.to_path_buf() });
        }

        let encoded = fs::read(path).map_err(|e| CheckpointError::IoError {
            operation: "read".to_string(),
            path: path.to_path_buf(),
            source: e,
        })?;
        let (checkpoint, _): (OQNLPCheckpoint, usize) =
            bincode::serde::decode_from_slice(&encoded, bincode::config::legacy())
                .map_err(BincodeError::DecodeError)
                .map_err(|e| CheckpointError::SerializationError {
                    operation: "decode".to_string(),
                    path: path.to_path_buf(),
                    source: e,
                })?;

        Ok(checkpoint)
    }

    /// Check if a checkpoint exists
    pub fn checkpoint_exists(&self) -> bool {
        if self.config.keep_all {
            self.find_latest_checkpoint().is_ok()
        } else {
            let filename = format!("{}.bin", self.config.checkpoint_name);
            self.config.checkpoint_dir.join(filename).exists()
        }
    }

    /// Find the latest checkpoint file when keep_all is enabled
    fn find_latest_checkpoint(&self) -> Result<PathBuf, CheckpointError> {
        let entries =
            fs::read_dir(&self.config.checkpoint_dir).map_err(|e| CheckpointError::IoError {
                operation: "read_directory".to_string(),
                path: self.config.checkpoint_dir.clone(),
                source: e,
            })?;
        let pattern = format!("{}_", self.config.checkpoint_name);

        let mut latest_iteration = 0;
        let mut latest_path = None;

        for entry in entries {
            let entry = entry.map_err(|e| CheckpointError::IoError {
                operation: "read_directory_entry".to_string(),
                path: self.config.checkpoint_dir.clone(),
                source: e,
            })?;
            let path = entry.path();

            if let Some(filename) = path.file_name().and_then(|n| n.to_str()) {
                if filename.starts_with(&pattern) && filename.ends_with(".bin") {
                    let iteration_str = &filename[pattern.len()..filename.len() - 4];
                    if let Ok(iteration) = iteration_str.parse::<usize>() {
                        if iteration > latest_iteration {
                            latest_iteration = iteration;
                            latest_path = Some(path);
                        }
                    }
                }
            }
        }

        latest_path.ok_or_else(|| CheckpointError::CheckpointNotFound {
            path: self.config.checkpoint_dir.clone(),
        })
    }

    /// Clean up old checkpoint files (keep only the latest N files)
    pub fn cleanup_old_checkpoints(&self, keep_count: usize) -> Result<(), CheckpointError> {
        if !self.config.keep_all || keep_count == 0 {
            return Ok(());
        }

        let entries =
            fs::read_dir(&self.config.checkpoint_dir).map_err(|e| CheckpointError::IoError {
                operation: "read_directory".to_string(),
                path: self.config.checkpoint_dir.clone(),
                source: e,
            })?;
        let pattern = format!("{}_", self.config.checkpoint_name);

        let mut checkpoints = Vec::new();

        for entry in entries {
            let entry = entry.map_err(|e| CheckpointError::IoError {
                operation: "read_directory_entry".to_string(),
                path: self.config.checkpoint_dir.clone(),
                source: e,
            })?;
            let path = entry.path();

            if let Some(filename) = path.file_name().and_then(|n| n.to_str()) {
                if filename.starts_with(&pattern) && filename.ends_with(".bin") {
                    let iteration_str = &filename[pattern.len()..filename.len() - 4];
                    if let Ok(iteration) = iteration_str.parse::<usize>() {
                        checkpoints.push((iteration, path));
                    }
                }
            }
        }

        checkpoints.sort_by(|a, b| b.0.cmp(&a.0));
        for (_, path) in checkpoints.iter().skip(keep_count) {
            fs::remove_file(path).map_err(|e| CheckpointError::IoError {
                operation: "delete".to_string(),
                path: path.clone(),
                source: e,
            })?;
        }

        Ok(())
    }

    /// Get the checkpoint configuration
    pub fn config(&self) -> &CheckpointConfig {
        &self.config
    }
}

impl Default for CheckpointManager {
    fn default() -> Self {
        Self::new(CheckpointConfig::default()).unwrap()
    }
}

/// Read a checkpoint file directly from a given path
///
/// This is a convenience function that allows reading checkpoint files
/// without creating a `CheckpointManager` instance.
/// # Example
///
/// ```rust,no_run
/// use globalsearch::checkpoint::read_checkpoint_file;
/// use std::path::Path;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let checkpoint = read_checkpoint_file(Path::new("./checkpoints/optimization.bin"))?;
/// println!("Loaded checkpoint:");
/// println!("{}", checkpoint);
/// # Ok(())
/// # }
/// ```
pub fn read_checkpoint_file(path: &Path) -> Result<OQNLPCheckpoint, CheckpointError> {
    if !path.exists() {
        return Err(CheckpointError::CheckpointNotFound { path: path.to_path_buf() });
    }

    let encoded = fs::read(path).map_err(|e| CheckpointError::IoError {
        operation: "read".to_string(),
        path: path.to_path_buf(),
        source: e,
    })?;
    let (checkpoint, _): (OQNLPCheckpoint, usize) =
        bincode::serde::decode_from_slice(&encoded, bincode::config::legacy())
            .map_err(BincodeError::DecodeError)
            .map_err(|e| CheckpointError::SerializationError {
                operation: "decode".to_string(),
                path: path.to_path_buf(),
                source: e,
            })?;

    Ok(checkpoint)
}

#[cfg(test)]
mod tests_checkpointing {
    use crate::checkpoint::{
        CheckpointConfig, CheckpointError, CheckpointManager, OQNLPCheckpoint,
    };
    use crate::types::{LocalSolution, OQNLPParams, SolutionSet};
    use ndarray::{Array1, array};
    use std::env;
    use std::fs;

    // Helper function to count checkpoint files matching the pattern
    fn count_checkpoint_files(dir: &std::path::Path, prefix: &str) -> usize {
        let entries = fs::read_dir(dir).unwrap();
        entries
            .filter_map(|e| e.ok())
            .filter(|e| {
                if let Some(filename) = e.file_name().to_str() {
                    let pattern = format!("{}_", prefix);
                    if filename.starts_with(&pattern) && filename.ends_with(".bin") {
                        let iteration_str = &filename[pattern.len()..filename.len() - 4];
                        iteration_str.parse::<usize>().is_ok()
                    } else {
                        false
                    }
                } else {
                    false
                }
            })
            .count()
    }

    #[test]
    fn test_checkpoint_manager_creation() {
        let temp_dir = env::temp_dir().join("test_checkpoints");
        let config = CheckpointConfig {
            checkpoint_dir: temp_dir.clone(),
            checkpoint_name: "test".to_string(),
            save_frequency: 5,
            keep_all: false,
            auto_resume: true,
        };

        let _manager = CheckpointManager::new(config).unwrap();
        assert!(temp_dir.exists());

        // Cleanup
        let _ = fs::remove_dir_all(temp_dir);
    }

    #[test]
    fn test_save_and_load_checkpoint() {
        let temp_dir = env::temp_dir().join("test_checkpoints_2");
        let config = CheckpointConfig {
            checkpoint_dir: temp_dir.clone(),
            checkpoint_name: "test".to_string(),
            save_frequency: 5,
            keep_all: false,
            auto_resume: true,
        };

        let manager = CheckpointManager::new(config).unwrap();

        // Create a test checkpoint
        let checkpoint = OQNLPCheckpoint {
            params: OQNLPParams::default(),
            current_iteration: 42,
            merit_threshold: 1.5,
            solution_set: Some(SolutionSet {
                solutions: Array1::from(vec![LocalSolution {
                    point: array![1.0, 2.0],
                    objective: -1.0,
                }]),
            }),
            reference_set: vec![array![1.0, 2.0], array![3.0, 4.0]],
            unchanged_cycles: 5,
            elapsed_time: 120.5,
            distance_filter_solutions: vec![],
            current_seed: 10,
            target_objective: None,
            exclude_out_of_bounds: false,
            #[cfg(feature = "rayon")]
            batch_iterations: None,
            #[cfg(feature = "rayon")]
            enable_parallel: false,
            abs_tol: 1e-8,
            rel_tol: 1e-6,
            timestamp: "2025-01-01T00:00:00Z".to_string(),
        };

        // Save checkpoint
        let saved_path = manager.save_checkpoint(&checkpoint, 42).unwrap();
        assert!(saved_path.exists());

        // Load checkpoint
        let loaded_checkpoint = manager.load_latest_checkpoint().unwrap();
        assert_eq!(loaded_checkpoint.current_iteration, 42);
        assert_eq!(loaded_checkpoint.merit_threshold, 1.5);

        // Cleanup
        let _ = fs::remove_dir_all(temp_dir);
    }

    #[test]
    fn test_checkpoint_exists() {
        let temp_dir = env::temp_dir().join("test_checkpoints_3");
        let config = CheckpointConfig {
            checkpoint_dir: temp_dir.clone(),
            checkpoint_name: "test".to_string(),
            save_frequency: 5,
            keep_all: false,
            auto_resume: true,
        };

        let manager = CheckpointManager::new(config).unwrap();
        assert!(!manager.checkpoint_exists());

        // Create a dummy checkpoint
        let checkpoint = OQNLPCheckpoint {
            params: OQNLPParams::default(),
            current_iteration: 0,
            merit_threshold: f64::INFINITY,
            solution_set: None,
            reference_set: vec![],
            unchanged_cycles: 0,
            elapsed_time: 0.0,
            distance_filter_solutions: vec![],
            current_seed: 0,
            target_objective: None,
            exclude_out_of_bounds: false,
            #[cfg(feature = "rayon")]
            batch_iterations: None,
            #[cfg(feature = "rayon")]
            enable_parallel: false,
            abs_tol: 1e-8,
            rel_tol: 1e-6,
            timestamp: "2025-01-01T00:00:00Z".to_string(),
        };

        manager.save_checkpoint(&checkpoint, 0).unwrap();
        assert!(manager.checkpoint_exists());

        // Cleanup
        let _ = fs::remove_dir_all(temp_dir);
    }

    #[test]
    fn test_find_latest_checkpoint_with_keep_all() {
        let temp_dir = env::temp_dir().join("test_checkpoints_find_latest");
        let config = CheckpointConfig {
            checkpoint_dir: temp_dir.clone(),
            checkpoint_name: "test".to_string(),
            save_frequency: 5,
            keep_all: true, // Enable keep_all to test find_latest_checkpoint
            auto_resume: true,
        };

        let manager = CheckpointManager::new(config).unwrap();

        // Create a test checkpoint
        let checkpoint = OQNLPCheckpoint {
            params: OQNLPParams::default(),
            current_iteration: 0,
            merit_threshold: f64::INFINITY,
            solution_set: None,
            reference_set: vec![],
            unchanged_cycles: 0,
            elapsed_time: 0.0,
            distance_filter_solutions: vec![],
            current_seed: 0,
            target_objective: None,
            exclude_out_of_bounds: false,
            #[cfg(feature = "rayon")]
            batch_iterations: None,
            #[cfg(feature = "rayon")]
            enable_parallel: false,
            abs_tol: 1e-8,
            rel_tol: 1e-6,
            timestamp: "2025-01-01T00:00:00Z".to_string(),
        };

        // Save multiple checkpoints with different iterations
        manager.save_checkpoint(&checkpoint, 1).unwrap();
        manager.save_checkpoint(&checkpoint, 5).unwrap();
        manager.save_checkpoint(&checkpoint, 3).unwrap();
        manager.save_checkpoint(&checkpoint, 10).unwrap();
        manager.save_checkpoint(&checkpoint, 7).unwrap();

        // Verify that find_latest_checkpoint returns the highest iteration (10)
        let latest_path = manager.find_latest_checkpoint().unwrap();
        let filename = latest_path.file_name().unwrap().to_str().unwrap();
        assert!(
            filename.contains("000010"),
            "Expected filename to contain '000010', got: {}",
            filename
        );

        // Test loading the latest checkpoint
        let loaded_checkpoint = manager.load_latest_checkpoint().unwrap();
        assert_eq!(loaded_checkpoint.current_iteration, 0); // The checkpoint data itself

        // Test that checkpoint_exists returns true when keep_all is enabled
        assert!(manager.checkpoint_exists());

        // Create some non-matching files to ensure they're ignored
        let dummy_file1 = temp_dir.join("other_file.bin");
        let dummy_file2 = temp_dir.join("test_abc.bin"); // Wrong pattern
        let dummy_file3 = temp_dir.join("test_999.txt"); // Wrong extension
        fs::write(&dummy_file1, b"dummy").unwrap();
        fs::write(&dummy_file2, b"dummy").unwrap();
        fs::write(&dummy_file3, b"dummy").unwrap();

        // Verify that find_latest_checkpoint still returns the correct file
        let latest_path_after_dummies = manager.find_latest_checkpoint().unwrap();
        assert_eq!(latest_path, latest_path_after_dummies);

        // Cleanup
        let _ = fs::remove_dir_all(temp_dir);
    }

    #[test]
    fn test_find_latest_checkpoint_no_files() {
        let temp_dir = env::temp_dir().join("test_checkpoints_no_files");
        let config = CheckpointConfig {
            checkpoint_dir: temp_dir.clone(),
            checkpoint_name: "test".to_string(),
            save_frequency: 5,
            keep_all: true,
            auto_resume: true,
        };

        let manager = CheckpointManager::new(config).unwrap();

        // Test when no checkpoint files exist
        let result = manager.find_latest_checkpoint();
        assert!(result.is_err());
        match result {
            Err(CheckpointError::CheckpointNotFound { path }) => {
                assert_eq!(path, temp_dir);
            }
            _ => panic!("Expected CheckpointNotFound error"),
        }

        // Test that checkpoint_exists returns false
        assert!(!manager.checkpoint_exists());

        // Cleanup
        let _ = fs::remove_dir_all(temp_dir);
    }

    #[test]
    fn test_cleanup_old_checkpoints() {
        let temp_dir = env::temp_dir().join("test_checkpoints_cleanup");
        let config = CheckpointConfig {
            checkpoint_dir: temp_dir.clone(),
            checkpoint_name: "test".to_string(),
            save_frequency: 5,
            keep_all: true, // Enable keep_all to test cleanup
            auto_resume: true,
        };

        let manager = CheckpointManager::new(config).unwrap();

        // Create a test checkpoint
        let checkpoint = OQNLPCheckpoint {
            params: OQNLPParams::default(),
            current_iteration: 0,
            merit_threshold: f64::INFINITY,
            solution_set: None,
            reference_set: vec![],
            unchanged_cycles: 0,
            elapsed_time: 0.0,
            distance_filter_solutions: vec![],
            current_seed: 0,
            target_objective: None,
            exclude_out_of_bounds: false,
            #[cfg(feature = "rayon")]
            batch_iterations: None,
            #[cfg(feature = "rayon")]
            enable_parallel: false,
            abs_tol: 1e-8,
            rel_tol: 1e-6,
            timestamp: "2025-01-01T00:00:00Z".to_string(),
        };

        // Save multiple checkpoints
        manager.save_checkpoint(&checkpoint, 1).unwrap();
        manager.save_checkpoint(&checkpoint, 2).unwrap();
        manager.save_checkpoint(&checkpoint, 3).unwrap();
        manager.save_checkpoint(&checkpoint, 4).unwrap();
        manager.save_checkpoint(&checkpoint, 5).unwrap();
        manager.save_checkpoint(&checkpoint, 6).unwrap();
        manager.save_checkpoint(&checkpoint, 7).unwrap();

        // Verify all files exist
        assert_eq!(count_checkpoint_files(&temp_dir, "test"), 7);

        // Keep only 3 files
        manager.cleanup_old_checkpoints(3).unwrap();

        // Verify only 3 files remain
        assert_eq!(count_checkpoint_files(&temp_dir, "test"), 3);

        // Verify that the latest files are kept (5, 6, 7)
        let entries = fs::read_dir(&temp_dir).unwrap();
        let remaining_files: Vec<_> = entries
            .filter_map(|e| e.ok())
            .filter(|e| {
                if let Some(filename) = e.file_name().to_str() {
                    if filename.starts_with("test_") && filename.ends_with(".bin") {
                        let iteration_str = &filename[5..filename.len() - 4];
                        iteration_str.parse::<usize>().is_ok()
                    } else {
                        false
                    }
                } else {
                    false
                }
            })
            .collect();
        let mut filenames: Vec<_> =
            remaining_files.iter().map(|e| e.file_name().to_str().unwrap().to_string()).collect();
        filenames.sort();
        assert!(filenames.contains(&"test_000005.bin".to_string()));
        assert!(filenames.contains(&"test_000006.bin".to_string()));
        assert!(filenames.contains(&"test_000007.bin".to_string()));

        // Cleanup
        let _ = fs::remove_dir_all(temp_dir);
    }

    #[test]
    fn test_cleanup_old_checkpoints_keep_all_disabled() {
        let temp_dir = env::temp_dir().join("test_checkpoints_cleanup_disabled");
        let config = CheckpointConfig {
            checkpoint_dir: temp_dir.clone(),
            checkpoint_name: "test".to_string(),
            save_frequency: 5,
            keep_all: false, // Disable keep_all
            auto_resume: true,
        };

        let manager = CheckpointManager::new(config).unwrap();

        // Create a test checkpoint
        let checkpoint = OQNLPCheckpoint {
            params: OQNLPParams::default(),
            current_iteration: 0,
            merit_threshold: f64::INFINITY,
            solution_set: None,
            reference_set: vec![],
            unchanged_cycles: 0,
            elapsed_time: 0.0,
            distance_filter_solutions: vec![],
            current_seed: 0,
            target_objective: None,
            exclude_out_of_bounds: false,
            #[cfg(feature = "rayon")]
            batch_iterations: None,
            #[cfg(feature = "rayon")]
            enable_parallel: false,
            abs_tol: 1e-8,
            rel_tol: 1e-6,
            timestamp: "2025-01-01T00:00:00Z".to_string(),
        };

        // Save a checkpoint (this will overwrite the same file since keep_all is false)
        manager.save_checkpoint(&checkpoint, 1).unwrap();

        // Cleanup should do nothing when keep_all is false
        let result = manager.cleanup_old_checkpoints(1);
        assert!(result.is_ok());

        // File should still exist
        let filename = "test.bin".to_string();
        let filepath = temp_dir.join(filename);
        assert!(filepath.exists());

        // Cleanup
        let _ = fs::remove_dir_all(temp_dir);
    }

    #[test]
    fn test_cleanup_old_checkpoints_keep_count_zero() {
        let temp_dir = env::temp_dir().join("test_checkpoints_cleanup_zero");
        let config = CheckpointConfig {
            checkpoint_dir: temp_dir.clone(),
            checkpoint_name: "test".to_string(),
            save_frequency: 5,
            keep_all: true,
            auto_resume: true,
        };

        let manager = CheckpointManager::new(config).unwrap();

        // Create a test checkpoint
        let checkpoint = OQNLPCheckpoint {
            params: OQNLPParams::default(),
            current_iteration: 0,
            merit_threshold: f64::INFINITY,
            solution_set: None,
            reference_set: vec![],
            unchanged_cycles: 0,
            elapsed_time: 0.0,
            distance_filter_solutions: vec![],
            current_seed: 0,
            target_objective: None,
            exclude_out_of_bounds: false,
            #[cfg(feature = "rayon")]
            batch_iterations: None,
            #[cfg(feature = "rayon")]
            enable_parallel: false,
            abs_tol: 1e-8,
            rel_tol: 1e-6,
            timestamp: "2025-01-01T00:00:00Z".to_string(),
        };

        // Save multiple checkpoints
        manager.save_checkpoint(&checkpoint, 1).unwrap();
        manager.save_checkpoint(&checkpoint, 2).unwrap();

        // Cleanup with keep_count = 0 should do nothing
        let result = manager.cleanup_old_checkpoints(0);
        assert!(result.is_ok());

        // Both files should still exist
        assert_eq!(count_checkpoint_files(&temp_dir, "test"), 2);

        // Cleanup
        let _ = fs::remove_dir_all(temp_dir);
    }

    #[test]
    fn test_cleanup_old_checkpoints_with_non_matching_files() {
        let temp_dir = env::temp_dir().join("test_checkpoints_cleanup_mixed");
        let config = CheckpointConfig {
            checkpoint_dir: temp_dir.clone(),
            checkpoint_name: "test".to_string(),
            save_frequency: 5,
            keep_all: true,
            auto_resume: true,
        };

        let manager = CheckpointManager::new(config).unwrap();

        // Create a test checkpoint
        let checkpoint = OQNLPCheckpoint {
            params: OQNLPParams::default(),
            current_iteration: 0,
            merit_threshold: f64::INFINITY,
            solution_set: None,
            reference_set: vec![],
            unchanged_cycles: 0,
            elapsed_time: 0.0,
            distance_filter_solutions: vec![],
            current_seed: 0,
            target_objective: None,
            exclude_out_of_bounds: false,
            #[cfg(feature = "rayon")]
            batch_iterations: None,
            #[cfg(feature = "rayon")]
            enable_parallel: false,
            abs_tol: 1e-8,
            rel_tol: 1e-6,
            timestamp: "2025-01-01T00:00:00Z".to_string(),
        };

        // Save checkpoint files
        manager.save_checkpoint(&checkpoint, 1).unwrap();
        manager.save_checkpoint(&checkpoint, 2).unwrap();
        manager.save_checkpoint(&checkpoint, 3).unwrap();

        // Create some non-matching files that should be ignored
        let dummy_file1 = temp_dir.join("other_file.bin");
        let dummy_file2 = temp_dir.join("test_abc.bin"); // Wrong pattern
        let dummy_file3 = temp_dir.join("test_999.txt"); // Wrong extension
        fs::write(&dummy_file1, b"dummy").unwrap();
        fs::write(&dummy_file2, b"dummy").unwrap();
        fs::write(&dummy_file3, b"dummy").unwrap();

        // Keep only 1 checkpoint file
        manager.cleanup_old_checkpoints(1).unwrap();

        // Verify only 1 checkpoint file remains (the latest one)
        assert_eq!(count_checkpoint_files(&temp_dir, "test"), 1);

        // Verify the dummy files are still there (not affected by cleanup)
        assert!(dummy_file1.exists());
        assert!(dummy_file2.exists());
        assert!(dummy_file3.exists());

        // Verify the remaining checkpoint is the latest one
        let entries = fs::read_dir(&temp_dir).unwrap();
        let checkpoint_files: Vec<_> = entries
            .filter_map(|e| e.ok())
            .filter(|e| {
                if let Some(filename) = e.file_name().to_str() {
                    if filename.starts_with("test_") && filename.ends_with(".bin") {
                        let iteration_str = &filename[5..filename.len() - 4];
                        iteration_str.parse::<usize>().is_ok()
                    } else {
                        false
                    }
                } else {
                    false
                }
            })
            .collect();
        let filename = checkpoint_files[0].file_name();
        let remaining_filename = filename.to_str().unwrap();
        assert_eq!(remaining_filename, "test_000003.bin");

        // Cleanup
        let _ = fs::remove_dir_all(temp_dir);
    }

    #[test]
    fn test_read_checkpoint_file() {
        use crate::checkpoint::read_checkpoint_file;

        let temp_dir = env::temp_dir().join("test_read_checkpoint_file");
        let config = CheckpointConfig {
            checkpoint_dir: temp_dir.clone(),
            checkpoint_name: "test".to_string(),
            save_frequency: 5,
            keep_all: false,
            auto_resume: true,
        };

        let manager = CheckpointManager::new(config).unwrap();

        // Create a test checkpoint
        let checkpoint = OQNLPCheckpoint {
            params: OQNLPParams::default(),
            current_iteration: 123,
            merit_threshold: 2.5,
            solution_set: Some(SolutionSet {
                solutions: Array1::from(vec![LocalSolution {
                    point: array![3.0, 4.0],
                    objective: -2.5,
                }]),
            }),
            reference_set: vec![array![1.0, 2.0], array![5.0, 6.0]],
            unchanged_cycles: 10,
            elapsed_time: 250.75,
            distance_filter_solutions: vec![],
            current_seed: 42,
            target_objective: Some(-3.0),
            exclude_out_of_bounds: false,
            #[cfg(feature = "rayon")]
            batch_iterations: Some(7),
            #[cfg(feature = "rayon")]
            enable_parallel: true,
            abs_tol: 1e-8,
            rel_tol: 1e-6,
            timestamp: "2025-08-01T12:00:00Z".to_string(),
        };

        // Save the checkpoint using the manager
        let saved_path = manager.save_checkpoint(&checkpoint, 123).unwrap();
        assert!(saved_path.exists());

        // Test reading the checkpoint file directly
        let loaded_checkpoint = read_checkpoint_file(&saved_path).unwrap();

        // Verify all fields match
        assert_eq!(loaded_checkpoint.current_iteration, 123);
        assert_eq!(loaded_checkpoint.merit_threshold, 2.5);
        assert_eq!(loaded_checkpoint.unchanged_cycles, 10);
        assert_eq!(loaded_checkpoint.elapsed_time, 250.75);
        assert_eq!(loaded_checkpoint.current_seed, 42);
        assert_eq!(loaded_checkpoint.target_objective, Some(-3.0));
        assert_eq!(loaded_checkpoint.timestamp, "2025-08-01T12:00:00Z");
        assert_eq!(loaded_checkpoint.reference_set.len(), 2);

        // Verify solution set
        if let Some(solution_set) = loaded_checkpoint.solution_set {
            assert_eq!(solution_set.solutions.len(), 1);
            assert_eq!(solution_set.solutions[0].point, array![3.0, 4.0]);
            assert_eq!(solution_set.solutions[0].objective, -2.5);
        } else {
            panic!("Expected solution set to be Some");
        }

        // Cleanup
        let _ = fs::remove_dir_all(temp_dir);
    }

    #[test]
    fn test_read_checkpoint_file_not_found() {
        use crate::checkpoint::read_checkpoint_file;

        let non_existent_path = env::temp_dir().join("non_existent_checkpoint.bin");

        // Ensure the file doesn't exist
        assert!(!non_existent_path.exists());

        // Test reading non-existent file
        let result = read_checkpoint_file(&non_existent_path);
        assert!(result.is_err());

        match result {
            Err(CheckpointError::CheckpointNotFound { path }) => {
                assert_eq!(path, non_existent_path);
            }
            _ => panic!("Expected CheckpointNotFound error"),
        }
    }

    #[test]
    fn test_read_checkpoint_file_corrupted_data() {
        use crate::checkpoint::read_checkpoint_file;

        let temp_dir = env::temp_dir().join("test_read_checkpoint_corrupted");
        fs::create_dir_all(&temp_dir).unwrap();

        // Create a file with invalid/corrupted data
        let corrupted_file = temp_dir.join("corrupted.bin");
        fs::write(&corrupted_file, b"invalid checkpoint data").unwrap();

        // Test reading corrupted file
        let result = read_checkpoint_file(&corrupted_file);
        assert!(result.is_err());

        match result {
            Err(CheckpointError::SerializationError { operation: _, path: _, source: _ }) => {
                // Expected error type
            }
            _ => panic!("Expected SerializationError"),
        }

        // Cleanup
        let _ = fs::remove_dir_all(temp_dir);
    }

    #[test]
    fn test_read_checkpoint_file_empty_file() {
        use crate::checkpoint::read_checkpoint_file;

        let temp_dir = env::temp_dir().join("test_read_checkpoint_empty");
        fs::create_dir_all(&temp_dir).unwrap();

        // Create an empty file
        let empty_file = temp_dir.join("empty.bin");
        fs::write(&empty_file, b"").unwrap();

        // Test reading empty file
        let result = read_checkpoint_file(&empty_file);
        assert!(result.is_err());

        match result {
            Err(CheckpointError::SerializationError { operation: _, path: _, source: _ }) => {
                // Expected error type
            }
            _ => panic!("Expected SerializationError"),
        }

        // Cleanup
        let _ = fs::remove_dir_all(temp_dir);
    }
}