mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:50:52 +00:00
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:
@@ -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
|
||||
}))
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user