Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 32 additions & 9 deletions crates/factory-runner/src/checks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,26 @@ use std::process::Stdio;
use factory_core::Event;
use tokio::process::Command;

use crate::packages;
use crate::worker::{WORK_DIR, WorkerConfig};

const MAX_REPORT: usize = 30_000;
const MAX_PACKAGE_ERROR: usize = 4_000;
/// Exit codes podman uses for its own errors, as opposed to the command's.
const PODMAN_ERRORS: [i32; 3] = [125, 126, 127];

/// The arguments after `podman` to run `command` with bash in the job's
/// checkout. The container gets no Claude token and no GitHub credentials.
/// With `packages`, the command runs in a `nix shell` with them on `PATH`, and
/// bash is not a login shell, because the image's `/etc/profile` resets `PATH`
/// and would drop them.
#[must_use]
pub fn checks_args(
config: &WorkerConfig,
name: &str,
workspace: &Path,
command: &str,
packages: &[String],
) -> Vec<OsString> {
let mut volume = OsString::from(workspace.as_os_str());
volume.push(format!(":{WORK_DIR}"));
Expand All @@ -45,9 +51,15 @@ pub fn checks_args(
args.push("--volume".into());
args.push(volume.into());
}
for arg in [config.image.as_str(), "bash", "-lc", command] {
args.push(arg.into());
}
args.push(config.image.as_str().into());
let flag = if packages.is_empty() { "-lc" } else { "-c" };
args.extend(packages::wrap(
packages,
["bash", flag, command]
.into_iter()
.map(OsString::from)
.collect(),
));
args
}

Expand All @@ -63,9 +75,10 @@ pub async fn run_checks(
name: &str,
workspace: &Path,
command: &str,
packages: &[String],
) -> Result<Event, String> {
let output = Command::new(&config.podman)
.args(checks_args(config, name, workspace, command))
.args(checks_args(config, name, workspace, command, packages))
.stdin(Stdio::null())
.kill_on_drop(true)
.output()
Expand All @@ -76,6 +89,12 @@ pub async fn run_checks(
}
let mut text = String::from_utf8_lossy(&output.stdout).into_owned();
text.push_str(&String::from_utf8_lossy(&output.stderr));
if !packages.is_empty() && output.status.code() == Some(packages::FAILED_CODE) {
return Err(packages::failure(
packages,
&format!(": {}", tail(text.trim(), MAX_PACKAGE_ERROR)),
));
}
if output
.status
.code()
Expand All @@ -87,15 +106,19 @@ pub async fn run_checks(
text.trim()
));
}
let mut start = text.len().saturating_sub(MAX_REPORT);
while !text.is_char_boundary(start) {
start += 1;
}
Ok(Event::ChecksFailed {
report: format!(
"`{command}` failed ({}):\n\n{}",
output.status,
&text[start..]
tail(&text, MAX_REPORT)
),
})
}

fn tail(text: &str, max: usize) -> &str {
let mut start = text.len().saturating_sub(max);
while !text.is_char_boundary(start) {
start += 1;
}
&text[start..]
}
1 change: 1 addition & 0 deletions crates/factory-runner/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ mod github;
mod gitlab;
mod images;
mod outcome;
mod packages;
mod prompt;
mod stream;
mod worker;
Expand Down
51 changes: 51 additions & 0 deletions crates/factory-runner/src/packages.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
use std::ffi::OsString;

/// The exit code the wrapper uses when the packages cannot be built, so the
/// factory tells that apart from the wrapped command's own failure.
pub const FAILED_CODE: i32 = 86;

/// Takes the package count, then that many package names, and runs the rest
/// as the command. It builds the packages first so a failure is reported
/// before the command starts. The command writes a line to a deleted file
/// held open on a descriptor when it starts, which command cleanup of
/// temporary files cannot erase, so an exit before that is a setup failure and exits 86. A command
/// that exits 86 itself is reported as 1. The package names arrive as
/// arguments, never inside this text.
const SCRIPT: &str = r#"n=$1; shift
pkgs=()
for ((i = 0; i < n; i++)); do pkgs+=("nixpkgs#$1"); shift; done
nix build --no-link "${pkgs[@]}" >&2 || exit 86
f=$(mktemp) || exit 86
exec 9>"$f" 8<"$f" || exit 86
rm -f "$f" || exit 86
nix shell "${pkgs[@]}" --command bash -c 'echo >&9 || exit 86; exec "$@" 8<&- 9>&-' bash "$@"
code=$?
if ! IFS= read -r -u 8 _; then exit 86; fi
if [ "$code" -eq 86 ]; then exit 1; fi
exit "$code""#;

