Reap idle local code-mode hosts after five seconds (#63537)

## Why

The local code-mode host could stay running after its last session
closed. A short grace period allows nearby sessions to reuse the same
process while releasing it after sustained inactivity.

## What changed

Keep the host active while session leases or operation RPCs are in
flight. Once they drain, start a five-second idle timer. New activity
cancels retirement and starts a fresh grace period when it drains.
Process metrics only sample an existing host and leave the idle timer
untouched. Opening a session after retirement starts a fresh host.

## Testing

Add a lifecycle test that covers overlapping sessions, reuse during the
grace period, retirement despite metrics polling, and startup on the
next session.

GitOrigin-RevId: 2ebf7f7b3b3bf2d5a602b0e5b9085195eee13446
This commit is contained in:
Charlie Marsh
2026-11-24 04:29:16 +00:00
committed by copyberry
parent 1985925638
commit 714bc44f0d
8 changed files with 217 additions and 72 deletions
+1
View File
@@ -3153,6 +3153,7 @@ dependencies = [
"eventsource-stream",
"futures",
"http 1.4.0",
"http-body-util",
"hyper-util",
"iana-time-zone",
"image",
+10 -3
View File
@@ -75,8 +75,15 @@ where
}
}
#[derive(Clone)]
struct SessionAdmission;
/// Request extension for calls with special host lifecycle requirements.
/// Untagged calls need a running host and keep it active.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GrpcCallKind {
/// Opens a session and may start or replace the host.
Admission,
/// Samples a running host without extending its lifetime.
Observation,
}
const SHUTDOWN_ERROR: &str = "code mode session is shutting down";
const ROUTE_HEADER: &str = "x-code-mode-route";
@@ -204,7 +211,7 @@ impl GrpcCodeModeSessionProvider {
}
},
});
request.extensions_mut().insert(SessionAdmission);
request.extensions_mut().insert(GrpcCallKind::Admission);
inject_span_traceparent(&mut request, &open_session_span);
let result = async {
let response = client.as_ref().clone().open_session(request).await?;
@@ -9,6 +9,7 @@ use codex_code_mode_protocol::CodeModeProcessMetricsSample;
use codex_code_mode_protocol::grpc;
use tonic::Code;
use super::GrpcCallKind;
use super::GrpcCodeModeSessionProvider;
pub(super) async fn sample(
@@ -18,6 +19,7 @@ pub(super) async fn sample(
tokio::time::timeout(deadline, async {
let client = provider.transport.client().await?;
let mut request = tonic::Request::new(grpc::GetProcessMetricsRequest {});
request.extensions_mut().insert(GrpcCallKind::Observation);
request.set_timeout(deadline);
match client.as_ref().clone().get_process_metrics(request).await {
Ok(response) => {
@@ -19,8 +19,8 @@ use tower::ServiceExt;
use tower::service_fn;
use tower::util::BoxCloneSyncService;
use super::GrpcCallKind;
use super::GrpcClient;
use super::SessionAdmission;
pub(super) type GrpcTransport = BoxCloneSyncService<Request<Body>, Response<Body>, Status>;
@@ -121,7 +121,7 @@ impl SharedTransport {
let transport = service_fn(move |request: Request<Body>| {
let client = client.clone();
async move {
let admission = request.extensions().get::<SessionAdmission>().is_some();
let kind = request.extensions().get::<GrpcCallKind>().copied();
let request =
request.map(|body| reqwest::Body::wrap_stream(body.into_data_stream()));
let request = reqwest::Request::try_from(request)
@@ -145,7 +145,9 @@ impl SharedTransport {
status
})?
.into_http_response();
if admission && response.status() == StatusCode::SERVICE_UNAVAILABLE {
if kind == Some(GrpcCallKind::Admission)
&& response.status() == StatusCode::SERVICE_UNAVAILABLE
{
// A 503 cannot grant a lease. Leave headers and trailers for tonic
// to read the gRPC status, or infer Unavailable when it is absent.
return Ok(response.map(|body| {
+1
View File
@@ -4,5 +4,6 @@ mod tool_catalog;
pub use codex_code_mode_protocol::*;
pub use disabled::DisabledCodeModeSessionProvider;
pub use grpc_session::GrpcCallKind;
pub use grpc_session::GrpcCodeModeSessionProvider;
pub use grpc_session::GrpcSessionOpenError;
+1
View File
@@ -97,6 +97,7 @@ dunce = { workspace = true }
eventsource-stream = { workspace = true }
futures = { workspace = true }
http = { workspace = true }
http-body-util = "0.1.3"
hyper-util = { workspace = true }
iana-time-zone = { workspace = true }
image = { workspace = true, features = ["jpeg", "png", "webp"] }
+123 -58
View File
@@ -1,6 +1,7 @@
//! Owns Core's local code-mode output rollout and gRPC host. Sessions share a lazy
//! HTTP/2 connection. Only session admission can replace a dead host; metrics
//! use the current generation and cannot reconnect. Dropping its I/O reaps the child.
//! use the current generation and cannot reconnect. Once session and operation
//! streams drain, we briefly retain the host for reuse before dropping its I/O.
use std::io;
use std::path::Path;
@@ -11,6 +12,7 @@ use std::sync::Arc;
use std::sync::Mutex;
use std::sync::OnceLock;
use std::sync::PoisonError;
use std::sync::Weak;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::task::Context;
@@ -24,9 +26,11 @@ use codex_code_mode::CodeModeSessionOptions;
use codex_code_mode::CodeModeSessionProvider;
use codex_code_mode::CodeModeSessionProviderFuture;
use codex_code_mode::CodeModeSessionResultFuture;
use codex_code_mode::GrpcCallKind;
use codex_code_mode::GrpcCodeModeSessionProvider;
use codex_protocol::shell_environment::scrub_non_inheritable_env_vars;
use codex_utils_process::background_command;
use http_body_util::BodyExt;
use hyper_util::rt::TokioIo;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncRead;
@@ -37,6 +41,8 @@ use tokio::process::Child;
use tokio::process::ChildStdin;
use tokio::process::ChildStdout;
use tokio::process::Command;
use tokio::sync::oneshot;
use tokio_util::task::AbortOnDropHandle;
use tonic::Status;
use tonic::body::Body;
use tonic::transport::Channel;
@@ -44,6 +50,7 @@ use tonic::transport::Endpoint;
use tower::ServiceExt;
use tower::service_fn;
const HOST_IDLE_GRACE: Duration = Duration::from_secs(/*secs*/ 5);
const MAX_DISPLAYED_HOST_PROGRAM_BYTES: usize = 512;
/// Only wraps Core's built-in providers; injected providers own their session settings.
@@ -172,10 +179,12 @@ impl CodeModeSessionProvider for ProcessOwnedGrpcCodeModeSessionProvider {
host_program: self.host_program.clone(),
current: self.current.clone(),
});
GrpcCodeModeSessionProvider::with_transport(service_fn(move |request| {
let transport = transport.clone();
async move { transport.send(request).await }
}))
GrpcCodeModeSessionProvider::with_transport(service_fn(
move |request: http::Request<Body>| {
let transport = transport.clone();
async move { transport.select(request.extensions())?.send(request).await }
},
))
});
provider.create_session_with_options(options).await
})
@@ -193,66 +202,122 @@ struct HostTransport {
struct HostChannel {
channel: Channel,
alive: Arc<AtomicBool>,
activity: Weak<oneshot::Sender<()>>,
retirement: Option<AbortOnDropHandle<()>>,
}
struct HostRpc {
channel: Channel,
activity: Option<Arc<oneshot::Sender<()>>>,
}
impl HostTransport {
async fn send(&self, request: http::Request<Body>) -> Result<http::Response<Body>, Status> {
self.channel(request.uri().path())?
.oneshot(request)
.await
.map_err(|error| {
// Channel errors are transport failures, not host RPC statuses.
// In particular a child exiting during handshake can surface as
// BrokenPipe, which generic tonic conversion calls Unknown and
// would prevent the existing bounded OpenSession retry policy.
let mut status = Status::unavailable("code-mode host transport failed");
status.set_source(Arc::new(error));
status
})
fn select(&self, extensions: &http::Extensions) -> Result<HostRpc, Status> {
let kind = extensions.get::<GrpcCallKind>().copied();
let mut current = self.current.lock().unwrap_or_else(PoisonError::into_inner);
let host = match current
.as_mut()
.filter(|host| host.alive.load(Ordering::Acquire))
{
Some(host) => host,
None if kind == Some(GrpcCallKind::Admission) => {
current.insert(HostChannel::spawn(&self.host_program)?)
}
None => return Err(Status::unavailable("code-mode host is not running")),
};
let activity = match kind {
Some(GrpcCallKind::Observation) => None,
Some(GrpcCallKind::Admission) | None => {
Some(host.acquire(Arc::downgrade(&self.current)))
}
};
Ok(HostRpc {
channel: host.channel.clone(),
activity,
})
}
}
impl HostChannel {
fn spawn(host_program: &Path) -> Result<Self, Status> {
let connection = HostConnection::spawn(host_program)
.map_err(|error| Status::unavailable(error.to_string()))?;
let alive = connection.alive.clone();
let connection = Arc::new(Mutex::new(Some(connection)));
// Preserve execution liveness detection independently of metrics cadence.
let channel = Endpoint::from_static("http://code-mode-host")
.http2_keep_alive_interval(Duration::from_secs(/*secs*/ 30))
.keep_alive_timeout(Duration::from_secs(/*secs*/ 10))
.keep_alive_while_idle(/*enabled*/ true)
.connect_with_connector_lazy(service_fn(move |_| {
let connection = connection
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take();
async move {
connection.map(TokioIo::new).ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotConnected,
"code-mode host connection ended",
)
})
}
}));
Ok(Self {
channel,
alive,
activity: Weak::new(),
retirement: None,
})
}
fn channel(&self, rpc_path: &str) -> Result<Channel, Status> {
Ok({
let mut current = self.current.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(host) = current
.as_ref()
.filter(|host| host.alive.load(Ordering::Acquire))
{
host.channel.clone()
} else {
if rpc_path != "/codex.code_mode.v1.CodeModeHost/OpenSession" {
return Err(Status::unavailable("code-mode host is not running"));
/// Overlapping RPCs share a sender. Dropping the last sender starts the grace
/// period. A new RPC during that grace gets a distinct sender under the same
/// lock used by the timer, so an expiring timer can only retire its own host.
fn acquire(&mut self, current: Weak<Mutex<Option<Self>>>) -> Arc<oneshot::Sender<()>> {
if let Some(active) = self.activity.upgrade() {
return active;
}
let (sender, idle) = oneshot::channel();
let active = Arc::new(sender);
self.activity = Arc::downgrade(&active);
let activity = self.activity.clone();
self.retirement = Some(AbortOnDropHandle::new(tokio::spawn(async move {
let _ = idle.await;
tokio::time::sleep(HOST_IDLE_GRACE).await;
if let Some(current) = current.upgrade() {
let mut current = current.lock().unwrap_or_else(PoisonError::into_inner);
if current
.as_ref()
.is_some_and(|host| host.activity.ptr_eq(&activity))
{
current.take();
}
let connection = HostConnection::spawn(&self.host_program)
.map_err(|error| Status::unavailable(error.to_string()))?;
let alive = connection.alive.clone();
let connection = Arc::new(Mutex::new(Some(connection)));
// Preserve execution liveness detection independently of metrics cadence.
let channel = Endpoint::from_static("http://code-mode-host")
.http2_keep_alive_interval(Duration::from_secs(/*secs*/ 30))
.keep_alive_timeout(Duration::from_secs(/*secs*/ 10))
.keep_alive_while_idle(/*enabled*/ true)
.connect_with_connector_lazy(service_fn(move |_| {
let connection = connection
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take();
async move {
connection.map(TokioIo::new).ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotConnected,
"code-mode host connection ended",
)
})
}
}));
*current = Some(HostChannel {
channel: channel.clone(),
alive,
});
channel
}
})
})));
active
}
}
impl HostRpc {
async fn send(self, request: http::Request<Body>) -> Result<http::Response<Body>, Status> {
let response = self.channel.oneshot(request).await.map_err(|error| {
// Channel errors are transport failures, not host RPC statuses.
// In particular a child exiting during handshake can surface as
// BrokenPipe, which generic tonic conversion calls Unknown and
// would prevent the existing bounded OpenSession retry policy.
let mut status = Status::unavailable("code-mode host transport failed");
status.set_source(Arc::new(error));
status
})?;
// OpenSession's response body is the session lease. Keep each RPC
// active from selection through the lifetime of its response stream.
Ok(response.map(|body| {
Body::new(body.map_frame(move |frame| {
let _activity = &self.activity;
frame
}))
}))
}
}
@@ -1,5 +1,5 @@
#![cfg(test)]
//! Deterministic child failures around channel selection and session recovery.
//! Child retirement and failure recovery around channel selection.
use std::sync::Arc;
use std::sync::Mutex;
@@ -21,9 +21,7 @@ use tokio::sync::Notify;
use tokio::sync::Semaphore;
use tokio::time::timeout;
use tokio_util::sync::CancellationToken;
use tonic::Status;
use tonic::body::Body;
use tower::ServiceExt;
use tower::service_fn;
use super::super::HostTransport;
@@ -88,17 +86,14 @@ async fn child_exit_after_channel_selection_does_not_replay_execution() -> Resul
async move {
// Exercise the production selector, pausing exactly between
// selecting a live generation and dispatching to that channel.
let channel = transport.channel(request.uri().path())?;
let rpc = transport.select(request.extensions())?;
if request.uri().path() == "/codex.code_mode.v1.CodeModeHost/Execute"
&& armed.swap(false, Ordering::SeqCst)
{
selected.notify_one();
dispatch.acquire().await.unwrap().forget();
}
channel
.oneshot(request)
.await
.map_err(|error| Status::from_error(Box::new(error)))
rpc.send(request).await
}
}
}));
@@ -187,3 +182,74 @@ async fn child_exit_after_channel_selection_does_not_replay_execution() -> Resul
}
Ok(())
}
/// Advance through a quiet period with real pipes and no outstanding unary RPCs.
async fn elapse(duration: Duration) {
tokio::time::pause();
tokio::time::sleep(duration).await;
tokio::time::resume();
}
#[tokio::test]
async fn idle_host_is_reused_then_reaped_after_last_session_closes() -> Result<()> {
let recorder = CodeModeHostRecorder::new()?;
let provider = ProcessOwnedGrpcCodeModeSessionProvider::with_host_program(recorder.program());
let (first, second) = tokio::try_join!(provider.create_session(), provider.create_session())
.map_err(anyhow::Error::msg)?;
let pid = recorder.pid()?;
execute(&second, r#"store("answer", 42);"#).await?;
first.shutdown().await.map_err(anyhow::Error::msg)?;
elapse(Duration::from_secs(/*secs*/ 6)).await;
assert_eq!(
execute(&second, r#"text(load("answer"));"#).await?,
vec![FunctionCallOutputContentItem::InputText {
text: "42".to_string()
}]
);
second.shutdown().await.map_err(anyhow::Error::msg)?;
let interval = Duration::from_secs(/*secs*/ 3);
elapse(interval).await;
let third = provider
.create_session()
.await
.map_err(anyhow::Error::msg)?;
third.shutdown().await.map_err(anyhow::Error::msg)?;
// Cross the first deadline. Sampling must observe the fresh grace period
// without extending it.
elapse(interval).await;
assert_eq!(
provider
.sample_process_metrics()
.await
.map_err(anyhow::Error::msg)?,
CodeModeProcessMetricsSample::Unsupported
);
elapse(interval).await;
assert_eq!(
provider
.sample_process_metrics()
.await
.map_err(anyhow::Error::msg)?,
CodeModeProcessMetricsSample::NotRunning
);
timeout(TEST_TIMEOUT, async {
while unsafe {
libc::kill(pid as libc::pid_t, /*sig*/ 0)
} == 0
{
tokio::time::sleep(Duration::from_millis(/*millis*/ 10)).await;
}
})
.await
.context("idle child was not reaped")?;
assert_eq!(recorder.invocations()?.len(), 1);
let fresh = provider
.create_session()
.await
.map_err(anyhow::Error::msg)?;
execute(&fresh, "text(1);").await?;
assert_eq!(recorder.invocations()?.len(), 2);
Ok(())
}