The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
perf(portal): reduce Unix socket initial retry backoff to 1ms (#3163)
lfld28774f61504f714
diff --git a/docs/contributing/architecture/README.md b/docs/contributing/architecture/README.mdindex e13a011f4..d53d90f29 100644--- a/docs/contributing/architecture/README.md+++ b/docs/contributing/architecture/README.md@@ -276,8 +276,10 @@ gRPC-based communication layer between host and guest.Guest-ready confirms the guest agent's listener, while libkrun initializes thehost Unix listener asynchronously. The portal attempts to connect immediately,-then retries missing or refused sockets with asynchronous backoff from 10 ms to-100 ms, bounded by the existing 30-second connection timeout.+then retries missing or refused sockets with asynchronous exponential backoff+starting at 1 ms and doubling up to 100 ms, bounded by the 30-second connection+timeout. Starting at 1 ms avoids a coarse initial wait when the host listener+appears within a few milliseconds of guest-ready.Other connection errors return immediately. A socket that never becomesconnectable reaches the timeout; the retry covers connection establishment anddiff --git a/src/boxlite/src/portal/connection.rs b/src/boxlite/src/portal/connection.rsindex 30bdb997b..1e990b276 100644--- a/src/boxlite/src/portal/connection.rs+++ b/src/boxlite/src/portal/connection.rs@@ -2,15 +2,21 @@//!//! Converts BoxTransport to tonic Channel with lazy initialization.+use std::io::{self, ErrorKind};+use std::path::Path;use std::sync::Arc;use std::time::Duration;use boxlite_shared::{BoxTransport, BoxliteError, BoxliteResult};use hyper_util::rt::TokioIo;+use tokio::net::UnixStream;use tokio::sync::OnceCell;use tonic::transport::{Channel, Endpoint, Uri};use tower::service_fn;+const INITIAL_CONNECT_RETRY_DELAY: Duration = Duration::from_millis(1);+const MAX_CONNECT_RETRY_DELAY: Duration = Duration::from_millis(100);+/// Lazy connection to guest.////// Connects on first use to ensure connection happens in the correct async runtime.@@ -58,35 +64,14 @@ async fn connect_transport(transport: &BoxTransport) -> BoxliteResult<Channel> {}}-async fn connect_unix(socket_path: &std::path::Path) -> BoxliteResult<Channel> {+async fn connect_unix(socket_path: &Path) -> BoxliteResult<Channel> {let socket_path = socket_path.to_path_buf();let channel = Endpoint::try_from("http://[::]:50051")?.connect_timeout(Duration::from_secs(30)).connect_with_connector(service_fn(move |_: Uri| {let socket_path = socket_path.clone();- async move {- // Guest-ready can precede libkrun's host listener. Retry only- // connection establishment; tonic's connect_timeout bounds- // this entire future, including every asynchronous backoff.- let mut retry_delay = Duration::from_millis(10);- loop {- match tokio::net::UnixStream::connect(&socket_path).await {- Ok(stream) => return Ok::<_, std::io::Error>(TokioIo::new(stream)),- Err(error)- if matches!(- error.kind(),- std::io::ErrorKind::NotFound- | std::io::ErrorKind::ConnectionRefused- ) =>- {- tokio::time::sleep(retry_delay).await;- retry_delay = (retry_delay * 2).min(Duration::from_millis(100));- }- Err(error) => return Err(error),- }- }- }+ async move { connect_with_retry(&socket_path).await.map(TokioIo::new) }})).await?;@@ -94,6 +79,27 @@ async fn connect_unix(socket_path: &std::path::Path) -> BoxliteResult<Channel> {Ok(channel)}+async fn connect_with_retry(socket_path: &Path) -> io::Result<UnixStream> {+ // Guest readiness can precede libkrun's host listener. Tonic's connect+ // timeout bounds this entire future, including every asynchronous backoff.+ let mut retry_delay = INITIAL_CONNECT_RETRY_DELAY;+ loop {+ match UnixStream::connect(socket_path).await {+ Ok(stream) => return Ok(stream),+ Err(error)+ if matches!(+ error.kind(),+ ErrorKind::NotFound | ErrorKind::ConnectionRefused+ ) =>+ {+ tokio::time::sleep(retry_delay).await;+ retry_delay = (retry_delay * 2).min(MAX_CONNECT_RETRY_DELAY);+ }+ Err(error) => return Err(error),+ }+ }+}+async fn connect_tcp(port: u16) -> BoxliteResult<Channel> {let addr = format!("http://127.0.0.1:{}", port);let channel = Endpoint::try_from(addr)?diff --git a/src/boxlite/src/portal/connection/tests.rs b/src/boxlite/src/portal/connection/tests.rsindex 4f2239941..d938a4f6d 100644--- a/src/boxlite/src/portal/connection/tests.rs+++ b/src/boxlite/src/portal/connection/tests.rs@@ -1,8 +1,10 @@use super::connect_unix;use boxlite_shared::{Ssh, SshClient, SshControlRequest, SshControlResponse, SshServer};-use std::path::PathBuf;+use std::path::{Path, PathBuf};use std::time::Duration;use tokio::net::{UnixListener, UnixStream};+use tokio::sync::oneshot;+use tokio::task::JoinHandle;use tokio::time::Instant;use tonic::{Request, Response, Status};@@ -25,23 +27,27 @@ impl Ssh for Control {}}-async fn assert_connects_when_listener_appears(path: PathBuf) {- let connect_path = path.clone();- let connection = tokio::spawn(async move { connect_unix(&connect_path).await });-- // Virtual time advances only after runnable work has drained, so the- // connector encounters the missing/refused socket before it can listen.- tokio::time::sleep(Duration::from_millis(100)).await;- tokio::time::resume();-+fn spawn_ssh_server(path: &Path) -> (oneshot::Sender<()>, JoinHandle<()>) {if path.exists() {- std::fs::remove_file(&path).unwrap();+ std::fs::remove_file(path).unwrap();}- let listener = UnixListener::bind(&path).unwrap();- let incoming = futures::stream::unfold(listener, |listener| async {- Some((listener.accept().await.map(|(stream, _)| stream), listener))- });- let (stop, stopped) = tokio::sync::oneshot::channel();+ let listener = UnixListener::bind(path).unwrap();+ spawn_ssh_server_with_first(listener, None)+}++fn spawn_ssh_server_with_first(+ listener: UnixListener,+ first_stream: Option<UnixStream>,+) -> (oneshot::Sender<()>, JoinHandle<()>) {+ let incoming =+ futures::stream::unfold((first_stream, listener), |(first, listener)| async move {+ let item = match first {+ Some(stream) => Ok(stream),+ None => listener.accept().await.map(|(stream, _)| stream),+ };+ Some((item, (None, listener)))+ });+ let (stop, stopped) = oneshot::channel();let server = tokio::spawn(async move {tonic::transport::Server::builder().add_service(SshServer::new(Control))@@ -51,6 +57,19 @@ async fn assert_connects_when_listener_appears(path: PathBuf) {.await.unwrap();});+ (stop, server)+}++async fn assert_connects_when_listener_appears(path: PathBuf) {+ let connect_path = path.clone();+ let connection = tokio::spawn(async move { connect_unix(&connect_path).await });++ // Virtual time advances only after runnable work has drained, so the+ // connector encounters the missing/refused socket before it can listen.+ tokio::time::sleep(Duration::from_millis(100)).await;+ tokio::time::resume();++ let (stop, server) = spawn_ssh_server(&path);let channel = tokio::time::timeout(Duration::from_secs(2), connection).await@@ -65,6 +84,45 @@ async fn assert_connects_when_listener_appears(path: PathBuf) {server.await.unwrap();}+#[tokio::test(start_paused = true)]+async fn unix_connect_retries_with_initial_1ms_backoff() {+ let home = tempfile::tempdir().unwrap();+ let path = home.path().join("control.sock");+ let connect_path = path.clone();+ let started = Instant::now();+ let connection = tokio::spawn(async move { connect_unix(&connect_path).await });++ // Virtual time advances only after runnable work has drained, so connect_unix+ // hits NotFound and enters its 1ms backoff sleep before the listener binds.+ tokio::time::sleep(Duration::from_micros(500)).await;+ let listener = UnixListener::bind(&path).unwrap();+ let (first_stream, _) = tokio::time::timeout(Duration::from_millis(5), listener.accept())+ .await+ .expect("connect_unix must retry and connect before 5ms")+ .unwrap();+ let elapsed = started.elapsed();+ assert!(+ elapsed >= Duration::from_millis(1) && elapsed < Duration::from_millis(10),+ "expected 1ms-scale initial backoff recovery, got {elapsed:?}"+ );++ // Resume time for tonic's HTTP/2 I/O handshake, matching the other RPC tests.+ tokio::time::resume();+ let (stop, server) = spawn_ssh_server_with_first(listener, Some(first_stream));++ let channel = tokio::time::timeout(Duration::from_secs(2), connection)+ .await+ .expect("listener readiness must complete promptly")+ .unwrap()+ .expect("a listener appearing before 1ms retry must connect");+ SshClient::new(channel)+ .control(SshControlRequest::default())+ .await+ .expect("the recovered connection must carry a real RPC");+ stop.send(()).unwrap();+ server.await.unwrap();+}+#[tokio::test(start_paused = true)]async fn unix_connect_waits_for_missing_socket() {let home = tempfile::tempdir().unwrap();