aft-base 0.68.1

Shared foundation for Agent Foundational Toolkit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
//! Last-use retention for shared, identity-keyed executable fixture directories.

#![allow(dead_code)]

use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};

#[path = "image_cache_usage.rs"]
pub mod usage;

#[cfg(any(test, feature = "test-support"))]
pub use usage::Usage;

pub const RETENTION: Duration = Duration::from_secs(24 * 60 * 60);
pub const PRESSURE_RETENTION: Duration = Duration::from_secs(30 * 60);
pub const LEASE_RETENTION: Duration = Duration::from_secs(3 * 60 * 60);
pub const FREE_FLOOR: u64 = 40 * 1024 * 1024 * 1024;
pub const KEEP_UNUSED: usize = 4;

/// Refresh under the publication lock so pruning cannot race a cache hit.
pub fn refresh(directory: &Path) -> io::Result<()> {
    let leases = directory.join(".leases");
    fs::create_dir_all(&leases)?;
    fs::write(leases.join(std::process::id().to_string()), [])?;
    filetime::set_file_mtime(directory, filetime::FileTime::now())
}

/// Prune only identity directories; the current lookup is always protected.
pub fn prune(root: &Path, current: &Path, now: SystemTime) -> io::Result<()> {
    prune_cache(root, current, now, false)
}

/// Include old Cargo/nextest cache roots left behind by older test binaries.
pub fn prune_real_images(root: &Path, current: &Path, now: SystemTime) -> io::Result<()> {
    prune_cache(root, current, now, true)
}

/// Use test-supplied live PIDs and open-file identities instead of scanning
/// unrelated host processes when asserting eviction.
#[cfg(any(test, feature = "test-support"))]
pub fn prune_with_usage(
    root: &Path,
    current: &Path,
    now: SystemTime,
    legacy: bool,
    usage: &Usage,
) -> io::Result<()> {
    prune_with(root, current, now, legacy, usage, |_| Some(FREE_FLOOR))
}

fn prune_cache(root: &Path, current: &Path, now: SystemTime, legacy: bool) -> io::Result<()> {
    let free = usage::free_bytes(root);
    let candidates = cache_entries(root, legacy)?;
    let pids = usage::Usage::default();
    let mut unused = Vec::new();
    for entry in &candidates {
        let live_lease = match leased(&entry.0, now, &pids) {
            Ok(active) => active,
            Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
            Err(error) => return Err(error),
        };
        if entry.0 != current && !live_lease && !entry.2.is_some_and(|pid| pids.pid_alive(pid)) {
            unused.push(entry);
        }
    }
    if unused.len() <= KEEP_UNUSED
        && !unused.iter().any(|entry| {
            let age = now.duration_since(entry.1).unwrap_or_default();
            age > RETENTION
                || (free.is_some_and(|free| free < FREE_FLOOR) && age > PRESSURE_RETENTION)
        })
    {
        return Ok(());
    }
    let Ok(usage) = usage::snapshot() else {
        // Incomplete process visibility cannot establish that an image is unused.
        return Ok(());
    };
    prune_with(root, current, now, legacy, &usage, |_| free)
}

fn identity(name: &str) -> bool {
    name.len() == 64
        && name
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}

fn legacy_pid(name: &str) -> Option<Option<u32>> {
    if let Some(hash) = name.strip_prefix("aft-real-module-images-nextest-") {
        return identity(hash).then_some(None);
    }
    let pid = name.strip_prefix("aft-real-module-images-cargo-")?;
    let number = pid.parse::<u32>().ok()?;
    (number > 0 && number.to_string() == pid).then_some(Some(number))
}

pub fn last_used(directory: &Path) -> io::Result<SystemTime> {
    let mut modified = fs::metadata(directory)?.modified()?;
    for child in fs::read_dir(directory)? {
        let child = child?;
        if child.file_type()?.is_dir() && identity(&child.file_name().to_string_lossy()) {
            modified = modified.max(child.metadata()?.modified()?);
        }
    }
    Ok(modified)
}

fn leased(directory: &Path, now: SystemTime, usage: &usage::Usage) -> io::Result<bool> {
    let mut active = false;
    let children = match fs::read_dir(directory.join(".leases")) {
        Ok(children) => children,
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
        Err(error) => return Err(error),
    };
    for child in children {
        let child = child?;
        let name = child.file_name();
        let name = name.to_string_lossy();
        let Ok(pid) = name.parse() else {
            continue;
        };
        if !child.file_type()?.is_file() {
            continue;
        }
        let age = now
            .duration_since(child.metadata()?.modified()?)
            .unwrap_or_default();
        if age < LEASE_RETENTION && usage.pid_alive(pid) {
            active = true;
        } else {
            let _ = fs::remove_file(child.path());
        }
    }
    Ok(active)
}

