Skip to content

Commit 025cd51

Browse files
agorischekCopilot
andauthored
Extractions get a temporary directory the runner removes; Go builds in it, and a full disk says so (#334)
* Extractions get a temporary directory the runner removes, Go builds in it, and a full disk says so Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> * Plainer wording Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> * Changelog fragment for #334 Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> * Temporary directories: own entries only, owner-only permission recovery, SDK forwards TMPDIR, disk advice in reports Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --------- Co-authored-by: agorischek <6295280+agorischek@users.noreply.github.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
1 parent f87c196 commit 025cd51

12 files changed

Lines changed: 426 additions & 18 deletions

File tree

‎changelog.d/334.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
section: fixes
3+
---
4+
5+
- **A timed-out or cancelled extraction no longer leaves temporary files behind** (#334). Each extractor run gets a private temporary directory (`TMPDIR`, `TMP`, and `TEMP`) that the runner removes when the extractor finishes or is killed. If the runner itself is killed, the next run cleans up its leftover directories. `go-public-api` used to leave a `/tmp/go-build*` directory after every timeout, enough to fill a disk over a sweep; Go now builds in a private `GOTMPDIR` inside that directory, and the Rust extractor SDK passes `TMPDIR`, `TMP` and `TEMP` on to the tools an extractor runs.
6+
- **Full-disk errors now report free space** (#334). An extractor that fails with "no space left on device" now says the disk is full and reports how much space is free where its temporary files go. When there isn't enough space for a second copy of the repository, the automatic workspace strategy now reports the free space and how much a copy needs, rather than only saying there is too little free disk space.

‎docs/builtins/extractors/go-public-api.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,9 @@ the repository root), loading them the same way the Go toolchain does:
5454
`HOME`. In offline environments, module dependencies must already be cached or
5555
vendored. When `go.mod` needs a newer Go than the one on `PATH`, the error
5656
names the version: install it, or set `GOTOOLCHAIN=auto` and grant
57-
`GOTOOLCHAIN` so Go may switch to it.
57+
`GOTOOLCHAIN` so Go may switch to it. Go's temporary build directories
58+
(`go-build*`) go in a private `GOTMPDIR` that is removed when the extraction
59+
ends, even on timeout.
5860

5961
Each importable package becomes a `package` entity, and each exported symbol
6062
becomes a `constant`, `variable`, `function`, or `type`, with `method` entities

‎docs/contracts/extractors.md‎

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -123,14 +123,23 @@ which was the only option before nested projects).
123123

124124
The runner gives the extractor process a minimal, explicit environment:
125125

126-
| Variable | Value |
127-
| ------------------------------------ | ------------------------------------------------------------ |
128-
| `LANG`, `LC_ALL` | `C.UTF-8` |
129-
| `TZ` | `UTC` |
130-
| `PATH`, `SystemRoot` (Windows) | The runner's own |
131-
| Each name in `execution.environment` | The runner's own, when set |
132-
| `PYTHONPATH` (custom extractors) | See below |
133-
| `GIT_EXEC_PATH`, `GIT_TEMPLATE_DIR` | The runner's own, only for a built-in that reads Git objects |
126+
| Variable | Value |
127+
| ------------------------------------ | -------------------------------------------------------------- |
128+
| `LANG`, `LC_ALL` | `C.UTF-8` |
129+
| `TZ` | `UTC` |
130+
| `PATH`, `SystemRoot` (Windows) | The runner's own |
131+
| Each name in `execution.environment` | The runner's own, when set |
132+
| `PYTHONPATH` (custom extractors) | See below |
133+
| `GIT_EXEC_PATH`, `GIT_TEMPLATE_DIR` | The runner's own, only for a built-in that reads Git objects |
134+
| `TMPDIR`, `TMP`, `TEMP` | A private directory the runner removes when the extractor ends |
135+
136+
Each extractor run gets a new temporary directory inside the one granted by
137+
`execution.environment`, or the system temp directory if none is granted. The
138+
runner removes it when the extractor finishes or is killed (including on timeout
139+
or cancellation), so interrupted build tools leave nothing behind. If the runner
140+
itself is killed, the next run removes the directory. Containerized runs keep
141+
the container's `/tmp`. The Rust extractor SDK passes `TMPDIR`, `TMP` and `TEMP`
142+
on to every tool an extractor runs, so a built-in's tools use the directory too.
134143

135144
Nothing else is inherited—no `HOME`, tokens, proxies, or loader hooks unless the
136145
definition explicitly lists them (aside from the runner's own preload for

‎docs/reference/extractor-sdk.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -479,7 +479,7 @@ same whoever starts it.
479479
| `diagnostics` | `pub fn diagnostics(&self) -> String` | The diagnostics recorded so far, bounded. |
480480
| `directory` | `pub fn directory(&self) -> Option<&Path>` | The project's directory, or `None` when the revision is read from Git objects. |
481481
| `entry` | `pub fn entry(&self, relative: &str) -> Result<FileEntry>` | One of the revision's files: whether it is a symlink, and its size. |
482-
| `environment` | `pub fn environment(&self, names: &[String]) -> BTreeMap<String, String>` | The base tool environment (a UTF-8 locale, UTC, `PATH` and `SystemRoot`) plus each of `names` this process received. |
482+
| `environment` | `pub fn environment(&self, names: &[String]) -> BTreeMap<String, String>` | The base tool environment (a UTF-8 locale, UTC, `PATH`, `SystemRoot`, and the temporary directory the runner gives the extractor in `TMPDIR`, `TMP` and `TEMP`) plus each of `names` this process received. |
483483
| `exists` | `pub fn exists(&self, relative: &str) -> Result<bool>` | Whether `relative` is a file or directory of the examined revision: one of its files, or a directory some file is inside. A path Git ignores in a checkout isn't part of the revision. |
484484
| `extractor` | `pub fn extractor(&self) -> &str` | The name of the extractor this process runs. |
485485
| `files` | `pub fn files(&self) -> Result<&[String]>` | The project's files, as project-relative POSIX paths in byte order: everything materialized under it, what Git lists in a checkout (tracked and untracked, not ignored), or the Git tree's blobs; only those in the scope when one is declared. Files outside the project aren't listed, but a scope that includes them lets them be read with `..` paths. |

‎packages/cli/src/runtime/extract.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -279,9 +279,13 @@ impl Runner {
279279
None => argv,
280280
};
281281
let directory = crate::project::directory(program);
282+
let parent = super::temporary::parent(&environment);
283+
// Removed once the extractor has ended, however it ended.
284+
let _temporary = super::temporary::Temporary::within(&parent, &mut environment);
282285
self.run_argv(argv, &directory, Some(&serde_json::to_string(&request)?), timeout, &environment)
283286
.map_err(timeout_advice)
284-
.map_err(|error| start_advice(definition, error))?
287+
.map_err(|error| start_advice(definition, error))
288+
.map_err(|error| super::temporary::disk_advice(error, &parent))?
285289
};
286290
self.record_output(
287291
self.current.lock().expect("revision lock")["ref"].as_str().unwrap_or(""),

‎packages/cli/src/runtime/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ mod placement;
1818
mod portable;
1919
mod process;
2020
mod revision;
21+
mod temporary;
2122
mod upstream;
2223

2324
pub use batch::{DefinitionChoice, batch_document};
Lines changed: 256 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,256 @@
1+
//! Per-extraction temporary directory owned by the runner. The extractor and
2+
//! any tools it spawns receive it via `TMPDIR`, `TMP`, and `TEMP`. The runner
3+
//! removes it when the extractor finishes or is killed (including on timeout or
4+
//! cancellation). If the runner itself is killed, the next run removes its
5+
//! leftover directories.
6+
7+
use std::{
8+
collections::BTreeMap,
9+
fs,
10+
path::{Path, PathBuf},
11+
sync::atomic::{AtomicU64, Ordering},
12+
};
13+
14+
/// Names start with this, then the runner's process ID.
15+
const PREFIX: &str = "projections-extraction-";
16+
17+
/// The variables that name the temporary directory, on any platform.
18+
const VARIABLES: [&str; 3] = ["TMPDIR", "TMP", "TEMP"];
19+
20+
pub(super) struct Temporary(PathBuf);
21+
22+
impl Temporary {
23+
/// Creates a new private directory in `parent` after cleaning up
24+
/// directories left by dead runners. Returns `None` if creation fails,
25+
/// letting the extractor run without one as before.
26+
pub(super) fn new(parent: &Path) -> Option<Self> {
27+
static NEXT: AtomicU64 = AtomicU64::new(0);
28+
sweep(parent);
29+
let process = std::process::id();
30+
(0..100).find_map(|_| {
31+
let directory = parent.join(format!("{PREFIX}{process}-{}", NEXT.fetch_add(1, Ordering::SeqCst)));
32+
private(&directory).ok().map(|()| Self(directory))
33+
})
34+
}
35+
36+
/// Creates a new directory in `parent` and points `environment`'s
37+
/// temporary directory variables at it.
38+
pub(super) fn within(parent: &Path, environment: &mut BTreeMap<String, String>) -> Option<Self> {
39+
let temporary = Self::new(parent)?;
40+
temporary.apply(environment);
41+
Some(temporary)
42+
}
43+
44+
/// Points the extractor's temporary directory variables at this directory.
45+
fn apply(&self, environment: &mut BTreeMap<String, String>) {
46+
for name in VARIABLES {
47+
environment.insert(name.into(), self.0.to_string_lossy().into_owned());
48+
}
49+
}
50+
}
51+
52+
/// Parent directory for an extractor's temporary directory: the one named in
53+
/// `environment` (if granted by the definition), or the system temp directory.
54+
pub(super) fn parent(environment: &BTreeMap<String, String>) -> PathBuf {
55+
VARIABLES
56+
.iter()
57+
.find_map(|name| environment.get(*name))
58+
.map_or_else(std::env::temp_dir, PathBuf::from)
59+
}
60+
61+
/// Adds to an out-of-space failure that the disk is full and how much space is
62+
/// free in `parent`, so a full disk isn't mistaken for a broken extractor. An
63+
/// extractor's failure keeps it in its own message, which reports show.
64+
pub(super) fn disk_advice(error: anyhow::Error, parent: &Path) -> anyhow::Error {
65+
let full = |said: &str| {
66+
let said = said.to_ascii_lowercase();
67+
["no space left on device", "not enough space on the disk"]
68+
.iter()
69+
.any(|words| said.contains(words))
70+
};
71+
let advice = || {
72+
let free = crate::workspaces::free_space(parent).map_or_else(|| "an unknown amount".to_owned(), crate::workspaces::gib);
73+
format!(
74+
"The disk is full: {free} is free in {}, where the extractor's temporary files go. Free some space and run it again",
75+
parent.display()
76+
)
77+
};
78+
match error.downcast::<super::ProcessFailure>() {
79+
Ok(mut failure) => {
80+
if full(&format!("{} {}", failure.message, failure.stderr())) {
81+
failure.message.push_str(&format!(". {}", advice()));
82+
}
83+
failure.into()
84+
}
85+
Err(error) if full(&format!("{error:#}")) => error.context(advice()),
86+
Err(error) => error,
87+
}
88+
}
89+
90+
impl Drop for Temporary {
91+
fn drop(&mut self) {
92+
remove(&self.0);
93+
}
94+
}
95+
96+
#[cfg(unix)]
97+
fn private(directory: &Path) -> std::io::Result<()> {
98+
use std::os::unix::fs::DirBuilderExt;
99+
fs::DirBuilder::new().mode(0o700).create(directory)
100+
}
101+
102+
#[cfg(not(unix))]
103+
fn private(directory: &Path) -> std::io::Result<()> {
104+
fs::create_dir(directory)
105+
}
106+
107+
/// Removes `directory`. If that fails, it gives its owner (this process's
108+
/// user) access to every directory inside, which Go's read-only module cache
109+
/// takes away, and tries again. Links are never followed.
110+
fn remove(directory: &Path) {
111+
if fs::remove_dir_all(directory).is_ok() || fs::symlink_metadata(directory).is_err() {
112+
return;
113+
}
114+
accessible(directory);
115+
let _ = fs::remove_dir_all(directory);
116+
}
117+
118+
#[cfg(unix)]
119+
fn accessible(directory: &Path) {
120+
use std::os::unix::fs::PermissionsExt;
121+
let Ok(metadata) = fs::symlink_metadata(directory) else { return };
122+
if !metadata.is_dir() {
123+
return;
124+
}
125+
let mode = metadata.permissions().mode();
126+
let _ = fs::set_permissions(directory, fs::Permissions::from_mode(mode | 0o700));
127+
for entry in fs::read_dir(directory).into_iter().flatten().flatten() {
128+
accessible(&entry.path());
129+
}
130+
}
131+
132+
/// Elsewhere a read-only attribute on files is what stops removal.
133+
#[cfg(not(unix))]
134+
fn accessible(path: &Path) {
135+
let Ok(metadata) = fs::symlink_metadata(path) else { return };
136+
if metadata.file_type().is_symlink() {
137+
return;
138+
}
139+
let mut permissions = metadata.permissions();
140+
#[allow(clippy::permissions_set_readonly_false)]
141+
permissions.set_readonly(false);
142+
let _ = fs::set_permissions(path, permissions);
143+
if metadata.is_dir() {
144+
for entry in fs::read_dir(path).into_iter().flatten().flatten() {
145+
accessible(&entry.path());
146+
}
147+
}
148+
}
149+
150+
/// Removes directories in `parent` left by runner processes that have exited.
151+
fn sweep(parent: &Path) {
152+
let own = std::process::id();
153+
for entry in fs::read_dir(parent).into_iter().flatten().flatten() {
154+
let name = entry.file_name();
155+
let Some(process) = name
156+
.to_str()
157+
.and_then(|name| name.strip_prefix(PREFIX))
158+
.and_then(|rest| rest.split_once('-'))
159+
.and_then(|(process, _)| process.parse::<u32>().ok())
160+
else {
161+
continue;
162+
};
163+
if process != own && mine(&entry.path()) && !running(process, &entry.path()) {
164+
remove(&entry.path());
165+
}
166+
}
167+
}
168+
169+
/// Whether `path` is a directory, not a link, that this process's user owns:
170+
/// another user's entry in a shared temporary directory is never touched.
171+
#[cfg(unix)]
172+
fn mine(path: &Path) -> bool {
173+
use std::os::unix::fs::MetadataExt;
174+
fs::symlink_metadata(path).is_ok_and(|metadata| metadata.is_dir() && metadata.uid() == unsafe { libc::geteuid() })
175+
}
176+
177+
#[cfg(not(unix))]
178+
fn mine(path: &Path) -> bool {
179+
fs::symlink_metadata(path).is_ok_and(|metadata| metadata.is_dir())
180+
}
181+
182+
/// Whether the runner with process ID `process` may still be using `directory`.
183+
#[cfg(unix)]
184+
fn running(process: u32, _directory: &Path) -> bool {
185+
let Ok(process) = i32::try_from(process) else { return false };
186+
// Signal 0 only checks: EPERM means it runs as another user.
187+
unsafe { libc::kill(process, 0) == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM) }
188+
}
189+
190+
/// Without a cheap liveness check, treat a directory untouched for a day as abandoned.
191+
#[cfg(not(unix))]
192+
fn running(_process: u32, directory: &Path) -> bool {
193+
fs::metadata(directory)
194+
.and_then(|metadata| metadata.modified())
195+
.ok()
196+
.and_then(|modified| modified.elapsed().ok())
197+
.is_none_or(|age| age < std::time::Duration::from_secs(24 * 60 * 60))
198+
}
199+
200+
#[cfg(test)]
201+
mod tests {
202+
use super::*;
203+
204+
#[test]
205+
fn the_directory_is_private_named_in_the_environment_and_removed() {
206+
let parent = tempfile::tempdir().unwrap();
207+
let temporary = Temporary::new(parent.path()).unwrap();
208+
let directory = temporary.0.clone();
209+
assert!(directory.is_dir());
210+
#[cfg(unix)]
211+
{
212+
use std::os::unix::fs::PermissionsExt;
213+
assert_eq!(fs::metadata(&directory).unwrap().permissions().mode() & 0o777, 0o700);
214+
}
215+
let mut environment = BTreeMap::new();
216+
temporary.apply(&mut environment);
217+
assert_eq!(environment["TMPDIR"], directory.to_string_lossy());
218+
assert_eq!(environment["TEMP"], environment["TMP"]);
219+
// What a killed tool leaves, read-only parts included.
220+
let left = directory.join("go-build123/b001");
221+
fs::create_dir_all(&left).unwrap();
222+
fs::write(left.join("a.out"), "binary").unwrap();
223+
let mut permissions = fs::metadata(&left).unwrap().permissions();
224+
permissions.set_readonly(true);
225+
fs::set_permissions(&left, permissions).unwrap();
226+
drop(temporary);
227+
assert!(!directory.exists());
228+
}
229+
230+
#[cfg(unix)]
231+
#[test]
232+
fn directories_of_runners_no_longer_running_are_removed() {
233+
let parent = tempfile::tempdir().unwrap();
234+
// A process that has exited, so its ID names no running process (for now).
235+
let mut child = std::process::Command::new("true").spawn().unwrap();
236+
let gone = child.id();
237+
child.wait().unwrap();
238+
let abandoned = parent.path().join(format!("{PREFIX}{gone}-0"));
239+
let live = parent.path().join(format!("{PREFIX}1-0"));
240+
let unrelated = parent.path().join("go-build42");
241+
for directory in [&abandoned, &live, &unrelated] {
242+
fs::create_dir(directory).unwrap();
243+
}
244+
// A link with the name is never followed.
245+
let elsewhere = tempfile::tempdir().unwrap();
246+
fs::write(elsewhere.path().join("kept"), "").unwrap();
247+
let link = parent.path().join(format!("{PREFIX}{gone}-1"));
248+
std::os::unix::fs::symlink(elsewhere.path(), &link).unwrap();
249+
let temporary = Temporary::new(parent.path()).unwrap();
250+
assert!(!abandoned.exists());
251+
assert!(live.exists(), "process 1 is always running");
252+
assert!(unrelated.exists());
253+
assert!(temporary.0.exists());
254+
assert!(elsewhere.path().join("kept").exists());
255+
}
256+
}

‎packages/cli/src/workspaces/mod.rs‎

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -196,16 +196,36 @@ pub fn automatic(runner: &Runner) -> Result<Choice> {
196196
_ if clones(&root) => Ok(Choice {
197197
strategy: Strategy::Clone,
198198
source: "automatic",
199-
reason: format!("{size}, with little free disk space; the filesystem clones copy-on-write"),
199+
reason: format!("{size}, {}; the filesystem clones copy-on-write", room(free, bytes, &base)),
200200
}),
201201
_ => Ok(Choice {
202202
strategy: Strategy::None,
203203
source: "automatic",
204-
reason: format!("{size}, with too little free disk space for a second copy"),
204+
reason: format!("{size}, {}", room(free, bytes, &base)),
205205
}),
206206
}
207207
}
208208

