Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

perf(runtime,guest): lazy SendInput and in-memory init exit check (#3241)

lfld287626390f79f6c
diff --git a/docs/contributing/architecture/README.md b/docs/contributing/architecture/README.md
index 0ce6b6a2a..245a835fd 100644
--- a/docs/contributing/architecture/README.md
+++ b/docs/contributing/architecture/README.md
@@ -492,6 +492,20 @@ service Execution {
}
```
+### Execution streams and init exit status
+
+The host opens the `SendInput` stream only when stdin first receives data or its
+sender closes. Closing stdin without writing still sends an explicit EOF frame.
+Read-only attaches never open `SendInput`. The host drives stdin alongside `Wait`
+in one task, but a `Wait` result does not stop stdin forwarding: descendants may
+still be using stdin after the original process exits.
+
+Before starting a container command, the guest checks the init process's exit
+slot in memory. The reaper fills that slot before the exit action writes the
+shared exit file, so `Exec` can reject a stopped container with its init exit
+code without touching virtiofs. The shared exit file remains a durable record
+for the host.
+
### Initialization sequence
```text
diff --git a/src/boxlite/src/portal/interfaces/exec.rs b/src/boxlite/src/portal/interfaces/exec.rs
index 28ce1afa2..1ae45f552 100644
--- a/src/boxlite/src/portal/interfaces/exec.rs
+++ b/src/boxlite/src/portal/interfaces/exec.rs
@@ -12,7 +12,6 @@ use boxlite_shared::{
ExecutionClient, KillRequest, WaitRequest, WaitResponse, exec_output,
};
use tokio::sync::mpsc;
-use tokio_stream::wrappers::ReceiverStream;
use tokio_util::sync::CancellationToken;
use tonic::transport::Channel;
@@ -25,8 +24,7 @@ pub struct ExecutionInterface {
/// Components for building an Execution.
pub struct ExecComponents {
pub execution_id: String,
- /// `None` for a read-only attach: no stdin pump was spawned, so there is
- /// no sender for the caller to write into.
+ /// `None` for a read-only attach, which has no stdin writer.
pub stdin_tx: Option<mpsc::UnboundedSender<Vec<u8>>>,
pub stdout_rx: mpsc::UnboundedReceiver<String>,
pub stderr_rx: mpsc::UnboundedReceiver<String>,
@@ -91,7 +89,13 @@ impl ExecutionInterface {
shutdown: CancellationToken,
) -> mpsc::UnboundedReceiver<ExecResult> {
let (tx, rx) = mpsc::unbounded_channel();
- ExecProtocol::spawn_wait(self.client.clone(), execution_id.to_owned(), tx, shutdown);
+ ExecProtocol::spawn_wait(
+ self.client.clone(),
+ execution_id.to_owned(),
+ tx,
+ shutdown,
+ None,
+ );
rx
}
@@ -126,14 +130,6 @@ impl ExecutionInterface {
tracing::debug!(execution_id = %execution_id, "spawning background streams");
- // Spawn stdin pump (cancellable — exits cleanly during shutdown)
- ExecProtocol::spawn_stdin(
- self.client.clone(),
- execution_id.clone(),
- stdin_rx,
- shutdown_token.clone(),
- );
-
// Spawn attach fanout (cancellable)
let output_drops = ExecProtocol::spawn_attach(
self.client.clone(),
@@ -144,12 +140,13 @@ impl ExecutionInterface {
None,
);
- // Spawn wait task for terminal status (cancellable)
+ // Drive optional stdin from the existing wait task.
ExecProtocol::spawn_wait(
self.client.clone(),
execution_id.clone(),
result_tx,
shutdown_token,
+ Some(stdin_rx),
);
Ok(ExecComponents {
@@ -201,17 +198,11 @@ impl ExecutionInterface {
})?
.into_inner();
- let stdin_tx = if wire_stdin {
- let (stdin_tx, stdin_rx) = mpsc::unbounded_channel::<Vec<u8>>();
- ExecProtocol::spawn_stdin(
- self.client.clone(),
- execution_id.clone(),
- stdin_rx,
- shutdown_token.clone(),
- );
- Some(stdin_tx)
+ let (stdin_tx, stdin_rx) = if wire_stdin {
+ let (tx, rx) = mpsc::unbounded_channel();
+ (Some(tx), Some(rx))
} else {
- None
+ (None, None)
};
let output_drops = ExecProtocol::spawn_attach(
@@ -227,6 +218,7 @@ impl ExecutionInterface {
execution_id.clone(),
result_tx,
shutdown_token,
+ stdin_rx,
);
Ok(ExecComponents {
@@ -574,102 +566,84 @@ impl ExecProtocol {
}
fn spawn_wait(
- mut client: ExecutionClient<Channel>,
+ client: ExecutionClient<Channel>,
execution_id: String,
result_tx: mpsc::UnboundedSender<ExecResult>,
shutdown_token: CancellationToken,
+ stdin_rx: Option<mpsc::UnboundedReceiver<Vec<u8>>>,
) {
tokio::spawn(async move {
- let request = WaitRequest {
- execution_id: execution_id.clone(),
- };
-
- tracing::debug!(execution_id = %execution_id, "wait: sending request");
+ let wait =
+ Self::wait_for_exit(client.clone(), &execution_id, result_tx, &shutdown_token);
+ if let Some(stdin_rx) = stdin_rx {
+ let stdin = Self::send_stdin(client, &execution_id, stdin_rx, &shutdown_token);
+ // Wait reports the first process's exit, not that its
+ // descendants have closed stdin. Keep serving the input
+ // handle so dropping it can still deliver EOF after Wait.
+ tokio::join!(biased; wait, stdin);
+ } else {
+ wait.await;
+ }
+ });
+ }
- // Use select! to handle cancellation during wait
- let result = tokio::select! {
- biased;
- _ = shutdown_token.cancelled() => {
- tracing::debug!(execution_id = %execution_id, "Wait cancelled during shutdown");
- // Preserve the shutdown sentinel used by the main-session
- // exit-file fallback when the guest connection closes.
- let _ = result_tx.send(ExecResult { exit_code: -1, error_message: None });
- return;
- }
- _ = result_tx.closed() => {
- tracing::debug!(execution_id = %execution_id, "Wait cancelled after last receiver dropped");
- return;
- }
- result = client.wait(request) => result,
- };
+ async fn wait_for_exit(
+ mut client: ExecutionClient<Channel>,
+ execution_id: &str,
+ result_tx: mpsc::UnboundedSender<ExecResult>,
+ shutdown_token: &CancellationToken,
+ ) {
+ let result = tokio::select! {
+ biased;
+ _ = shutdown_token.cancelled() => {
+ // Preserve the shutdown sentinel used by the main-session
+ // exit-file fallback when the guest connection closes.
+ let _ = result_tx.send(ExecResult { exit_code: -1, error_message: None });
+ return;
+ }
+ _ = result_tx.closed() => return,
+ result = client.wait(WaitRequest { execution_id: execution_id.to_owned() }) => result,
+ };
- match result {
- Ok(resp) => {
- let mapped = Self::map_wait_response(resp.into_inner());
- let _ = result_tx.send(mapped);
- }
- Err(e) => {
- tracing::warn!(
- execution_id = %execution_id,
- error = %e,
- "Wait failed"
- );
- }
+ match result {
+ Ok(resp) => {
+ let _ = result_tx.send(Self::map_wait_response(resp.into_inner()));
}
- });
+ Err(error) => {
+ tracing::warn!(%execution_id, %error, "Wait failed");
+ }
+ }
}
- fn spawn_stdin(
+ async fn send_stdin(
mut client: ExecutionClient<Channel>,
- execution_id: String,
+ execution_id: &str,
mut stdin_rx: mpsc::UnboundedReceiver<Vec<u8>>,
- shutdown_token: CancellationToken,
+ shutdown_token: &CancellationToken,
) {
- tokio::spawn(async move {
- tracing::debug!(execution_id = %execution_id, "stdin: starting stream");
- let (tx, rx) = mpsc::channel::<ExecStdin>(8);
-
- // Producer: forward stdin channel into tonic stream
- let exec_id_clone = execution_id.clone();
- tokio::spawn(async move {
- while let Some(data) = stdin_rx.recv().await {
- let msg = ExecStdin {
- execution_id: exec_id_clone.clone(),
- data,
- close: false,
- };
- if tx.send(msg).await.is_err() {
- return;
- }
- }
-
- // Signal stdin close
- let _ = tx
- .send(ExecStdin {
- execution_id: exec_id_clone,
- data: Vec::new(),
- close: true,
- })
- .await;
- });
-
- let stream = ReceiverStream::new(rx);
- tokio::select! {
- biased;
- _ = shutdown_token.cancelled() => {
- tracing::debug!(execution_id = %execution_id, "SendInput cancelled during shutdown");
- }
- result = client.send_input(stream) => {
- if let Err(e) = result {
- tracing::warn!(
- execution_id = %execution_id,
- error = %e,
- "SendInput failed"
- );
+ tokio::select! {
+ biased;
+ _ = shutdown_token.cancelled() => {}
+ result = async {
+ // Wait for data or EOF before opening the HTTP/2 stream. A
+ // sender closed before any write still needs a close frame.
+ let first = stdin_rx.recv().await;
+ let id = execution_id.to_owned();
+ let stream = async_stream::stream! {
+ let mut next = first;
+ while let Some(data) = next {
+ yield ExecStdin { execution_id: id.clone(), data, close: false };
+ next = stdin_rx.recv().await;
}
+ yield ExecStdin { execution_id: id, data: Vec::new(), close: true };
+ };
+ client.send_input(stream).await
+ } => {
+ if let Err(error) = result {
+ tracing::warn!(%execution_id, %error, "SendInput failed");
}
}
- });
+ }
}
}
diff --git a/src/boxlite/src/portal/interfaces/exec/tests.rs b/src/boxlite/src/portal/interfaces/exec/tests.rs
index 51c450db2..c159b5809 100644
--- a/src/boxlite/src/portal/interfaces/exec/tests.rs
+++ b/src/boxlite/src/portal/interfaces/exec/tests.rs
@@ -4,8 +4,11 @@ use boxlite_shared::{
ListExecutionsRequest, ListExecutionsResponse, ResizeTtyRequest, ResizeTtyResponse,
SendInputAck,
};
+use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::{future::Future, pin::Pin, time::Duration};
use tokio::sync::oneshot;
+use tokio_stream::StreamExt;
use tonic::{Request, Response, Status, Streaming};
#[derive(Debug)]
@@ -28,12 +31,23 @@ impl Drop for CancelOnDrop {
struct RecordingExecutionService {
waits: mpsc::UnboundedSender<WaitCall>,
attaches: mpsc::UnboundedSender<(String, oneshot::Receiver<()>)>,
+ attach_pending: Arc<AtomicBool>,
+ send_input_started: mpsc::UnboundedSender<()>,
+ send_input_calls: Arc<AtomicUsize>,
+ send_input_frames: mpsc::UnboundedSender<ExecStdin>,
+ send_input_stream_ended: mpsc::UnboundedSender<()>,
+ fail_send_input: Arc<AtomicBool>,
}
#[tonic::async_trait]
impl ExecutionService for RecordingExecutionService {
async fn exec(&self, _: Request<ExecRequest>) -> Result<Response<ExecResponse>, Status> {
- Err(Status::unimplemented("exec is not used by these tests"))
+ Ok(Response::new(ExecResponse {
+ execution_id: "exec-1".to_string(),
+ pid: 100,
+ started_at_ms: 1,
+ error: None,
+ }))
}
async fn list_executions(
@@ -55,14 +69,36 @@ impl ExecutionService for RecordingExecutionService {
self.attaches
.send((request.into_inner().execution_id, cancelled))
.expect("attach recorder must remain open");
- std::future::pending().await
+ if self.attach_pending.load(Ordering::SeqCst) {
+ std::future::pending().await
+ } else {
+ let stream: Self::AttachStream = Box::pin(futures::stream::pending());
+ Ok(Response::new(stream))
+ }
}
async fn send_input(
&self,
- _: Request<Streaming<ExecStdin>>,
+ request: Request<Streaming<ExecStdin>>,
) -> Result<Response<SendInputAck>, Status> {
- Err(Status::unimplemented("stdin is not used by these tests"))
+ self.send_input_calls.fetch_add(1, Ordering::SeqCst);
+ let _ = self.send_input_started.send(());
+
+ if self.fail_send_input.load(Ordering::SeqCst) {
+ return Err(Status::internal("mock send_input failure"));
+ }
+
+ let mut stream = request.into_inner();
+ while let Some(item) = stream.next().await {
+ match item {
+ Ok(frame) => {
+ let _ = self.send_input_frames.send(frame);
+ }
+ Err(_) => break,
+ }
+ }
+ let _ = self.send_input_stream_ended.send(());
+ Ok(Response::new(SendInputAck {}))
}
async fn wait(&self, request: Request<WaitRequest>) -> Result<Response<WaitResponse>, Status> {
@@ -97,6 +133,12 @@ struct RpcFixture {
interface: ExecutionInterface,
waits: mpsc::UnboundedReceiver<WaitCall>,
attaches: mpsc::UnboundedReceiver<(String, oneshot::Receiver<()>)>,
+ attach_pending: Arc<AtomicBool>,
+ send_input_started: mpsc::UnboundedReceiver<()>,
+ send_input_calls: Arc<AtomicUsize>,
+ send_input_frames: mpsc::UnboundedReceiver<ExecStdin>,
+ send_input_stream_ended: mpsc::UnboundedReceiver<()>,
+ fail_send_input: Arc<AtomicBool>,
server: tokio::task::JoinHandle<()>,
}
@@ -106,9 +148,21 @@ impl RpcFixture {
let address = listener.local_addr().unwrap();
let (waits_tx, waits) = mpsc::unbounded_channel();
let (attaches_tx, attaches) = mpsc::unbounded_channel();
+ let (send_input_started_tx, send_input_started) = mpsc::unbounded_channel();
+ let (send_input_frames_tx, send_input_frames) = mpsc::unbounded_channel();
+ let (send_input_stream_ended_tx, send_input_stream_ended) = mpsc::unbounded_channel();
+ let attach_pending = Arc::new(AtomicBool::new(true));
+ let send_input_calls = Arc::new(AtomicUsize::new(0));
+ let fail_send_input = Arc::new(AtomicBool::new(false));
let service = RecordingExecutionService {
waits: waits_tx,
attaches: attaches_tx,
+ attach_pending: Arc::clone(&attach_pending),
+ send_input_started: send_input_started_tx,
+ send_input_calls: Arc::clone(&send_input_calls),
+ send_input_frames: send_input_frames_tx,
+ send_input_stream_ended: send_input_stream_ended_tx,
+ fail_send_input: Arc::clone(&fail_send_input),
};
let incoming = futures::stream::unfold(listener, |listener| async move {
let connection = listener.accept().await.map(|(socket, _)| socket);
@@ -130,6 +184,12 @@ impl RpcFixture {
interface: ExecutionInterface::new(channel),
waits,
attaches,
+ attach_pending,
+ send_input_started,
+ send_input_calls,
+ send_input_frames,
+ send_input_stream_ended,
+ fail_send_input,
server,
}
}
@@ -290,3 +350,364 @@ async fn attach_existing_cancels_pending_claim_on_shutdown() {
Err(mpsc::error::TryRecvError::Empty)
));
}
+
+#[tokio::test]
+async fn lazy_stdin_opens_send_input_only_on_first_write_and_sends_eof_on_drop() {
+ let mut fixture = RpcFixture::new().await;
+ let shutdown = CancellationToken::new();
+ let mut components = within_deadline(
+ fixture
+ .interface
+ .exec(BoxCommand::new("/bin/cat"), shutdown),
+ )
+ .await
+ .unwrap();
+ let wait_call = fixture.next_wait().await;
+ assert_eq!(wait_call.execution_id, "exec-1");
+
+ // Give the background task a chance to poll; SendInput must stay unopened.
+ tokio::task::yield_now().await;
+ assert_eq!(fixture.send_input_calls.load(Ordering::SeqCst), 0);
+ assert!(fixture.send_input_started.try_recv().is_err());
+
+ let stdin_tx = components.stdin_tx.take().expect("exec must wire stdin");
+ stdin_tx.send(b"hello ".to_vec()).unwrap();
+ within_deadline(fixture.send_input_started.recv())
+ .await
+ .expect("first write must open SendInput RPC");
+
+ let frame1 = within_deadline(fixture.send_input_frames.recv())
+ .await
+ .unwrap();
+ assert_eq!(frame1.execution_id, "exec-1");
+ assert_eq!(frame1.data, b"hello ");
+ assert!(!frame1.close);
+
+ stdin_tx.send(b"world".to_vec()).unwrap();
+ let frame2 = within_deadline(fixture.send_input_frames.recv())
+ .await
+ .unwrap();
+ assert_eq!(frame2.execution_id, "exec-1");
+ assert_eq!(frame2.data, b"world");
+ assert!(!frame2.close);
+
+ drop(stdin_tx);
+ let eof = within_deadline(fixture.send_input_frames.recv())
+ .await
+ .unwrap();
+ assert_eq!(eof.execution_id, "exec-1");
+ assert!(eof.data.is_empty());
+ assert!(eof.close);
+ within_deadline(fixture.send_input_stream_ended.recv())
+ .await
+ .unwrap();
+
+ wait_call
+ .result
+ .send(Ok(WaitResponse {
+ exit_code: 0,
+ ..Default::default()
+ }))
+ .unwrap();
+ let result = within_deadline(components.result_rx.recv()).await.unwrap();
+ assert_eq!(result.exit_code, 0);
+ assert_eq!(fixture.send_input_calls.load(Ordering::SeqCst), 1);
+}
+
+#[tokio::test]
+async fn lazy_stdin_sends_single_eof_frame_when_closed_without_write() {
+ let mut fixture = RpcFixture::new().await;
+ let shutdown = CancellationToken::new();
+ let mut components = within_deadline(
+ fixture
+ .interface
+ .exec(BoxCommand::new("/bin/true"), shutdown),
+ )
+ .await
+ .unwrap();
+ let wait_call = fixture.next_wait().await;
+
+ assert_eq!(fixture.send_input_calls.load(Ordering::SeqCst), 0);
+
+ drop(components.stdin_tx.take().expect("exec must wire stdin"));
+ within_deadline(fixture.send_input_started.recv())
+ .await
+ .expect("dropping stdin_tx without write must open SendInput for EOF");
+
+ let eof = within_deadline(fixture.send_input_frames.recv())
+ .await
+ .unwrap();
+ assert_eq!(eof.execution_id, "exec-1");
+ assert!(eof.data.is_empty());
+ assert!(eof.close);
+ within_deadline(fixture.send_input_stream_ended.recv())
+ .await
+ .unwrap();
+ assert!(fixture.send_input_frames.try_recv().is_err());
+
+ wait_call
+ .result
+ .send(Ok(WaitResponse {
+ exit_code: 0,
+ ..Default::default()
+ }))
+ .unwrap();
+ let result = within_deadline(components.result_rx.recv()).await.unwrap();
+ assert_eq!(result.exit_code, 0);
+}
+
+#[tokio::test]
+async fn read_only_attach_and_wait_existing_never_invoke_send_input() {
+ let mut fixture = RpcFixture::new().await;
+ fixture.attach_pending.store(false, Ordering::SeqCst);
+ let shutdown = CancellationToken::new();
+
+ let ro_components = within_deadline(fixture.interface.attach_existing(
+ "ro-attach",
+ false,
+ shutdown.clone(),
+ ))
+ .await
+ .unwrap();
+ assert!(ro_components.stdin_tx.is_none());
+
+ let wait_ro = fixture.next_wait().await;
+ assert_eq!(wait_ro.execution_id, "ro-attach");
+ wait_ro
+ .result
+ .send(Ok(WaitResponse {
+ exit_code: 0,
+ ..Default::default()
+ }))
+ .unwrap();
+ let mut ro_result_rx = ro_components.result_rx;
+ assert_eq!(
+ within_deadline(ro_result_rx.recv())
+ .await
+ .unwrap()
+ .exit_code,
+ 0
+ );
+
+ let mut wait_only_rx = fixture.interface.wait_existing("wait-only", shutdown);
+ let wait_only = fixture.next_wait().await;
+ assert_eq!(wait_only.execution_id, "wait-only");
+ wait_only
+ .result
+ .send(Ok(WaitResponse {
+ exit_code: 7,
+ ..Default::default()
+ }))
+ .unwrap();
+ assert_eq!(
+ within_deadline(wait_only_rx.recv())
+ .await
+ .unwrap()
+ .exit_code,
+ 7
+ );
+
+ tokio::task::yield_now().await;
+ assert_eq!(fixture.send_input_calls.load(Ordering::SeqCst), 0);
+ assert!(fixture.send_input_started.try_recv().is_err());
+}
+
+#[tokio::test]
+async fn stdin_writes_and_eof_succeed_after_wait_returns() {
+ let mut fixture = RpcFixture::new().await;
+ let shutdown = CancellationToken::new();
+ let mut components =
+ within_deadline(fixture.interface.exec(BoxCommand::new("/bin/sh"), shutdown))
+ .await
+ .unwrap();
+ let wait_call = fixture.next_wait().await;
+
+ // Complete Wait before any stdin activity.
+ wait_call
+ .result
+ .send(Ok(WaitResponse {
+ exit_code: 0,
+ ..Default::default()
+ }))
+ .unwrap();
+ let result = within_deadline(components.result_rx.recv()).await.unwrap();
+ assert_eq!(result.exit_code, 0);
+ assert_eq!(fixture.send_input_calls.load(Ordering::SeqCst), 0);
+
+ // Background task must still be alive to forward stdin and EOF.
+ let stdin_tx = components.stdin_tx.take().unwrap();
+ stdin_tx.send(b"after-wait".to_vec()).unwrap();
+ within_deadline(fixture.send_input_started.recv())
+ .await
+ .unwrap();
+
+ let frame = within_deadline(fixture.send_input_frames.recv())
+ .await
+ .unwrap();
+ assert_eq!(frame.data, b"after-wait");
+ assert!(!frame.close);
+
+ drop(stdin_tx);
+ let eof = within_deadline(fixture.send_input_frames.recv())
+ .await
+ .unwrap();
+ assert!(eof.data.is_empty());
+ assert!(eof.close);
+ within_deadline(fixture.send_input_stream_ended.recv())
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn closing_stdin_without_write_after_wait_returns_sends_eof() {
+ let mut fixture = RpcFixture::new().await;
+ let shutdown = CancellationToken::new();
+ let mut components =
+ within_deadline(fixture.interface.exec(BoxCommand::new("/bin/sh"), shutdown))
+ .await
+ .unwrap();
+ let wait_call = fixture.next_wait().await;
+
+ // Complete Wait before any stdin activity.
+ wait_call
+ .result
+ .send(Ok(WaitResponse {
+ exit_code: 0,
+ ..Default::default()
+ }))
+ .unwrap();
+ let result = within_deadline(components.result_rx.recv()).await.unwrap();
+ assert_eq!(result.exit_code, 0);
+ assert_eq!(fixture.send_input_calls.load(Ordering::SeqCst), 0);
+
+ // Dropping stdin_tx without writing after Wait must still open SendInput for EOF.
+ drop(components.stdin_tx.take().unwrap());
+ within_deadline(fixture.send_input_started.recv())
+ .await
+ .unwrap();
+
+ let eof = within_deadline(fixture.send_input_frames.recv())
+ .await
+ .unwrap();
+ assert!(eof.data.is_empty());
+ assert!(eof.close);
+ within_deadline(fixture.send_input_stream_ended.recv())
+ .await
+ .unwrap();
+ assert!(fixture.send_input_frames.try_recv().is_err());
+}
+
+#[tokio::test]
+async fn shutdown_cancels_wait_with_sentinel_and_exits_blocked_send_stdin() {
+ // Subcase 1: send_stdin blocked before first write when shutdown fires.
+ let mut fixture = RpcFixture::new().await;
+ let shutdown = CancellationToken::new();
+ let mut components = within_deadline(
+ fixture
+ .interface
+ .exec(BoxCommand::new("/bin/sleep"), shutdown.clone()),
+ )
+ .await
+ .unwrap();
+ let wait_call = fixture.next_wait().await;
+
+ shutdown.cancel();
+ let sentinel = within_deadline(components.result_rx.recv())
+ .await
+ .expect("shutdown must deliver sentinel ExecResult");
+ assert_eq!(sentinel.exit_code, -1);
+ assert_eq!(sentinel.error_message, None);
+ within_deadline(wait_call.cancelled)
+ .await
+ .expect("shutdown must cancel Wait RPC");
+ within_deadline(components.stdin_tx.as_ref().unwrap().closed()).await;
+ assert_eq!(fixture.send_input_calls.load(Ordering::SeqCst), 0);
+
+ // Subcase 2: send_stdin actively streaming when shutdown fires.
+ let mut fixture2 = RpcFixture::new().await;
+ let shutdown2 = CancellationToken::new();
+ let mut components2 = within_deadline(
+ fixture2
+ .interface
+ .exec(BoxCommand::new("/bin/cat"), shutdown2.clone()),
+ )
+ .await
+ .unwrap();
+ let wait_call2 = fixture2.next_wait().await;
+ let stdin_tx = components2.stdin_tx.take().unwrap();
+ stdin_tx.send(b"partial".to_vec()).unwrap();
+ within_deadline(fixture2.send_input_started.recv())
+ .await
+ .unwrap();
+ let frame = within_deadline(fixture2.send_input_frames.recv())
+ .await
+ .unwrap();
+ assert_eq!(frame.data, b"partial");
+
+ shutdown2.cancel();
+ let sentinel2 = within_deadline(components2.result_rx.recv()).await.unwrap();
+ assert_eq!(sentinel2.exit_code, -1);
+ assert_eq!(sentinel2.error_message, None);
+ within_deadline(wait_call2.cancelled).await.unwrap();
+ within_deadline(fixture2.send_input_stream_ended.recv())
+ .await
+ .expect("cancelling shutdown must terminate active SendInput stream");
+}
+
+#[tokio::test]
+async fn dropping_result_rx_cancels_wait_for_exit_without_hanging() {
+ let mut fixture = RpcFixture::new().await;
+ let shutdown = CancellationToken::new();
+ let components = within_deadline(
+ fixture
+ .interface
+ .exec(BoxCommand::new("/bin/cat"), shutdown),
+ )
+ .await
+ .unwrap();
+ let wait_call = fixture.next_wait().await;
+
+ drop(components.result_rx);
+ within_deadline(wait_call.cancelled)
+ .await
+ .expect("dropping result_rx must cancel wait_for_exit");
+
+ drop(components.stdin_tx);
+ let eof = within_deadline(fixture.send_input_frames.recv())
+ .await
+ .unwrap();
+ assert!(eof.close);
+ within_deadline(fixture.send_input_stream_ended.recv())
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn wait_and_send_input_rpc_errors_complete_cleanly() {
+ let mut fixture = RpcFixture::new().await;
+ fixture.fail_send_input.store(true, Ordering::SeqCst);
+ let shutdown = CancellationToken::new();
+ let mut components = within_deadline(
+ fixture
+ .interface
+ .exec(BoxCommand::new("/bin/cat"), shutdown),
+ )
+ .await
+ .unwrap();
+ let wait_call = fixture.next_wait().await;
+
+ // Trigger SendInput error path.
+ let stdin_tx = components.stdin_tx.take().unwrap();
+ stdin_tx.send(b"x".to_vec()).unwrap();
+ within_deadline(fixture.send_input_started.recv())
+ .await
+ .unwrap();
+ within_deadline(stdin_tx.closed()).await;
+
+ // Trigger Wait error path: result_rx closes with no ExecResult.
+ wait_call
+ .result
+ .send(Err(Status::unavailable("transport closed")))
+ .unwrap();
+ assert!(within_deadline(components.result_rx.recv()).await.is_none());
+}
diff --git a/src/guest/src/service/exec/mod.rs b/src/guest/src/service/exec/mod.rs
index d62d2efe9..9efd7fb78 100644
--- a/src/guest/src/service/exec/mod.rs
+++ b/src/guest/src/service/exec/mod.rs
@@ -69,7 +69,7 @@ impl GuestServer {
&self,
exec_id: &str,
) -> Result<mpsc::Receiver<Result<ExecOutput, Status>>, ExecutionError> {
- info!(execution_id = %exec_id, "attach request");
+ debug!(execution_id = %exec_id, "attach request");
match self.execution_lookup(exec_id).await? {
ExecutionLookup::Live(state) => match state.attach(exec_id).await {
Ok(output) => Ok(output),
@@ -358,6 +358,17 @@ async fn start_execution(
};
let reservation = if ssh_workload.is_some() {
+ if server
+ .shutting_down
+ .load(std::sync::atomic::Ordering::SeqCst)
+ || server.registry.is_shutting_down().await
+ {
+ return error_response(
+ execution_id,
+ "execution_cancelled",
+ "Execution registry is shutting down",
+ );
+ }
if server.registry.exists(&execution_id).await {
return error_response(execution_id, "execution_exists", "Execution already exists");
}
@@ -633,9 +644,8 @@ async fn spawn_with_executor(
format!("Invalid {}: missing container_id", executor_const::ENV_VAR),
));
}
- // Caller-controllable (a client can override BOXLITE_EXECUTOR in its
- // exec env) and joined into a filesystem path below, so require a
- // single normal component — `..`/`/…` must not escape containers/.
+ // BOXLITE_EXECUTOR can be overridden by the caller. Require the
+ // same single-component ID shape as the container's state paths.
if !is_single_path_component(container_id) {
return Err(spawn_error(
execution_id,
@@ -650,26 +660,6 @@ async fn spawn_with_executor(
container_id = %container_id,
"Using ContainerExecutor"
);
- // Refuse cleanly when the container's init has already exited
- // (docker semantics: no exec in a stopped container). Without
- // this, the tenant build reaches libcontainer against a dead
- // init and surfaces an opaque procfs internal error.
- //
- // Presence is the signal, not parseability: a torn record still
- // means init is gone, and letting a bad parse fall through here
- // would hand the exec straight back to the panic.
- let exit_file = server.layout.shared().container(container_id).exit_file();
- if exit_file.exists() {
- let how = boxlite_shared::layout::ExitRecord::read(&exit_file).map_or_else(
- || "init exited".to_string(),
- |record| format!("init exited with code {}", record.exit_code),
- );
- return Err(spawn_error(
- execution_id,
- format!("container is not running: {how}"),
- ));
- }
-
// Look up container from registry
let container_arc = {
let containers_guard = server.containers.lock().await;
@@ -680,6 +670,14 @@ async fn spawn_with_executor(
)
})?
};
+ // The reaper fills the slot before the exit action writes to
+ // virtiofs. No exec in a container whose init has exited.
+ if let Some(code) = server.init_exit_code(container_id).await {
+ return Err(spawn_error(
+ execution_id,
+ format!("container is not running: init exited with code {code}"),
+ ));
+ }
let executor = ContainerExecutor::new(container_arc);
let container_ref = executor.container_ref();
let spawn = match ssh_workload.as_ref() {
@@ -894,6 +892,45 @@ mod container_id_path_tests {
);
}
+ #[tokio::test]
+ async fn ssh_execution_is_rejected_before_spawn_when_shutting_down() {
+ use crate::service::ssh::SshWorkload;
+ use boxlite_shared::ExecRequest;
+ use std::collections::HashMap;
+ use std::sync::atomic::Ordering;
+
+ let make_req = |id: &str| ExecRequest {
+ execution_id: Some(id.to_string()),
+ program: "boxlite-internal:ssh".to_string(),
+ args: Vec::new(),
+ env: HashMap::from([("BOXLITE_EXECUTOR".to_string(), "container=c1".to_string())]),
+ workdir: "/".to_string(),
+ timeout_ms: 0,
+ tty: None,
+ user: None,
+ };
+
+ let server = GuestServer::new(GuestLayout::new());
+ server.shutting_down.store(true, Ordering::SeqCst);
+ let response =
+ super::start_ssh_execution(&server, make_req("ssh-1"), SshWorkload::Shell).await;
+ let error = response
+ .error
+ .expect("shutting_down flag must reject ssh exec");
+ assert_eq!(error.reason, "execution_cancelled");
+ assert_eq!(error.detail, "Execution registry is shutting down");
+
+ let server = GuestServer::new(GuestLayout::new());
+ server.registry.shutdown_all(0).await;
+ let response =
+ super::start_ssh_execution(&server, make_req("ssh-2"), SshWorkload::Shell).await;
+ let error = response
+ .error
+ .expect("registry shutdown must reject ssh exec");
+ assert_eq!(error.reason, "execution_cancelled");
+ assert_eq!(error.detail, "Execution registry is shutting down");
+ }
+
/// A failure that is not a command refusal still reaches the host as an error.
#[tokio::test]
async fn guest_executor_spawn_failure_is_reported_as_an_error() {
@@ -1332,4 +1369,71 @@ mod container_id_path_tests {
assert!(stdout.data.is_empty());
assert_eq!(stdout.total_bytes, Some(0));
}
+
+ #[tokio::test]
+ async fn spawn_with_executor_rejects_exec_when_container_init_exited() {
+ use super::spawn_with_executor;
+ use crate::container::Container;
+ use boxlite_shared::constants::executor as executor_const;
+ use boxlite_shared::ExecRequest;
+ use nix::sys::signal::Signal;
+ use std::collections::HashMap;
+ use std::sync::Arc;
+ use tokio::sync::Mutex;
+
+ for (container_id, status, expected_code) in [
+ ("init-exited-code", ExitStatus::Code(42), 42),
+ (
+ "init-exited-sigterm",
+ ExitStatus::Signal(Signal::SIGTERM),
+ 143,
+ ),
+ (
+ "init-exited-sigkill",
+ ExitStatus::Signal(Signal::SIGKILL),
+ 137,
+ ),
+ ] {
+ let server = GuestServer::new(GuestLayout::new());
+ let dir = tempfile::tempdir().unwrap();
+ let container = Container::for_unit_test(
+ container_id,
+ dir.path().to_path_buf(),
+ dir.path().join("bundle"),
+ );
+ server
+ .containers
+ .lock()
+ .await
+ .insert(container_id.to_string(), Arc::new(Mutex::new(container)));
+ server
+ .init_exits
+ .lock()
+ .await
+ .insert(container_id.to_string(), ExitSlot::settled(status));
+
+ let mut env = HashMap::new();
+ env.insert(
+ executor_const::ENV_VAR.to_string(),
+ format!("{}={container_id}", executor_const::CONTAINER_KEY),
+ );
+ let req = ExecRequest {
+ program: "/bin/sh".to_string(),
+ args: vec![],
+ env,
+ ..Default::default()
+ };
+
+ let err = match spawn_with_executor(&server, &req, "exec-1", None).await {
+ Ok(_) => panic!("exec must be rejected once container init has exited"),
+ Err(err) => err,
+ };
+ let exec_err = err.error.expect("rejection must include ExecError");
+ assert_eq!(exec_err.reason, "spawn_failed");
+ assert_eq!(
+ exec_err.detail,
+ format!("container is not running: init exited with code {expected_code}")
+ );
+ }
+ }
}
diff --git a/src/guest/src/service/exec/registry.rs b/src/guest/src/service/exec/registry.rs
index 182ad738f..e80cca5d0 100644
--- a/src/guest/src/service/exec/registry.rs
+++ b/src/guest/src/service/exec/registry.rs
@@ -222,6 +222,11 @@ impl ExecutionRegistry {
self.inner.lock().await.entries.contains_key(exec_id)
}
+ /// Check if the registry is shutting down.
+ pub async fn is_shutting_down(&self) -> bool {
+ self.inner.lock().await.is_shutting_down
+ }
+
/// Get execution state.
pub async fn get(&self, exec_id: &str) -> Option<ExecutionState> {
match self.lookup(exec_id).await {
diff --git a/src/guest/src/service/exec/state.rs b/src/guest/src/service/exec/state.rs
index 60bff4c7b..0429e6b96 100644
--- a/src/guest/src/service/exec/state.rs
+++ b/src/guest/src/service/exec/state.rs
@@ -465,7 +465,7 @@ impl ExecutionState {
break;
}
}
- tracing::info!(%execution_id, "execution output forwarding ended");
+ tracing::debug!(%execution_id, "execution output forwarding ended");
});
let (task_to_abort, displaced) = {
diff --git a/src/guest/src/service/guest.rs b/src/guest/src/service/guest.rs
index 7228596e5..805d1bb40 100644
--- a/src/guest/src/service/guest.rs
+++ b/src/guest/src/service/guest.rs
@@ -143,7 +143,13 @@ impl GuestService for GuestServer {
// the record is on disk before the RPC returns and the host reads the
// exit file (its `stop()` reports that code as the box's exit status —
// docker leaves ExitCode 137 after a `docker stop`).
- let init_exits: Vec<_> = self.init_exits.lock().await.drain().collect();
+ let init_exits: Vec<_> = self
+ .init_exits
+ .lock()
+ .await
+ .iter()
+ .map(|(id, slot)| (id.clone(), slot.clone()))
+ .collect();
for (container_id, exit_slot) in init_exits {
match tokio::time::timeout(
std::time::Duration::from_millis(CONTAINER_SHUTDOWN_TIMEOUT_MS),
@@ -529,6 +535,32 @@ mod tests {
assert_eq!(written.map(|record| record.exit_code), Some(7));
}
+ /// Shutdown must keep `init_exits` populated so concurrent or subsequent
+ /// `init_exit_code` lookups still observe the container's exit status.
+ #[tokio::test]
+ async fn shutdown_preserves_init_exits_after_writing_exit_records() {
+ crate::test_syscalls::deny(nix::libc::SYS_sync);
+ let root = tempfile::tempdir().expect("tempdir");
+ let server = GuestServer::new(GuestLayout::with_base(root.path()));
+ let exit_file = server.layout.shared().container("c1").exit_file();
+ std::fs::create_dir_all(exit_file.parent().expect("container root"))
+ .expect("container dir");
+ server
+ .init_exits
+ .lock()
+ .await
+ .insert("c1".to_string(), ExitSlot::settled(ExitStatus::Code(7)));
+
+ server
+ .shutdown(Request::new(ShutdownRequest {}))
+ .await
+ .expect("shutdown succeeds");
+
+ assert_eq!(server.init_exit_code("c1").await, Some(7));
+ let written = boxlite_shared::layout::ExitRecord::read(&exit_file);
+ assert_eq!(written.map(|record| record.exit_code), Some(7));
+ }
+
/// Structural bounds only: a bad subsecond part or a pre-epoch instant
/// are rejected, while past instants, today's host time, and stamps far
/// ahead (a long host suspend) are accepted unchanged.
diff --git a/src/guest/src/service/server.rs b/src/guest/src/service/server.rs
index 9e0792577..0239c8aac 100644
--- a/src/guest/src/service/server.rs
+++ b/src/guest/src/service/server.rs
@@ -84,6 +84,20 @@ impl GuestServer {
}
}
+ /// In-memory exit status for Exec admission. The shared exit file is only
+ /// a durable record for the host, not a guest-side liveness probe.
+ pub(super) async fn init_exit_code(&self, container_id: &str) -> Option<i32> {
+ let exit = self
+ .init_exits
+ .lock()
+ .await
+ .get(container_id)
+ .filter(|slot| slot.has_exited())
+ .cloned()?;
+ // Once populated, the slot never clears, so get() will not wait.
+ Some(exit.get().await.shell_code())
+ }
+
/// Run the tonic server listening on the specified transport.
///
/// Binds to the specified transport (Unix, TCP, or Vsock) and serves
@@ -341,6 +355,10 @@ fn is_host_vsock_peer(peer: tokio_vsock::VsockAddr) -> bool {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::reaper::ExitSlot;
+ use crate::service::exec::exec_handle::ExitStatus;
+ use nix::sys::signal::Signal;
+ use std::time::Duration;
use tokio_vsock::{VsockAddr, VMADDR_CID_HOST, VMADDR_CID_LOCAL};
#[test]
@@ -349,4 +367,51 @@ mod tests {
assert!(!is_host_vsock_peer(VsockAddr::new(VMADDR_CID_LOCAL, 1234)));
assert!(!is_host_vsock_peer(VsockAddr::new(42, 1234)));
}
+
+ #[tokio::test]
+ async fn init_exit_code_returns_none_for_unknown_and_pending_slots() {
+ let server = GuestServer::new(GuestLayout::new());
+ assert_eq!(server.init_exit_code("unknown-container").await, None);
+
+ let (pending_slot, _tx) = ExitSlot::pending_for_test();
+ server
+ .init_exits
+ .lock()
+ .await
+ .insert("pending-container".to_string(), pending_slot);
+
+ let result = tokio::time::timeout(
+ Duration::from_millis(50),
+ server.init_exit_code("pending-container"),
+ )
+ .await
+ .expect("init_exit_code must not block on a pending ExitSlot");
+ assert_eq!(result, None);
+ }
+
+ #[tokio::test]
+ async fn init_exit_code_maps_normal_and_signal_exit_statuses() {
+ let server = GuestServer::new(GuestLayout::new());
+ {
+ let mut exits = server.init_exits.lock().await;
+ exits.insert("c-zero".to_string(), ExitSlot::settled(ExitStatus::Code(0)));
+ exits.insert(
+ "c-code".to_string(),
+ ExitSlot::settled(ExitStatus::Code(42)),
+ );
+ exits.insert(
+ "c-sigterm".to_string(),
+ ExitSlot::settled(ExitStatus::Signal(Signal::SIGTERM)),
+ );
+ exits.insert(
+ "c-sigkill".to_string(),
+ ExitSlot::settled(ExitStatus::Signal(Signal::SIGKILL)),
+ );
+ }
+
+ assert_eq!(server.init_exit_code("c-zero").await, Some(0));
+ assert_eq!(server.init_exit_code("c-code").await, Some(42));
+ assert_eq!(server.init_exit_code("c-sigterm").await, Some(143));
+ assert_eq!(server.init_exit_code("c-sigkill").await, Some(137));
+ }
}