/// The container command that runs `command` with `packages` on `PATH`,
/// which is `command` itself when the list is empty.
#[must_use]
pub fn wrap(packages: &[String], command: Vec<OsString>) -> Vec<OsString> {
if packages.is_empty() {
return command;
}
let mut args: Vec<OsString> = ["bash", "-c", SCRIPT, "factory-worker-packages"]
.into_iter()
.map(OsString::from)
.collect();
args.push(packages.len().to_string().into());
args.extend(packages.iter().map(OsString::from));
args.extend(command);
args
}

/// Why a run failed when its packages could not be installed.
#[must_use]
pub fn failure(packages: &[String], detail: &str) -> String {
format!(
"the worker packages ({}) could not be installed{detail}",
packages.join(", ")
)
}
14 changes: 13 additions & 1 deletion crates/factory-runner/src/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use tokio::process::Command;

use crate::agent::{AgentItem, Credential, RunResult, TokenUsage, backend};
use crate::outcome::{Expect, failed_event};
use crate::packages;
use crate::stream::LogLine;

/// Where the job's checkout appears inside the worker.
Expand Down Expand Up @@ -192,6 +193,9 @@ pub struct WorkerRun {
/// The MCP servers active for this run, or `None` when none is. `None`
/// passes no MCP config, so the arguments are unchanged.
pub mcp: Option<McpConfig>,
/// The project's nixpkgs packages. A non-empty list runs the agent inside
/// `nix shell` with them on `PATH`; an empty one changes nothing.
pub packages: Vec<String>,
}

#[derive(Debug, Clone, PartialEq)]
Expand Down Expand Up @@ -298,7 +302,7 @@ pub fn podman_args(config: &WorkerConfig, run: &WorkerRun) -> Vec<OsString> {
}

args.push(config.image.clone().into());
args.extend(backend.command(config, run));
args.extend(packages::wrap(&run.packages, backend.command(config, run)));
args
}

Expand Down Expand Up @@ -399,6 +403,14 @@ pub async fn run(
Credential::File(name) => fs::read_to_string(run.config_dir.join(name)).ok(),
Credential::Env(_) => None,
};
if !run.packages.is_empty()
&& collected.result.is_none()
&& status
.as_ref()
.is_ok_and(|status| status.code() == Some(packages::FAILED_CODE))
{
return failed(packages::failure(&run.packages, &tail(&stderr)));
}
collected.into_report(run.expect, credential, status, &stderr)
}

Expand Down
2 changes: 2 additions & 0 deletions crates/factory-runner/tests/codex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ fn codex_run(dir: &Path, session: SessionRun) -> WorkerRun {
model: None,
effort: None,
mcp: None,
packages: Vec::new(),
}
}

Expand Down Expand Up @@ -343,6 +344,7 @@ fn a_claude_run_is_unchanged_by_the_codex_backend() {
name: "context7".into(),
}],
}),
packages: Vec::new(),
};
let args = strings(&factory_runner::podman_args(&WorkerConfig::default(), &run));

Expand Down
1 change: 1 addition & 0 deletions crates/factory-runner/tests/copilot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ fn copilot_run(dir: &Path, session: SessionRun) -> WorkerRun {
model: None,
effort: None,
mcp: None,
packages: Vec::new(),
}
}

Expand Down
143 changes: 143 additions & 0 deletions crates/factory-runner/tests/github.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,7 @@ fn checks_run_with_bash_in_the_checkout_without_tokens() {
"factory-job-7",
Path::new("/jobs/7/work"),
"just lint",
&[],
)
.iter()
.map(|arg| arg.to_string_lossy().into_owned())
Expand All @@ -256,6 +257,147 @@ fn checks_run_with_bash_in_the_checkout_without_tokens() {
assert!(!args.iter().any(|arg| arg.contains("secret")));
}

