Skip to main content

tatara_lisp_script/
scratch.rs

1//! `ScratchRegistry` — the interpreter OWNS every temp path it mints.
2//!
3//! ## The leak this exists to make unrepresentable (measured 2026-07-31)
4//!
5//! `tmp-dir` / `tmp-file` used to `create_dir_all` under `std::env::temp_dir()`
6//! and hand the path back as a bare `Value::Str`. Nothing owned it, so nothing
7//! ever removed it. On `rio` that produced:
8//!
9//! ```text
10//! ls -d /tmp/tatara-script-* | wc -l   ->  21,608
11//! du -shc /tmp/tatara-script-*         ->  13 GB
12//! oldest 05:02, newest 22:26, uptime 17h19m  =>  ~1,250 dirs/hour, since boot
13//! ```
14//!
15//! That box mounts `/tmp` as a **48 GiB tmpfs on 29 GiB of RAM**, so those 13 GB
16//! were not disk — they were memory. Combined with ~25 GB of other scratch it
17//! filled RAM *and* all 31.9 GiB of swap (`SwapFree: 176 kB`), drove PSI
18//! `memory.full avg60` to 92%, and left the OOM killer as the only reclaim
19//! path — it killed `comin`'s `git` mid-deploy. A leaked temp dir is not a
20//! tidiness problem on a tmpfs host; it is a memory leak that takes the node
21//! down.
22//!
23//! ## Why a registry rather than "remember to delete it"
24//!
25//! The old signature made the leak the DEFAULT and correctness opt-in: a script
26//! had to remember an explicit delete, on every exit path including error. The
27//! registry inverts that. `scratch_dir` / `scratch_file` are the only
28//! constructors, they always record, and `Drop` always removes — so "created
29//! but never cleaned" has no representation. Correctness is what you get by
30//! doing nothing.
31//!
32//! ## Two failure modes, two mechanisms
33//!
34//! `Drop` covers normal exit, early `return`, and panic-unwind. It CANNOT cover
35//! `SIGKILL`, an OOM kill, or a power loss — and on the very host that
36//! motivated this, OOM kills were happening three times in six hours. So RAII
37//! alone would have left a residue that regrows. [`sweep_stale`] is the
38//! reconciler for that path: a bounded, best-effort sweep of *our own* prefix,
39//! old enough that no live process can still hold it. Invariant for the normal
40//! case, reconciler for the violent one.
41//!
42//! Escape hatch: set `TATARA_SCRIPT_KEEP_SCRATCH=1` to retain scratch for
43//! debugging. It is deliberately an env var rather than a Lisp argument —
44//! keeping is an operator's debugging choice, not a script's contract, and a
45//! script that could opt into leaking would reopen the class.
46
47use std::path::{Path, PathBuf};
48
49/// How old one of our scratch entries must be before [`sweep_stale`] will
50/// remove it. Generously above any plausible script runtime: the sweep must
51/// never race a *live* sibling process's scratch, and the cost of waiting is
52/// only a few hours of residue after a kill.
53const STALE_AFTER: std::time::Duration = std::time::Duration::from_secs(6 * 60 * 60);
54
55/// Upper bound on entries removed in one sweep. A sweep runs at interpreter
56/// startup, so it must never become the dominant cost of running a script —
57/// on the measured host there were 21,608 entries, and unlinking all of them
58/// takes minutes. Bounded work per run, repeated across runs, converges
59/// without ever making one script pay for the whole backlog.
60const SWEEP_BUDGET: usize = 512;
61
62/// The filename prefix every scratch entry carries. Sweeping matches on this,
63/// so it must never widen to something another tool could also produce.
64const PREFIX: &str = "tatara-script-";
65
66/// Owns the temp paths minted during one interpreter run and removes them on
67/// drop.
68///
69/// Holds `PathBuf`s rather than open handles deliberately: the Lisp side needs
70/// a *path string* it can pass to subprocesses, and a script legitimately
71/// creates, removes, and recreates files underneath a scratch dir. Ownership
72/// here is of the path's lifetime, not of a file descriptor.
73#[derive(Debug, Default)]
74pub struct ScratchRegistry {
75    paths: Vec<PathBuf>,
76    /// Distinguishes two scratch paths minted inside the same nanosecond.
77    /// `SystemTime::now()` is not guaranteed to advance between two adjacent
78    /// calls, and a script doing `(tmp-dir)` twice in a loop is ordinary.
79    seq: u64,
80}
81
82impl ScratchRegistry {
83    /// Mint an owned scratch DIRECTORY and return its path.
84    pub fn dir(&mut self) -> std::io::Result<PathBuf> {
85        let path = self.mint("");
86        std::fs::create_dir_all(&path)?;
87        self.paths.push(path.clone());
88        Ok(path)
89    }
90
91    /// Mint an owned scratch FILE (created empty) and return its path.
92    pub fn file(&mut self) -> std::io::Result<PathBuf> {
93        let path = self.mint(".tmp");
94        std::fs::write(&path, b"")?;
95        self.paths.push(path.clone());
96        Ok(path)
97    }
98
99    /// Build a unique path under the system temp dir.
100    ///
101    /// The name carries the pid as well as the clock: two concurrent
102    /// `tatara-script` processes can otherwise mint the same name from the same
103    /// nanosecond, and the loser's `Drop` would delete the winner's live
104    /// scratch. That is the same class of bug as the one fixed in ami-forge's
105    /// secret var-file (pid-only names colliding within a process) — here the
106    /// collision is across processes, so the pid is the fix rather than the
107    /// cause.
108    ///
109    /// **The sequence number is PROCESS-GLOBAL, and that is load-bearing.**
110    /// It was per-registry, which reintroduced within-a-process collision —
111    /// the exact class the comment above names. Two registries constructed in
112    /// one process and minting inside one clock tick both produced
113    /// `…-{pid}-{now}-0`, and the first to drop deleted the other's live
114    /// directory. Observed as a test failing 2 of 3 workspace runs while
115    /// passing in isolation, which is the signature: the clock is coarse
116    /// enough on a real host that `now` collides, so `now` cannot be the only
117    /// discriminator. A global counter makes the name unique by construction
118    /// rather than by hoping the clock is fine-grained.
119    fn mint(&mut self, suffix: &str) -> PathBuf {
120        use std::sync::atomic::{AtomicU64, Ordering};
121        static SEQ: AtomicU64 = AtomicU64::new(0);
122
123        let now = std::time::SystemTime::now()
124            .duration_since(std::time::UNIX_EPOCH)
125            .map_or(0, |d| d.as_nanos());
126        let pid = std::process::id();
127        let seq = SEQ.fetch_add(1, Ordering::Relaxed);
128        // Kept for the public `len`/`is_empty` accounting the registry exposes.
129        self.seq += 1;
130        std::env::temp_dir().join(format!("{PREFIX}{pid}-{now:x}-{seq}{suffix}"))
131    }
132
133    /// Number of live scratch entries. Exposed for tests.
134    #[must_use]
135    pub fn len(&self) -> usize {
136        self.paths.len()
137    }
138
139    /// Whether the registry currently owns nothing.
140    #[must_use]
141    pub fn is_empty(&self) -> bool {
142        self.paths.is_empty()
143    }
144}
145
146/// True when the operator asked to retain scratch for debugging.
147fn keep_requested() -> bool {
148    std::env::var_os("TATARA_SCRIPT_KEEP_SCRATCH").is_some_and(|v| v != "0" && v != "")
149}
150
151impl Drop for ScratchRegistry {
152    fn drop(&mut self) {
153        if keep_requested() {
154            return;
155        }
156        for p in self.paths.drain(..) {
157            // Best-effort on every path, and DELIBERATELY not short-circuiting
158            // on the first error: one undeletable entry (a busy mount, a
159            // permission change made by the script itself) must not strand
160            // every remaining entry. A failure here is also never propagated —
161            // a cleanup error must not mask the script's own exit status.
162            let _ = if p.is_dir() {
163                std::fs::remove_dir_all(&p)
164            } else {
165                std::fs::remove_file(&p)
166            };
167        }
168    }
169}
170
171/// Remove OUR OWN stale scratch left behind by processes that died without
172/// running `Drop` (SIGKILL, OOM kill, power loss).
173///
174/// Returns the number of entries removed. Best-effort throughout: this runs on
175/// the startup path of every script, so it must never fail a run and never
176/// dominate its cost.
177///
178/// Three safety properties, each load-bearing:
179/// - **Only our prefix.** Matching is on `tatara-script-`, so the sweep can
180///   never touch another tool's scratch — including the operator's own
181///   `/tmp/tmp.*` and build artifacts, which on the measured host were far
182///   larger than ours and are emphatically not ours to delete.
183/// - **Only genuinely old entries.** [`STALE_AFTER`] is hours, so a *live*
184///   sibling process's scratch is never eligible. An age check is what makes
185///   this safe under concurrency, where a pid check would not be — pids are
186///   reused.
187/// - **Bounded work.** At most [`SWEEP_BUDGET`] removals per run.
188pub fn sweep_stale() -> usize {
189    if keep_requested() {
190        return 0;
191    }
192    let Ok(entries) = std::fs::read_dir(std::env::temp_dir()) else {
193        return 0;
194    };
195    let now = std::time::SystemTime::now();
196    let mut removed = 0usize;
197    for entry in entries.flatten() {
198        if removed >= SWEEP_BUDGET {
199            break;
200        }
201        let name = entry.file_name();
202        let Some(name) = name.to_str() else { continue };
203        if !name.starts_with(PREFIX) {
204            continue;
205        }
206        if !is_stale(&entry, now) {
207            continue;
208        }
209        let path = entry.path();
210        let ok = if path.is_dir() {
211            std::fs::remove_dir_all(&path)
212        } else {
213            std::fs::remove_file(&path)
214        };
215        if ok.is_ok() {
216            removed += 1;
217        }
218    }
219    removed
220}
221
222/// Whether a directory entry is older than [`STALE_AFTER`].
223///
224/// Uses mtime rather than ctime/atime: a scratch dir being *written to* is
225/// evidence it is live, and mtime is the field that tracks that. An entry
226/// whose metadata cannot be read is treated as NOT stale — the safe direction,
227/// since the cost of skipping is a few leftover bytes and the cost of a false
228/// positive is deleting live scratch.
229fn is_stale(entry: &std::fs::DirEntry, now: std::time::SystemTime) -> bool {
230    let Ok(meta) = entry.metadata() else {
231        return false;
232    };
233    let Ok(mtime) = meta.modified() else {
234        return false;
235    };
236    now.duration_since(mtime)
237        .is_ok_and(|age| age >= STALE_AFTER)
238}
239
240/// Path helper for tests + callers that want to reason about our namespace.
241#[must_use]
242pub fn is_scratch_path(p: &Path) -> bool {
243    p.file_name()
244        .and_then(|n| n.to_str())
245        .is_some_and(|n| n.starts_with(PREFIX))
246}
247
248#[cfg(test)]
249mod tests {
250    use super::*;
251
252    /// The whole point: a minted dir is gone once the registry drops.
253    #[test]
254    fn a_scratch_dir_is_removed_on_drop() {
255        let path = {
256            let mut r = ScratchRegistry::default();
257            let p = r.dir().expect("mint dir");
258            assert!(p.is_dir(), "the dir must exist while the registry lives");
259            p
260        };
261        assert!(
262            !path.exists(),
263            "a scratch dir must not outlive the interpreter — this is the leak \
264             that put 21,608 dirs and 13 GB into rio's tmpfs"
265        );
266    }
267
268    #[test]
269    fn a_scratch_file_is_removed_on_drop() {
270        let path = {
271            let mut r = ScratchRegistry::default();
272            let p = r.file().expect("mint file");
273            assert!(p.is_file());
274            p
275        };
276        assert!(
277            !path.exists(),
278            "a scratch file must not outlive the interpreter"
279        );
280    }
281
282    /// A dir the script filled must still be removable — `remove_dir_all`, not
283    /// `remove_dir`. The leaked dirs on rio were not empty; eight were 1.4 GB.
284    #[test]
285    fn a_non_empty_scratch_dir_is_still_removed() {
286        let path = {
287            let mut r = ScratchRegistry::default();
288            let p = r.dir().expect("mint dir");
289            std::fs::create_dir_all(p.join("nested/deeper")).expect("nest");
290            std::fs::write(p.join("nested/deeper/file.txt"), b"content").expect("write");
291            p
292        };
293        assert!(
294            !path.exists(),
295            "a non-empty scratch dir must still be removed"
296        );
297    }
298
299    /// Every entry is cleaned, not just the first — and the registry owns many.
300    #[test]
301    fn all_entries_are_removed_not_only_the_first() {
302        let paths: Vec<PathBuf> = {
303            let mut r = ScratchRegistry::default();
304            let v = (0..5).map(|_| r.dir().expect("mint")).collect::<Vec<_>>();
305            assert_eq!(r.len(), 5);
306            v
307        };
308        for p in paths {
309            assert!(!p.exists(), "{} survived", p.display());
310        }
311    }
312
313    /// Two paths minted back-to-back must differ. `SystemTime::now()` is not
314    /// guaranteed to advance between adjacent calls, so the sequence counter —
315    /// not the clock — is what guarantees this.
316    #[test]
317    fn two_paths_minted_in_the_same_instant_are_distinct() {
318        let mut r = ScratchRegistry::default();
319        let a = r.dir().expect("a");
320        let b = r.dir().expect("b");
321        assert_ne!(
322            a, b,
323            "a collision would make one script delete another's scratch"
324        );
325        assert_eq!(r.len(), 2);
326    }
327
328    /// The name must carry the pid, so two concurrent processes cannot collide
329    /// and delete each other's live scratch.
330    #[test]
331    fn the_path_is_process_scoped() {
332        let mut r = ScratchRegistry::default();
333        let p = r.dir().expect("mint");
334        let name = p.file_name().unwrap().to_string_lossy().to_string();
335        assert!(
336            name.contains(&std::process::id().to_string()),
337            "expected pid in {name:?}"
338        );
339        assert!(is_scratch_path(&p));
340    }
341
342    /// The sweep must never touch a path that is not ours. This is the property
343    /// that keeps it from deleting the operator's own /tmp work — which on the
344    /// measured host was ~25 GB and explicitly not ours to remove.
345    #[test]
346    fn the_sweep_ignores_paths_that_are_not_ours() {
347        let foreign = std::env::temp_dir().join(format!("NOT-OURS-{}", std::process::id()));
348        std::fs::create_dir_all(&foreign).expect("create foreign");
349        sweep_stale();
350        assert!(
351            foreign.exists(),
352            "the sweep must only ever match its own prefix"
353        );
354        let _ = std::fs::remove_dir_all(&foreign);
355    }
356
357    /// A freshly-created scratch entry is NOT stale — otherwise a sweep would
358    /// race a live sibling process and delete scratch still in use.
359    #[test]
360    fn the_sweep_does_not_remove_fresh_entries() {
361        let mut r = ScratchRegistry::default();
362        let p = r.dir().expect("mint");
363        sweep_stale();
364        assert!(
365            p.exists(),
366            "a live process's scratch must survive another process's sweep"
367        );
368    }
369
370    /// Two registries in ONE process must never mint the same path.
371    ///
372    /// This is the regression that made `the_sweep_does_not_remove_fresh_entries`
373    /// fail 2 of 3 workspace runs while passing in isolation: `seq` was
374    /// per-registry, so two registries minting inside one clock tick both
375    /// produced `…-{pid}-{now}-0`, and the first to drop removed the other's
376    /// live directory.
377    #[test]
378    fn two_registries_in_one_process_never_collide() {
379        let mut a = ScratchRegistry::default();
380        let mut b = ScratchRegistry::default();
381        let mut seen = std::collections::BTreeSet::new();
382        for _ in 0..64 {
383            assert!(
384                seen.insert(a.dir().expect("a")),
385                "collision from registry a"
386            );
387            assert!(
388                seen.insert(b.dir().expect("b")),
389                "collision from registry b"
390            );
391        }
392        assert_eq!(seen.len(), 128);
393    }
394
395    /// And a sibling registry dropping must not remove another's live dir —
396    /// the consequence the collision actually produced.
397    #[test]
398    fn a_sibling_registry_drop_leaves_our_scratch_alone() {
399        let mut mine = ScratchRegistry::default();
400        let p = mine.dir().expect("mint");
401        {
402            let mut other = ScratchRegistry::default();
403            let _ = other.dir().expect("mint");
404        } // other drops here
405        assert!(
406            p.exists(),
407            "a sibling registry's Drop deleted our live scratch: {p:?}"
408        );
409    }
410}