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).is_ok_and(|age| age >= STALE_AFTER)
237}
238
239/// Path helper for tests + callers that want to reason about our namespace.
240#[must_use]
241pub fn is_scratch_path(p: &Path) -> bool {
242 p.file_name()
243 .and_then(|n| n.to_str())
244 .is_some_and(|n| n.starts_with(PREFIX))
245}
246
247#[cfg(test)]
248mod tests {
249 use super::*;
250
251 /// The whole point: a minted dir is gone once the registry drops.
252 #[test]
253 fn a_scratch_dir_is_removed_on_drop() {
254 let path = {
255 let mut r = ScratchRegistry::default();
256 let p = r.dir().expect("mint dir");
257 assert!(p.is_dir(), "the dir must exist while the registry lives");
258 p
259 };
260 assert!(
261 !path.exists(),
262 "a scratch dir must not outlive the interpreter — this is the leak \
263 that put 21,608 dirs and 13 GB into rio's tmpfs"
264 );
265 }
266
267 #[test]
268 fn a_scratch_file_is_removed_on_drop() {
269 let path = {
270 let mut r = ScratchRegistry::default();
271 let p = r.file().expect("mint file");
272 assert!(p.is_file());
273 p
274 };
275 assert!(!path.exists(), "a scratch file must not outlive the interpreter");
276 }
277
278 /// A dir the script filled must still be removable — `remove_dir_all`, not
279 /// `remove_dir`. The leaked dirs on rio were not empty; eight were 1.4 GB.
280 #[test]
281 fn a_non_empty_scratch_dir_is_still_removed() {
282 let path = {
283 let mut r = ScratchRegistry::default();
284 let p = r.dir().expect("mint dir");
285 std::fs::create_dir_all(p.join("nested/deeper")).expect("nest");
286 std::fs::write(p.join("nested/deeper/file.txt"), b"content").expect("write");
287 p
288 };
289 assert!(!path.exists(), "a non-empty scratch dir must still be removed");
290 }
291
292 /// Every entry is cleaned, not just the first — and the registry owns many.
293 #[test]
294 fn all_entries_are_removed_not_only_the_first() {
295 let paths: Vec<PathBuf> = {
296 let mut r = ScratchRegistry::default();
297 let v = (0..5).map(|_| r.dir().expect("mint")).collect::<Vec<_>>();
298 assert_eq!(r.len(), 5);
299 v
300 };
301 for p in paths {
302 assert!(!p.exists(), "{} survived", p.display());
303 }
304 }
305
306 /// Two paths minted back-to-back must differ. `SystemTime::now()` is not
307 /// guaranteed to advance between adjacent calls, so the sequence counter —
308 /// not the clock — is what guarantees this.
309 #[test]
310 fn two_paths_minted_in_the_same_instant_are_distinct() {
311 let mut r = ScratchRegistry::default();
312 let a = r.dir().expect("a");
313 let b = r.dir().expect("b");
314 assert_ne!(a, b, "a collision would make one script delete another's scratch");
315 assert_eq!(r.len(), 2);
316 }
317
318 /// The name must carry the pid, so two concurrent processes cannot collide
319 /// and delete each other's live scratch.
320 #[test]
321 fn the_path_is_process_scoped() {
322 let mut r = ScratchRegistry::default();
323 let p = r.dir().expect("mint");
324 let name = p.file_name().unwrap().to_string_lossy().to_string();
325 assert!(
326 name.contains(&std::process::id().to_string()),
327 "expected pid in {name:?}"
328 );
329 assert!(is_scratch_path(&p));
330 }
331
332 /// The sweep must never touch a path that is not ours. This is the property
333 /// that keeps it from deleting the operator's own /tmp work — which on the
334 /// measured host was ~25 GB and explicitly not ours to remove.
335 #[test]
336 fn the_sweep_ignores_paths_that_are_not_ours() {
337 let foreign = std::env::temp_dir().join(format!("NOT-OURS-{}", std::process::id()));
338 std::fs::create_dir_all(&foreign).expect("create foreign");
339 sweep_stale();
340 assert!(
341 foreign.exists(),
342 "the sweep must only ever match its own prefix"
343 );
344 let _ = std::fs::remove_dir_all(&foreign);
345 }
346
347 /// A freshly-created scratch entry is NOT stale — otherwise a sweep would
348 /// race a live sibling process and delete scratch still in use.
349 #[test]
350 fn the_sweep_does_not_remove_fresh_entries() {
351 let mut r = ScratchRegistry::default();
352 let p = r.dir().expect("mint");
353 sweep_stale();
354 assert!(
355 p.exists(),
356 "a live process's scratch must survive another process's sweep"
357 );
358 }
359
360 /// Two registries in ONE process must never mint the same path.
361 ///
362 /// This is the regression that made `the_sweep_does_not_remove_fresh_entries`
363 /// fail 2 of 3 workspace runs while passing in isolation: `seq` was
364 /// per-registry, so two registries minting inside one clock tick both
365 /// produced `…-{pid}-{now}-0`, and the first to drop removed the other's
366 /// live directory.
367 #[test]
368 fn two_registries_in_one_process_never_collide() {
369 let mut a = ScratchRegistry::default();
370 let mut b = ScratchRegistry::default();
371 let mut seen = std::collections::BTreeSet::new();
372 for _ in 0..64 {
373 assert!(seen.insert(a.dir().expect("a")), "collision from registry a");
374 assert!(seen.insert(b.dir().expect("b")), "collision from registry b");
375 }
376 assert_eq!(seen.len(), 128);
377 }
378
379 /// And a sibling registry dropping must not remove another's live dir —
380 /// the consequence the collision actually produced.
381 #[test]
382 fn a_sibling_registry_drop_leaves_our_scratch_alone() {
383 let mut mine = ScratchRegistry::default();
384 let p = mine.dir().expect("mint");
385 {
386 let mut other = ScratchRegistry::default();
387 let _ = other.dir().expect("mint");
388 } // other drops here
389 assert!(
390 p.exists(),
391 "a sibling registry's Drop deleted our live scratch: {p:?}"
392 );
393 }
394
395}