Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions md/transport-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand Down
265 changes: 223 additions & 42 deletions src/agent-client-protocol/src/acp_agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -689,7 +693,7 @@ where
async fn write_line_with_shutdown_timeout<W>(
writer: &mut W,
line: String,
stdout_eof_rx: &mut Option<futures::channel::oneshot::Receiver<()>>,
stdout_eof_rx: &mut Option<crate::component::InputClosedSignal>,
stdout_eof_seen: &mut bool,
grace: Duration,
) -> std::io::Result<()>
Expand Down Expand Up @@ -756,9 +760,9 @@ impl<Counterpart: AcpAgentCounterpartRole> crate::ConnectTo<Counterpart> for Acp
self,
client: impl crate::ConnectTo<Counterpart::Counterpart>,
) -> Result<(), crate::Error> {
let (lines, process) = self.spawn_connection()?;
process
.supervise(crate::ConnectTo::<Counterpart>::connect_to(lines, client))
let (channel, driver) = self.spawn_connection()?;
driver
.connect_line_transport::<Counterpart>(channel, client)
.await
}

Expand All @@ -771,14 +775,7 @@ impl<Counterpart: AcpAgentCounterpartRole> crate::ConnectTo<Counterpart> for Acp
/// dropped (which would kill the agent without closing stdin first).
fn into_channel_and_future(self) -> (crate::Channel, Option<crate::ConnectionDriver>) {
match self.spawn_connection() {
Ok((lines, process)) => {
let (channel, driver) =
crate::ConnectTo::<Counterpart>::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 {
Expand Down Expand Up @@ -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<AgentOutgoingLines, AgentIncomingLines>,
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()?;

Expand Down Expand Up @@ -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| {
Expand All @@ -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),
Expand All @@ -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))
}
}

Expand All @@ -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
Expand All @@ -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)]
Expand Down Expand Up @@ -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};

Expand Down Expand Up @@ -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::<Client>::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::Agent>) -> 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::<Client>::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() {
Expand Down Expand Up @@ -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() {
Expand All @@ -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::<Client>::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() {
Expand Down
Loading