roma_lib 0.1.2

A Rust metaheuristics framework inspired by jMetal for optimization and experimentation.
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
use std::fs;
use std::io;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use std::time::{SystemTime, UNIX_EPOCH};

use crate::utils::cli::{prompt_checkpoint_selection, CliArgs};

use crate::utils::binary::{
    byte_to_status, push_option_string, push_string, push_u64, push_u8, read_option_string,
    read_string, read_u64, read_u8, status_to_byte,
};
use crate::utils::hash::checkpoint_signature_hashes;
use crate::utils::path::{
    checkpoint_file_path, checkpoint_scope_dir, initialize_checkpoint_dir, list_checkpoint_files,
    resolve_checkpoint_dir, run_id_timestamp_ms, CheckpointInitMode, CheckpointPathConfig,
};

pub const DEFAULT_FREQUENCY_OF_CHECKPOINT_WRITES: usize = 10;

// Binary file signature used to validate checkpoint file integrity.
const CHECKPOINT_BIN_MAGIC: [u8; 4] = *b"RCKP";
const ERR_INVALID_CHECKPOINT_MAGIC: &str = "invalid checkpoint magic header";
const ERR_TRAILING_BYTES: &str = "trailing bytes found in checkpoint file";
static RUN_ID_SEQUENCE: AtomicU64 = AtomicU64::new(0);

pub struct CheckpointPolicy {
    checkpoint_dir: PathBuf,
    storage_ready: bool,
    writes_requested: bool,
    resume_requested: bool,
}

impl CheckpointPolicy {
    pub fn from_cli(checkpoint_cfg: &CheckpointPathConfig) -> Self {
        let args = CliArgs::from_env();
        Self::resolve(&args, checkpoint_cfg)
    }

    pub fn resolve(args: &CliArgs, checkpoint_cfg: &CheckpointPathConfig) -> Self {
        let default_dir = resolve_checkpoint_dir(checkpoint_cfg);
        let checkpoint_dir = args.checkpoint_dir_or(default_dir);
        let explicit_checkpoint_dir = args.has_checkpoint_dir_override();
        let storage_ready = if explicit_checkpoint_dir {
            fs::create_dir_all(&checkpoint_dir).is_ok()
        } else {
            resolve_checkpoint_dir_from_config_for_writes(checkpoint_cfg).is_ok()
        };

        Self {
            checkpoint_dir,
            storage_ready,
            writes_requested: !args.checkpoints_disabled(),
            resume_requested: args.resume_requested(),
        }
    }

    pub fn checkpoint_dir(&self) -> &Path {
        &self.checkpoint_dir
    }

    pub fn resume_requested(&self) -> bool {
        self.resume_requested
    }

    pub fn should_write(&self) -> bool {
        self.storage_ready && self.writes_requested
    }

    pub fn persist_record(
        &self,
        last_checkpoint_path: &mut Option<PathBuf>,
        record: &CheckpointRecord,
    ) {
        if self.should_write() {
            if let Ok(path) = write_snapshot(self.checkpoint_dir(), record) {
                *last_checkpoint_path = Some(path);
            }
        }
    }
}

fn resolve_checkpoint_dir_from_config_for_writes(
    config: &CheckpointPathConfig,
) -> Result<PathBuf, String> {
    initialize_checkpoint_dir(config, CheckpointInitMode::BestEffort)
        .map_err(|err| format!("failed to initialize checkpoint directory: {}", err))
        .and_then(|result| {
            result.directory.ok_or_else(|| {
                "no writable checkpoint directory available; checkpoint writes disabled".to_string()
            })
        })
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CheckpointRunStatus {
    Running,
    Completed,
    Failed,
    Interrupted,
}

impl CheckpointRunStatus {
    pub fn as_str(self) -> &'static str {
        match self {
            CheckpointRunStatus::Running => "running",
            CheckpointRunStatus::Completed => "completed",
            CheckpointRunStatus::Failed => "failed",
            CheckpointRunStatus::Interrupted => "interrupted",
        }
    }
}

/// Shared execution snapshot emitted by algorithms and consumed by
/// termination logic/observers.
#[derive(Clone, Debug)]
pub struct ExecutionStateSnapshot {
    pub iteration: usize,
    pub evaluations: usize,
    /// Cached scalar metric for termination/monitoring.
    pub best_fitness: f64,
    pub average_fitness: f64,
    pub worst_fitness: f64,
    pub best_solution_presentation: String,
}

