forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

tool_cache.rs326 lines, 10.1 KiBHistoryRawDownload
1//! Content-addressed cache of external-tool results, for test builds only.
2//!
3//! The gates shell out to ffmpeg (lavfi source generation, y4m and raw
4//! loaders), aomenc (encodes) and aomdec / ffmpeg (oracle decodes). Those
5//! results are deterministic functions of the program, its arguments, its
6//! explicit environment, its working directory, its stdin and the contents of
7//! every input file, so a second run can reuse them. The decoder under test is
8//! never routed through here: only the external tool's `Output` is cached.
9//!
10//! Shell scripts are never cached: they can read hidden inputs (the control
11//! tests' ffmpeg/aomdec shims read a sibling file), which no key can cover.
12//!
13//! A call is cached only when every path-like argument already names an
14//! existing file (its content is hashed into the key) or a `/dev/` node. Any
15//! other path-like argument is an output the tool would write, which cannot be
16//! snapshotted, so that call simply runs. Only successful runs are stored.
17//!
18//! Environment: `EC_TOOL_CACHE=0|off` disables the cache; `EC_TOOL_CACHE_DIR`
19//! overrides the directory (default `$HOME/.cache/ec-tool-cache`).
20
21use std::ffi::OsStr;
22use std::fs;
23use std::io::{self, Read};
24use std::os::unix::ffi::OsStrExt;
25use std::os::unix::process::ExitStatusExt;
26use std::path::{Path, PathBuf};
27use std::process::{Command, ExitStatus, Output};
28use std::time::{SystemTime, UNIX_EPOCH};
29
30/// Outputs larger than this are run every time instead of stored.
31const CAP_BYTES: u64 = 256 << 20;
32const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
33const BASIS_A: u64 = 0xcbf2_9ce4_8422_2325;
34const BASIS_B: u64 = 0x8422_2325_cbf2_9ce4;
35
36/// Two independent 64-bit FNV-1a passes, giving a 128-bit key without deps.
37struct Hash {
38 a: u64,
39 b: u64,
40}
41
42impl Hash {
43 fn new() -> Self {
44 Hash {
45 a: BASIS_A,
46 b: BASIS_B,
47 }
48 }
49
50 fn bytes(&mut self, data: &[u8]) {
51 for &x in data {
52 self.a = (self.a ^ u64::from(x)).wrapping_mul(FNV_PRIME);
53 self.b = (self.b ^ u64::from(x)).wrapping_mul(FNV_PRIME);
54 }
55 }
56
57 /// A length-prefixed field, so adjacent fields cannot run together.
58 fn part(&mut self, data: &[u8]) {
59 self.bytes(&u64::try_from(data.len()).unwrap_or(u64::MAX).to_le_bytes());
60 self.bytes(data);
61 }
62
63 fn hex(&self) -> String {
64 format!("{:016x}{:016x}", self.a, self.b)
65 }
66}
67
68/// The cache directory, or `None` when the cache is disabled.
69fn env_dir() -> Option<PathBuf> {
70 if matches!(
71 std::env::var("EC_TOOL_CACHE").as_deref(),
72 Ok("0" | "off")
73 ) {
74 return None;
75 }
76 if let Some(d) = std::env::var_os("EC_TOOL_CACHE_DIR") {
77 return Some(PathBuf::from(d));
78 }
79 Some(PathBuf::from(std::env::var_os("HOME")?).join(".cache/ec-tool-cache"))
80}
81
82/// Runs `cmd` through the cache (or straight through when disabled). `run`
83/// performs the real spawn; it is called at most once.
84///
85/// # Panics
86/// Never from the cache itself; `run` is infallible here, so the internal
87/// `io::Result` is always `Ok`.
88pub(crate) fn cached_output(
89 cmd: &mut Command,
90 stdin: Option<&[u8]>,
91 run: impl FnOnce(&mut Command) -> Output,
92) -> Output {
93 match cached_output_io(cmd, stdin, |c| Ok(run(c))) {
94 Ok(out) => out,
95 Err(e) => panic!("tool cache: infallible run failed: {e}"),
96 }
97}
98
99/// [`cached_output`] for callers that handle the `io::Result` of `.output()`.
100pub(crate) fn cached_output_io(
101 cmd: &mut Command,
102 stdin: Option<&[u8]>,
103 run: impl FnOnce(&mut Command) -> io::Result<Output>,
104) -> io::Result<Output> {
105 match env_dir() {
106 None => run(cmd),
107 Some(dir) => cached_output_in(&dir, cmd, stdin, run),
108 }
109}
110
111fn cached_output_in(
112 dir: &Path,
113 cmd: &mut Command,
114 stdin: Option<&[u8]>,
115 run: impl FnOnce(&mut Command) -> io::Result<Output>,
116) -> io::Result<Output> {
117 let Some(key) = build_key(cmd, stdin) else {
118 return run(cmd);
119 };
120 if let Some(hit) = load(dir, &key) {
121 return Ok(hit);
122 }
123 let out = run(cmd)?;
124 let size = u64::try_from(out.stdout.len()).unwrap_or(u64::MAX)
125 + u64::try_from(out.stderr.len()).unwrap_or(u64::MAX);
126 if out.status.success() && size <= CAP_BYTES {
127 // A failed store only costs the next run its cache hit.
128 let _ = store(dir, &key, &out);
129 }
130 Ok(out)
131}
132
133/// Resolves `prog` to a canonical path, searching PATH for bare names.
134fn resolve_program(prog: &OsStr) -> Option<PathBuf> {
135 let p = Path::new(prog);
136 let found = if p.components().count() > 1 {
137 p.to_path_buf()
138 } else {
139 let path = std::env::var_os("PATH")?;
140 std::env::split_paths(&path)
141 .map(|d| d.join(prog))
142 .find(|c| c.is_file())?
143 };
144 fs::canonicalize(found).ok()
145}
146
147/// A path-like argument: contains '/' and is not a `key:value` filter or a
148/// string with spaces. Those are the arguments that could name an output.
149fn path_like(c: &[u8]) -> bool {
150 c.contains(&b'/') && !c.contains(&b':') && !c.contains(&b' ')
151}
152
153/// The argument itself and, for `--opt=path` / `key=path`, the part after the
154/// first '='.
155fn candidates(arg: &[u8]) -> [&[u8]; 2] {
156 let after = arg
157 .iter()
158 .position(|&b| b == b'=')
159 .map_or(&arg[0..0], |i| &arg[i + 1..]);
160 [arg, after]
161}
162
163fn hash_file(h: &mut Hash, path: &Path) -> io::Result<()> {
164 let mut f = fs::File::open(path)?;
165 let len = f.metadata()?.len();
166 h.bytes(b"file");
167 h.bytes(&len.to_le_bytes());
168 let mut buf = vec![0u8; 1 << 16];
169 loop {
170 let n = f.read(&mut buf)?;
171 if n == 0 {
172 break;
173 }
174 h.bytes(&buf[..n]);
175 }
176 Ok(())
177}
178
179/// The key for this call, or `None` when the call must not be cached.
180fn build_key(cmd: &Command, stdin: Option<&[u8]>) -> Option<String> {
181 let prog = resolve_program(cmd.get_program())?;
182 let meta = fs::metadata(&prog).ok()?;
183 // A script can read state the key cannot see (the test shims read a
184 // sibling `offsets` file), so only real binaries are cached.
185 let mut magic = [0u8; 2];
186 if fs::File::open(&prog).ok()?.read(&mut magic).ok()? == 2 && &magic == b"#!" {
187 return None;
188 }
189 let mtime = meta
190 .modified()
191 .ok()?
192 .duration_since(UNIX_EPOCH)
193 .ok()?
194 .as_nanos();
195
196 let mut h = Hash::new();
197 h.part(b"ec-tool-cache/v1");
198 h.part(prog.as_os_str().as_bytes());
199 h.bytes(&meta.len().to_le_bytes());
200 h.bytes(&mtime.to_le_bytes());
201
202 let args: Vec<&OsStr> = cmd.get_args().collect();
203 h.part(&u64::try_from(args.len()).ok()?.to_le_bytes());
204 for arg in &args {
205 h.part(arg.as_bytes());
206 }
207
208 // Relative paths resolve against the process cwd unless the command sets
209 // its own, so both are part of the identity.
210 h.part(std::env::current_dir().ok()?.as_os_str().as_bytes());
211 match cmd.get_current_dir() {
212 Some(d) => {
213 h.bytes(b"\x01");
214 h.part(d.as_os_str().as_bytes());
215 }
216 None => h.bytes(b"\x00"),
217 }
218 for (k, v) in cmd.get_envs() {
219 h.part(k.as_bytes());
220 match v {
221 Some(v) => {
222 h.bytes(b"\x01");
223 h.part(v.as_bytes());
224 }
225 None => h.bytes(b"\x00"),
226 }
227 }
228
229 match stdin {
230 Some(data) => {
231 h.bytes(b"stdin\x01");
232 h.part(data);
233 }
234 None => h.bytes(b"stdin\x00"),
235 }
236
237 for arg in &args {
238 for cand in candidates(arg.as_bytes()) {
239 if cand.is_empty() {
240 continue;
241 }
242 let os = OsStr::from_bytes(cand);
243 let path = Path::new(os);
244 if path.is_file() {
245 hash_file(&mut h, path).ok()?;
246 } else if path_like(cand) && !path.exists() && !cand.starts_with(b"/dev/") {
247 return None;
248 }
249 }
250 }
251 Some(h.hex())
252}
253
254fn load(dir: &Path, key: &str) -> Option<Output> {
255 let code = fs::read_to_string(dir.join(format!("{key}.code"))).ok()?;
256 if code.trim() != "0" {
257 return None;
258 }
259 Some(Output {
260 status: ExitStatus::from_raw(0),
261 stdout: fs::read(dir.join(format!("{key}.out"))).ok()?,
262 stderr: fs::read(dir.join(format!("{key}.err"))).ok()?,
263 })
264}
265
266fn store(dir: &Path, key: &str, out: &Output) -> io::Result<()> {
267 fs::create_dir_all(dir)?;
268 let nanos = SystemTime::now()
269 .duration_since(UNIX_EPOCH)
270 .unwrap_or_default()
271 .as_nanos();
272 let nonce = format!("tmp.{}.{nanos}", std::process::id());
273 let files: [(&str, &[u8]); 3] = [
274 ("out", &out.stdout[..]),
275 ("err", &out.stderr[..]),
276 ("code", &b"0"[..]),
277 ];
278 for (ext, bytes) in files {
279 let tmp = dir.join(format!("{key}.{nonce}.{ext}"));
280 fs::write(&tmp, bytes)?;
281 fs::rename(&tmp, dir.join(format!("{key}.{ext}")))?;
282 }
283 Ok(())
284}
285
286#[cfg(test)]
287mod tests {
288 use super::*;
289 use std::cell::Cell;
290
291 #[test]
292 fn second_call_replays_and_uncacheable_calls_always_run() {
293 let nanos = SystemTime::now()
294 .duration_since(UNIX_EPOCH)
295 .unwrap_or_default()
296 .as_nanos();
297 let dir = std::env::temp_dir().join(format!(
298 "ec-tool-cache-test-{}-{nanos}",
299 std::process::id()
300 ));
301 let sh = || {
302 let mut c = Command::new("sh");
303 c.args(["-c", "echo $RANDOM$$"]);
304 c
305 };
306 let first = cached_output_in(&dir, &mut sh(), None, |c| c.output()).unwrap();
307 let second = cached_output_in(&dir, &mut sh(), None, |c| c.output()).unwrap();
308 assert_eq!(first.stdout, second.stdout);
309
310 // An output path that does not exist yet cannot be snapshotted, so
311 // both calls must reach the run closure.
312 let runs = Cell::new(0);
313 let missing = dir.join("no-such-dir/out.bin");
314 for _ in 0..2 {
315 let mut c = Command::new("sh");
316 c.args(["-c", "true"]).arg(&missing);
317 cached_output_in(&dir, &mut c, None, |c| {
318 runs.set(runs.get() + 1);
319 c.output()
320 })
321 .unwrap();
322 }
323 assert_eq!(runs.get(), 2);
324 let _ = fs::remove_dir_all(&dir);
325 }
326}