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 serde::{Deserialize, Serialize};
9use std::fs;
10use std::path::{Path, PathBuf};
11use std::time::Duration;
12use uuid::Uuid;
13
14const METADATA_TEMP_PREFIX: &str = ".checkpoint-metadata-";
15const METADATA_TEMP_SUFFIX: &str = ".tmp";
16const STALE_METADATA_TEMP_AGE: Duration = Duration::from_secs(24 * 60 * 60);
17
18#[derive(Debug, Clone, Serialize, Deserialize)]
19/// Metadata identifying a saved kernel checkpoint.
20pub struct CheckpointMeta {
21    /// Unique identifier for this record.
22    pub id: Uuid,
23    /// Human-readable label for the checkpoint.
24    pub label: String,
25    /// Kernel step captured in the checkpoint.
26    pub step: u64,
27    /// UTC timestamp when the checkpoint was created.
28    pub created_at: crate::UtcTimestamp,
29    /// Average prediction error recorded when the checkpoint was created.
30    pub avg_err: f64,
31    /// Prediction-error damping factor recorded when the checkpoint was created.
32    pub damping: f64,
33}
34
35/// Filesystem storage configuration for kernel checkpoints.
36pub struct CheckpointStore {
37    /// Directory containing checkpoint snapshots and metadata.
38    pub dir: PathBuf,
39    /// Maximum number of checkpoints retained by cleanup operations.
40    pub max_keep: usize,
41}
42
43struct CheckpointSave<'a> {
44    label: &'a str,
45    step: u64,
46    avg_err: f64,
47    damping: f64,
48    snapshot: &'a KernelSnapshot,
49    redact_user_content: bool,
50    id: Uuid,
51}
52
53impl CheckpointStore {
54    /// Performs beside state for this type.
55    pub fn beside_state(state_path: &Path) -> Self {
56        let dir = state_path
57            .parent()
58            .unwrap_or_else(|| Path::new("."))
59            .join("checkpoints");
60        Self { dir, max_keep: 32 }
61    }
62
63    fn meta_path(&self, id: Uuid) -> PathBuf {
64        self.dir.join(format!("{id}.meta.json"))
65    }
66
67    fn snap_path(&self, id: Uuid) -> PathBuf {
68        self.dir.join(format!("{id}.state.json"))
69    }
70
71    /// Saves the current value.
72    pub fn save(
73        &self,
74        label: &str,
75        step: u64,
76        avg_err: f64,
77        damping: f64,
78        snapshot: &KernelSnapshot,
79    ) -> Result<CheckpointMeta> {
80        self.save_with_privacy(label, step, avg_err, damping, snapshot, false)
81    }
82
83    /// Save a checkpoint, optionally redacting known user-provided content.
84    pub fn save_with_privacy(
85        &self,
86        label: &str,
87        step: u64,
88        avg_err: f64,
89        damping: f64,
90        snapshot: &KernelSnapshot,
91        redact_user_content: bool,
92    ) -> Result<CheckpointMeta> {
93        self.save_with_privacy_and_id(CheckpointSave {
94            label,
95            step,
96            avg_err,
97            damping,
98            snapshot,
99            redact_user_content,
100            id: crate::new_uuid(),
101        })
102    }
103
104    fn save_with_privacy_and_id(&self, request: CheckpointSave<'_>) -> Result<CheckpointMeta> {
105        let CheckpointSave {
106            label,
107            step,
108            avg_err,
109            damping,
110            snapshot,
111            redact_user_content,
112            id,
113        } = request;
114        crate::private_fs::create_dir_all(&self.dir)
115            .map_err(|e| OmegaError::Persist(e.to_string()))?;
116        self.cleanup_stale_metadata_temps();
117        let meta = CheckpointMeta {
118            id,
119            label: if redact_user_content {
120                "[REDACTED]".into()
121            } else {
122                label.into()
123            },
124            step,
125            created_at: crate::now_utc(),
126            avg_err,
127            damping,
128        };
129        let mut persisted_snapshot = snapshot.clone();
130        if redact_user_content {
131            persisted_snapshot.redact_user_content();
132        }
133        let snapshot_path = self.snap_path(meta.id);
134        save_snapshot_without_overwrite(&persisted_snapshot, &snapshot_path)?;
135        let json =
136            serde_json::to_string_pretty(&meta).map_err(|e| OmegaError::Persist(e.to_string()))?;
137        let meta_path = self.meta_path(meta.id);
138        if let Err(error) = write_metadata_atomically(&meta_path, json.as_bytes()) {
139            let _ = fs::remove_file(&snapshot_path);
140            return Err(error);
141        }
142        self.prune()?;
143        Ok(meta)
144    }
145
146    fn prune(&self) -> Result<()> {
147        let mut list = self.list()?;
148        if list.len() <= self.max_keep {
149            return Ok(());
150        }
151        list.sort_by_key(|a| a.created_at);
152        let excess = list.len().saturating_sub(self.max_keep);
153        for meta in list.into_iter().take(excess) {
154            let _ = fs::remove_file(self.meta_path(meta.id));
155            let _ = fs::remove_file(self.snap_path(meta.id));
156        }
157        Ok(())
158    }
159
160    fn cleanup_stale_metadata_temps(&self) {
161        self.cleanup_metadata_temps_older_than(STALE_METADATA_TEMP_AGE);
162    }
163
164    fn cleanup_metadata_temps_older_than(&self, minimum_age: Duration) {
165        let Ok(entries) = fs::read_dir(&self.dir) else {
166            return;
167        };
168        for entry in entries.flatten() {
169            let Ok(file_type) = entry.file_type() else {
170                continue;
171            };
172            if !file_type.is_file() {
173                continue;
174            }
175            let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
176                continue;
177            };
178            if !name.starts_with(METADATA_TEMP_PREFIX) || !name.ends_with(METADATA_TEMP_SUFFIX) {
179                continue;
180            }
181            let stale = entry
182                .metadata()
183                .and_then(|metadata| metadata.modified())
184                .ok()
185                .and_then(|modified| modified.elapsed().ok())
186                .is_some_and(|age| age >= minimum_age);
187            if stale {
188                if let Err(error) = fs::remove_file(entry.path()) {
189                    tracing::warn!(
190                        metadata_temp = %entry.path().display(),
191                        error = %error,
192                        "failed to remove stale checkpoint metadata temp file"
193                    );
194                }
195            }
196        }
197    }
198
199    /// Performs list for this type.
200    pub fn list(&self) -> Result<Vec<CheckpointMeta>> {
201        if !self.dir.exists() {
202            return Ok(vec![]);
203        }
204        let mut out = Vec::new();
205        for entry in fs::read_dir(&self.dir).map_err(|e| OmegaError::Persist(e.to_string()))? {
206            let entry = entry.map_err(|e| OmegaError::Persist(e.to_string()))?;
207            let path = entry.path();
208            if !path
209                .file_name()
210                .and_then(|n| n.to_str())
211                .map(|n| n.ends_with(".meta.json"))
212                .unwrap_or(false)
213            {
214                continue;
215            }
216            let data = match fs::read_to_string(&path) {
217                Ok(data) => data,
218                Err(error) => {
219                    tracing::warn!(
220                        metadata_path = %path.display(),
221                        error = %error,
222                        "skipping unreadable checkpoint metadata"
223                    );
224                    continue;
225                }
226            };
227            let meta = match serde_json::from_str::<CheckpointMeta>(&data) {
228                Ok(meta) => meta,
229                Err(error) => {
230                    tracing::warn!(
231                        metadata_path = %path.display(),
232                        error = %error,
233                        "skipping malformed checkpoint metadata"
234                    );
235                    continue;
236                }
237            };
238            out.push(meta);
239        }
240        out.sort_by_key(|a| std::cmp::Reverse(a.created_at));
241        Ok(out)
242    }
243
244    /// Loads snapshot.
245    pub fn load_snapshot(&self, id: Uuid) -> Result<KernelSnapshot> {
246        KernelSnapshot::load_from(&self.snap_path(id))
247    }
248}
249
250fn write_metadata_atomically(path: &Path, json: &[u8]) -> Result<()> {
251    let parent = path.parent().unwrap_or_else(|| Path::new("."));
252    let temp_path = parent.join(format!(
253        "{METADATA_TEMP_PREFIX}{}{METADATA_TEMP_SUFFIX}",
254        crate::new_uuid()
255    ));
256    let result = (|| {
257        use std::io::Write;
258        let mut file = crate::private_fs::open_options()
259            .write(true)
260            .create_new(true)
261            .open(&temp_path)
262            .map_err(|error| {
263                OmegaError::Persist(format!("checkpoint metadata temp create: {error}"))
264            })?;
265        file.write_all(json)
266            .and_then(|()| file.sync_all())
267            .map_err(|error| {
268                OmegaError::Persist(format!("checkpoint metadata temp write: {error}"))
269            })?;
270        fs::hard_link(&temp_path, path).map_err(|error| {
271            OmegaError::Persist(format!("checkpoint metadata publish: {error}"))
272        })?;
273        Ok(())
274    })();
275    let _ = fs::remove_file(temp_path);
276    result
277}
278
279fn save_snapshot_without_overwrite(snapshot: &KernelSnapshot, path: &Path) -> Result<()> {
280    let parent = path.parent().unwrap_or_else(|| Path::new("."));
281    let file_name = path
282        .file_name()
283        .and_then(|name| name.to_str())
284        .ok_or_else(|| {
285            OmegaError::Persist(format!("invalid checkpoint path: {}", path.display()))
286        })?;
287    let temp_path = parent.join(format!(".{file_name}.{}.tmp", crate::new_uuid()));
288    let result = (|| {
289        snapshot.save_to(&temp_path)?;
290        fs::hard_link(&temp_path, path).map_err(|error| {
291            OmegaError::Persist(format!("checkpoint snapshot publish: {error}"))
292        })?;
293        Ok(())
294    })();
295    let _ = fs::remove_file(temp_path);
296    result
297}
298
299#[cfg(test)]
300mod tests {
301    use super::*;
302    use crate::types::RuleEffect;
303    use alloc::collections::BTreeMap;
304    use std::env::temp_dir;
305
306    #[test]
307    fn save_list_load() {
308        let dir = temp_dir().join(format!("omega-ckpt-{}", crate::new_uuid()));
309        let store = CheckpointStore {
310            dir: dir.clone(),
311            max_keep: 32,
312        };
313        let snap = KernelSnapshot {
314            version: 1,
315            total_steps: 3,
316            biases: BTreeMap::new(),
317            constraints: BTreeMap::new(),
318            cas_total_steps: 3,
319            cas_avg_prediction_error: 0.4,
320            cas_adaptation_score: 0.6,
321            cognitive_effect: RuleEffect::default(),
322            cases: vec![],
323            case_capacity: 256,
324            strategies: BTreeMap::new(),
325            active_modules: BTreeMap::new(),
326            patch_history: vec![],
327            ..KernelSnapshot::default()
328        };
329        let meta = store.save("before-patch", 3, 0.4, 1.0, &snap).unwrap();
330        assert_eq!(store.list().unwrap().len(), 1);
331        assert_eq!(store.load_snapshot(meta.id).unwrap().total_steps, 3);
332        #[cfg(unix)]
333        {
334            use std::os::unix::fs::PermissionsExt;
335            assert_eq!(
336                fs::metadata(&dir).unwrap().permissions().mode() & 0o777,
337                0o700
338            );
339            assert_eq!(
340                fs::metadata(store.snap_path(meta.id))
341                    .unwrap()
342                    .permissions()
343                    .mode()
344                    & 0o777,
345                0o600
346            );
347            assert_eq!(
348                fs::metadata(store.meta_path(meta.id))
349                    .unwrap()
350                    .permissions()
351                    .mode()
352                    & 0o777,
353                0o600
354            );
355        }
356        let _ = fs::remove_dir_all(&dir);
357    }
358
359    #[test]
360    fn malformed_metadata_does_not_block_listing_or_pruning() {
361        let dir = temp_dir().join(format!("omega-ckpt-corrupt-{}", crate::new_uuid()));
362        let store = CheckpointStore {
363            dir: dir.clone(),
364            max_keep: 1,
365        };
366        let snapshot = KernelSnapshot::default();
367        let first = store.save("first", 1, 0.0, 1.0, &snapshot).unwrap();
368        fs::write(dir.join("broken.meta.json"), b"{not-json}").unwrap();
369        let second = store.save("second", 2, 0.0, 1.0, &snapshot).unwrap();
370
371        let listed = store.list().unwrap();
372        assert_eq!(listed.len(), 1);
373        assert!(listed[0].id == first.id || listed[0].id == second.id);
374        store.prune().unwrap();
375        assert_eq!(store.list().unwrap().len(), 1);
376        assert!(dir.join("broken.meta.json").exists());
377        let _ = fs::remove_dir_all(dir);
378    }
379
380    #[test]
381    fn stale_metadata_temp_files_are_removed_without_touching_other_files() {
382        let dir = temp_dir().join(format!("omega-ckpt-temp-{}", crate::new_uuid()));
383        fs::create_dir_all(&dir).unwrap();
384        let store = CheckpointStore {
385            dir: dir.clone(),
386            max_keep: 32,
387        };
388        let stale_temp = dir.join(format!(
389            "{METADATA_TEMP_PREFIX}orphan{METADATA_TEMP_SUFFIX}"
390        ));
391        let unrelated = dir.join("unrelated.tmp");
392        fs::write(&stale_temp, b"partial metadata").unwrap();
393        fs::write(&unrelated, b"leave me alone").unwrap();
394
395        store.cleanup_metadata_temps_older_than(Duration::ZERO);
396
397        assert!(!stale_temp.exists());
398        assert!(unrelated.exists());
399        let _ = fs::remove_dir_all(dir);
400    }
401
402    #[test]
403    fn id_collision_does_not_replace_existing_snapshot_or_metadata() {
404        let dir = temp_dir().join(format!("omega-ckpt-collision-{}", crate::new_uuid()));
405        let store = CheckpointStore {
406            dir: dir.clone(),
407            max_keep: 32,
408        };
409        fs::create_dir_all(&dir).unwrap();
410        let id = crate::new_uuid();
411        let old_snapshot = b"original snapshot contents";
412        let old_metadata = b"original metadata contents";
413        fs::write(store.snap_path(id), old_snapshot).unwrap();
414        fs::write(store.meta_path(id), old_metadata).unwrap();
415
416        let result = store.save_with_privacy_and_id(CheckpointSave {
417            label: "collision",
418            step: 1,
419            avg_err: 0.0,
420            damping: 1.0,
421            snapshot: &KernelSnapshot::default(),
422            redact_user_content: false,
423            id,
424        });
425
426        assert!(result.is_err());
427        assert_eq!(fs::read(store.snap_path(id)).unwrap(), old_snapshot);
428        assert_eq!(fs::read(store.meta_path(id)).unwrap(), old_metadata);
429        let _ = fs::remove_dir_all(dir);
430    }
431
432    #[test]
433    fn metadata_collision_removes_only_the_new_snapshot() {
434        let dir = temp_dir().join(format!("omega-ckpt-meta-collision-{}", crate::new_uuid()));
435        let store = CheckpointStore {
436            dir: dir.clone(),
437            max_keep: 32,
438        };
439        fs::create_dir_all(&dir).unwrap();
440        let id = crate::new_uuid();
441        let old_metadata = b"original metadata contents";
442        fs::write(store.meta_path(id), old_metadata).unwrap();
443
444        let result = store.save_with_privacy_and_id(CheckpointSave {
445            label: "collision",
446            step: 1,
447            avg_err: 0.0,
448            damping: 1.0,
449            snapshot: &KernelSnapshot::default(),
450            redact_user_content: false,
451            id,
452        });
453
454        assert!(result.is_err());
455        assert_eq!(fs::read(store.meta_path(id)).unwrap(), old_metadata);
456        assert!(!store.snap_path(id).exists());
457        let _ = fs::remove_dir_all(dir);
458    }
459}