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
//! Immutable executable files shared by tests that need a named fixture.

#![allow(dead_code)]

use sha2::{Digest, Sha256};
use std::fs::{self, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};

#[path = "image_cache.rs"]
pub mod image_cache;

const CACHE_ROOT: &str = "aft-test-executables";

fn cache_root() -> PathBuf {
    std::env::temp_dir().join(CACHE_ROOT)
}

pub fn cache_path(root: &Path, bytes: &[u8], name: &str) -> PathBuf {
    let mut digest = Sha256::new();
    digest.update(b"mode:755\0");
    digest.update(bytes);
    root.join(format!("{:x}", digest.finalize())).join(name)
}

/// Return the immutable cache path for these executable bytes.
///
/// Publishing by hard link is atomic and refuses to replace an existing path,
/// so concurrent test processes either share one inode or verify the winner.
pub fn cached_executable(bytes: &[u8]) -> io::Result<PathBuf> {
    cached_executable_named(
        bytes,
        if cfg!(windows) {
            "executable.exe"
        } else {
            "executable"
        },
    )
}

/// Return the content-addressed executable under a caller-required basename.
pub fn cached_executable_named(bytes: &[u8], name: &str) -> io::Result<PathBuf> {
    cached_executable_named_in(&cache_root(), bytes, name)
}

/// Cache an executable inside a fixture root that must remain visible to a sandbox.
pub fn cached_executable_named_in(root: &Path, bytes: &[u8], name: &str) -> io::Result<PathBuf> {
    validate_name(name)?;
    let result = publish_executable(root, bytes, name);
    match result {
        // Another language's cache pruner can claim an old identity between
        // lookup and refresh. Republish once rather than exposing that race.
        Err(error) if error.kind() == io::ErrorKind::NotFound => {
            publish_executable(root, bytes, name)
        }
        result => result,
    }
}

/// Warm a new executable at its final path under the publication lock.
/// Use a separate root from un-warmed publishers: a cache hit must mean the
/// same warmup already succeeded. Warmup failure removes the new entry.
pub fn cached_executable_named_in_with_warmup(
    root: &Path,
    bytes: &[u8],
    name: &str,
    warm: impl Fn(&Path) -> io::Result<()>,
) -> io::Result<PathBuf> {
    validate_name(name)?;
    publish_with_pruner_and_warmup(root, bytes, name, image_cache::prune, warm)
}

fn validate_name(name: &str) -> io::Result<()> {
    if Path::new(name).file_name().and_then(|value| value.to_str()) != Some(name) {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "cached executable name must be one path component",
        ));
    }
    Ok(())
}

fn publish_executable(root: &Path, bytes: &[u8], name: &str) -> io::Result<PathBuf> {
    publish_with_pruner(root, bytes, name, image_cache::prune)
}

pub fn publish_with_pruner(
    root: &Path,
    bytes: &[u8],
    name: &str,
    prune: impl Fn(&Path, &Path, std::time::SystemTime) -> io::Result<()>,
) -> io::Result<PathBuf> {
    publish_with_pruner_and_warmup(root, bytes, name, prune, |_| Ok(()))
}

fn publish_with_pruner_and_warmup(
    root: &Path,
    bytes: &[u8],
    name: &str,
    prune: impl Fn(&Path, &Path, std::time::SystemTime) -> io::Result<()>,
    warm: impl Fn(&Path) -> io::Result<()>,
) -> io::Result<PathBuf> {
    fs::create_dir_all(root)?;
    let lock = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(root.join("publish.lock"))?;
    lock.lock()?;
    let path = cache_path(root, bytes, name);
    let directory = path.parent().expect("cache path has a parent");
    if path.exists() {
        verify_cached(&path, bytes)?;
        image_cache::refresh(directory)?;
        return Ok(path);
    }

    let cache_root = root;
    fs::create_dir_all(path.parent().expect("cache path has a parent"))?;
    let pending_dir = tempfile::Builder::new()
        .prefix(".pending-")
        .tempdir_in(cache_root)?;
    let pending = pending_dir.path().join("executable");
    write_executable_with_mode(&pending, bytes, 0o755)?;
    #[cfg(target_os = "linux")]
    aft_store::sync::sync_all(&OpenOptions::new().read(true).open(&pending)?, &pending)?;
    // Windows requires a writable handle for FlushFileBuffers.
    #[cfg(not(target_os = "linux"))]
    aft_store::sync::sync_all(&OpenOptions::new().write(true).open(&pending)?, &pending)?;

    match fs::hard_link(&pending, &path) {
        Ok(()) => {}
        Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
        Err(error) => return Err(error),
    }
    verify_cached(&path, bytes)?;
    if let Err(error) = warm(&path) {
        fs::remove_file(&path)?;
        return Err(error);
    }
    image_cache::refresh(directory)?;
    prune(root, directory, std::time::SystemTime::now())?;
    Ok(path)
}

