Skip to content

Commit 20e4d94

Browse files
committed
Harden stdio MCP cleanup across process exits
Why: Owned stdio servers could outlive their session when cleanup callers were cancelled, the Tokio runtime exited, or a remote executor disconnected before TERM-to-KILL escalation completed. What changed: Share and verify process cleanup results, supervise Unix process groups across hard parent exits, assign Windows children to a strict Job before resuming them, and terminate detached remote-executor sessions through their captured process handles. Validation: Pass macOS process-group cleanup 7/7, utils-pty 22/22, repeated hard-parent-kill soak 20/20, exec-server detached-session expiry, fmt, scoped fix, Bazel lock update, and diff checks. Native Windows execution remains pending because the Windows server is unavailable.
1 parent a5e403e commit 20e4d94

15 files changed

Lines changed: 655 additions & 115 deletions

File tree

‎codex-rs/Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎codex-rs/arg0/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ codex-sandboxing = { workspace = true }
2222
codex-shell-escalation = { workspace = true }
2323
codex-utils-absolute-path = { workspace = true }
2424
codex-utils-home-dir = { workspace = true }
25+
codex-utils-pty = { workspace = true }
2526
dotenvy = { workspace = true }
2627
tempfile = { workspace = true }
2728
tokio = { workspace = true, features = ["rt-multi-thread"] }

‎codex-rs/arg0/src/lib.rs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,10 @@ pub fn arg0_dispatch() -> Option<Arg0PathEntryGuard> {
104104
if argv1 == CODEX_ARG0_EXEC_HELPER_ARG1 {
105105
codex_exec_server::run_arg0_exec_helper_main();
106106
}
107+
#[cfg(unix)]
108+
if argv1 == codex_utils_pty::CODEX_MCP_PROCESS_SUPERVISOR_ARG1 {
109+
codex_utils_pty::run_mcp_process_supervisor_main();
110+
}
107111
if argv1 == CODEX_FS_HELPER_ARG1 {
108112
codex_exec_server::run_fs_helper_main();
109113
}
@@ -226,6 +230,10 @@ where
226230
// would be nice to avoid leaving temporary directories behind, if possible.
227231
let path_entry_guard = arg0_dispatch();
228232
let current_exe = std::env::current_exe().ok();
233+
#[cfg(unix)]
234+
if let Some(current_exe) = &current_exe {
235+
codex_utils_pty::configure_mcp_process_supervisor_exe(current_exe.clone());
236+
}
229237

230238
// Regular invocation. Run the async entry point on a thread with the same
231239
// stack budget as Tokio workers; `Runtime::block_on` otherwise runs the

‎codex-rs/exec-server/src/server/processor.rs‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -481,6 +481,73 @@ mod tests {
481481
.expect("second processor should join");
482482
}
483483

484+
#[cfg(unix)]
485+
#[tokio::test]
486+
async fn detached_session_expiry_terminates_its_process_group() {
487+
let registry = SessionRegistry::new(crate::ExecServerTelemetry::default());
488+
let (mut writer, mut lines, task) = spawn_test_connection(registry, "detached-expiry");
489+
send_request(
490+
&mut writer,
491+
/*id*/ 1,
492+
INITIALIZE_METHOD,
493+
&InitializeParams {
494+
client_name: "exec-server-test".to_string(),
495+
resume_session_id: None,
496+
},
497+
)
498+
.await;
499+
let _: InitializeResponse = read_response(&mut lines, /*expected_id*/ 1).await;
500+
send_notification(&mut writer, INITIALIZED_METHOD, &()).await;
501+
502+
let temp_dir = tempfile::tempdir().expect("tempdir");
503+
let pid_file = temp_dir.path().join("detached-process.pid");
504+
let mut params = exec_params(ProcessId::from("detached-process"));
505+
params.argv = vec![
506+
"/bin/sh".to_string(),
507+
"-c".to_string(),
508+
"echo $$ > \"$PID_FILE\"; trap '' TERM; while :; do sleep 1; done".to_string(),
509+
];
510+
params.env.insert(
511+
"PID_FILE".to_string(),
512+
pid_file.to_string_lossy().into_owned(),
513+
);
514+
send_request(&mut writer, /*id*/ 2, EXEC_METHOD, &params).await;
515+
let _: ExecResponse = read_response(&mut lines, /*expected_id*/ 2).await;
516+
let process_id = loop {
517+
match std::fs::read_to_string(&pid_file) {
518+
Ok(pid) => break pid.trim().parse::<u32>().expect("process pid"),
519+
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
520+
tokio::time::sleep(Duration::from_millis(10)).await;
521+
}
522+
Err(error) => panic!("failed to read process pid: {error}"),
523+
}
524+
};
525+
526+
drop(writer);
527+
drop(lines);
528+
timeout(Duration::from_secs(1), task)
529+
.await
530+
.expect("processor should exit")
531+
.expect("processor should join");
532+
533+
let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
534+
loop {
535+
let alive = std::process::Command::new("kill")
536+
.args(["-0", &process_id.to_string()])
537+
.stderr(std::process::Stdio::null())
538+
.status()
539+
.is_ok_and(|status| status.success());
540+
if !alive {
541+
break;
542+
}
543+
assert!(
544+
tokio::time::Instant::now() < deadline,
545+
"detached exec-server process survived session expiry"
546+
);
547+
tokio::time::sleep(Duration::from_millis(25)).await;
548+
}
549+
}
550+
484551
fn spawn_test_connection(
485552
registry: Arc<SessionRegistry>,
486553
label: &str,

‎codex-rs/rmcp-client/src/bin/test_stdio_server.rs‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -960,6 +960,34 @@ async fn remove_sync_barrier_if_current(barrier_id: &str, barrier: &Arc<Barrier>
960960
}
961961
}
962962