impl ExecutionStateSnapshot {
    pub fn increment_iteration(&mut self) {
        self.iteration += 1;
    }

    pub fn increment_evaluations(&mut self, count: usize) {
        self.evaluations += count;
    }
}

/// Runtime metadata attached to checkpoint records for one algorithm run.
pub struct CheckpointRuntimeMetadata<'a> {
    pub algorithm_name: &'a str,
    pub algorithm_parameters: &'a str,
    pub problem_description: &'a str,
    pub problem_parameters: &'a str,
    pub algorithm_signature_hash: u64,
    pub problem_signature_hash: u64,
}

impl<'a> CheckpointRuntimeMetadata<'a> {
    pub fn new(
        algorithm_name: &'a str,
        algorithm_parameters: &'a str,
        problem_description: &'a str,
        problem_parameters: &'a str,
    ) -> Self {
        let (algorithm_signature_hash, problem_signature_hash) = checkpoint_signature_hashes(
            algorithm_name,
            algorithm_parameters,
            problem_description,
            problem_parameters,
        );

        Self {
            algorithm_name,
            algorithm_parameters,
            problem_description,
            problem_parameters,
            algorithm_signature_hash,
            problem_signature_hash,
        }
    }
}

fn select_checkpoint_record(entries: Vec<CheckpointEntry>) -> Result<Option<CheckpointRecord>, String> {
    if entries.is_empty() {
        return Ok(None);
    }

    let selected_index = if entries.len() == 1 {
        Some(0)
    } else {
        prompt_checkpoint_selection(&entries)?
    };

    Ok(selected_index.map(|index| entries[index].record.clone()))
}

pub trait StepStateCheckpoint<T, Q = f64>
where
    T: Clone,
    Q: Clone + Default,
{
    fn random_seed(&self) -> u64;

    fn to_payload(&self) -> String;

    fn from_payload(payload: &str) -> Self;

    fn iteration(&self) -> usize;

    fn evaluations(&self) -> usize;

    fn build_checkpoint_record(
        &self,
        run_id: &str,
        runtime_metadata: &CheckpointRuntimeMetadata<'_>,
        elapsed_millis: Duration,
    ) -> CheckpointRecord {
        CheckpointRecord {
            created_at_ms: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .map(|d| d.as_millis())
                .ok()
                .and_then(|ms| u64::try_from(ms).ok())
                .unwrap_or(0),
            run_id: run_id.to_string(),
            random_seed: self.random_seed(),
            algorithm_name: runtime_metadata.algorithm_name.to_string(),
            algorithm_parameters: runtime_metadata.algorithm_parameters.to_string(),
            problem_description: runtime_metadata.problem_description.to_string(),
            problem_parameters: runtime_metadata.problem_parameters.to_string(),
            algorithm_signature_hash: runtime_metadata.algorithm_signature_hash,
            problem_signature_hash: runtime_metadata.problem_signature_hash,
            step_state_payload: self.to_payload(),
            seed_payload: None,
            elapsed_millis: elapsed_millis.as_millis() as u64,
            status: CheckpointRunStatus::Running,
            error_message: None,
        }
    }
}

/// Generates a stable run id format used by checkpoint persistence.
pub fn generate_run_id(algorithm_name: &str) -> String {
    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis())
        .ok()
        .and_then(|ms| u64::try_from(ms).ok())
        .unwrap_or(0);
    let sequence = RUN_ID_SEQUENCE.fetch_add(1, Ordering::Relaxed);
    format!(
        "{}-{}-{:020}-{}",
        algorithm_name,
        std::process::id(),
        sequence,
        timestamp
    )
}

#[derive(Debug, Clone, PartialEq)]
pub struct CheckpointRecord {
    pub created_at_ms: u64,
    pub run_id: String,
    pub random_seed: u64,
    pub algorithm_name: String,
    pub algorithm_parameters: String,
    pub problem_description: String,
    pub problem_parameters: String,
    pub algorithm_signature_hash: u64,
    pub problem_signature_hash: u64,
    pub step_state_payload: String,
    pub seed_payload: Option<String>,
    pub elapsed_millis: u64,
    pub status: CheckpointRunStatus,
    pub error_message: Option<String>,
}