/// Make a named fixture resolve to an already cached executable without copying it.
pub fn link_cached_path(source: &Path, destination: &Path) -> io::Result<PathBuf> {
    if let Some(parent) = destination.parent() {
        fs::create_dir_all(parent)?;
    }
    #[cfg(unix)]
    std::os::unix::fs::symlink(source, destination)?;
    #[cfg(windows)]
    fs::hard_link(source, destination)?;
    Ok(destination.to_path_buf())
}

/// Make a named fixture resolve to the shared executable without copying it.
pub fn link_cached_executable(destination: &Path, bytes: &[u8]) -> io::Result<PathBuf> {
    link_cached_executable_with(destination, bytes, cached_executable, link_cached_path)
}

pub fn link_cached_executable_with(
    destination: &Path,
    bytes: &[u8],
    mut lookup: impl FnMut(&[u8]) -> io::Result<PathBuf>,
    mut link: impl FnMut(&Path, &Path) -> io::Result<PathBuf>,
) -> io::Result<PathBuf> {
    for attempt in 0..2 {
        let cached = lookup(bytes)?;
        let result = link(&cached, destination).and_then(|path| {
            // Unix symlink creation succeeds even when its target vanished.
            fs::metadata(&cached)?;
            Ok(path)
        });
        match result {
            Err(error) if error.kind() == io::ErrorKind::NotFound && attempt == 0 => {
                let _ = fs::remove_file(destination);
            }
            result => return result,
        }
    }
    unreachable!()
}

/// Executing an executable while any process still has it open for writing can fail
/// with `ETXTBSY` (text file busy) on Linux. A short-lived writer process keeps test-thread forks
/// from inheriting the staged file's write descriptor before it is renamed.
pub fn write_executable(path: &Path, bytes: &[u8]) -> io::Result<()> {
    write_executable_with_mode(path, bytes, 0o755)
}

/// Publish a staged executable with the requested Unix permission bits.
pub fn write_executable_with_mode(path: &Path, bytes: &[u8], mode: u32) -> io::Result<()> {
    let parent = path
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."));
    fs::create_dir_all(parent)?;

    static NEXT_TEMPORARY_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let file_name = path.file_name().unwrap_or_default().to_string_lossy();
    let (temporary_path, file) = loop {
        let temporary_path = parent.join(format!(
            ".{file_name}.tmp.{}.{}",
            std::process::id(),
            NEXT_TEMPORARY_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
        ));
        match OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&temporary_path)
        {
            Ok(file) => break (temporary_path, file),
            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
            Err(error) => return Err(error),
        }
    };
    drop(file);

    let write_result = write_staged_bytes(&temporary_path, bytes);
    if let Err(error) = write_result {
        let _ = fs::remove_file(&temporary_path);
        return Err(error);
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if let Err(error) = fs::set_permissions(&temporary_path, fs::Permissions::from_mode(mode)) {
            let _ = fs::remove_file(&temporary_path);
            return Err(error);
        }
    }
    #[cfg(not(unix))]
    let _ = mode;
    if let Err(error) = fs::rename(&temporary_path, path) {
        let _ = fs::remove_file(&temporary_path);
        return Err(error);
    }
    Ok(())
}

#[cfg(unix)]
fn write_staged_bytes(path: &Path, bytes: &[u8]) -> io::Result<()> {
    use std::process::{Command, Stdio};

    let mut writer = Command::new("/bin/sh")
        .args(["-c", "/bin/cat > \"$1\"", "aft-test-executable-writer"])
        .arg(path)
        .stdin(Stdio::piped())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let write_result = writer
        .stdin
        .take()
        .ok_or_else(|| io::Error::other("test executable writer has no stdin"))
        .and_then(|mut stdin| stdin.write_all(bytes));
    let status = writer.wait()?;
    write_result?;
    if !status.success() {
        return Err(io::Error::other("test executable writer process failed"));
    }
    Ok(())
}

#[cfg(not(unix))]
fn write_staged_bytes(path: &Path, bytes: &[u8]) -> io::Result<()> {
    OpenOptions::new()
        .write(true)
        .truncate(true)
        .open(path)?
        .write_all(bytes)
}