963+
#[cfg(unix)]
964+
async fn run_supervisor_parent_harness() -> Result<(), Box<dyn std::error::Error>> {
965+
let current_exe = std::env::current_exe()?;
966+
let pid_file = std::env::var_os("MCP_TEST_PID_FILE")
967+
.ok_or("MCP supervisor parent harness requires MCP_TEST_PID_FILE")?;
968+
let client = codex_rmcp_client::RmcpClient::new_stdio_client(
969+
current_exe.clone().into_os_string(),
970+
Vec::new(),
971+
Some(std::collections::HashMap::from([
972+
(std::ffi::OsString::from("MCP_TEST_PID_FILE"), pid_file),
973+
(
974+
std::ffi::OsString::from("MCP_TEST_TERM_RESISTANT_ROLE"),
975+
std::ffi::OsString::from("1"),
976+
),
977+
])),
978+
&[],
979+
/*cwd*/ None,
980+
Arc::new(
981+
codex_rmcp_client::LocalStdioServerLauncher::new(std::env::current_dir()?)
982+
.with_process_supervisor(Some(current_exe)),
983+
),
984+
)
985+
.await?;
986+
std::future::pending::<()>().await;
987+
drop(client);
988+
Ok(())
989+
}
990+
963991
fn parse_data_url(url: &str) -> Option<(String, String)> {
964992
let rest = url.strip_prefix("data:")?;
965993
let (mime_and_opts, data) = rest.split_once(',')?;
@@ -969,6 +997,32 @@ fn parse_data_url(url: &str) -> Option<(String, String)> {
969997

970998
#[tokio::main]
971999
async fn main() -> Result<(), Box<dyn std::error::Error>> {
1000+
#[cfg(unix)]
1001+
if std::env::args_os().nth(1).as_deref()
1002+
== Some(std::ffi::OsStr::new(
1003+
codex_utils_pty::CODEX_MCP_PROCESS_SUPERVISOR_ARG1,
1004+
))
1005+
{
1006+
codex_utils_pty::run_mcp_process_supervisor_main();
1007+
}
1008+
1009+
#[cfg(unix)]
1010+
if std::env::var_os("MCP_TEST_SUPERVISOR_PARENT_ROLE").is_some() {
1011+
return run_supervisor_parent_harness().await;
1012+
}
1013+
1014+
#[cfg(unix)]
1015+
if std::env::var_os("MCP_TEST_TERM_RESISTANT_ROLE").is_some() {
1016+
unsafe {
1017+
libc::signal(libc::SIGTERM, libc::SIG_IGN);
1018+
}
1019+
let pid_file = std::env::var_os("MCP_TEST_PID_FILE")
1020+
.ok_or("TERM-resistant test process requires MCP_TEST_PID_FILE")?;
1021+
std::fs::write(pid_file, std::process::id().to_string())?;
1022+
std::future::pending::<()>().await;
1023+
return Ok(());
1024+
}
1025+
9721026
#[cfg(windows)]
9731027
if std::env::var_os("MCP_TEST_DESCENDANT_ROLE").is_some() {
9741028
tokio::time::sleep(Duration::from_secs(30)).await;

‎codex-rs/rmcp-client/src/lib.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,12 @@ pub use auth_status::determine_streamable_http_auth_status;
2828
pub use auth_status::determine_streamable_http_auth_status_from_credentials;
2929
pub use auth_status::discover_streamable_http_oauth;
3030
pub use codex_protocol::protocol::McpAuthStatus;
31+
#[cfg(unix)]
32+
pub use codex_utils_pty::configured_mcp_process_supervisor_exe;
33+
#[cfg(not(unix))]
34+
pub fn configured_mcp_process_supervisor_exe() -> Option<std::path::PathBuf> {
35+
None
36+
}
3137
pub use event_notification_transport::EventNotificationReceiver;
3238
pub use http_client_adapter::StreamableHttpRedirectMode;
3339
pub use http_headers::with_http_headers_helper;

‎codex-rs/rmcp-client/src/rmcp_client.rs‎

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -950,20 +950,28 @@ impl RmcpClient {
950950
}
951951
}
952952

953-
/// Stop the MCP transport and any stdio server process owned by this client.
954-
pub async fn shutdown(&self) {
953+
/// Stop the MCP transport and confirm termination of any owned stdio process.
954+
pub async fn try_shutdown(&self) -> io::Result<()> {
955955
let previous_state = {
956956
let mut guard = self.state.lock().await;
957957
std::mem::replace(&mut *guard, ClientState::Closed)
958958
};
959959

960-
if let Some(process) = &self.stdio_process
961-
&& let Err(error) = process.terminate().await
962-
{
963-
warn!("failed to terminate MCP stdio server process: {error}");
964-
}
960+
let cleanup_result = if let Some(process) = &self.stdio_process {
961+
process.terminate_with_retry().await
962+
} else {
963+
Ok(())
964+
};
965965

966966
drop(previous_state);
967+
cleanup_result
968+
}
969+
970+
/// Stop the MCP transport and log any stdio process cleanup failure.
971+
pub async fn shutdown(&self) {
972+
if let Err(error) = self.try_shutdown().await {
973+
warn!("failed to terminate MCP stdio server process: {error}");
974+
}
967975
}
968976

969977
/// This should be called after every tool call so that if a given tool call triggered

‎codex-rs/rmcp-client/src/stdio_server_launcher.rs‎

Lines changed: 52 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ impl Transport<RoleClient> for StdioServerTransport {
124124
}
125125

126126
async fn close(&mut self) -> std::result::Result<(), Self::Error> {
127-
self.process.terminate().await?;
127+
self.process.terminate_with_retry().await?;
128128
match &mut self.inner {
129129
StdioServerTransportInner::LocalLegacy(transport) => transport.close().await,
130130
StdioServerTransportInner::LocalModern(transport) => transport.close().await,
@@ -171,6 +171,7 @@ impl StdioServerCommand {
171171
#[derive(Clone)]
172172
pub struct LocalStdioServerLauncher {
173173
fallback_cwd: PathBuf,
174+
process_supervisor_exe: Option<PathBuf>,
174175
}
175176

176177
impl LocalStdioServerLauncher {
@@ -179,7 +180,16 @@ impl LocalStdioServerLauncher {
179180
/// `fallback_cwd` is used when the MCP server config omits `cwd`, so
180181
/// relative commands resolve from the caller's runtime working directory.
181182
pub fn new(fallback_cwd: PathBuf) -> Self {
182-
Self { fallback_cwd }
183+
Self {
184+
fallback_cwd,
185+
process_supervisor_exe: None,
186+
}
187+
}
188+
189+
/// Uses a Codex arg-dispatch executable to supervise Unix MCP processes.
190+
pub fn with_process_supervisor(mut self, process_supervisor_exe: Option<PathBuf>) -> Self {
191+
self.process_supervisor_exe = process_supervisor_exe;
192+
self
183193
}
184194
}
185195

@@ -189,12 +199,15 @@ impl StdioServerLauncher for LocalStdioServerLauncher {
189199
command: StdioServerCommand,
190200
) -> BoxFuture<'static, io::Result<StdioServerTransport>> {
191201
let fallback_cwd = self.fallback_cwd.clone();
202+
let process_supervisor_exe = self.process_supervisor_exe.clone();
192203
async move {
193204
// Keep synchronous program resolution and process creation from blocking the
194205
// caller's startup deadline.
195-
tokio::task::spawn_blocking(move || Self::launch_server(command, fallback_cwd))
196-
.await
197-
.map_err(io::Error::other)?
206+
tokio::task::spawn_blocking(move || {
207+
Self::launch_server(command, fallback_cwd, process_supervisor_exe)
208+
})
209+
.await
210+
.map_err(io::Error::other)?
198211
}
199212
.boxed()
200213
}
@@ -212,6 +225,7 @@ impl LocalStdioServerLauncher {
212225
fn launch_server(
213226
command: StdioServerCommand,
214227
fallback_cwd: PathBuf,
228+
process_supervisor_exe: Option<PathBuf>,
215229
) -> io::Result<StdioServerTransport> {
216230
let StdioServerCommand {
217231
program,
@@ -228,6 +242,17 @@ impl LocalStdioServerLauncher {
228242
program_resolver::resolve(program, &envs, &cwd).map_err(io::Error::other)?;
229243

230244
let build_command = || {
245+
#[cfg(unix)]
246+
let mut command = if let Some(process_supervisor_exe) = &process_supervisor_exe {
247+
let mut command = Command::new(process_supervisor_exe);
248+
command
249+
.arg(codex_utils_pty::CODEX_MCP_PROCESS_SUPERVISOR_ARG1)
250+
.arg(&resolved_program);
251+
command
252+
} else {
253+
Command::new(&resolved_program)
254+
};
255+
#[cfg(not(unix))]
231256
let mut command = Command::new(&resolved_program);
232257
command
233258
.kill_on_drop(true)
@@ -246,16 +271,14 @@ impl LocalStdioServerLauncher {
246271
#[cfg(not(windows))]
247272
let command = build_command();
248273
#[cfg(windows)]
249-
let job = match codex_utils_pty::JobObject::create_without_breakaway() {
250-
Ok(job) => {
251-
job.prepare_suspended_spawn(&mut command);
252-
Some(job)
253-
}
254-
Err(error) => {
255-
warn!("Windows MCP process job containment unavailable: {error}");
256-
None
257-
}
258-
};
274+
let job = codex_utils_pty::JobObject::create_without_breakaway().map_err(|error| {
275+
io::Error::new(
276+
error.kind(),
277+
format!("Windows MCP process job containment unavailable: {error}"),
278+
)
279+
})?;
280+
#[cfg(windows)]
281+
job.prepare_suspended_spawn(&mut command);
259282

260283
let spawn_transport = |command: Command| -> io::Result<(
261284
StdioServerTransportInner,
@@ -288,39 +311,22 @@ impl LocalStdioServerLauncher {
288311
};
289312
let (transport, stderr, process_id) = spawn_transport(command)?;
290313
#[cfg(windows)]
291-
let (transport, stderr, process_id, job) = match job {
292-
Some(job) => match process_id
293-
.ok_or_else(|| io::Error::other("missing suspended MCP server process id"))
294-
.and_then(|process_id| job.assign_and_resume_process(process_id))
295-
{
296-
Ok(true) => (transport, stderr, process_id, Some(job)),
297-
Ok(false) => (transport, stderr, process_id, None),
298-
Err(error) => {
299-
warn!(
300-
"Windows MCP process job containment failed; retrying without it: {error}"
301-
);
302-
drop(stderr);
303-
drop(transport);
304-
drop(job);
305-
let (transport, stderr, process_id) = spawn_transport(build_command())?;
306-
(transport, stderr, process_id, None)
307-
}
308-
},
309-
None => (transport, stderr, process_id, None),
314+
let job = {
315+
let process_id = process_id
316+
.ok_or_else(|| io::Error::other("missing suspended MCP server process id"))?;
317+
if let Err(error) = job.assign_and_resume_process_strict(process_id) {
318+
drop(stderr);
319+
drop(transport);
320+
drop(job);
321+
return Err(io::Error::new(
322+
error.kind(),
323+
format!("Windows MCP process job containment failed: {error}"),
324+
));
325+
}
326+
job
310327
};
311328
#[cfg(windows)]
312-
let terminator = match job {
313-
Some(job) => Some(LocalProcessTerminator::Job(job)),
314-
None => process_id.and_then(|process_id| {
315-
match codex_utils_pty::JobObject::open_process_handle(process_id) {
316-
Ok(handle) => Some(LocalProcessTerminator::Process(handle)),
317-
Err(error) => {
318-
warn!("Windows MCP process handle unavailable: {error}");
319-
None
320-
}
321-
}
322-
}),
323-
};
329+
let terminator = Some(LocalProcessTerminator::new(job));
324330
#[cfg(not(windows))]
325331
let terminator = process_id.map(LocalProcessTerminator::new);
326332
let process = StdioServerProcessHandle::local(program_name.clone(), terminator);

0 commit comments

Comments
 (0)