#[derive(Debug, Clone)]
pub struct CheckpointEntry {
    pub path: PathBuf,
    pub record: CheckpointRecord,
}

/// Binary checkpoint file layout (little-endian):
///
/// Header:
/// - magic: 4 bytes (`RCKP`)
///
/// Identity and matching metadata:
/// - created_at_ms: u64 (UTC epoch millis when this checkpoint was produced)
/// - run_id: string
/// - algorithm_name: string
/// - algorithm_parameters: string
/// - problem_description: string
/// - problem_parameters: string
/// - algorithm_signature_hash: u64
/// - problem_signature_hash: u64
///
/// Progress and quality:
/// - seq_id: u64
/// - iteration: usize encoded as u64
/// - evaluations: usize encoded as u64
/// - best_fitness, average_fitness, worst_fitness: f64
/// - best_solution_presentation: string
/// - current_solution_payload: `Option<String>`
///
/// Optional payloads:
/// - state_payload: `Option<String>` (algorithm-defined UTF-8 payload; e.g. JSON text)
/// - elapsed_millis: `Option<u64>`
/// - status: u8
/// - error_message: `Option<String>`
///
/// Example metadata values:
/// - algorithm_name: `HillClimbing`
/// - algorithm_parameters: `mutation_probability=0.20;termination=max_iterations:100`
/// - problem_description: `roma::problem::implementations::tsp_problem::TspProblem`
/// - problem_parameters: `cities=52;close_tour=true;fixed_start_city=none`
/// - algorithm_signature_hash: `11399437687642648721`
/// - problem_signature_hash: `7769642201919903012`

/// Writes a snapshot to the canonical checkpoint location for a run.
pub fn write_snapshot(base_dir: &Path, record: &CheckpointRecord) -> io::Result<PathBuf> {
    write_execution_checkpoint(base_dir, record)
}

/// Writes one checkpoint record under `base_dir` using canonical naming.
/// Returns the full file path used for persistence.
pub(crate) fn write_execution_checkpoint(
    base_dir: &Path,
    record: &CheckpointRecord,
) -> io::Result<PathBuf> {
    let scope_dir = checkpoint_scope_dir(
        base_dir,
        &record.algorithm_name,
        &record.problem_description,
        record.algorithm_signature_hash,
        record.problem_signature_hash,
    );
    fs::create_dir_all(&scope_dir)?;
    let path = checkpoint_file_path(&scope_dir, &record.run_id);
    write_checkpoint_record(&path, record)?;
    Ok(path)
}

/// Writes one checkpoint payload in a compact binary format.
///
/// Note: the file format is always binary. Some fields inside it are UTF-8
/// strings, including `state_payload`, which algorithms may encode as JSON.
pub(crate) fn write_checkpoint_record(path: &Path, record: &CheckpointRecord) -> io::Result<()> {
    let mut bytes = Vec::with_capacity(512);
    bytes.extend_from_slice(&CHECKPOINT_BIN_MAGIC);

    push_u64(&mut bytes, record.created_at_ms);
    push_string(&mut bytes, &record.run_id)?;
    push_u64(&mut bytes, record.random_seed);
    push_string(&mut bytes, &record.algorithm_name)?;
    push_string(&mut bytes, &record.algorithm_parameters)?;
    push_string(&mut bytes, &record.problem_description)?;
    push_string(&mut bytes, &record.problem_parameters)?;
    push_u64(&mut bytes, record.algorithm_signature_hash);
    push_u64(&mut bytes, record.problem_signature_hash);
    push_string(&mut bytes, &record.step_state_payload)?;
    push_option_string(&mut bytes, &record.seed_payload)?;
    push_u64(&mut bytes, record.elapsed_millis);
    push_u8(&mut bytes, status_to_byte(record.status));
    push_option_string(&mut bytes, &record.error_message)?;

    fs::write(path, bytes)
}

/// Reads one snapshot record from disk.
pub fn read_snapshot(path: &Path) -> io::Result<CheckpointRecord> {
    read_checkpoint_record(path)
}

