diff --git a/README.md b/README.md index 13128895..d4dcd4a2 100644 --- a/README.md +++ b/README.md @@ -167,6 +167,12 @@ 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. 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`. @@ -304,10 +310,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 67bb4142..d65533fd 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")] @@ -726,7 +727,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); } } @@ -766,189 +767,148 @@ 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. 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 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...", 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}"); } - - 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) + tokio::spawn(async move { + if let Err(e) = proxy.run().await { + eprintln!("AXIS: proxy exited: {e}"); } - 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); - } - } + }); + 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 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, + }; - // 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. - let terminated = terminate_signal()?; - let mut sandbox = - axis_sandbox::Sandbox::create(config).map_err(|e| anyhow::anyhow!("{e}"))?; - sandbox.start().map_err(|e| anyhow::anyhow!("{e}"))?; + // Registered before the create, which already makes the tmpdir on some + // 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}"))?; - 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, terminated).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, terminated).await?; + sandbox.destroy().ok(); + std::process::exit(code); + } else { + // Non-interactive: wait for the process, Ctrl+C or SIGTERM. 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. A caller's timeout sends SIGTERM: + // destroy() then stops the command and removes the sandbox's tmpdir, + // which the next run in this workspace needs gone. + 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, Ctrl+C or SIGTERM. - // 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. - // A caller's timeout sends SIGTERM: destroy() then stops the - // command and removes the sandbox's tmpdir, which the next - // run in this workspace needs gone. - 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}"))?; - } - () = terminated => { - sandbox.destroy().map_err(|e| anyhow::anyhow!("{e}"))?; - std::process::exit(TERMINATED_EXIT_CODE); - } - } + } + () = interrupted => { + sandbox.destroy().map_err(|e| anyhow::anyhow!("{e}"))?; + std::process::exit(INTERRUPTED_EXIT_CODE); + } + () = terminated => { + sandbox.destroy().map_err(|e| anyhow::anyhow!("{e}"))?; + std::process::exit(TERMINATED_EXIT_CODE); } } } - Ok(()) } /// Runs `command` in an existing daemon sandbox and exits with its status. @@ -1009,6 +969,9 @@ async fn wait_for_interactive_standalone_sandbox( } } +/// The status `axis run` exits with when Ctrl+C stopped its sandbox. +const INTERRUPTED_EXIT_CODE: i32 = 130; + /// The status `axis run` exits with when SIGTERM stopped its sandbox. #[cfg(unix)] const TERMINATED_EXIT_CODE: i32 = 128 + libc::SIGTERM; @@ -1030,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/Cargo.toml b/crates/axis-sandbox/Cargo.toml index e820e404..e81ef55a 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/macos/mod.rs b/crates/axis-sandbox/src/macos/mod.rs index e49915af..21bfec45 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,65 @@ 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; + }; + 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 { @@ -74,6 +135,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()))?; @@ -89,21 +155,34 @@ 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)); + if self.child.is_none() { + return Err(SandboxError::SpawnFailed("no child process".into())); + } + loop { + if let Some(status) = self.reap()? { + 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; + } }) } 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(); @@ -111,8 +190,8 @@ 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); @@ -144,7 +223,133 @@ fn sandbox_env(env: &[(String, String)], proxy_port: u16) -> Vec<(String, String #[cfg(test)] mod tests { - use super::sandbox_env; + 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); + } + + #[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() diff --git a/docs/setup-and-install.md b/docs/setup-and-install.md index 911e584b..bade2b73 100644 --- a/docs/setup-and-install.md +++ b/docs/setup-and-install.md @@ -377,7 +377,7 @@ therefore the BaseContainer strict proxy 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/docs/windows-mxc-1.md b/docs/windows-mxc-1.md index f17ecfc3..e500680b 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. diff --git a/e2e/linux/test_sandbox.sh b/e2e/linux/test_sandbox.sh index ee8bdd6c..5c62fd4b 100755 --- a/e2e/linux/test_sandbox.sh +++ b/e2e/linux/test_sandbox.sh @@ -500,6 +500,128 @@ else fail "timeout stops long-running sandbox (status=$timeout_status elapsed=${elapsed}s started=$timeout_started)" fi +echo "--- axis run does not use 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" +stall_connections="${stall_dir}/connections" +python3 - "$stall_socket" "$stall_connections" <<'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: + continue + with open(sys.argv[2], "a") as f: + f.write("accepted\n") +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 [ -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 + 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 "--- 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 1e4f8d5d..a4be235d 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")