fn verify_cached(path: &Path, bytes: &[u8]) -> io::Result<()> {
    let metadata = fs::metadata(path)?;
    if !metadata.is_file() || fs::read(path)? != bytes {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            format!(
                "content-addressed test executable is invalid: {}",
                path.display()
            ),
        ));
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if metadata.permissions().mode() & 0o777 != 0o755 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "cached test executable is not mode 0755: {}",
                    path.display()
                ),
            ));
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::{Duration, SystemTime};

    #[test]
    fn executable_cache_refreshes_hits_and_prunes_on_publication() {
        let root = tempfile::tempdir().unwrap();
        let bytes = b"#!/bin/sh\nexit 0\n";
        let mut usage = image_cache::Usage::default();
        usage.live_pids = Some([std::process::id()].into());
        let publish = |bytes: &[u8]| {
            publish_with_pruner(root.path(), bytes, "executable", |root, current, now| {
                image_cache::prune_with_usage(root, current, now, false, &usage)
            })
        };
        let old = publish(bytes).unwrap();
        let stale_time = SystemTime::now() - Duration::from_secs(25 * 60 * 60);
        let stale = filetime::FileTime::from_system_time(stale_time);
        filetime::set_file_mtime(old.parent().unwrap(), stale).unwrap();
        assert_eq!(publish(bytes).unwrap(), old);
        assert!(
            fs::metadata(old.parent().unwrap())
                .unwrap()
                .modified()
                .unwrap()
                > stale_time
        );
        let abandoned = root.path().join("f".repeat(64));
        fs::create_dir(&abandoned).unwrap();
        filetime::set_file_mtime(&abandoned, stale).unwrap();
        publish(b"another image").unwrap();
        assert!(old.exists());
        assert!(!abandoned.exists());
    }

    #[test]
    fn executable_cache_republishes_when_entry_disappears_before_linking() {
        let root = tempfile::tempdir().unwrap();
        let destination = root.path().join("fixture");
        let cache = root.path().join("cache");
        let mut links = 0;
        let path = link_cached_executable_with(
            &destination,
            b"#!/bin/sh\nexit 0\n",
            |bytes| cached_executable_named_in(&cache, bytes, "executable"),
            |source, destination| {
                links += 1;
                if links == 1 {
                    fs::remove_dir_all(source.parent().unwrap())?;
                }
                link_cached_path(source, destination)
            },
        )
        .unwrap();
        assert_eq!(links, 2);
        assert_eq!(fs::read(&path).unwrap(), b"#!/bin/sh\nexit 0\n");
        #[cfg(unix)]
        assert!(std::process::Command::new(path).status().unwrap().success());
    }

    #[test]
    fn executable_cache_warms_once_at_final_owner_writable_path() {
        let root = tempfile::tempdir().unwrap();
        let warmed = std::cell::RefCell::new(Vec::new());
        let bytes = b"private shim image bytes";
        let daemon = root.path().join("daemon-image");
        fs::write(&daemon, bytes).unwrap();
        let image = cached_executable_named_in_with_warmup(root.path(), bytes, "aft", |path| {
            assert_eq!(fs::read(path).unwrap(), bytes);
            assert_eq!(path.file_name().unwrap(), "aft");
            assert_eq!(path.parent().unwrap().parent().unwrap(), root.path());
            assert!(!fs::metadata(path).unwrap().permissions().readonly());
            OpenOptions::new().write(true).open(path).unwrap();
            #[cfg(unix)]
            {
                use std::os::unix::fs::MetadataExt;
                assert_ne!(
                    fs::metadata(path).unwrap().ino(),
                    fs::metadata(&daemon).unwrap().ino(),
                    "a sandbox write regression must not corrupt the daemon image"
                );
            }
            warmed.borrow_mut().push(path.to_path_buf());
            Ok(())
        })
        .unwrap();
        assert_eq!(*warmed.borrow(), vec![image.clone()]);
        let cached = cached_executable_named_in_with_warmup(root.path(), bytes, "aft", |_| {
            panic!("a cached executable must not be warmed again")
        })
        .unwrap();
        assert_eq!(cached, image);
    }

    #[test]
    fn executable_cache_failed_warmup_is_not_reused() {
        let root = tempfile::tempdir().unwrap();
        let bytes = b"private shim image bytes";
        let path = cache_path(root.path(), bytes, "aft");
        let attempts = std::cell::Cell::new(0);
        let error = cached_executable_named_in_with_warmup(root.path(), bytes, "aft", |_| {
            attempts.set(attempts.get() + 1);
            Err(io::Error::new(
                io::ErrorKind::NotFound,
                "injected warmup failure",
            ))
        })
        .unwrap_err();
        assert_eq!(error.to_string(), "injected warmup failure");
        assert_eq!(attempts.get(), 1, "warmup errors must not be retried");
        assert!(!path.exists(), "a failed warmup must not be cached");
        let warmed = std::cell::Cell::new(false);
        let retry = cached_executable_named_in_with_warmup(root.path(), bytes, "aft", |_| {
            warmed.set(true);
            Ok(())
        })
        .unwrap();
        assert_eq!(retry, path);
        assert!(warmed.get(), "the republished image must finish warmup");
    }
}