Skip to main content

qualia_core_db/inference/runtime/artifacts/
run_dir.rs

1use std::fs;
2use std::path::{Path, PathBuf};
3
4use tempfile::{Builder, TempDir};
5
6use super::budget::{validate_label, validate_relative_artifact_path, ArtifactError};
7
8pub const RUN_MARKER_FILE: &str = ".qualia-inference-run";
9
10#[derive(Debug, Clone)]
11pub enum ArtifactRetention {
12    Ephemeral,
13    RetainTo(PathBuf),
14}
15
16#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
17pub struct ArtifactStats {
18    pub created_bytes: u64,
19    pub removed_bytes: u64,
20    pub retained_bytes: u64,
21    pub cleanup_failures: u64,
22}
23
24#[derive(Debug)]
25pub struct ArtifactFinish {
26    pub retained_path: Option<PathBuf>,
27    pub stats: ArtifactStats,
28}
29
30/// One bounded, marker-owned scratch directory.
31///
32/// Dropping an unfinished run removes it through [`TempDir`]. Call [`Self::finish`] to obtain
33/// cleanup counters or atomically promote retained evidence.
34#[derive(Debug)]
35pub struct RunArtifactDir {
36    dir: Option<TempDir>,
37    retention: ArtifactRetention,
38    byte_budget: u64,
39    stats: ArtifactStats,
40}
41
42impl RunArtifactDir {
43    /// Creates a run artifact dir under the given parent with a byte budget.
44    pub fn new_in(
45        scratch_parent: &Path,
46        label: &str,
47        byte_budget: u64,
48        retention: ArtifactRetention,
49    ) -> Result<Self, ArtifactError> {
50        validate_label(label)?;
51        fs::create_dir_all(scratch_parent)?;
52        let dir = Builder::new()
53            .prefix(&format!("qualia-inference-{label}-"))
54            .tempdir_in(scratch_parent)?;
55        fs::write(
56            dir.path().join(RUN_MARKER_FILE),
57            b"qualia-inference-run-v1\n",
58        )?;
59        Ok(Self {
60            dir: Some(dir),
61            retention,
62            byte_budget,
63            stats: ArtifactStats::default(),
64        })
65    }
66
67    /// Filesystem path of the run dir.
68    pub fn path(&self) -> &Path {
69        self.dir
70            .as_ref()
71            .expect("artifact directory is unavailable after finish")
72            .path()
73    }
74
75    /// Byte budget remaining.
76    pub fn remaining_bytes(&self) -> u64 {
77        self.byte_budget.saturating_sub(self.stats.created_bytes)
78    }
79
80    /// Current artifact stats.
81    pub fn stats(&self) -> ArtifactStats {
82        self.stats
83    }
84
85    /// Writes an artifact file, failing closed when the budget would be exceeded.
86    pub fn write_bounded(
87        &mut self,
88        relative_path: impl AsRef<Path>,
89        bytes: &[u8],
90    ) -> Result<PathBuf, ArtifactError> {
91        let relative_path = relative_path.as_ref();
92        validate_relative_artifact_path(relative_path)?;
93        let attempted_bytes = self.stats.created_bytes.saturating_add(bytes.len() as u64);
94        if attempted_bytes > self.byte_budget {
95            return Err(ArtifactError::BudgetExceeded {
96                budget_bytes: self.byte_budget,
97                attempted_bytes,
98            });
99        }
100        let output = self.path().join(relative_path);
101        if let Some(parent) = output.parent() {
102            fs::create_dir_all(parent)?;
103        }
104        fs::write(&output, bytes)?;
105        self.stats.created_bytes = attempted_bytes;
106        Ok(output)
107    }
108
109    /// Finalizes the run dir, producing an `ArtifactFinish` summary.
110    pub fn finish(mut self) -> Result<ArtifactFinish, ArtifactError> {
111        let dir = self
112            .dir
113            .take()
114            .expect("artifact directory can only be finished once");
115        match self.retention {
116            ArtifactRetention::Ephemeral => {
117                let path = dir.path().to_path_buf();
118                match dir.close() {
119                    Ok(()) => {
120                        self.stats.removed_bytes = self.stats.created_bytes;
121                        Ok(ArtifactFinish {
122                            retained_path: None,
123                            stats: self.stats,
124                        })
125                    }
126                    Err(source) => {
127                        self.stats.cleanup_failures = self.stats.cleanup_failures.saturating_add(1);
128                        Err(ArtifactError::Cleanup { path, source })
129                    }
130                }
131            }
132            ArtifactRetention::RetainTo(target) => {
133                if target.exists() {
134                    return Err(ArtifactError::TargetExists);
135                }
136                if let Some(parent) = target.parent() {
137                    fs::create_dir_all(parent)?;
138                }
139                let staging = dir.keep();
140                if let Err(source) = fs::rename(&staging, &target) {
141                    return Err(ArtifactError::Promotion {
142                        staging,
143                        target,
144                        source,
145                    });
146                }
147                self.stats.retained_bytes = self.stats.created_bytes;
148                Ok(ArtifactFinish {
149                    retained_path: Some(target),
150                    stats: self.stats,
151                })
152            }
153        }
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    use std::panic::{catch_unwind, AssertUnwindSafe};
160
161    use super::*;
162
163    #[test]
164    fn ephemeral_finish_removes_run_directory() {
165        let parent = tempfile::tempdir().unwrap();
166        let mut run =
167            RunArtifactDir::new_in(parent.path(), "cleanup", 16, ArtifactRetention::Ephemeral)
168                .unwrap();
169        let run_path = run.path().to_path_buf();
170        run.write_bounded("nested/out.bin", b"1234").unwrap();
171        let finish = run.finish().unwrap();
172        assert!(!run_path.exists());
173        assert_eq!(finish.stats.created_bytes, 4);
174        assert_eq!(finish.stats.removed_bytes, 4);
175        assert_eq!(finish.stats.retained_bytes, 0);
176    }
177
178    #[test]
179    fn drop_removes_directory_during_unwind() {
180        let parent = tempfile::tempdir().unwrap();
181        let mut run_path = PathBuf::new();
182        let result = catch_unwind(AssertUnwindSafe(|| {
183            let mut run =
184                RunArtifactDir::new_in(parent.path(), "panic", 16, ArtifactRetention::Ephemeral)
185                    .unwrap();
186            run_path = run.path().to_path_buf();
187            run.write_bounded("out.bin", b"1234").unwrap();
188            panic!("test unwind");
189        }));
190        assert!(result.is_err());
191        assert!(!run_path.exists());
192    }
193
194    #[test]
195    fn budget_fails_closed_without_partial_file() {
196        let parent = tempfile::tempdir().unwrap();
197        let mut run =
198            RunArtifactDir::new_in(parent.path(), "budget", 3, ArtifactRetention::Ephemeral)
199                .unwrap();
200        let err = run.write_bounded("too-large.bin", b"1234").unwrap_err();
201        assert!(matches!(err, ArtifactError::BudgetExceeded { .. }));
202        assert!(!run.path().join("too-large.bin").exists());
203    }
204
205    #[test]
206    fn traversal_is_rejected() {
207        let parent = tempfile::tempdir().unwrap();
208        let mut run =
209            RunArtifactDir::new_in(parent.path(), "paths", 16, ArtifactRetention::Ephemeral)
210                .unwrap();
211        assert!(matches!(
212            run.write_bounded("../escape.bin", b"x"),
213            Err(ArtifactError::InvalidRelativePath)
214        ));
215    }
216
217    #[test]
218    fn retained_run_is_promoted_out_of_staging() {
219        let parent = tempfile::tempdir().unwrap();
220        let target = parent.path().join("evidence").join("run-1");
221        let mut run = RunArtifactDir::new_in(
222            parent.path(),
223            "retain",
224            16,
225            ArtifactRetention::RetainTo(target.clone()),
226        )
227        .unwrap();
228        let staging = run.path().to_path_buf();
229        run.write_bounded("receipt.json", b"{}").unwrap();
230        let finish = run.finish().unwrap();
231        assert!(!staging.exists());
232        assert_eq!(finish.retained_path.as_deref(), Some(target.as_path()));
233        assert!(target.join(RUN_MARKER_FILE).is_file());
234        assert_eq!(finish.stats.retained_bytes, 2);
235    }
236}