/// Deletes a checkpoint file when an execution finishes successfully.
///
/// Runs can persist checkpoints while they are in progress to support resume.
/// Once a run completes without errors, that checkpoint is no longer needed,
/// and this function removes it.
///
/// Returns `Ok(true)` when the file was removed, `Ok(false)` when it did not
/// exist, and `Err(...)` for any other filesystem error.
pub fn delete_snapshot_on_success(path: &Path) -> io::Result<bool> {
    match fs::remove_file(path) {
        Ok(()) => Ok(true),
        Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(false),
        Err(err) => Err(err),
    }
}

/// Reads one checkpoint payload from disk.
pub(crate) fn read_checkpoint_record(path: &Path) -> io::Result<CheckpointRecord> {
    let data = fs::read(path)?;
    let mut cursor = io::Cursor::new(data.as_slice());

    let mut magic = [0u8; 4];
    cursor.read_exact(&mut magic)?;
    if magic != CHECKPOINT_BIN_MAGIC {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            ERR_INVALID_CHECKPOINT_MAGIC,
        ));
    }

    let record = CheckpointRecord {
        created_at_ms: read_u64(&mut cursor)?,
        run_id: read_string(&mut cursor)?,
        random_seed: read_u64(&mut cursor)?,
        algorithm_name: read_string(&mut cursor)?,
        algorithm_parameters: read_string(&mut cursor)?,
        problem_description: read_string(&mut cursor)?,
        problem_parameters: read_string(&mut cursor)?,
        algorithm_signature_hash: read_u64(&mut cursor)?,
        problem_signature_hash: read_u64(&mut cursor)?,
        step_state_payload: read_string(&mut cursor)?,
        seed_payload: read_option_string(&mut cursor)?,
        elapsed_millis: read_u64(&mut cursor)?,
        status: byte_to_status(read_u8(&mut cursor)?)?,
        error_message: read_option_string(&mut cursor)?,
    };

    if (cursor.position() as usize) != data.len() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            ERR_TRAILING_BYTES,
        ));
    }

    Ok(record)
}

/// Lists resumable checkpoints for one algorithm + problem pair ordered oldest->newest.
pub(crate) fn list_resumable_checkpoint_entries_for(
    base_dir: &Path,
    algorithm_name: &str,
    algorithm_signature_hash: u64,
    problem_signature_hash: u64,
) -> io::Result<Vec<CheckpointEntry>> {
    let mut entries: Vec<((u128, String), CheckpointEntry)> = Vec::new();

    for path in list_checkpoint_files(base_dir)? {
        let Ok(record) = read_checkpoint_record(&path) else {
            continue;
        };

        if record.algorithm_name != algorithm_name {
            continue;
        }
        if record.algorithm_signature_hash != algorithm_signature_hash {
            continue;
        }
        if record.problem_signature_hash != problem_signature_hash {
            continue;
        }
        if !is_resumable_status(record.status) {
            continue;
        }

        let timestamp_ms = run_id_timestamp_ms(&record.run_id).unwrap_or(0);
        let key = (timestamp_ms, record.run_id.clone());
        entries.push((key, CheckpointEntry { path, record }));
    }

    entries.sort_by(|(a, _), (b, _)| a.cmp(b));
    Ok(entries.into_iter().map(|(_, entry)| entry).collect())
}

/// Lists resumable checkpoints for precomputed runtime metadata.
pub fn list_resumable_checkpoint_entries_for_metadata(
    base_dir: &Path,
    runtime_metadata: &CheckpointRuntimeMetadata<'_>,
) -> io::Result<Vec<CheckpointEntry>> {
    list_resumable_checkpoint_entries_for(
        base_dir,
        runtime_metadata.algorithm_name,
        runtime_metadata.algorithm_signature_hash,
        runtime_metadata.problem_signature_hash,
    )
}

/// Selects one resumable checkpoint from precomputed runtime metadata.
pub fn select_resume_checkpoint_for_metadata(
    base_dir: &Path,
    runtime_metadata: &CheckpointRuntimeMetadata<'_>,
) -> Result<Option<CheckpointRecord>, String> {
    let entries = list_resumable_checkpoint_entries_for_metadata(base_dir, runtime_metadata)
        .map_err(|err| {
            format!(
                "failed to list resumable checkpoints in '{}': {}",
                base_dir.display(),
                err
            )
        })?;

    select_checkpoint_record(entries)
}

