Bound app-server stdio shutdown and handle Unix SIGTERM gracefully (#44523)

## Why

Stdio shutdown can hang on open pipes or blocked I/O, and Unix `SIGTERM` needs to run connection cleanup so owned commands terminate and session-end hooks execute.

## What changed

- Handle `SIGTERM` on a dedicated signal thread and close the stdio connection through the existing cleanup path.
- Move blocking stdin and stdout operations to dedicated threads so they do not hold the Tokio runtime open. Cancel message forwarding on `SIGTERM` to release blocked producers.
- When shutdown signal handling is enabled on Unix, start a shared 45-second watchdog on EOF or `SIGTERM`. Preserve the first deadline and exit with status `1` if cleanup or runtime teardown stalls, even when logging is blocked.

## Testing

Add Unix integration coverage for shutdown with open pipes, blocked stdout, blocked stderr, and a stalled filesystem write. Verify command and child-process termination, preserve the EOF deadline when `SIGTERM` follows, and extend session-end hook coverage to `SIGTERM`.

GitOrigin-RevId: 43a80b8277eb50519cdc293eb3b5dc2cad00b3aa
This commit is contained in:
jif authored and copyberry committed 2026-09-10 13:02:57 +00:00
1 parent ed6dde9fda
commit 713caa89f3
9 files changed
+501 -45

No files matched your search

+3
View File
@@ -55,6 +55,9 @@ tracing = { workspace = true, features = ["log"] }
url = { workspace = true }
uuid = { workspace = true, features = ["serde", "v7"] }
[target.'cfg(unix)'.dependencies]
signal-hook = { workspace = true }
[dev-dependencies]
chrono = { workspace = true }
codex-config = { workspace = true }
@@ -1,3 +1,8 @@
//! Stdio transport with EOF cleanup and Unix SIGTERM shutdown. Dedicated I/O
//! threads let SIGTERM abandon blocked pipes without holding the runtime open.
//! A dedicated signal thread arms the shared EOF/SIGTERM deadline even when
//! logging or the Tokio runtime is blocked.
use super::CHANNEL_CAPACITY;
use super::ConnectionOrigin;
use super::TransportEvent;
@@ -8,24 +13,42 @@ use crate::outgoing_message::QueuedOutgoingMessage;
use codex_app_server_protocol::InitializeParams;
use codex_app_server_protocol::JSONRPCMessage;
use codex_app_server_protocol::JSONRPCRequest;
use std::io::BufRead;
use std::io::ErrorKind;
use std::io::Result as IoResult;
use tokio::io;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncWriteExt;
use tokio::io::BufReader;
use std::io::Write;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use tracing::debug;
use tracing::error;
use tracing::info;
pub async fn start_stdio_connection(
transport_event_tx: mpsc::Sender<TransportEvent>,
stdio_handles: &mut Vec<JoinHandle<()>>,
initialize_client_name_tx: oneshot::Sender<String>,
) -> IoResult<()> {
install_shutdown_signal_handler: bool,
) -> IoResult<JoinHandle<()>> {
let shutdown_signal = CancellationToken::new();
#[cfg(unix)]
if install_shutdown_signal_handler {
use signal_hook::consts::SIGTERM;
use signal_hook::iterator::Signals;
// Register before accepting requests. Receiving SIGTERM and arming the
// watchdog must not depend on Tokio or synchronous transport logging.
let mut signals = Signals::new([SIGTERM])?;
let shutdown_signal = shutdown_signal.clone();
std::thread::Builder::new()
.name("app-server-signal".to_string())
.spawn(move || {
if signals.forever().next().is_some() {
start_shutdown_watchdog();
shutdown_signal.cancel();
}
})?;
}
let connection_id = next_connection_id();
let (writer_tx, mut writer_rx) = mpsc::channel::<QueuedOutgoingMessage>(CHANNEL_CAPACITY);
let writer_tx_for_reader = writer_tx.clone();
@@ -40,55 +63,84 @@ pub async fn start_stdio_connection(
.await
.map_err(|_| std::io::Error::new(ErrorKind::BrokenPipe, "processor unavailable"))?;
let transport_event_tx_for_reader = transport_event_tx.clone();
stdio_handles.push(tokio::spawn(async move {
let stdin = io::stdin();
let reader = BufReader::new(stdin);
let mut lines = reader.lines();
let mut initialize_client_name_tx = Some(initialize_client_name_tx);
loop {
match lines.next_line().await {
Ok(Some(line)) => {
if let Some(client_name) = stdio_initialize_client_name(&line)
&& let Some(initialize_client_name_tx) = initialize_client_name_tx.take()
{
let _ = initialize_client_name_tx.send(client_name);
}
if !forward_incoming_message(
&transport_event_tx_for_reader,
&writer_tx_for_reader,
connection_id,
&line,
)
.await
{
break;
}
// Tokio's stdin uses an uncancellable blocking task, which keeps its runtime
// alive while the client leaves stdin open. This process-owned thread may
// remain blocked until process exit, but is not joined by the runtime.
let (stdin_tx, mut stdin_rx) = mpsc::channel(/*buffer*/ 1);
std::thread::Builder::new()
.name("app-server-stdin".to_string())
.spawn(move || {
for line in std::io::stdin().lock().lines() {
if stdin_tx.blocking_send(line).is_err() {
break;
}
Ok(None) => break,
}
})?;
// Keep stdout's blocking writes off Tokio's pool too. The forwarding future
// owns writer_rx so cancelling it also releases producers stuck on a full queue.
let (stdout_tx, mut stdout_rx) =
mpsc::channel::<(String, oneshot::Sender<()>)>(/*buffer*/ 1);
std::thread::Builder::new()
.name("app-server-stdout".to_string())
.spawn(move || {
let mut stdout = std::io::stdout().lock();
while let Some((json, written_tx)) = stdout_rx.blocking_recv() {
if let Err(err) = stdout.write_all(json.as_bytes()) {
error!("Failed to write to stdout: {err}");
break;
}
let _ = written_tx.send(());
}
})?;
let transport_event_tx_for_reader = transport_event_tx.clone();
let read_messages = async move {
let mut initialize_client_name_tx = Some(initialize_client_name_tx);
while let Some(line) = stdin_rx.recv().await {
let line = match line {
Ok(line) => line,
Err(err) => {
error!("Failed reading stdin: {err}");
break;
}
};
if let Some(client_name) = stdio_initialize_client_name(&line)
&& let Some(initialize_client_name_tx) = initialize_client_name_tx.take()
{
let _ = initialize_client_name_tx.send(client_name);
}
if !forward_incoming_message(
&transport_event_tx_for_reader,
&writer_tx_for_reader,
connection_id,
&line,
)
.await
{
break;
}
}
// EOF can finish the transport before RPC or runtime cleanup. Start
// the same process deadline even if no SIGTERM arrives.
if cfg!(unix) && install_shutdown_signal_handler {
start_shutdown_watchdog();
}
let _ = transport_event_tx_for_reader
.send(TransportEvent::ConnectionClosed { connection_id })
.await;
debug!("stdin reader finished (EOF)");
}));
};
stdio_handles.push(tokio::spawn(async move {
let mut stdout = io::stdout();
let write_messages = async move {
while let Some(queued_message) = writer_rx.recv().await {
let Some(mut json) = serialize_outgoing_message(queued_message.message) else {
continue;
};
json.push('\n');
if let Err(err) = stdout.write_all(json.as_bytes()).await {
error!("Failed to write to stdout: {err}");
let (written_tx, written_rx) = oneshot::channel();
if stdout_tx.send((json, written_tx)).await.is_err() || written_rx.await.is_err() {
break;
}
if let Some(write_complete_tx) = queued_message.write_complete_tx {
@@ -96,9 +148,37 @@ pub async fn start_stdio_connection(
}
}
info!("stdout writer exited (channel closed)");
}));
};
Ok(())
Ok(tokio::spawn(async move {
tokio::select! {
_ = shutdown_signal.cancelled() => {
// Cancelling both forwarding futures drops their queues before
// connection teardown, including when EOF already began draining.
info!("SIGTERM received; closing stdio connection (45s shutdown deadline)");
let _ = transport_event_tx
.send(TransportEvent::ConnectionClosed { connection_id })
.await;
}
_ = async move { tokio::join!(read_messages, write_messages); } => {}
}
}))
}
fn start_shutdown_watchdog() {
// EOF and SIGTERM can both start cleanup; keep the first process deadline.
static STARTED: std::sync::Once = std::sync::Once::new();
STARTED.call_once(|| {
std::thread::Builder::new()
.name("app-server-shutdown".to_string())
.spawn(|| {
// Allow the processor's 30s RPC drain, then bound even Tokio's
// runtime teardown. Do not log here: stderr may also be blocked.
std::thread::sleep(std::time::Duration::from_secs(45));
std::process::exit(/*code*/ 1);
})
.unwrap_or_else(|_| std::process::exit(/*code*/ 1));
});
}
fn stdio_initialize_client_name(line: &str) -> Option<String> {