diff --git a/md/transport-architecture.md b/md/transport-architecture.md index 79773b07..a02a4872 100644 --- a/md/transport-architecture.md +++ b/md/transport-architecture.md @@ -393,6 +393,12 @@ sent `SIGTERM`, followed by `SIGKILL` if it has not exited two seconds later. On Windows the process is killed. An exit that the SDK forced this way is not reported as an error. +If a write fails or an unanswered request ends the connection on stdout EOF, +`AcpAgent` also waits up to one second for the child to exit. A nonzero exit +in that window supplies the connection error, including the stderr tail. +A successful exit or an expired wait preserves the original error. +An independent client error, such as a cancelled operation, bypasses this wait. + Dropping the connection future is cancellation and cannot wait, so it kills the agent's process group immediately with `SIGKILL`. diff --git a/src/agent-client-protocol/src/acp_agent.rs b/src/agent-client-protocol/src/acp_agent.rs index 5287d9f4..b55f82ca 100644 --- a/src/agent-client-protocol/src/acp_agent.rs +++ b/src/agent-client-protocol/src/acp_agent.rs @@ -181,6 +181,10 @@ impl AcpAgentConfig { /// Dropping an active connection (cancellation) cannot wait, so it kills the process /// immediately; on Unix it sends `SIGKILL` to the whole process group. /// +/// A failed write or a request that ends the connection on stdout EOF also gives +/// the agent one second to exit. A nonzero exit takes precedence over that error. +/// A successful exit or an expired wait preserves the original error. +/// /// Nonzero process exits include a bounded stderr tail in the returned error. /// Collection waits only for a bounded shutdown period; if stderr EOF does not /// arrive, bytes already captured are still reported. @@ -689,7 +693,7 @@ where async fn write_line_with_shutdown_timeout( writer: &mut W, line: String, - stdout_eof_rx: &mut Option>, + stdout_eof_rx: &mut Option, stdout_eof_seen: &mut bool, grace: Duration, ) -> std::io::Result<()> @@ -756,9 +760,9 @@ impl crate::ConnectTo for Acp self, client: impl crate::ConnectTo, ) -> Result<(), crate::Error> { - let (lines, process) = self.spawn_connection()?; - process - .supervise(crate::ConnectTo::::connect_to(lines, client)) + let (channel, driver) = self.spawn_connection()?; + driver + .connect_line_transport::(channel, client) .await } @@ -771,14 +775,7 @@ impl crate::ConnectTo for Acp /// dropped (which would kill the agent without closing stdin first). fn into_channel_and_future(self) -> (crate::Channel, Option) { match self.spawn_connection() { - Ok((lines, process)) => { - let (channel, driver) = - crate::ConnectTo::::into_channel_and_future(lines); - let driver = driver - .expect("the line transport owns its I/O") - .map_future(|work| process.supervise(work)); - (channel, Some(driver)) - } + Ok((channel, driver)) => (channel, Some(driver)), Err(error) => { let (channel, peer) = crate::Channel::duplex(); let driver = crate::ConnectionDriver::new(async move { @@ -807,18 +804,10 @@ struct AgentProcess { } impl AcpAgent { - /// Spawns the agent process and splits it into the line transport over - /// its stdio and the process that `AgentProcess::supervise` monitors. - fn spawn_connection( - self, - ) -> Result< - ( - crate::Lines, - AgentProcess, - ), - crate::Error, - > { - use futures::StreamExt; + /// Spawns the agent process and supervises the line transport over its stdio. + fn spawn_connection(self) -> Result<(crate::Channel, crate::ConnectionDriver), crate::Error> { + use futures::future::{Either, select}; + use futures::{FutureExt as _, StreamExt}; let (child_stdin, child_stdout, child_stderr, child) = self.spawn_process()?; @@ -872,6 +861,7 @@ impl AcpAgent { // reading cannot hold a final write open forever. Dropping this stream // merely cancels the signal and is not treated as EOF. let (stdout_eof_tx, stdout_eof_rx) = futures::channel::oneshot::channel(); + let stdout_eof_rx = stdout_eof_rx.shared(); let mut stdout_eof_tx = Some(stdout_eof_tx); let mut incoming_lines = incoming_lines; let incoming_lines: AgentIncomingLines = Box::pin(futures::stream::poll_fn(move |cx| { @@ -889,7 +879,7 @@ impl AcpAgent { ( child_stdin, self.debug_callback.clone(), - Some(stdout_eof_rx), + Some(stdout_eof_rx.clone()), false, ), async move |(mut writer, callback, mut stdout_eof_rx, mut stdout_eof_seen), @@ -909,16 +899,37 @@ impl AcpAgent { }, )); - Ok(( - crate::Lines::new(outgoing_sink, incoming_lines), - AgentProcess { - stderr_future: Box::pin(stderr_future), - child_wait: Box::pin(child_wait), - #[cfg(unix)] - child_pid, - shutdown_timeouts, - }, - )) + let (channel, driver) = + crate::Lines::new(outgoing_sink, incoming_lines).into_channel_transport(); + let process = AgentProcess { + stderr_future: Box::pin(stderr_future), + child_wait: Box::pin(child_wait), + #[cfg(unix)] + child_pid, + shutdown_timeouts, + }; + let (eof_error_tx, eof_error_rx) = futures::channel::oneshot::channel(); + let (process_done_tx, process_done_rx) = futures::channel::oneshot::channel(); + let driver = driver.map_future(|work| { + process + .supervise(async move { + match select(work, eof_error_rx).await { + Either::Left((result, _)) => result, + Either::Right((Ok(error), _)) => Err(error), + Either::Right((Err(_), work)) => work.await, + } + }) + .inspect(move |_| { + let _ = process_done_tx.send(()); + }) + }); + let driver = driver.with_eof_error_report(eof_error_tx, stdout_eof_rx, async move { + // A decorator can suspend its driver or start separate cleanup. + // EOF only waits through the child's exit and stderr deadlines. + let deadline = async_io::Timer::after(shutdown_timeouts.exit + SHUTDOWN_GRACE_PERIOD); + drop(select(process_done_rx, deadline).await); + }); + Ok((channel, driver)) } } @@ -939,14 +950,11 @@ impl AgentProcess { // Boxed (not stack-pinned) so `select` drops it on completion. let protocol_future = Box::pin(protocol_future); - // Run stderr reader alongside the main race. Errors still stop the - // connection immediately. After protocol shutdown succeeds, give the - // child a bounded grace period so delayed failures remain observable - // without letting a non-exiting launcher hang shutdown forever. + // Keep reading stderr while waiting for the child's exit, including + // when a protocol write fails before the exit can be observed. let main_race = async { match futures::future::select(protocol_future, child_wait).await { futures::future::Either::Left((result, child_wait)) => { - result?; // `select` has dropped the completed protocol future and, // with it, the outgoing sink that owns `child_stdin`. The // agent therefore sees EOF on stdin, which is the ACP @@ -957,10 +965,14 @@ impl AgentProcess { ) .await { - futures::future::Either::Left((child, _)) => { - finish_child_exit(child?).await + futures::future::Either::Left((Ok(child), _)) => { + finish_child_exit(child).await.and(result) + } + futures::future::Either::Left((Err(wait_error), _)) => { + result.and(Err(wait_error)) } futures::future::Either::Right((_, child_wait)) => { + result?; terminate_unresponsive_child( child_wait, #[cfg(unix)] @@ -1097,6 +1109,8 @@ impl FromStr for AcpAgent { #[cfg(test)] mod tests { use super::*; + #[cfg(unix)] + use crate::{schema::ProtocolVersion, v1::schema::InitializeRequest}; use std::sync::Mutex; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -1394,6 +1408,132 @@ mod tests { assert!(tail.ends_with("ACP_END")); } + #[cfg(unix)] + #[tokio::test] + async fn direct_connection_preserves_client_error_before_child_exit() { + let (nested, peer) = crate::Channel::duplex(); + drop(peer); + let nested_eof = Client + .v1() + .connect_with(nested, async |cx| { + cx.send_request(InitializeRequest::new(ProtocolVersion::V1)) + .block_task() + .await + }) + .await + .unwrap_err(); + assert!(crate::is_incoming_transport_closed(&nested_eof)); + for expected in [ + crate::Error::request_cancelled().data("client stopped"), + nested_eof, + ] { + let agent = AcpAgent::from_args(["/bin/sh", "-c", "cat >/dev/null; exit 17"]).unwrap(); + let client_error = expected.clone(); + let client = Client + .v1() + .with_spawned(move |_cx| async move { Err(client_error) }); + let error = crate::ConnectTo::::connect_to(agent, client) + .await + .unwrap_err(); + assert_eq!(error.code, expected.code); + assert_eq!(error.data.unwrap()["data"], expected.data.unwrap()); + } + } + + #[cfg(unix)] + #[tokio::test] + async fn failed_initialize_write_reports_agent_exit_and_stderr() { + // A separate pipe releases the agent when the SDK attempts the + // initialize write. Its real stdin is already closed at that point. + let markers = ShutdownMarkers::new("initialize-write"); + let release = markers.dir.join("release"); + let (stderr_tx, mut stderr) = tokio::sync::mpsc::unbounded_channel(); + let agent = AcpAgent::from_args([ + "/bin/sh", + "-c", + r#"exec 0<&- + mkfifo "$1" && exec 3<>"$1" || exit 1 + echo ready >&2 + read -r release <&3 + echo 'error: unknown flag' >&2 + exit 2"#, + "sh", + release.to_str().unwrap(), + ]) + .unwrap() + .with_debug(move |line, direction| match direction { + LineDirection::Stdin => std::fs::write(&release, b"go\n").unwrap(), + LineDirection::Stderr => drop(stderr_tx.send(line.to_owned())), + LineDirection::Stdout => {} + }); + let connection = Client.v1().connect_with(agent, async |cx| { + assert_eq!(stderr.recv().await.as_deref(), Some("ready")); + cx.send_request(InitializeRequest::new(ProtocolVersion::V1)) + .block_task() + .await + }); + let error = tokio::time::timeout(Duration::from_secs(5), connection) + .await + .expect("the failed launch should finish") + .expect_err("initialize should fail after the agent closes stdin"); + + assert_eq!( + error.data.as_ref().and_then(serde_json::Value::as_str), + Some("Process exited with exit status: 2: ready\nerror: unknown flag\n"), + "{error:?}" + ); + assert_eq!(stderr.try_recv().as_deref(), Ok("error: unknown flag")); + } + + #[cfg(unix)] + #[tokio::test] + async fn unanswered_initialize_reports_child_failure_or_original_eof() { + async fn initialize(cx: crate::v1::ConnectionTo) -> crate::Result<()> { + cx.send_request(InitializeRequest::new(ProtocolVersion::V1)) + .block_task() + .await?; + Ok(()) + } + + for (direct, status) in [(false, "0"), (true, "0"), (false, "2"), (true, "2")] { + // Both the initialize write and stdout EOF precede the child exit. + // The child waits for the client to close stdin before exiting. + let agent = AcpAgent::from_args([ + "/bin/sh", + "-c", + r#"read -r request; exec 1>&-; while read -r line; do :; done; echo 'closing' >&2; exit "$1""#, + "sh", + status, + ]) + .unwrap(); + let connection = async { + if direct { + crate::ConnectTo::::connect_to( + agent, + Client.v1().with_spawned(initialize), + ) + .await + } else { + Client.v1().connect_with(agent, initialize).await + } + }; + let error = tokio::time::timeout(Duration::from_secs(5), connection) + .await + .expect("an unanswered initialize should finish after stdout EOF") + .expect_err("the agent never answered initialize"); + + if status == "0" { + assert!(crate::is_incoming_transport_closed(&error), "{error:?}"); + } else { + assert_eq!( + error.data.as_ref().and_then(serde_json::Value::as_str), + Some("Process exited with exit status: 2: closing\n"), + "{error:?}" + ); + } + } + } + #[cfg(unix)] #[tokio::test] async fn protocol_eof_still_reports_nonzero_child_exit() { @@ -1639,6 +1779,28 @@ mod tests { cleanup.disarm(); } + #[cfg(unix)] + #[tokio::test] + async fn cancellation_during_eof_diagnostics_kills_the_child() { + let (mut agent, mut pid_rx) = wrapper_agent( + "read -r request; exec 1>&-; cat >/dev/null; echo ACP_TEST_CHILD_PID=$$ >&2; exec sleep 30", + ); + agent.shutdown_timeouts.exit = Duration::from_secs(30); + let mut connection = Box::pin(Client.v1().connect_with(agent, async |cx| { + cx.send_request(InitializeRequest::new(ProtocolVersion::V1)) + .block_task() + .await?; + Ok(()) + })); + // The PID is emitted only after the supervisor closes stdin and + // begins waiting for the child to exit. + let pid = reported_descendant_pid(&mut connection, &mut pid_rx).await; + let mut cleanup = KillOnDrop(Some(pid)); + drop(connection); + assert_process_exits(pid).await; + cleanup.disarm(); + } + #[cfg(unix)] #[tokio::test] async fn test_connection_drop_kills_wrapper_descendant() { @@ -1656,6 +1818,25 @@ mod tests { cleanup.disarm(); } + #[cfg(unix)] + #[tokio::test] + async fn cancelling_process_work_kills_the_child_before_decorator_cleanup() { + use futures::FutureExt as _; + + let (agent, mut pid_rx) = wrapper_agent("echo ACP_TEST_CHILD_PID=$$ >&2; exec sleep 30"); + let (_channel, driver) = crate::ConnectTo::::into_channel_and_future(agent); + let mut driver = driver.unwrap(); + let pid = reported_descendant_pid(&mut driver, &mut pid_rx).await; + let mut cleanup = KillOnDrop(Some(pid)); + let mut decorated = driver.map_future(|work| async { + drop(work); + futures::future::pending().await + }); + assert!((&mut decorated).now_or_never().is_none()); + assert_process_exits(pid).await; + cleanup.disarm(); + } + #[cfg(unix)] #[tokio::test] async fn test_launcher_exit_kills_descendant_before_stderr_wait() { diff --git a/src/agent-client-protocol/src/component.rs b/src/agent-client-protocol/src/component.rs index 3f73d991..cb840cca 100644 --- a/src/agent-client-protocol/src/component.rs +++ b/src/agent-client-protocol/src/component.rs @@ -26,7 +26,7 @@ //! } //! ``` -use futures::future::BoxFuture; +use futures::future::{BoxFuture, Shared}; use std::{ fmt::Debug, future::Future, @@ -57,6 +57,33 @@ impl FinishControl { } } +pub(crate) type InputClosedSignal = Shared>; + +/// Lets a caller that observed EOF wait for the process to report its exit. +pub(crate) struct EofErrorReport { + error_tx: futures::channel::oneshot::Sender, + input_closed: InputClosedSignal, + completion: BoxFuture<'static, ()>, +} + +impl EofErrorReport { + pub(crate) fn applies_to(&self, error: &crate::Error) -> bool { + use futures::FutureExt as _; + + // A client can propagate an EOF error from another connection. + // A completed or dropped stdout reader identifies this transport's closure. + crate::is_incoming_transport_closed(error) + && self.input_closed.clone().now_or_never().is_some() + } + + pub(crate) async fn wait(self, error: crate::Error) { + drop(self.error_tx.send(error)); + // The driver publishes the result, including any error mapping its + // caller installed. This notification does not own the process. + self.completion.await; + } +} + /// Drives owned endpoint work. /// /// A driver owns the endpoint: successful completion means no further @@ -76,6 +103,7 @@ impl FinishControl { pub struct ConnectionDriver { future: BoxFuture<'static, Result<()>>, finish: Option, + pub(crate) eof_error_report: Option, } impl ConnectionDriver { @@ -91,6 +119,7 @@ impl ConnectionDriver { Self { future: Box::pin(future), finish: None, + eof_error_report: None, } } @@ -146,6 +175,7 @@ impl ConnectionDriver { Self { future: Box::pin(future), finish: Some(FinishControl::new(finish)), + eof_error_report: None, } } @@ -178,9 +208,25 @@ impl ConnectionDriver { Self { future: Box::pin(map(self.future)), finish: self.finish, + eof_error_report: self.eof_error_report, } } + #[cfg(all(feature = "process", not(target_family = "wasm")))] + pub(crate) fn with_eof_error_report( + mut self, + error_tx: futures::channel::oneshot::Sender, + input_closed: InputClosedSignal, + completion: impl Future + Send + 'static, + ) -> Self { + self.eof_error_report = Some(EofErrorReport { + error_tx, + input_closed, + completion: Box::pin(completion), + }); + self + } + /// Request graceful completion, without waiting for it. /// /// Returns `true` if this driver supports cooperative finish, including @@ -205,6 +251,40 @@ impl ConnectionDriver { pub(crate) fn take_finish(&mut self) -> Option { self.finish.take() } + + /// Connect a line transport to its peer. Peer failures can end the + /// connection immediately, while successful completion drains accepted output. + pub(crate) async fn connect_line_transport( + mut self, + channel: Channel, + peer: impl ConnectTo, + ) -> Result<()> { + use futures::future::{Either, select}; + + let mut finish = self + .take_finish() + .expect("the line transport supports finish"); + let peer = Box::pin(ConnectTo::::connect_to(channel, peer)); + match select(peer, self).await { + Either::Left((Ok(()), driver)) => { + finish.request(); + driver.await + } + Either::Left((Err(error), mut driver)) => { + if let Some(report) = driver.eof_error_report.take() + && report.applies_to(&error) + { + return crate::util::run_until(driver, async { + report.wait(error.clone()).await; + Err(error) + }) + .await; + } + Err(error) + } + Either::Right((result, _)) => result, + } + } } impl Future for ConnectionDriver { diff --git a/src/agent-client-protocol/src/jsonrpc.rs b/src/agent-client-protocol/src/jsonrpc.rs index a9bbc5c7..ec4fb5ec 100644 --- a/src/agent-client-protocol/src/jsonrpc.rs +++ b/src/agent-client-protocol/src/jsonrpc.rs @@ -1774,6 +1774,9 @@ impl< let transport_finish = transport_future .as_mut() .and_then(crate::ConnectionDriver::take_finish); + let eof_error_report = transport_future + .as_mut() + .and_then(|driver| driver.eof_error_report.take()); let (transport_completion_tx, transport_completion_rx) = oneshot::channel(); let transport_completion = transport_completion_rx .map(|result| { @@ -1972,7 +1975,19 @@ impl< }, connection.incoming_closed.clone(), ) - .await?; + .await; + // A pending request can fail at EOF before its transport + // driver has reported why the connection closed. + if let Err(error) = &result + && connection.is_incoming_closing() + && let Some(report) = eof_error_report + && report.applies_to(error) + { + // The close coordinator polls the background driver + // once more before returning this foreground error. + report.wait(error.clone()).await; + } + let result = result?; let _ = foreground_done_tx.send(()); let drained = connection .drain_outgoing(transport_finish, wait_owned_transport) @@ -7421,7 +7436,7 @@ where Self { outgoing, incoming } } - fn into_channel_transport(self) -> (Channel, crate::ConnectionDriver) { + pub(crate) fn into_channel_transport(self) -> (Channel, crate::ConnectionDriver) { let Self { outgoing, incoming } = self; let (channel_for_caller, channel_for_lines) = Channel::duplex(); let Channel { mut rx, tx } = channel_for_lines; @@ -7495,22 +7510,8 @@ where IncomingStream: futures::Stream> + Send + 'static, { async fn connect_to(self, client: impl ConnectTo) -> Result<(), crate::Error> { - let (channel, mut serve_self) = self.into_channel_transport(); - let mut finish = serve_self - .take_finish() - .expect("built-in Lines transport supports explicit finishing"); - let client_future = Box::pin(ConnectTo::::connect_to(channel, client)); - - match futures::future::select(client_future, serve_self).await { - Either::Left((result, serve_self)) => { - result?; - // The local bridge has transferred all accepted client output. - // Finish the physical sink without waiting for remote read EOF. - finish.request(); - serve_self.await - } - Either::Right((result, _)) => result, - } + let (channel, driver) = self.into_channel_transport(); + driver.connect_line_transport::(channel, client).await } fn into_channel_and_future(self) -> (Channel, Option) { diff --git a/src/agent-client-protocol/tests/jsonrpc_transport_close.rs b/src/agent-client-protocol/tests/jsonrpc_transport_close.rs index b46acad6..59d66ba6 100644 --- a/src/agent-client-protocol/tests/jsonrpc_transport_close.rs +++ b/src/agent-client-protocol/tests/jsonrpc_transport_close.rs @@ -246,6 +246,43 @@ impl ConnectTo for DrivenEndpoint { } } +#[cfg(all(unix, feature = "process"))] +#[tokio::test] +async fn process_eof_respects_driver_error_mapping_and_bounds_the_wait() { + use agent_client_protocol::{AcpAgent, Client}; + + for pending_cleanup in [false, true] { + let agent = AcpAgent::from_args([ + "/bin/sh", + "-c", + "read -r request; exec 1>&-; cat >/dev/null; exit 17", + ]) + .unwrap(); + let (channel, driver) = ConnectTo::::into_channel_and_future(agent); + let driver = driver.unwrap().map_future(move |work| async move { + let result = work.await; + if pending_cleanup { + future::pending::<()>().await; + } + result.map_err(|_| Error::internal_error().data("wrapped process error")) + }); + let connection = UntypedRole + .builder() + .connect_with(DrivenEndpoint { channel, driver }, async |cx| { + cx.send_request(MyRequest {}).block_task().await + }); + let error = tokio::time::timeout(TIMEOUT, connection) + .await + .expect("an EOF error must not wait for unrelated decorator cleanup") + .unwrap_err(); + if pending_cleanup { + assert_connection_closed(&error, "myRequest"); + } else { + assert_eq!(error, Error::internal_error().data("wrapped process error")); + } + } +} + fn assert_connection_closed(error: &Error, method: &str) { assert!(is_incoming_transport_closed(error)); assert_eq!(error.message, "Incoming transport closed");