Skip to main content

omega_cognitive_kernel/
checkpoint.rs

1//! Named checkpoints for rollback (S3).
2
3#[allow(unused_imports)]
4use crate::prelude::*;
5
6use crate::error::{OmegaError, Result};
7use crate::persist::KernelSnapshot;
8use chrono::{DateTime, Utc};
9use serde::{Deserialize, Serialize};
10use std::fs;
11use std::path::{Path, PathBuf};
12use uuid::Uuid;
13
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct CheckpointMeta {
16    pub id: Uuid,
17    pub label: String,
18    pub step: u64,
19    pub created_at: DateTime<Utc>,
20    pub avg_err: f64,
21    pub damping: f64,
22}
23
24pub struct CheckpointStore {
25    pub dir: PathBuf,
26    pub max_keep: usize,
27}
28
29impl CheckpointStore {
30    pub fn beside_state(state_path: &Path) -> Self {
31        let dir = state_path
32            .parent()
33            .unwrap_or_else(|| Path::new("."))
34            .join("checkpoints");
35        Self { dir, max_keep: 32 }
36    }
37
38    fn meta_path(&self, id: Uuid) -> PathBuf {
39        self.dir.join(format!("{id}.meta.json"))
40    }
41
42    fn snap_path(&self, id: Uuid) -> PathBuf {
43        self.dir.join(format!("{id}.state.json"))
44    }
45
46    pub fn save(
47        &self,
48        label: &str,
49        step: u64,
50        avg_err: f64,
51        damping: f64,
52        snapshot: &KernelSnapshot,
53    ) -> Result<CheckpointMeta> {
54        fs::create_dir_all(&self.dir).map_err(|e| OmegaError::Persist(e.to_string()))?;
55        let meta = CheckpointMeta {
56            id: crate::new_uuid(),
57            label: label.into(),
58            step,
59            created_at: crate::now_utc(),
60            avg_err,
61            damping,
62        };
63        snapshot.save_to(&self.snap_path(meta.id))?;
64        let json =
65            serde_json::to_string_pretty(&meta).map_err(|e| OmegaError::Persist(e.to_string()))?;
66        fs::write(self.meta_path(meta.id), json).map_err(|e| OmegaError::Persist(e.to_string()))?;
67        self.prune()?;
68        Ok(meta)
69    }
70
71    fn prune(&self) -> Result<()> {
72        let mut list = self.list()?;
73        if list.len() <= self.max_keep {
74            return Ok(());
75        }
76        list.sort_by_key(|a| a.created_at);
77        let excess = list.len().saturating_sub(self.max_keep);
78        for meta in list.into_iter().take(excess) {
79            let _ = fs::remove_file(self.meta_path(meta.id));
80            let _ = fs::remove_file(self.snap_path(meta.id));
81        }
82        Ok(())
83    }
84
85    pub fn list(&self) -> Result<Vec<CheckpointMeta>> {
86        if !self.dir.exists() {
87            return Ok(vec![]);
88        }
89        let mut out = Vec::new();
90        for entry in fs::read_dir(&self.dir).map_err(|e| OmegaError::Persist(e.to_string()))? {
91            let entry = entry.map_err(|e| OmegaError::Persist(e.to_string()))?;
92            let path = entry.path();
93            if !path
94                .file_name()
95                .and_then(|n| n.to_str())
96                .map(|n| n.ends_with(".meta.json"))
97                .unwrap_or(false)
98            {
99                continue;
100            }
101            let data = fs::read_to_string(&path).map_err(|e| OmegaError::Persist(e.to_string()))?;
102            if let Ok(m) = serde_json::from_str::<CheckpointMeta>(&data) {
103                out.push(m);
104            }
105        }
106        out.sort_by_key(|a| std::cmp::Reverse(a.created_at));
107        Ok(out)
108    }
109
110    pub fn load_snapshot(&self, id: Uuid) -> Result<KernelSnapshot> {
111        KernelSnapshot::load_from(&self.snap_path(id))
112    }
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118    use crate::types::RuleEffect;
119    use hashbrown::HashMap;
120    use std::env::temp_dir;
121
122    #[test]
123    fn save_list_load() {
124        let dir = temp_dir().join(format!("omega-ckpt-{}", crate::new_uuid()));
125        let store = CheckpointStore {
126            dir: dir.clone(),
127            max_keep: 32,
128        };
129        let snap = KernelSnapshot {
130            version: 1,
131            total_steps: 3,
132            biases: HashMap::new(),
133            constraints: HashMap::new(),
134            cas_total_steps: 3,
135            cas_avg_prediction_error: 0.4,
136            cas_adaptation_score: 0.6,
137            cognitive_effect: RuleEffect::default(),
138            cases: vec![],
139            case_capacity: 256,
140            strategies: HashMap::new(),
141            active_modules: HashMap::new(),
142            patch_history: vec![],
143            ..KernelSnapshot::default()
144        };
145        let meta = store.save("before-patch", 3, 0.4, 1.0, &snap).unwrap();
146        assert_eq!(store.list().unwrap().len(), 1);
147        assert_eq!(store.load_snapshot(meta.id).unwrap().total_steps, 3);
148        let _ = fs::remove_dir_all(&dir);
149    }
150}