From 3637d5fc9d4fdac77c43254a44752ff19f137f13 Mon Sep 17 00:00:00 2001 From: johannayang-amd Date: Thu, 12 Nov 2026 15:21:17 +0100 Subject: [PATCH 1/4] fix(cli): run sandboxes without contacting axisd `axis run` first asked axisd to create the sandbox and fell back to running it in-process only when the connect failed. On Windows, axisd listens on loopback TCP and a refused connect takes about two seconds, so every `axis run` without axisd paid that wait. With axisd running, `axis run` handed the sandbox to it, printed no output, dropped the command's exit status and waited for Ctrl+C; GAS and the Linux e2e pass a dead --socket to avoid that. `axis run` now always runs the sandbox in-process and exits with the command's status. axisd-managed sandboxes stay available through `axis create`, `list`, `exec` and `destroy`. --socket is still accepted and ignored by `run`, so existing callers keep working. --- README.md | 4 + crates/axis-cli/src/main.rs | 259 +++++++++++++++--------------------- docs/setup-and-install.md | 2 +- e2e/linux/test_sandbox.sh | 48 +++++++ 4 files changed, 159 insertions(+), 154 deletions(-) diff --git a/README.md b/README.md index 4a35754..c718e31 100644 --- a/README.md +++ b/README.md @@ -158,6 +158,10 @@ axis list axis destroy ``` +`axis run` always runs the sandbox itself, with your terminal attached, and +exits with the command's status; it does not use axisd even when one is +running. Sandboxes that axisd manages are created with `axis create`. + On Linux, policies that request CPU, memory, or process limits require writable cgroups v2 or a documented fallback. `network.mode: proxy` uses an AXIS-owned strict proxy boundary and needs native `CAP_NET_ADMIN` support or the optional diff --git a/crates/axis-cli/src/main.rs b/crates/axis-cli/src/main.rs index 5e27297..e473ef7 100644 --- a/crates/axis-cli/src/main.rs +++ b/crates/axis-cli/src/main.rs @@ -14,7 +14,7 @@ mod pty_bridge; #[command(name = "axis", about = "AXIS: Agent eXecution Isolation Substrate")] #[command(version)] struct Cli { - /// Path to axisd Unix socket. + /// axisd Unix socket path, or TCP address on Windows. `run` ignores it. #[arg(long, global = true)] socket: Option, @@ -111,8 +111,9 @@ enum Commands { tail: usize, }, - /// Run a command in a new sandbox (auto-starts daemon). - /// Equivalent to: axis create + attach stdio + destroy on exit. + /// Run a command in a new sandbox and exit with its status. + /// The sandbox runs in this process with attached stdio; axisd is not + /// used. Run { /// Built-in policy name or path to a policy YAML file. #[arg(long, default_value = "minimal")] @@ -703,7 +704,7 @@ async fn main() -> Result<()> { }, Commands::Run { policy, command } => { - if let Err(err) = run_command(&cli.socket, &policy, &command, is_interactive).await { + if let Err(err) = run_command(&policy, &command, is_interactive).await { exit_with_axis_failure(&err); } } @@ -743,173 +744,125 @@ fn exit_with_axis_failure(err: &anyhow::Error) -> ! { std::process::exit(AXIS_FAILURE_EXIT_CODE); } -/// Runs `command` in a new sandbox and exits with its status. Returns only -/// when AXIS fails, or after Ctrl+C. -async fn run_command( - socket: &Option, - policy: &str, - command: &[String], - is_interactive: bool, -) -> Result<()> { +/// Runs `command` in a new sandbox in this process and exits with its status. +/// Returns only when AXIS fails, or after Ctrl+C. axisd is not involved; use +/// `axis create` for a sandbox that axisd manages. +async fn run_command(policy: &str, command: &[String], is_interactive: bool) -> Result<()> { let policy_yaml = resolve_policy_yaml(std::path::Path::new(policy))?; - - // Validate. - let parsed = axis_core::policy::Policy::from_yaml(&policy_yaml)?; + let policy = axis_core::policy::Policy::from_yaml(&policy_yaml)?; if !is_interactive { - eprintln!("AXIS: sandbox '{}' starting...", parsed.name); + eprintln!("AXIS: sandbox '{}' starting...", policy.name); } - // Try to connect to existing daemon, or start one inline. let (cmd, args) = command.split_first().expect("command required"); + let quiet = std::io::IsTerminal::is_terminal(&std::io::stdin()); - let request = serde_json::json!({ - "type": "create", - "policy_yaml": policy_yaml, - "command": cmd, - "args": args, - "env": [], - }); + let sandbox_id = axis_core::types::SandboxId::new(); + let workspace = std::env::current_dir()?; + let connect_attribution = + if axis_core::connect_attribution::policy_requires_connect_attribution(&policy) { + Some(axis_core::connect_attribution::ConnectAttributionStore::default()) + } else { + None + }; + let inference_endpoint = configured_standalone_inference_endpoint()?; - match send_ipc(socket, &request).await { - Ok(response) => { - if response["success"].as_bool() == Some(true) { - let id = response["data"]["sandbox_id"].as_str().unwrap_or("?"); - eprintln!("AXIS: sandbox {id} running"); - eprintln!("AXIS: press Ctrl+C to stop"); - - // Wait for Ctrl+C, then destroy. - tokio::signal::ctrl_c().await.ok(); - - eprintln!("\nAXIS: shutting down sandbox {id}..."); - let destroy_req = serde_json::json!({ - "type": "destroy", - "sandbox_id": id, - }); - let _ = send_ipc(socket, &destroy_req).await; - eprintln!("AXIS: done."); - } else { - let err = response["error"].as_str().unwrap_or("unknown"); - anyhow::bail!("{err}"); - } - } - Err(_) => { - // Daemon not running — run sandbox directly (standalone mode). - let quiet = std::io::IsTerminal::is_terminal(&std::io::stdin()); + // Start an inline proxy if policy uses proxy mode. + let proxy_addr = match standalone_proxy_config_for_sandbox( + sandbox_id, + &policy, + inference_endpoint, + connect_attribution.clone(), + ) { + Some(proxy_config) => { + let mut proxy = axis_proxy::proxy::AxisProxy::new(proxy_config) + .map_err(|e| anyhow::anyhow!("proxy: {e}"))?; + let addr = proxy + .bind() + .await + .map_err(|e| anyhow::anyhow!("proxy bind: {e}"))?; if !quiet { - eprintln!("AXIS: daemon not running, using standalone mode"); + eprintln!("AXIS: proxy on {addr}"); } + tokio::spawn(async move { + let _ = proxy.run().await; + }); + Some(addr) + } + None => None, + }; + let proxy_port = proxy_addr.map(|addr| addr.port()).unwrap_or(0); - let policy = axis_core::policy::Policy::from_yaml(&policy_yaml)?; - let sandbox_id = axis_core::types::SandboxId::new(); - let workspace = std::env::current_dir()?; - let connect_attribution = - if axis_core::connect_attribution::policy_requires_connect_attribution(&policy) { - Some(axis_core::connect_attribution::ConnectAttributionStore::default()) - } else { - None - }; - let inference_endpoint = configured_standalone_inference_endpoint()?; - - // Start an inline proxy if policy uses proxy mode. - let proxy_addr = match standalone_proxy_config_for_sandbox( - sandbox_id, - &policy, - inference_endpoint, - connect_attribution.clone(), - ) { - Some(proxy_config) => { - let mut proxy = axis_proxy::proxy::AxisProxy::new(proxy_config) - .map_err(|e| anyhow::anyhow!("proxy: {e}"))?; - let addr = proxy - .bind() - .await - .map_err(|e| anyhow::anyhow!("proxy bind: {e}"))?; - if !quiet { - eprintln!("AXIS: proxy on {addr}"); - } - tokio::spawn(async move { - let _ = proxy.run().await; - }); - Some(addr) - } - None => None, - }; - let proxy_port = proxy_addr.map(|addr| addr.port()).unwrap_or(0); - - let mut env = collect_standalone_sandbox_env(); - - // Auto-discover runtime directories (Node.js, Python) and - // append them to PATH so npm-installed agents and Python - // venvs work without users needing to configure PATH. - if cfg!(windows) { - let extra_dirs = discover_runtime_dirs(); - if !extra_dirs.is_empty() - && let Some(path_entry) = - env.iter_mut().find(|(k, _)| k.eq_ignore_ascii_case("PATH")) - { - for dir in &extra_dirs { - if !path_entry.1.to_lowercase().contains(&dir.to_lowercase()) { - path_entry.1.push(';'); - path_entry.1.push_str(dir); - } - } + let mut env = collect_standalone_sandbox_env(); + + // Auto-discover runtime directories (Node.js, Python) and + // append them to PATH so npm-installed agents and Python + // venvs work without users needing to configure PATH. + if cfg!(windows) { + let extra_dirs = discover_runtime_dirs(); + if !extra_dirs.is_empty() + && let Some(path_entry) = env.iter_mut().find(|(k, _)| k.eq_ignore_ascii_case("PATH")) + { + for dir in &extra_dirs { + if !path_entry.1.to_lowercase().contains(&dir.to_lowercase()) { + path_entry.1.push(';'); + path_entry.1.push_str(dir); } } + } + } - let timeout_sec = policy.process.timeout_sec; - let config = axis_sandbox::SandboxConfig { - id: sandbox_id, - policy, - command: cmd.to_string(), - args: args.to_vec(), - working_dir: Some(workspace.clone()), - workspace_dir: workspace, - env, - proxy_port, - proxy_addr, - connect_attribution, - capture_output: false, - interactive_terminal: quiet, - pty_bridge_helper: None, - timeout_sec, - backend_preflight: Default::default(), - startup_trace: None, - }; + let timeout_sec = policy.process.timeout_sec; + let config = axis_sandbox::SandboxConfig { + id: sandbox_id, + policy, + command: cmd.to_string(), + args: args.to_vec(), + working_dir: Some(workspace.clone()), + workspace_dir: workspace, + env, + proxy_port, + proxy_addr, + connect_attribution, + capture_output: false, + interactive_terminal: quiet, + pty_bridge_helper: None, + timeout_sec, + backend_preflight: Default::default(), + startup_trace: None, + }; - let mut sandbox = - axis_sandbox::Sandbox::create(config).map_err(|e| anyhow::anyhow!("{e}"))?; - sandbox.start().map_err(|e| anyhow::anyhow!("{e}"))?; + let mut sandbox = axis_sandbox::Sandbox::create(config).map_err(|e| anyhow::anyhow!("{e}"))?; + sandbox.start().map_err(|e| anyhow::anyhow!("{e}"))?; - if !quiet { - eprintln!( - "AXIS: sandbox running (pid={}), Ctrl+C to stop", - sandbox.pid.unwrap_or(0) - ); - } + if !quiet { + eprintln!( + "AXIS: sandbox running (pid={}), Ctrl+C to stop", + sandbox.pid.unwrap_or(0) + ); + } - if quiet { - // Interactive mode: just wait for the child to exit. - // Don't install a Ctrl+C handler, because it steals the - // TTY from the child process and breaks TUI apps like - // Claude Code (setRawMode fails). - let code = wait_for_interactive_standalone_sandbox(&mut sandbox).await?; + if quiet { + // Interactive mode: just wait for the child to exit. + // Don't install a Ctrl+C handler, because it steals the + // TTY from the child process and breaks TUI apps like + // Claude Code (setRawMode fails). + let code = wait_for_interactive_standalone_sandbox(&mut sandbox).await?; + sandbox.destroy().ok(); + std::process::exit(code); + } else { + // Non-interactive: wait for process or Ctrl+C. destroy() + // MUST run after the wait too: wait() only kills the local + // frontend (e.g. on timeout), so without an explicit + // destroy() the backend's VM/DomU would be orphaned. + tokio::select! { + code = sandbox.wait() => { + let code = code.map_err(|e| anyhow::anyhow!("{e}"))?; sandbox.destroy().ok(); std::process::exit(code); - } else { - // Non-interactive: wait for process or Ctrl+C. destroy() - // MUST run after the wait too: wait() only kills the local - // frontend (e.g. on timeout), so without an explicit - // destroy() the backend's VM/DomU would be orphaned. - tokio::select! { - code = sandbox.wait() => { - let code = code.map_err(|e| anyhow::anyhow!("{e}"))?; - sandbox.destroy().ok(); - std::process::exit(code); - } - _ = tokio::signal::ctrl_c() => { - sandbox.destroy().map_err(|e| anyhow::anyhow!("{e}"))?; - } - } + } + _ = tokio::signal::ctrl_c() => { + sandbox.destroy().map_err(|e| anyhow::anyhow!("{e}"))?; } } } diff --git a/docs/setup-and-install.md b/docs/setup-and-install.md index 55c558b..b9b53b1 100644 --- a/docs/setup-and-install.md +++ b/docs/setup-and-install.md @@ -375,7 +375,7 @@ therefore the BaseContainer/WFP tier. `action_on_exhaust: reject` is currently the only exact budget action; queue and fallback require the future trusted request scheduler and fail during proxy initialization. -For standalone `axis run`, set `AXIS_INFERENCE_ENDPOINT=127.0.0.1:` to +For `axis run`, set `AXIS_INFERENCE_ENDPOINT=127.0.0.1:` to map the sandbox-visible `inference.local` route to a managed host provider. AXIS consumes this value in the host proxy and does not project it into the sandbox environment. diff --git a/e2e/linux/test_sandbox.sh b/e2e/linux/test_sandbox.sh index 643a1b8..957fff6 100755 --- a/e2e/linux/test_sandbox.sh +++ b/e2e/linux/test_sandbox.sh @@ -408,6 +408,54 @@ else fail "timeout stops long-running sandbox (status=$timeout_status elapsed=${elapsed}s)" fi +echo "--- axis run does not use axisd ---" +# A socket that accepts and never answers stands in for a stuck axisd. +stall_dir="$(new_tmpdir)" +stall_socket="${stall_dir}/axisd.sock" +python3 - "$stall_socket" <<'PY' & +import socket +import sys +import time + +server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) +server.bind(sys.argv[1]) +server.listen(8) +server.settimeout(1) +held = [] +deadline = time.monotonic() + 30 +while time.monotonic() < deadline: + try: + held.append(server.accept()[0]) + except socket.timeout: + pass +PY +stall_pid=$! +for _ in $(seq 1 50); do + [ -S "$stall_socket" ] && break + sleep 0.1 +done +stall_policy="$(write_policy block "" "" axis_native)" +stall_output="${stall_dir}/output.txt" +set +e +( + cd "$stall_dir" + timeout 15 "$AXIS" --socket "$stall_socket" run --policy "$stall_policy" -- \ + python3 -c 'raise SystemExit(7)' +) >"$stall_output" 2>&1 +stall_status=$? +set -e +kill "$stall_pid" 2>/dev/null || true +wait "$stall_pid" 2>/dev/null || true +stall_text="$(cat "$stall_output")" +if capability_skip_output "$stall_text"; then + skip "axis run with a stalled axisd unavailable on this runner: ${stall_text//$'\n'/ }" +elif [ "$stall_status" -eq 7 ]; then + pass "axis run ignores axisd and returns the command's exit status" +else + echo "$stall_text" + fail "axis run ignores axisd and returns the command's exit status (status=$stall_status)" +fi + echo "" echo " ---------------------------------------------------------" echo " Result: ${PASS} passed, ${FAIL} failed, ${SKIP} skipped" From e106dade303cd24f64b4502b9575f627abfe44ce Mon Sep 17 00:00:00 2001 From: johannayang-amd Date: Fri, 13 Nov 2026 13:36:52 +0100 Subject: [PATCH 2/4] docs(windows): drop the axisd wait from the launch notes axis run no longer contacts axisd, so the two-second connect wait the launch notes describe is gone. --- docs/windows-mxc-1.md | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/docs/windows-mxc-1.md b/docs/windows-mxc-1.md index f17ecfc..e500680 100644 --- a/docs/windows-mxc-1.md +++ b/docs/windows-mxc-1.md @@ -153,7 +153,9 @@ cross-built from this change with `cargo xwin`. pre-1.x executor). `--socket 0.0.0.0:9` makes the axisd connect fail at once for both builds; without it, Windows retries the refused loopback connect for about two seconds before `axis run` falls back to standalone mode, which hides - the launch cost (2371 ms against 2498 ms median in block mode). + the launch cost (2371 ms against 2498 ms median in block mode). `axis run` no + longer contacts axisd, so that wait is gone and these numbers are what a + launch costs. | Build | Mode | Median | p90 | Failures | | --- | --- | --- | --- | --- | @@ -166,10 +168,7 @@ cross-built from this change with `cargo xwin`. MXC 1.x adds about 200 ms per launch. About 70 ms of it is the executor's own start: `wxc-exec.exe --version` takes 152 ms against 80 ms for the pre-1.x build. v0.4.0 proxy mode needs the installed broker and was not - measured. Launches through a running axisd were not measured: on Windows, - axisd currently falls back to `/tmp/axis/sandboxes` for sandbox state when - neither `XDG_DATA_HOME` nor `HOME` is set, and `axis run` through axisd - waits for Ctrl+C. + measured. ## Upgrading From v0.4.0 @@ -198,7 +197,6 @@ Remove-Item -Recurse -Force "$env:ProgramData\axis\wfp-leases" falls back to `/tmp/axis/sandboxes`, so daemon commands cannot create sandboxes on Windows. - Find where the rest of the added launch time goes (MXC 1.x container setup, - or AXIS's suspended start and resume) and measure launches through axisd once - it has a Windows state directory. + or AXIS's suspended start and resume). - Move the WSLc, Isolation Session and VM-style Windows config builders to the 1.0.0 contract before they gain a launch path. From a6749f6fdbbc3dc66f276f32e70a59cdb90974b4 Mon Sep 17 00:00:00 2001 From: johannayang-amd Date: Thu, 19 Nov 2026 11:18:15 +0100 Subject: [PATCH 3/4] fix(cli): stop, time out and refuse GPU in standalone axis run Now that axis run never goes through axisd, the standalone path has to do what axisd did for it. - Ctrl+C or SIGTERM without a terminal left the command running and axis hanging until it exited: the Linux backends move the child into a blocking wait task, so destroy() after the dropped wait killed nothing. They now remember that pid and kill its process group. axis run exits with 128 + the signal number instead of 0. - macOS ignored timeout_sec, and its blocking wait starved the signal branch. It now polls with a deadline like Windows MXC, and kills the process group when not attached to a terminal. - axis run refuses gpu.enabled: only axisd starts the HIP Remote GPU worker. The README GPU example uses axis create. - A failing inline proxy is logged instead of dropped. - The Linux e2e asserts that axis run never connects to the axisd socket (the old check also passed on main without an axisd token), that SIGINT stops the sandboxed process group, and that GPU policies are refused. --- README.md | 12 +- crates/axis-cli/src/main.rs | 39 +++++- crates/axis-sandbox/Cargo.toml | 3 + crates/axis-sandbox/src/linux/mod.rs | 67 +++++++++- crates/axis-sandbox/src/linux/mxc.rs | 14 ++- crates/axis-sandbox/src/macos/mod.rs | 170 ++++++++++++++++++++++++-- e2e/linux/test_sandbox.sh | 80 +++++++++++- e2e/windows/test_mxc_strict_proxy.ps1 | 5 +- 8 files changed, 365 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 20246ab..4bc84ad 100644 --- a/README.md +++ b/README.md @@ -169,7 +169,9 @@ axis destroy `axis run` always runs the sandbox itself, with your terminal attached, and exits with the command's status; it does not use axisd even when one is -running. Sandboxes that axisd manages are created with `axis create`. +running. Stopping `axis run` with Ctrl+C or SIGTERM also stops the sandboxed +processes. Sandboxes that axisd manages, including GPU sandboxes, are created +with `axis create`. The daemon commands (`axisd`, `axis create`, `list`, `exec`, `destroy`) do not work on Windows yet: axisd there cannot create sandboxes. Use `axis run`. @@ -303,10 +305,14 @@ Agents can use AMD GPUs without direct hardware access: # Download a model axis model pull TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF/tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf -# Run with GPU policy (requires hip-worker on GPU host) -axis run --policy gpu-agent -- python gpu_agent.py +# Run with GPU policy (requires axisd and hip-worker on GPU host) +axisd & +axis create --policy gpu-agent -- python gpu_agent.py ``` +axisd starts the GPU worker, so GPU policies need `axis create`; `axis run` +refuses a policy with `gpu.enabled: true`. + The sandbox sees the GPU through a HIP Remote client library proxied over TCP to a `hip-worker` on the GPU host. HIP Remote artifacts are optional runtime inputs that are built separately; they are not included in AXIS release diff --git a/crates/axis-cli/src/main.rs b/crates/axis-cli/src/main.rs index 078ab47..3f8ef2c 100644 --- a/crates/axis-cli/src/main.rs +++ b/crates/axis-cli/src/main.rs @@ -768,11 +768,17 @@ fn exit_with_axis_failure(err: &anyhow::Error) -> ! { } /// Runs `command` in a new sandbox in this process and exits with its status. -/// Returns only when AXIS fails, or after Ctrl+C. axisd is not involved; use -/// `axis create` for a sandbox that axisd manages. +/// Returns only when AXIS fails. axisd is not involved; use `axis create` for a +/// sandbox that axisd manages. async fn run_command(policy: &str, command: &[String], is_interactive: bool) -> Result<()> { let policy_yaml = resolve_policy_yaml(std::path::Path::new(policy))?; let policy = axis_core::policy::Policy::from_yaml(&policy_yaml)?; + if policy.gpu.enabled { + anyhow::bail!( + "policy '{}' sets gpu.enabled, but `axis run` does not start the HIP Remote GPU worker; use `axis create` with axisd instead", + policy.name + ); + } if !is_interactive { eprintln!("AXIS: sandbox '{}' starting...", policy.name); } @@ -808,7 +814,9 @@ async fn run_command(policy: &str, command: &[String], is_interactive: bool) -> eprintln!("AXIS: proxy on {addr}"); } tokio::spawn(async move { - let _ = proxy.run().await; + if let Err(e) = proxy.run().await { + eprintln!("AXIS: proxy exited: {e}"); + } }); Some(addr) } @@ -874,7 +882,7 @@ async fn run_command(policy: &str, command: &[String], is_interactive: bool) -> sandbox.destroy().ok(); std::process::exit(code); } else { - // Non-interactive: wait for process or Ctrl+C. destroy() + // Non-interactive: wait for the process or a stop signal. destroy() // MUST run after the wait too: wait() only kills the local // frontend (e.g. on timeout), so without an explicit // destroy() the backend's VM/DomU would be orphaned. @@ -884,12 +892,31 @@ async fn run_command(policy: &str, command: &[String], is_interactive: bool) -> sandbox.destroy().ok(); std::process::exit(code); } - _ = tokio::signal::ctrl_c() => { + code = stop_signal() => { + let code = code?; sandbox.destroy().map_err(|e| anyhow::anyhow!("{e}"))?; + std::process::exit(code); } } } - Ok(()) +} + +/// Waits for Ctrl+C or, on Unix, SIGTERM, and returns the exit status for it. +#[cfg(unix)] +async fn stop_signal() -> Result { + use tokio::signal::unix::{SignalKind, signal}; + let mut interrupt = signal(SignalKind::interrupt())?; + let mut terminate = signal(SignalKind::terminate())?; + tokio::select! { + _ = interrupt.recv() => Ok(128 + libc::SIGINT), + _ = terminate.recv() => Ok(128 + libc::SIGTERM), + } +} + +#[cfg(not(unix))] +async fn stop_signal() -> Result { + tokio::signal::ctrl_c().await?; + Ok(130) } /// Runs `command` in an existing daemon sandbox and exits with its status. diff --git a/crates/axis-sandbox/Cargo.toml b/crates/axis-sandbox/Cargo.toml index 6b17339..df95175 100644 --- a/crates/axis-sandbox/Cargo.toml +++ b/crates/axis-sandbox/Cargo.toml @@ -20,6 +20,9 @@ sha2 = { workspace = true } nix = { workspace = true } libc = { workspace = true } +[target.'cfg(target_os = "macos")'.dependencies] +libc = { workspace = true } + [target.'cfg(target_os = "windows")'.dependencies] windows = { version = "0.62", features = [ "Win32_Foundation", diff --git a/crates/axis-sandbox/src/linux/mod.rs b/crates/axis-sandbox/src/linux/mod.rs index 0120190..c5607c8 100644 --- a/crates/axis-sandbox/src/linux/mod.rs +++ b/crates/axis-sandbox/src/linux/mod.rs @@ -359,6 +359,10 @@ pub(crate) struct LinuxSandbox { config: SandboxConfig, plan: strategy::LinuxIsolationPlan, child: Option, + /// Process group of a child that `wait()` has moved into a blocking task. + /// Set until that wait finishes, so `destroy()` can still kill the group + /// when the wait future is dropped. + waiting_pid: Option, parent_death_guard: Option, exit_code: Option, netns_name: Option, @@ -386,6 +390,7 @@ impl LinuxSandbox { config, plan, child: None, + waiting_pid: None, parent_death_guard: None, exit_code: None, netns_name: None, @@ -2311,7 +2316,10 @@ impl SandboxImpl for LinuxSandbox { .ok_or_else(|| SandboxError::SpawnFailed("no child process".into()))?; let pid = child.id() as i32; - let status = match wait_child_with_timeout(child, self.config.timeout_sec).await { + self.waiting_pid = Some(pid); + let result = wait_child_with_timeout(child, self.config.timeout_sec).await; + self.waiting_pid = None; + let status = match result { Ok(status) => status, Err(e) => { self.exit_code = Some(-1); @@ -2378,6 +2386,10 @@ impl SandboxImpl for LinuxSandbox { } self.exit_code = Some(wait_for_killed_child(&mut child, pid)); kill_process_group(pid); + } else if let Some(pid) = self.waiting_pid.take() { + // The blocking wait task still owns the child and reaps it. + kill_process_group(pid); + self.exit_code = Some(-1); } self.finish_parent_death_guard(); self.stop_connect_supervisor(); @@ -2943,6 +2955,58 @@ mod tests { sandbox.destroy().unwrap(); } + #[tokio::test(flavor = "multi_thread")] + async fn destroy_kills_process_group_after_wait_is_dropped() { + if !Path::new("/bin/sh").exists() { + eprintln!("/bin/sh unavailable (test skipped)"); + return; + } + + let workspace = tempfile::tempdir().unwrap(); + let pid_path = workspace.path().join("background.pid"); + let mut cmd = Command::new("/bin/sh"); + cmd.arg("-c") + .arg("sleep 30 & echo $! > \"$PID_PATH\"; wait") + .env("PID_PATH", &pid_path); + unsafe { + cmd.pre_exec(|| { + if libc::setpgid(0, 0) < 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + }); + } + let child = cmd.spawn().unwrap(); + let leader = child.id() as libc::pid_t; + let mut sandbox = test_sandbox(SandboxId::new(), workspace.path(), Some(child)); + + let waited = tokio::time::timeout( + std::time::Duration::from_millis(500), + SandboxImpl::wait(&mut sandbox), + ) + .await; + assert!( + waited.is_err(), + "sandbox exited before the wait was dropped" + ); + let background_pid = std::fs::read_to_string(&pid_path) + .ok() + .and_then(|contents| contents.trim().parse::().ok()) + .filter(|pid| *pid > 0); + + sandbox.destroy().unwrap(); + + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while process_exists(leader) || background_pid.is_some_and(process_exists) { + if std::time::Instant::now() >= deadline { + kill_process_group(leader); + panic!("sandbox process group survived destroy after a dropped wait"); + } + std::thread::sleep(std::time::Duration::from_millis(20)); + } + assert!(background_pid.is_some(), "background pid was not recorded"); + } + #[test] fn destroy_is_idempotent_after_killing_child() { let workspace = tempfile::tempdir().unwrap(); @@ -4134,6 +4198,7 @@ mod tests { }, plan: test_plan(id, workspace), child, + waiting_pid: None, parent_death_guard: None, exit_code: None, netns_name: None, diff --git a/crates/axis-sandbox/src/linux/mxc.rs b/crates/axis-sandbox/src/linux/mxc.rs index 73693d8..4286b06 100644 --- a/crates/axis-sandbox/src/linux/mxc.rs +++ b/crates/axis-sandbox/src/linux/mxc.rs @@ -443,6 +443,10 @@ pub(crate) struct MxcLinuxSandbox { proxy_strategy: super::strategy::ProxyStrategy, resource_strategy: super::strategy::ResourceStrategy, child: Option, + /// Process group of a child that `wait()` has moved into a blocking task. + /// Set until that wait finishes, so `destroy()` can still kill the group + /// when the wait future is dropped. + waiting_pid: Option, parent_death_guard: Option, exit_code: Option, config_file: Option, @@ -1062,6 +1066,7 @@ impl MxcLinuxSandbox { proxy_strategy, resource_strategy, child: None, + waiting_pid: None, parent_death_guard: None, exit_code: None, config_file: None, @@ -2154,7 +2159,10 @@ impl SandboxImpl for MxcLinuxSandbox { .take() .ok_or_else(|| SandboxError::SpawnFailed("no MXC child process".into()))?; let pid = child.id() as i32; - let status = match wait_runtime_child_with_timeout(child, self.timeout_sec).await { + self.waiting_pid = Some(pid); + let result = wait_runtime_child_with_timeout(child, self.timeout_sec).await; + self.waiting_pid = None; + let status = match result { Ok(status) => status, Err(err) => { self.exit_code = Some(-1); @@ -2210,6 +2218,10 @@ impl SandboxImpl for MxcLinuxSandbox { } self.exit_code = Some(wait_for_killed_child(&mut child, pid)); kill_process_group(pid); + } else if let Some(pid) = self.waiting_pid.take() { + // The blocking wait task still owns the child and reaps it. + kill_process_group(pid); + self.exit_code = Some(-1); } self.cleanup_after_stop()?; tracing::info!("sandbox {} destroyed via MXC Linux backend", self.id); diff --git a/crates/axis-sandbox/src/macos/mod.rs b/crates/axis-sandbox/src/macos/mod.rs index 84023e0..bf15587 100644 --- a/crates/axis-sandbox/src/macos/mod.rs +++ b/crates/axis-sandbox/src/macos/mod.rs @@ -10,7 +10,9 @@ pub mod profile; use crate::sandbox::{SandboxConfig, SandboxError, SandboxImpl}; +use std::os::unix::process::CommandExt; use std::process::Child; +use std::time::{Duration, Instant}; /// macOS sandbox using Seatbelt profiles. pub(crate) struct MacosSandbox { @@ -26,6 +28,21 @@ impl MacosSandbox { child: None, }) } + + /// Kills the child and, outside an interactive terminal, its process group. + fn kill(&mut self) { + let Some(child) = self.child.as_mut() else { + return; + }; + // Once the child is reaped its pid can be reused by an unrelated group. + let running = matches!(child.try_wait(), Ok(None)); + if running && !self.config.interactive_terminal { + unsafe { + libc::kill(-(child.id() as i32), libc::SIGKILL); + } + } + let _ = child.kill(); + } } impl SandboxImpl for MacosSandbox { @@ -83,6 +100,11 @@ impl SandboxImpl for MacosSandbox { cmd.stderr(std::process::Stdio::from(stderr)); } + // A TUI must stay in the terminal's foreground process group. + if !self.config.interactive_terminal { + cmd.process_group(0); + } + let child = cmd .spawn() .map_err(|e| SandboxError::SpawnFailed(e.to_string()))?; @@ -98,13 +120,31 @@ impl SandboxImpl for MacosSandbox { &mut self, ) -> std::pin::Pin> + Send + '_>> { - Box::pin(async { - let child = self - .child - .as_mut() - .ok_or_else(|| SandboxError::SpawnFailed("no child process".into()))?; - let status = tokio::task::block_in_place(|| child.wait())?; - Ok(status.code().unwrap_or(-1)) + Box::pin(async move { + let mut deadline = self + .config + .timeout_sec + .map(|seconds| Instant::now() + Duration::from_secs(seconds)); + loop { + let status = self + .child + .as_mut() + .ok_or_else(|| SandboxError::SpawnFailed("no child process".into()))? + .try_wait()?; + if let Some(status) = status { + return Ok(status.code().unwrap_or(-1)); + } + if deadline.is_some_and(|deadline| Instant::now() >= deadline) { + tracing::warn!( + "sandbox {} exceeded timeout of {}s", + self.config.id, + self.config.timeout_sec.unwrap_or_default() + ); + self.kill(); + deadline = None; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } }) } @@ -120,11 +160,125 @@ impl SandboxImpl for MacosSandbox { } fn destroy(&mut self) -> Result<(), SandboxError> { + self.kill(); if let Some(ref mut child) = self.child { - let _ = child.kill(); let _ = child.wait(); } tracing::info!("sandbox {} destroyed", self.config.id); Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + use axis_core::policy::{ + FilesystemPolicy, GpuPolicy, InferencePolicy, NetworkMode, NetworkPolicy, Policy, + ProcessPolicy, SshPolicy, + }; + use axis_core::types::SandboxId; + use std::path::Path; + + const BACKGROUND_SLEEP: &str = "sleep 30 & echo $! > background.pid; wait"; + + fn test_config(workspace: &Path, timeout_sec: Option) -> SandboxConfig { + SandboxConfig { + id: SandboxId::new(), + policy: Policy { + version: 1, + name: "macos-test".into(), + runtime: Default::default(), + filesystem: FilesystemPolicy::default(), + process: ProcessPolicy::default(), + network: NetworkPolicy { + bypass_audit: Default::default(), + mode: NetworkMode::Block, + policies: Vec::new(), + }, + inference: InferencePolicy::default(), + gpu: GpuPolicy::default(), + ssh: SshPolicy::default(), + amd: None, + }, + command: "/bin/sh".into(), + args: vec!["-c".into(), BACKGROUND_SLEEP.into()], + working_dir: None, + workspace_dir: workspace.to_path_buf(), + env: vec![("PATH".into(), "/usr/bin:/bin".into())], + proxy_port: 0, + proxy_addr: None, + connect_attribution: None, + capture_output: false, + interactive_terminal: false, + pty_bridge_helper: None, + timeout_sec, + backend_preflight: Default::default(), + startup_trace: None, + } + } + + fn background_pid(workspace: &Path) -> i32 { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + if let Ok(contents) = std::fs::read_to_string(workspace.join("background.pid")) + && let Ok(pid) = contents.trim().parse::() + && pid > 0 + { + return pid; + } + assert!(Instant::now() < deadline, "background pid was not recorded"); + std::thread::sleep(Duration::from_millis(20)); + } + } + + fn assert_exits(pid: i32) { + let deadline = Instant::now() + Duration::from_secs(10); + while unsafe { libc::kill(pid, 0) } == 0 { + if Instant::now() >= deadline { + unsafe { + libc::kill(pid, libc::SIGKILL); + } + panic!("process {pid} survived the sandbox"); + } + std::thread::sleep(Duration::from_millis(20)); + } + } + + #[tokio::test(flavor = "multi_thread")] + async fn wait_enforces_timeout_and_kills_process_group() { + let dir = tempfile::tempdir().unwrap(); + let workspace = dir.path().canonicalize().unwrap(); + let mut sandbox = MacosSandbox::new(&test_config(&workspace, Some(1))).unwrap(); + sandbox.start().unwrap(); + let background = background_pid(&workspace); + + let start = Instant::now(); + let code = sandbox.wait().await.unwrap(); + + assert_eq!(code, -1); + assert!( + start.elapsed() < Duration::from_secs(10), + "timeout wait took too long" + ); + assert_exits(background); + sandbox.destroy().unwrap(); + } + + #[tokio::test(flavor = "multi_thread")] + async fn destroy_kills_process_group_after_wait_is_dropped() { + let dir = tempfile::tempdir().unwrap(); + let workspace = dir.path().canonicalize().unwrap(); + let mut sandbox = MacosSandbox::new(&test_config(&workspace, None)).unwrap(); + sandbox.start().unwrap(); + let background = background_pid(&workspace); + + let waited = tokio::time::timeout(Duration::from_millis(500), sandbox.wait()).await; + assert!( + waited.is_err(), + "sandbox exited before the wait was dropped" + ); + sandbox.destroy().unwrap(); + + assert_exits(background); + } +} diff --git a/e2e/linux/test_sandbox.sh b/e2e/linux/test_sandbox.sh index 957fff6..d88a187 100755 --- a/e2e/linux/test_sandbox.sh +++ b/e2e/linux/test_sandbox.sh @@ -409,10 +409,13 @@ else fi echo "--- axis run does not use axisd ---" -# A socket that accepts and never answers stands in for a stuck axisd. +# A socket that accepts and never answers stands in for a stuck axisd. It +# records every connection, because without an axisd token an older `axis run` +# connects, fails to authenticate, and still runs the command itself. stall_dir="$(new_tmpdir)" stall_socket="${stall_dir}/axisd.sock" -python3 - "$stall_socket" <<'PY' & +stall_connections="${stall_dir}/connections" +python3 - "$stall_socket" "$stall_connections" <<'PY' & import socket import sys import time @@ -427,7 +430,9 @@ while time.monotonic() < deadline: try: held.append(server.accept()[0]) except socket.timeout: - pass + continue + with open(sys.argv[2], "a") as f: + f.write("accepted\n") PY stall_pid=$! for _ in $(seq 1 50); do @@ -447,6 +452,11 @@ set -e kill "$stall_pid" 2>/dev/null || true wait "$stall_pid" 2>/dev/null || true stall_text="$(cat "$stall_output")" +if [ -e "$stall_connections" ]; then + fail "axis run connected to the axisd socket" +else + pass "axis run did not connect to the axisd socket" +fi if capability_skip_output "$stall_text"; then skip "axis run with a stalled axisd unavailable on this runner: ${stall_text//$'\n'/ }" elif [ "$stall_status" -eq 7 ]; then @@ -456,6 +466,70 @@ else fail "axis run ignores axisd and returns the command's exit status (status=$stall_status)" fi +echo "--- axis run refuses GPU policies ---" +gpu_run_output="$(new_tmpdir)/gpu.txt" +set +e +run_axis "$gpu_run_output" "$(dirname "$gpu_run_output")" --policy gpu-agent -- /bin/true +gpu_run_status=$? +set -e +if [ "$gpu_run_status" -eq 125 ] && grep -Fq "use \`axis create\`" "$gpu_run_output"; then + pass "axis run refuses gpu.enabled instead of running without the GPU worker" +else + cat "$gpu_run_output" + fail "axis run refuses gpu.enabled instead of running without the GPU worker (status=$gpu_run_status)" +fi + +echo "--- Stop signal through axis run ---" +if require_cmd pgrep "stop signal test"; then + signal_policy="$(write_policy block "" "" axis_native)" + signal_dir="$(new_tmpdir)" + signal_output="${signal_dir}/output.txt" + # A unique duration lets the host find both sleeps by command line. + signal_sleep="sleep 60.$$${RANDOM}" + ( + cd "$signal_dir" + exec "$AXIS" run --policy "$signal_policy" -- /bin/sh -c \ + "${signal_sleep} & ${signal_sleep}" + ) "$signal_output" 2>&1 & + signal_axis=$! + for _ in $(seq 1 100); do + [ "$(pgrep -cxf "$signal_sleep" || true)" -ge 2 ] && break + kill -0 "$signal_axis" 2>/dev/null || break + sleep 0.1 + done + if [ "$(pgrep -cxf "$signal_sleep" || true)" -lt 2 ]; then + kill -KILL "$signal_axis" 2>/dev/null || true + wait "$signal_axis" 2>/dev/null || true + pkill -KILL -xf "$signal_sleep" 2>/dev/null || true + signal_text="$(cat "$signal_output")" + if capability_skip_output "$signal_text"; then + skip "stop signal unavailable on this runner: ${signal_text//$'\n'/ }" + else + echo "$signal_text" + fail "SIGINT stops the sandboxed process group (sandbox did not start)" + fi + else + kill -INT "$signal_axis" + set +e + wait "$signal_axis" + signal_status=$? + set -e + for _ in $(seq 1 50); do + pgrep -xf "$signal_sleep" >/dev/null || break + sleep 0.1 + done + if pgrep -xf "$signal_sleep" >/dev/null; then + pkill -KILL -xf "$signal_sleep" 2>/dev/null || true + fail "SIGINT stops the sandboxed process group (a sandboxed process survived)" + elif [ "$signal_status" -ne 130 ]; then + cat "$signal_output" + fail "SIGINT stops the sandboxed process group (status=$signal_status)" + else + pass "SIGINT stops the sandboxed process group" + fi + fi +fi + echo "" echo " ---------------------------------------------------------" echo " Result: ${PASS} passed, ${FAIL} failed, ${SKIP} skipped" diff --git a/e2e/windows/test_mxc_strict_proxy.ps1 b/e2e/windows/test_mxc_strict_proxy.ps1 index 1e4f8d5..a4be235 100644 --- a/e2e/windows/test_mxc_strict_proxy.ps1 +++ b/e2e/windows/test_mxc_strict_proxy.ps1 @@ -135,8 +135,7 @@ try { # Proxy mode allows ingress and host loopback for MXC's proxy mapping, so # prove the sandbox still reaches no other loopback service: an ephemeral # listener, the axisd TCP port, and another sandbox's AXIS proxy. - # The test does not bind the axisd port itself: `axis run` connects to it - # first and would talk to a stand-in listener. + # The axisd port is probed only when axisd is listening on it. $loopbackListener = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback, 0) $loopbackListener.Start() try { @@ -190,7 +189,7 @@ try { } } if ($peerProxyPorts.Count -eq 0) { - Exit-Fail "peer sandbox's AXIS proxy never listened on 127.0.0.1 from its axis.exe; run this suite without axisd so each sandbox hosts its own proxy" + Exit-Fail "peer sandbox's AXIS proxy never listened on 127.0.0.1 from its axis.exe" } foreach ($port in $peerProxyPorts) { $result = Invoke-Probe @("tcp-hold", "127.0.0.1", "$port") From 53c6918e91b5701db7e87b40d9aa418702e62e5a Mon Sep 17 00:00:00 2001 From: johannayang-amd Date: Tue, 24 Nov 2026 11:24:04 +0100 Subject: [PATCH 4/4] fix(cli): stop the sandbox on an early Ctrl+C and macOS leftovers A Ctrl+C that arrived while axis run was still creating or starting the sandbox ended AXIS with the default SIGINT action, before tokio::select! listened for it. The tmpdir that create had already made stayed behind in the workspace. Outside a terminal, the Ctrl+C handler is now registered next to the SIGTERM one, before Sandbox::create, so it stops and destroys the sandbox whenever it arrives. Interactive runs still install no handler, so TUIs keep the terminal. On macOS, a command that exited normally left whatever it started in the background running, while Linux kills the whole process group. wait() and try_wait() now check with waitid(WNOWAIT) whether the child has exited, kill its process group while it is still unreaped (so its pid and group id cannot have been reused), and only then reap it. Co-authored-by: Cursor --- crates/axis-cli/src/main.rs | 39 ++++++++++-- crates/axis-sandbox/src/macos/mod.rs | 88 +++++++++++++++++++++++----- 2 files changed, 107 insertions(+), 20 deletions(-) diff --git a/crates/axis-cli/src/main.rs b/crates/axis-cli/src/main.rs index bddf173..d65533f 100644 --- a/crates/axis-cli/src/main.rs +++ b/crates/axis-cli/src/main.rs @@ -864,9 +864,10 @@ async fn run_command(policy: &str, command: &[String], is_interactive: bool) -> }; // Registered before the create, which already makes the tmpdir on some - // backends, so a SIGTERM from then on stops the sandbox instead of ending - // AXIS without its cleanup. + // backends, so a SIGTERM or, outside a terminal, a Ctrl+C from then on + // stops the sandbox instead of ending AXIS without its cleanup. let terminated = terminate_signal()?; + let interrupted = interrupt_signal(!quiet)?; let mut sandbox = axis_sandbox::Sandbox::create(config).map_err(|e| anyhow::anyhow!("{e}"))?; sandbox.start().map_err(|e| anyhow::anyhow!("{e}"))?; @@ -898,8 +899,7 @@ async fn run_command(policy: &str, command: &[String], is_interactive: bool) -> sandbox.destroy().ok(); std::process::exit(code); } - interrupted = tokio::signal::ctrl_c() => { - interrupted?; + () = interrupted => { sandbox.destroy().map_err(|e| anyhow::anyhow!("{e}"))?; std::process::exit(INTERRUPTED_EXIT_CODE); } @@ -993,6 +993,37 @@ fn terminate_signal() -> Result> { Ok(std::future::pending()) } +/// Settles on Ctrl+C, from the call on. When `handle` is false no handler is +/// installed, so Ctrl+C keeps its default effect, and this never settles. +#[cfg(unix)] +fn interrupt_signal(handle: bool) -> Result> { + use tokio::signal::unix::{SignalKind, signal}; + let mut interrupt = handle + .then(|| signal(SignalKind::interrupt())) + .transpose()?; + Ok(async move { + match interrupt.as_mut() { + Some(interrupt) => { + interrupt.recv().await; + } + None => std::future::pending().await, + } + }) +} + +#[cfg(windows)] +fn interrupt_signal(handle: bool) -> Result> { + let mut interrupt = handle.then(tokio::signal::windows::ctrl_c).transpose()?; + Ok(async move { + match interrupt.as_mut() { + Some(interrupt) => { + interrupt.recv().await; + } + None => std::future::pending().await, + } + }) +} + /// Git-style subcommand extension. /// /// If `axis claude -p "hello"` is run and "claude" is not a built-in diff --git a/crates/axis-sandbox/src/macos/mod.rs b/crates/axis-sandbox/src/macos/mod.rs index 17bb5a5..21bfec4 100644 --- a/crates/axis-sandbox/src/macos/mod.rs +++ b/crates/axis-sandbox/src/macos/mod.rs @@ -34,15 +34,59 @@ impl MacosSandbox { let Some(child) = self.child.as_mut() else { return; }; - // Once the child is reaped its pid can be reused by an unrelated group. - let running = matches!(child.try_wait(), Ok(None)); - if running && !self.config.interactive_terminal { - unsafe { - libc::kill(-(child.id() as i32), libc::SIGKILL); - } + if !self.config.interactive_terminal && child_state(child.id()).is_some() { + kill_process_group(child.id()); } let _ = child.kill(); } + + /// Reaps the child if it has exited. Outside an interactive terminal its + /// process group is killed first, so nothing it left in the background + /// outlives it, as on Linux. + fn reap(&mut self) -> std::io::Result> { + let Some(child) = self.child.as_mut() else { + return Ok(None); + }; + if !self.config.interactive_terminal && child_state(child.id()) == Some(ChildState::Exited) + { + kill_process_group(child.id()); + } + child.try_wait() + } +} + +#[derive(Debug, PartialEq, Eq)] +enum ChildState { + Running, + Exited, +} + +/// The state of an unreaped child, without reaping it; `None` once it is +/// reaped. Until then its pid, and so its process group id, cannot be reused. +fn child_state(pid: u32) -> Option { + // SAFETY: siginfo_t is plain data that waitid fills in. + let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() }; + // SAFETY: `info` is valid for writes; WNOWAIT leaves the child unreaped. + let rc = unsafe { + libc::waitid( + libc::P_PID, + pid as libc::id_t, + &mut info, + libc::WEXITED | libc::WNOHANG | libc::WNOWAIT, + ) + }; + match rc { + 0 if info.si_pid == 0 => Some(ChildState::Running), + 0 => Some(ChildState::Exited), + _ => None, + } +} + +fn kill_process_group(pid: u32) { + // SAFETY: plain signal delivery to the child's own process group. + unsafe { + libc::kill(-(pid as libc::pid_t), libc::SIGKILL); + } } impl SandboxImpl for MacosSandbox { @@ -116,13 +160,11 @@ impl SandboxImpl for MacosSandbox { .config .timeout_sec .map(|seconds| Instant::now() + Duration::from_secs(seconds)); + if self.child.is_none() { + return Err(SandboxError::SpawnFailed("no child process".into())); + } loop { - let status = self - .child - .as_mut() - .ok_or_else(|| SandboxError::SpawnFailed("no child process".into()))? - .try_wait()?; - if let Some(status) = status { + if let Some(status) = self.reap()? { return Ok(status.code().unwrap_or(-1)); } if deadline.is_some_and(|deadline| Instant::now() >= deadline) { @@ -140,10 +182,7 @@ impl SandboxImpl for MacosSandbox { } fn try_wait(&mut self) -> Result, SandboxError> { - let Some(child) = self.child.as_mut() else { - return Ok(None); - }; - let Some(status) = child.try_wait()? else { + let Some(status) = self.reap()? else { return Ok(None); }; self.child.take(); @@ -295,6 +334,23 @@ mod tests { assert_exits(background); } + #[tokio::test(flavor = "multi_thread")] + async fn wait_kills_what_the_command_left_in_the_background() { + let dir = tempfile::tempdir().unwrap(); + let workspace = dir.path().canonicalize().unwrap(); + let mut config = test_config(&workspace, None); + config.args = vec![ + "-c".into(), + "sleep 30 & echo $! > background.pid; exit 3".into(), + ]; + let mut sandbox = MacosSandbox::new(&config).unwrap(); + sandbox.start().unwrap(); + + assert_eq!(sandbox.wait().await.unwrap(), 3); + assert_exits(background_pid(&workspace)); + sandbox.destroy().unwrap(); + } + fn value<'a>(env: &'a [(String, String)], key: &str) -> Option<&'a str> { env.iter() .find(|(env_key, _)| env_key == key)