#[test]
fn checks_with_packages_run_the_command_inside_nix_shell() {
let config = WorkerConfig::default();
let packages = ["a".to_owned(), "b".to_owned()];
let args: Vec<String> = checks_args(
&config,
"factory-job-7",
Path::new("/jobs/7/work"),
"just lint; echo $HOME",
&packages,
)
.iter()
.map(|arg| arg.to_string_lossy().into_owned())
.collect();
let image = args.iter().position(|arg| *arg == config.image).unwrap();
assert_eq!(args[image + 1], "bash");
assert_eq!(args[image + 2], "-c");
assert!(args[image + 3].contains("nix shell"));
assert!(!args[image + 3].contains("just lint"));
assert_eq!(
args[image + 4..],
[
"factory-worker-packages",
"2",
"a",
"b",
"bash",
"-c",
"just lint; echo $HOME"
]
);
}

/// Runs the generated wrapper for `command` under a fake `nix` whose build
/// and shell steps succeed or fail as given, and returns its exit code.
fn wrapper_exit(build_ok: bool, shell_ok: bool, command: &str) -> Option<i32> {
wrapper_run(build_ok, shell_ok, command, true).0
}

/// Like [`wrapper_exit`], with a temporary directory that can be missing, and
/// whether the command ran, which it does by creating `$RAN`.
fn wrapper_run(
build_ok: bool,
shell_ok: bool,
command: &str,
tmp_exists: bool,
) -> (Option<i32>, bool) {
let dir = tempfile::tempdir().unwrap();
let nix = format!(
"case \"$1\" in\nbuild) {} ;;\nshell) {} ;;\nesac",
if build_ok { "exit 0" } else { "exit 1" },
if shell_ok {
"while [ \"$1\" != --command ]; do shift; done; shift; exec \"$@\""
} else {
"exit 1"
},
);
script(dir.path(), "nix", &nix);
let config = WorkerConfig::default();
let args: Vec<String> = checks_args(
&config,
"factory-job-7",
Path::new("/jobs/7/work"),
command,
&["--".to_owned(), "b".to_owned()],
)
.iter()
.map(|arg| arg.to_string_lossy().into_owned())
.collect();
let image = args.iter().position(|arg| *arg == config.image).unwrap();
let path = format!(
"{}:{}",
dir.path().display(),
std::env::var("PATH").unwrap()
);
let tmp = dir.path().join("tmp");
if tmp_exists {
fs::create_dir(&tmp).unwrap();
}
let ran = dir.path().join("ran");
let code = std::process::Command::new(&args[image + 1])
.args(&args[image + 2..])
.env("PATH", path)
.env("TMPDIR", &tmp)
.env("RAN", &ran)
.status()
.unwrap()
.code();
if tmp_exists {
assert_eq!(fs::read_dir(&tmp).unwrap().count(), 0, "left a marker");
}
(code, ran.exists())
}

#[test]
fn the_wrapper_does_not_run_the_command_when_its_start_signal_cannot_be_set_up() {
assert_eq!(
wrapper_run(true, true, "touch \"$RAN\"", false),
(Some(86), false)
);
}

#[test]
fn the_wrapper_tells_setup_failures_from_command_failures() {
assert_eq!(wrapper_exit(true, true, "exit 0"), Some(0));
assert_eq!(wrapper_exit(true, true, "exit 3"), Some(3));
assert_eq!(wrapper_exit(false, true, "exit 0"), Some(86));
assert_eq!(wrapper_exit(true, false, "exit 0"), Some(86));
assert_eq!(wrapper_exit(true, true, "exit 86"), Some(1));
assert_eq!(
wrapper_exit(true, true, "rm -f \"$TMPDIR\"/tmp.*; exit 3"),
Some(3)
);
}

#[tokio::test]
async fn packages_that_cannot_be_installed_are_a_checks_error() {
let dir = tempfile::tempdir().unwrap();
let podman = script(
dir.path(),
"podman",
"echo 'error: attribute nope missing' >&2\nexit 86",
);
let config = WorkerConfig {
podman,
..WorkerConfig::default()
};
let packages = ["nope".to_owned()];
let err = run_checks(
&config,
"factory-job-7",
Path::new("/jobs/7/work"),
"just lint",
&packages,
)
.await
.unwrap_err();
assert!(err.contains("worker packages (nope)"), "{err}");
assert!(err.contains("attribute nope missing"), "{err}");
}

#[tokio::test]
async fn check_results_become_events_and_podman_errors_are_retried() {
let dir = tempfile::tempdir().unwrap();
Expand All @@ -275,6 +417,7 @@ async fn check_results_become_events_and_podman_errors_are_retried() {
"factory-job-7",
Path::new("/jobs/7/work"),
"just lint",
&[],
)
.await
}
Expand Down
Loading