209+
/// Why `free` bytes on the disk holding `base` can't hold a second copy of
210+
/// `bytes` tracked: how much is free and how much a copy needs, so a full disk
211+
/// reads as one rather than as a repository too big to copy.
212+
fn room(free: Option<u64>, bytes: u64, base: &Path) -> String {
213+
match free {
214+
Some(free) => format!(
215+
"and only {} free on the disk holding {}, less than the {} a second copy needs (four times the tracked size)",
216+
gib(free),
217+
base.display(),
218+
gib(bytes.saturating_mul(4))
219+
),
220+
None => format!("and the free space on the disk holding {} can't be measured", base.display()),
221+
}
222+
}
223+
224+
/// `bytes` in GiB, to a tenth.
225+
pub fn gib(bytes: u64) -> String {
226+
format!("{:.1} GiB", bytes as f64 / 1_073_741_824.0)
227+
}
228+
209229
/// Free bytes on the filesystem holding `path`.
210230
#[cfg(unix)]
211231
pub fn free_space(path: &Path) -> Option<u64> {
@@ -264,3 +284,21 @@ pub fn directory(runner: &Runner) -> Result<PathBuf> {
264284
.join("workspaces")
265285
.join(crate::extraction_cache::repository_name(&runner.common_directory()?)))
266286
}
287+
288+
#[cfg(test)]
289+
mod tests {
290+
use super::*;
291+
292+
#[test]
293+
fn too_little_room_says_how_much_is_free_and_needed() {
294+
let base = Path::new("/home/dev/.cache/projections");
295+
assert_eq!(
296+
room(Some(200 * 1024 * 1024), 512 * 1024 * 1024, base),
297+
"and only 0.2 GiB free on the disk holding /home/dev/.cache/projections, less than the 2.0 GiB a second copy needs (four times the tracked size)"
298+
);
299+
assert_eq!(
300+
room(None, 1, base),
301+
"and the free space on the disk holding /home/dev/.cache/projections can't be measured"
302+
);
303+
}
304+
}

0 commit comments

Comments
 (0)