fn protected(
    directory: &Path,
    pid: Option<u32>,
    now: SystemTime,
    usage: &usage::Usage,
) -> io::Result<bool> {
    Ok(pid.is_some_and(|pid| usage.pid_alive(pid))
        || leased(directory, now, usage)?
        || usage.in_use(directory)? != usage::ImageUse::Absent)
}

fn cache_entries(root: &Path, legacy: bool) -> io::Result<Vec<(PathBuf, SystemTime, Option<u32>)>> {
    let mut entries: Vec<(PathBuf, SystemTime, Option<u32>)> = Vec::new();
    let mut add = |path: PathBuf, pid| -> io::Result<()> {
        match last_used(&path) {
            Ok(modified) => entries.push((path, modified, pid)),
            Err(error) if error.kind() == io::ErrorKind::NotFound => {}
            Err(error) => return Err(error),
        }
        Ok(())
    };
    for entry in fs::read_dir(root)? {
        let entry = entry?;
        let name = entry.file_name();
        let name = name.to_string_lossy();
        if identity(&name) && entry.file_type()?.is_dir() {
            add(entry.path(), None)?;
        }
    }
    if legacy {
        for entry in fs::read_dir(root.parent().expect("image cache has a parent"))? {
            let entry = entry?;
            if let Some(pid) = legacy_pid(&entry.file_name().to_string_lossy()) {
                if entry.file_type()?.is_dir() {
                    add(entry.path(), pid)?;
                }
            }
        }
    }
    Ok(entries)
}

pub fn prune_with(
    root: &Path,
    current: &Path,
    now: SystemTime,
    legacy: bool,
    usage: &usage::Usage,
    free_bytes: impl FnOnce(&Path) -> Option<u64>,
) -> io::Result<()> {
    let mut entries = cache_entries(root, legacy)?;
    entries.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
    let low_disk = free_bytes(root).is_some_and(|free| free < FREE_FLOOR);
    let mut unused = 0;
    for (directory, modified, pid) in entries {
        if directory == current {
            continue;
        }
        match protected(&directory, pid, now, usage) {
            Ok(true) => continue,
            Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
            Err(error) => return Err(error),
            Ok(false) => {}
        }
        let age = now.duration_since(modified).unwrap_or_default();
        let remove =
            unused >= KEEP_UNUSED || age > RETENTION || (low_disk && age > PRESSURE_RETENTION);
        unused += 1;
        if remove {
            prune_stale(&directory, modified, pid, now, usage, || {})?;
        }
    }
    Ok(())
}