/// Removes checkpoints older than the provided UTC epoch milliseconds.
///
/// Returns number of files removed.
#[allow(dead_code)]
pub fn purge_checkpoints_older_than(base_dir: &Path, older_than_ms: u64) -> io::Result<usize> {
    let mut removed = 0usize;
    for path in list_checkpoint_files(base_dir)? {
        let Ok(record) = read_checkpoint_record(&path) else {
            continue;
        };
        if record.created_at_ms < older_than_ms {
            fs::remove_file(&path)?;
            removed += 1;
        }
    }
    Ok(removed)
}

/// Removes checkpoints older than `max_age_ms` relative to current wall-clock time.
///
/// Returns number of files removed.
#[allow(dead_code)]
pub fn purge_checkpoints_older_than_age(base_dir: &Path, max_age_ms: u64) -> io::Result<usize> {
    let now_ms = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis())
        .ok()
        .and_then(|ms| u64::try_from(ms).ok())
        .unwrap_or(0);

    let threshold = now_ms.saturating_sub(max_age_ms);
    purge_checkpoints_older_than(base_dir, threshold)
}

fn is_resumable_status(status: CheckpointRunStatus) -> bool {
    matches!(
        status,
        CheckpointRunStatus::Running
            | CheckpointRunStatus::Failed
            | CheckpointRunStatus::Interrupted
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::utils::path::CheckpointPathConfig;

    struct TestCheckpointDir {
        path: std::path::PathBuf,
    }

    impl TestCheckpointDir {
        fn new(label: &str) -> Self {
            let stamp = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or(0);

            let path = std::env::temp_dir().join(format!(
                "roma_checkpoint_tests_{}_{}_{}",
                label,
                std::process::id(),
                stamp
            ));

            std::fs::create_dir_all(&path).expect("test checkpoint directory should be created");

            Self { path }
        }

        fn path(&self) -> &std::path::Path {
            &self.path
        }
    }

    impl Drop for TestCheckpointDir {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.path);
        }
    }

    fn build_record(
        run_id: &str,
        algorithm_name: &str,
        algorithm_parameters: &str,
        problem_description: &str,
        problem_parameters: &str,
        status: CheckpointRunStatus,
        step_state_payload: &str,
        created_at_ms: u64,
    ) -> CheckpointRecord {
        let metadata = CheckpointRuntimeMetadata::new(
            algorithm_name,
            algorithm_parameters,
            problem_description,
            problem_parameters,
        );

        CheckpointRecord {
            created_at_ms,
            run_id: run_id.to_string(),
            random_seed: 7,
            algorithm_name: algorithm_name.to_string(),
            algorithm_parameters: algorithm_parameters.to_string(),
            problem_description: problem_description.to_string(),
            problem_parameters: problem_parameters.to_string(),
            algorithm_signature_hash: metadata.algorithm_signature_hash,
            problem_signature_hash: metadata.problem_signature_hash,
            step_state_payload: step_state_payload.to_string(),
            seed_payload: None,
            elapsed_millis: 0,
            status,
            error_message: None,
        }
    }

    #[test]
    fn generate_run_id_is_unique_across_rapid_calls() {
        let mut ids = std::collections::HashSet::new();

        for _ in 0..256 {
            ids.insert(generate_run_id("HillClimbing"));
        }

        assert_eq!(ids.len(), 256);
    }

    #[test]
    fn write_snapshot_overwrites_when_run_id_is_reused_in_same_scope() {
        let dir = TestCheckpointDir::new("overwrite_same_run_id");

        let first = build_record(
            "HillClimbing-42-1000",
            "HillClimbing",
            "seed=11;mutation=0.2",
            "DemoProblem",
            "size=4",
            CheckpointRunStatus::Running,
            "state:one",
            1_000,
        );

        let second = build_record(
            "HillClimbing-42-1000",
            "HillClimbing",
            "seed=11;mutation=0.2",
            "DemoProblem",
            "size=4",
            CheckpointRunStatus::Running,
            "state:two",
            2_000,
        );

        let first_path =
            write_snapshot(dir.path(), &first).expect("first checkpoint should be written");
        let second_path =
            write_snapshot(dir.path(), &second).expect("second checkpoint should be written");

        assert_eq!(first_path, second_path);

        let files = list_checkpoint_files(dir.path()).expect("checkpoint files should be listed");
        assert_eq!(files.len(), 1);

        let stored = read_snapshot(&second_path).expect("stored checkpoint should be readable");
        assert_eq!(stored.step_state_payload, "state:two");
        assert_eq!(stored.created_at_ms, 2_000);
    }

    #[test]
    fn write_snapshot_keeps_distinct_files_for_different_run_ids_in_same_scope() {
        let dir = TestCheckpointDir::new("distinct_run_ids_same_scope");

        let first = build_record(
            "HillClimbing-42-1000",
            "HillClimbing",
            "seed=11;mutation=0.2",
            "DemoProblem",
            "size=4",
            CheckpointRunStatus::Running,
            "state:one",
            1_000,
        );

        let second = build_record(
            "HillClimbing-42-1001",
            "HillClimbing",
            "seed=11;mutation=0.2",
            "DemoProblem",
            "size=4",
            CheckpointRunStatus::Running,
            "state:two",
            1_001,
        );

        let first_path =
            write_snapshot(dir.path(), &first).expect("first checkpoint should be written");
        let second_path =
            write_snapshot(dir.path(), &second).expect("second checkpoint should be written");

        assert_ne!(first_path, second_path);

        let files = list_checkpoint_files(dir.path()).expect("checkpoint files should be listed");
        assert_eq!(files.len(), 2);
    }

    #[test]
    fn write_snapshot_keeps_distinct_files_when_signature_hashes_change() {
        let dir = TestCheckpointDir::new("same_run_id_different_hash");

        let first = build_record(
            "HillClimbing-42-1000",
            "HillClimbing",
            "seed=11;mutation=0.2",
            "DemoProblem",
            "size=4",
            CheckpointRunStatus::Running,
            "state:one",
            1_000,
        );

        let second = build_record(
            "HillClimbing-42-1000",
            "HillClimbing",
            "seed=99;mutation=0.2",
            "DemoProblem",
            "size=4",
            CheckpointRunStatus::Running,
            "state:two",
            1_001,
        );

        let first_path =
            write_snapshot(dir.path(), &first).expect("first checkpoint should be written");
        let second_path =
            write_snapshot(dir.path(), &second).expect("second checkpoint should be written");

        assert_ne!(first_path, second_path);

        let files = list_checkpoint_files(dir.path()).expect("checkpoint files should be listed");
        assert_eq!(files.len(), 2);
    }

    #[test]
    fn list_resumable_entries_filters_by_identity_and_status() {
        let dir = TestCheckpointDir::new("list_filters_identity_status");

        let matching_running = build_record(
            "HillClimbing-42-1000",
            "HillClimbing",
            "seed=11;mutation=0.2",
            "DemoProblem",
            "size=4",
            CheckpointRunStatus::Running,
            "state:running",
            1_000,
        );

        let matching_failed = build_record(
            "HillClimbing-42-1001",
            "HillClimbing",
            "seed=11;mutation=0.2",
            "DemoProblem",
            "size=4",
            CheckpointRunStatus::Failed,
            "state:failed",
            1_001,
        );

        let different_algorithm_params = build_record(
            "HillClimbing-42-1002",
            "HillClimbing",
            "seed=77;mutation=0.2",
            "DemoProblem",
            "size=4",
            CheckpointRunStatus::Running,
            "state:other-algorithm-params",
            1_002,
        );

        let different_problem_params = build_record(
            "HillClimbing-42-1003",
            "HillClimbing",
            "seed=11;mutation=0.2",
            "DemoProblem",
            "size=8",
            CheckpointRunStatus::Running,
            "state:other-problem-params",
            1_003,
        );

        let matching_completed = build_record(
            "HillClimbing-42-1004",
            "HillClimbing",
            "seed=11;mutation=0.2",
            "DemoProblem",
            "size=4",
            CheckpointRunStatus::Completed,
            "state:completed",
            1_004,
        );

        for record in [
            &matching_running,
            &matching_failed,
            &different_algorithm_params,
            &different_problem_params,
            &matching_completed,
        ] {
            write_snapshot(dir.path(), record).expect("checkpoint should be written");
        }

        let metadata = CheckpointRuntimeMetadata::new(
            "HillClimbing",
            "seed=11;mutation=0.2",
            "DemoProblem",
            "size=4",
        );

        let entries = list_resumable_checkpoint_entries_for_metadata(dir.path(), &metadata)
        .expect("entries should be listed");

        let run_ids: Vec<&str> = entries
            .iter()
            .map(|entry| entry.record.run_id.as_str())
            .collect();

        assert_eq!(
            run_ids,
            vec!["HillClimbing-42-1000", "HillClimbing-42-1001"]
        );
        assert!(entries.iter().all(|entry| {
            matches!(
                entry.record.status,
                CheckpointRunStatus::Running
                    | CheckpointRunStatus::Failed
                    | CheckpointRunStatus::Interrupted
            )
        }));
    }

    #[test]
    fn select_resume_checkpoint_returns_single_matching_record() {
        let dir = TestCheckpointDir::new("select_single_checkpoint");

        let matching = build_record(
            "HillClimbing-42-1000",
            "HillClimbing",
            "seed=11;mutation=0.2",
            "DemoProblem",
            "size=4",
            CheckpointRunStatus::Running,
            "state:matching",
            1_000,
        );

        let different_identity = build_record(
            "HillClimbing-42-1001",
            "HillClimbing",
            "seed=77;mutation=0.2",
            "DemoProblem",
            "size=4",
            CheckpointRunStatus::Running,
            "state:non-matching",
            1_001,
        );

        write_snapshot(dir.path(), &matching).expect("matching checkpoint should be written");
        write_snapshot(dir.path(), &different_identity)
            .expect("non matching checkpoint should be written");

        let metadata = CheckpointRuntimeMetadata::new(
            "HillClimbing",
            "seed=11;mutation=0.2",
            "DemoProblem",
            "size=4",
        );

        let selected = select_resume_checkpoint_for_metadata(dir.path(), &metadata)
        .expect("selection should not fail")
        .expect("one checkpoint should be auto-selected");

        assert_eq!(selected.run_id, matching.run_id);
        assert_eq!(selected.step_state_payload, "state:matching");
    }

    #[test]
    fn checkpoint_policy_distinguishes_requested_writes_from_storage_availability() {
        let base = std::env::temp_dir().join(format!(
            "roma_checkpoint_policy_test_{}_{}",
            std::process::id(),
            SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or(0)
        ));
        let explicit_dir = base.join("checkpoints");
        let config = CheckpointPathConfig::default();

        let writes_disabled = CheckpointPolicy::resolve(
            &CliArgs::from_iter(vec![
                crate::utils::cli::CLI_FLAG_CHECKPOINT_DIR.to_string(),
                explicit_dir.to_string_lossy().into_owned(),
                crate::utils::cli::CLI_FLAG_NO_CHECKPOINT.to_string(),
            ]),
            &config,
        );

        assert!(writes_disabled.storage_ready);
        assert!(!writes_disabled.writes_requested);
        assert!(!writes_disabled.should_write());

        let writes_enabled = CheckpointPolicy::resolve(
            &CliArgs::from_iter(vec![
                crate::utils::cli::CLI_FLAG_CHECKPOINT_DIR.to_string(),
                explicit_dir.to_string_lossy().into_owned(),
                crate::utils::cli::CLI_FLAG_RESUME.to_string(),
            ]),
            &config,
        );

        assert!(writes_enabled.storage_ready);
        assert!(writes_enabled.writes_requested);
        assert!(writes_enabled.should_write());
        assert!(writes_enabled.resume_requested());

        let _ = std::fs::remove_dir_all(base);
    }

    #[test]
    fn resolve_checkpoint_dir_for_writes_skips_unwritable_candidates() {
        let base = std::env::temp_dir().join(format!(
            "roma_checkpoint_dir_test_{}_{}",
            std::process::id(),
            SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or(0)
        ));
        let fallback = base.join("fallback");

        let config = CheckpointPathConfig {
            app_name: "/dev/null".to_string(),
            env_var_name: "ROMA_TEST_UNUSED_CHECKPOINT_ENV",
            explicit_dir: Some(PathBuf::from("/dev/null/roma")),
            project_fallback_dir: Some(fallback.clone()),
        };

        let resolved = resolve_checkpoint_dir_from_config_for_writes(&config)
            .expect("a writable fallback directory should be resolved");

        assert_eq!(resolved, fallback);
        assert!(resolved.exists());

        let _ = std::fs::remove_dir_all(base);
    }
}