pub fn prune_stale(
    directory: &Path,
    observed: SystemTime,
    pid: Option<u32>,
    now: SystemTime,
    usage: &usage::Usage,
    claimed: impl FnOnce(),
) -> io::Result<()> {
    let quarantine = tempfile::Builder::new()
        .prefix(".pruning-")
        .tempdir_in(directory.parent().expect("cache entry has a parent"))?;
    let removed = quarantine.path().join("image");
    // Claim the old pathname before the final age check. A concurrent lookup
    // either refreshed this directory already or will republish at its old path.
    // Windows may refuse to move an executing image; leave it for the next scan.
    if fs::rename(directory, &removed).is_err() {
        return Ok(());
    }
    claimed();
    let retain = (|| -> io::Result<bool> {
        Ok(last_used(&removed)? > observed || protected(&removed, pid, now, usage)?)
    })()
    .unwrap_or(true);
    if retain {
        match fs::rename(&removed, directory) {
            Ok(()) => {}
            // A concurrent publisher may already have restored the identity.
            Err(_) if directory.is_dir() => {}
            Err(error) => {
                // Keep a refreshed image even when restoring it was refused.
                let _ = quarantine.keep();
                return Err(error);
            }
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn entry(root: &Path, number: usize, age: Duration, now: SystemTime) -> PathBuf {
        let directory = root.join(format!("{number:064x}"));
        fs::create_dir_all(&directory).unwrap();
        fs::write(directory.join("image"), b"fixture").unwrap();
        filetime::set_file_mtime(&directory, filetime::FileTime::from_system_time(now - age))
            .unwrap();
        directory
    }

    fn lease(directory: &Path, pid: u32, modified: SystemTime) {
        let leases = directory.join(".leases");
        let previous = fs::metadata(directory).unwrap().modified().unwrap();
        fs::create_dir_all(&leases).unwrap();
        fs::write(leases.join(pid.to_string()), []).unwrap();
        filetime::set_file_mtime(
            leases.join(pid.to_string()),
            filetime::FileTime::from_system_time(modified),
        )
        .unwrap();
        filetime::set_file_mtime(directory, filetime::FileTime::from_system_time(previous))
            .unwrap();
    }

    #[test]
    fn image_cache_keeps_four_unused_plus_live_leases_and_open_images() {
        let root = tempfile::tempdir().unwrap();
        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
        let current = entry(root.path(), 99, Duration::ZERO, now);
        let mut usage = usage::Usage::default();
        usage.live_pids = Some([123].into());
        let live = entry(root.path(), 20, Duration::from_secs(4 * 3600), now);
        lease(&live, 123, now);
        let expired = entry(root.path(), 21, Duration::from_secs(4 * 3600), now);
        lease(&expired, 123, now - LEASE_RETENTION);
        let open = entry(root.path(), 22, RETENTION + Duration::from_secs(1), now);
        usage.hold(&open.join("image"));
        let unused: Vec<_> = (1..=6)
            .map(|n| entry(root.path(), n, Duration::from_secs(n as u64), now))
            .collect();
        prune_with(root.path(), &current, now, false, &usage, |_| {
            Some(FREE_FLOOR)
        })
        .unwrap();
        assert!(live.exists(), "a fresh lease protects a delayed exec");
        assert!(open.exists(), "an open image outlives age and count limits");
        assert!(
            !expired.exists(),
            "a reused live PID cannot retain a three-hour-old lease"
        );
        for (index, directory) in unused.iter().enumerate() {
            assert_eq!(directory.exists(), index < KEEP_UNUSED);
        }
    }

    #[test]
    fn image_cache_low_disk_uses_thirty_minute_grace() {
        let root = tempfile::tempdir().unwrap();
        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
        let current = entry(root.path(), 99, RETENTION + Duration::from_secs(1), now);
        let stale = entry(
            root.path(),
            1,
            PRESSURE_RETENTION + Duration::from_secs(1),
            now,
        );
        let boundary = entry(root.path(), 2, PRESSURE_RETENTION, now);
        let fresh = entry(
            root.path(),
            3,
            PRESSURE_RETENTION - Duration::from_secs(1),
            now,
        );
        let usage = usage::Usage::default();
        prune_with(root.path(), &current, now, false, &usage, |_| {
            Some(FREE_FLOOR)
        })
        .unwrap();
        assert!(stale.exists(), "exactly 40 GiB is not low disk");
        prune_with(root.path(), &current, now, false, &usage, |_| {
            Some(FREE_FLOOR - 1)
        })
        .unwrap();
        assert!(!stale.exists());
        assert!(boundary.exists());
        assert!(fresh.exists());
        assert!(current.exists());
    }

    #[test]
    fn image_cache_legacy_sweep_matches_exact_names_and_holds_live_cargo_pid() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path().join("aft-real-module-images");
        fs::create_dir(&root).unwrap();
        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
        let current = entry(&root, 99, Duration::ZERO, now);
        for n in 1..=4 {
            entry(&root, n, Duration::from_secs(n as u64), now);
        }
        let names = [
            format!("aft-real-module-images-nextest-{}", "a".repeat(64)),
            "aft-real-module-images-cargo-123".into(),
            "aft-real-module-images-cargo-124".into(),
            "aft-real-module-images-nextest-not-a-hash".into(),
            format!("aft-real-module-images-nextest-{}-suffix", "a".repeat(64)),
            "aft-real-module-images-cargo-0124".into(),
            "aft-real-module-images-cargo-124-extra".into(),
        ];
        for name in &names {
            let directory = temp.path().join(name);
            fs::create_dir(&directory).unwrap();
            filetime::set_file_mtime(
                directory,
                filetime::FileTime::from_system_time(now - Duration::from_secs(3 * 3600)),
            )
            .unwrap();
        }
        let mut usage = usage::Usage::default();
        usage.live_pids = Some([123].into());
        prune_with(&root, &current, now, true, &usage, |_| Some(FREE_FLOOR)).unwrap();
        assert!(!temp.path().join(&names[0]).exists());
        assert!(temp.path().join(&names[1]).exists());
        assert!(!temp.path().join(&names[2]).exists());
        for name in &names[3..] {
            assert!(temp.path().join(name).exists(), "matched unrelated {name}");
        }
    }

    #[cfg(unix)]
    #[test]
    fn image_cache_live_probe_finds_open_image_and_hardlink_alias() {
        let root = tempfile::tempdir().unwrap();
        let directory = entry(root.path(), 1, Duration::ZERO, SystemTime::now());
        let alias = root.path().join("alias");
        fs::hard_link(directory.join("image"), &alias).unwrap();
        let _open = fs::File::open(alias).unwrap();
        #[cfg(target_os = "linux")]
        let child = usage::non_dumpable_child();
        #[cfg(target_os = "linux")]
        let child_path = PathBuf::from(format!("/proc/{}", child.pid));
        #[cfg(target_os = "linux")]
        let snapshot = usage::snapshot_process_paths(
            [
                PathBuf::from(format!("/proc/{}", std::process::id())),
                child_path.clone(),
            ],
            &fs::read_to_string("/proc/self/mountinfo").unwrap(),
        );
        #[cfg(not(target_os = "linux"))]
        let snapshot = usage::snapshot().unwrap();
        #[cfg(target_os = "linux")]
        {
            let unreadable = snapshot
                .unreadable
                .iter()
                .find(|process| process.pid == child.pid)
                .expect("the non-dumpable child must be counted as unreadable");
            assert!(unreadable
                .paths
                .iter()
                .any(|path| path == &child_path || path.ends_with("fd") || path.ends_with("maps")));
        }
        assert_eq!(snapshot.in_use(&directory).unwrap(), usage::ImageUse::Found);
    }

    #[test]
    fn image_cache_unknown_usage_keeps_an_unobserved_image() {
        let root = tempfile::tempdir().unwrap();
        let now = SystemTime::now();
        let current = entry(root.path(), 99, Duration::ZERO, now);
        let old = entry(root.path(), 1, RETENTION + Duration::from_secs(1), now);
        let mut incomplete = usage::Usage::default();
        incomplete.unreadable.push(usage::UnreadableProcess {
            pid: 123,
            paths: vec![PathBuf::from("/proc/123/maps")],
        });
        assert_eq!(incomplete.in_use(&old).unwrap(), usage::ImageUse::Unknown);
        prune_with(root.path(), &current, now, false, &incomplete, |_| Some(0)).unwrap();
        assert!(
            old.exists(),
            "unknown ownership must defeat age and low-disk eviction"
        );
        let complete = usage::Usage::default();
        assert_eq!(complete.in_use(&old).unwrap(), usage::ImageUse::Absent);
        prune_with(root.path(), &current, now, false, &complete, |_| Some(0)).unwrap();
        assert!(!old.exists(), "known-absent ownership permits eviction");
    }

    #[test]
    fn image_cache_prunes_only_stale_siblings() {
        let root = tempfile::tempdir().unwrap();
        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
        let directory = |digit: &str, age| {
            let path = root.path().join(digit.repeat(64));
            fs::create_dir(&path).unwrap();
            fs::write(path.join("image"), b"fixture").unwrap();
            filetime::set_file_mtime(&path, filetime::FileTime::from_system_time(now - age))
                .unwrap();
            path
        };
        let stale = directory("a", RETENTION + Duration::from_secs(1));
        let fresh = directory("b", RETENTION - Duration::from_secs(1));
        let boundary = directory("c", RETENTION);
        let current = directory("d", RETENTION + Duration::from_secs(1));
        let refreshed = directory("e", RETENTION + Duration::from_secs(1));
        refresh(&refreshed).unwrap();
        let pending = root.path().join(".publishing-unrelated");
        fs::create_dir(&pending).unwrap();
        filetime::set_file_mtime(&pending, filetime::FileTime::from_unix_time(1, 0)).unwrap();
        prune_with(
            root.path(),
            &current,
            now,
            false,
            &usage::Usage::default(),
            |_| Some(FREE_FLOOR),
        )
        .unwrap();
        assert!(!stale.exists());
        for retained in [fresh, boundary, current, refreshed, pending] {
            assert!(retained.exists(), "removed {}", retained.display());
        }
    }

    #[test]
    fn image_cache_restores_a_directory_refreshed_during_pruning() {
        let root = tempfile::tempdir().unwrap();
        let directory = root.path().join("a".repeat(64));
        fs::create_dir(&directory).unwrap();
        fs::write(directory.join("image"), b"fixture").unwrap();
        let now = SystemTime::now();
        filetime::set_file_mtime(
            &directory,
            filetime::FileTime::from_system_time(now - RETENTION - Duration::from_secs(1)),
        )
        .unwrap();
        let observed = last_used(&directory).unwrap();
        prune_stale(
            &directory,
            observed,
            None,
            now,
            &usage::Usage::default(),
            || {
                let quarantine = fs::read_dir(root.path())
                    .unwrap()
                    .map(Result::unwrap)
                    .find(|entry| entry.file_name().to_string_lossy().starts_with(".pruning-"))
                    .unwrap();
                refresh(&quarantine.path().join("image")).unwrap();
            },
        )
        .unwrap();
        assert_eq!(fs::read(directory.join("image")).unwrap(), b"fixture");
    }
}