diff --git a/CHANGELOG.md b/CHANGELOG.md index 8db989067..b6febf1d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,9 @@ starts with **Upgrade notes**: read them before you upgrade. The upgrade procedu ### Fixed +- A session could stop taking prompts after a burst of prompts broke its harness connection. + The harness waited forever to exit while another task held its event channel, so it was + never replaced. It now exits within seconds and a fresh harness takes over. ([#1826]) - A request that a session's grants do not permit now gets a `403` with a JSON body that names the request. Before, HTTP/1 closed the connection and HTTP/2 sent an empty `403` or reset the stream, so clients printed nothing or a framing error. ([#1822]) @@ -440,3 +443,4 @@ The first tagged release. See the [#1789]: https://github.com/cortexapps/engrams/pull/1789 [#1822]: https://github.com/cortexapps/engrams/pull/1822 [#1825]: https://github.com/cortexapps/engrams/pull/1825 +[#1826]: https://github.com/cortexapps/engrams/pull/1826 diff --git a/crates/engram-harness-sdk/src/lib.rs b/crates/engram-harness-sdk/src/lib.rs index 8963dae16..cf4152d82 100644 --- a/crates/engram-harness-sdk/src/lib.rs +++ b/crates/engram-harness-sdk/src/lib.rs @@ -315,6 +315,47 @@ where pub const SUPERSEDED_TOKEN_GRACE: Duration = Duration::from_secs(15); +/// How long the transport waits for the engine to finish once it has closed +/// the engine's channels. +pub const ENGINE_EXIT_GRACE: Duration = Duration::from_secs(10); + +/// End the engine: close both of its channels, count the events it could not +/// send, and wait at most [`ENGINE_EXIT_GRACE`] for it. Returns the engine's +/// exit code, or `None` when it panicked or did not finish in time (it is then +/// aborted). +/// +/// The receiver is closed before the drain. A drain that waits for every +/// sender to drop never ends while another task still holds one (a hook +/// connection in flight), and a harness that cannot exit is never respawned. +async fn close_out( + command_tx: mpsc::Sender, + mut event_rx: mpsc::Receiver, + mut engine: tokio::task::JoinHandle, +) -> (usize, Option) { + drop(command_tx); + event_rx.close(); + let mut undelivered = 0; + while event_rx.recv().await.is_some() { + undelivered += 1; + } + let code = match tokio::time::timeout(ENGINE_EXIT_GRACE, &mut engine).await { + Ok(Ok(code)) => Some(code), + Ok(Err(e)) => { + tracing::error!(error = %e, "harness engine task panicked"); + None + } + Err(_) => { + tracing::error!( + grace_secs = ENGINE_EXIT_GRACE.as_secs(), + "harness engine did not finish after its channels closed; aborting it" + ); + engine.abort(); + None + } + }; + (undelivered, code) +} + async fn serve_loop( cfg: ConnectionConfig, mut dialer: D, @@ -332,10 +373,7 @@ where Ok(token) => token, Err(e) => { tracing::error!(error = %e, "attach token unavailable"); - drop(command_tx); - event_rx.close(); - while event_rx.recv().await.is_some() {} - let _ = engine.await; + close_out(command_tx, event_rx, engine).await; return ExitCode::from(2); } }; @@ -401,15 +439,10 @@ where epoch = token.binding_epoch, "attach fence remained after token grace" ); - drop(command_tx); - // Drain the close-out events even though this generation cannot send. let unacked = outbox.len(); - let mut undelivered = 0; - while event_rx.recv().await.is_some() { - undelivered += 1; - } + let (undelivered, code) = close_out(command_tx, event_rx, engine).await; tracing::warn!(unacked, undelivered, "fenced harness exit"); - return engine.await.unwrap_or(ExitCode::FAILURE); + return code.unwrap_or(ExitCode::FAILURE); } tokio::select! { _ = reconnect_nudge.recv() => {}, @@ -440,17 +473,10 @@ where } } } - drop(command_tx); let unacked = outbox.len(); - let mut undelivered = 0; - while event_rx.recv().await.is_some() { - undelivered += 1; - } + let (undelivered, code) = close_out(command_tx, event_rx, engine).await; tracing::info!(unacked, undelivered, "harness transport exit"); - engine.await.unwrap_or_else(|e| { - tracing::error!(error = %e, "harness engine task panicked"); - ExitCode::from(1) - }) + code.unwrap_or(ExitCode::from(1)) } async fn dial(cfg: &ConnectionConfig) -> Option<(BoxedReader, BoxedWriter)> { diff --git a/crates/engram-harness-sdk/tests/attach_token.rs b/crates/engram-harness-sdk/tests/attach_token.rs index f527aef78..723ff1541 100644 --- a/crates/engram-harness-sdk/tests/attach_token.rs +++ b/crates/engram-harness-sdk/tests/attach_token.rs @@ -4,7 +4,8 @@ use std::time::Duration; use engram_harness_proto::attach_token::*; use engram_harness_proto::{read_msg, write_msg, AttachReject, HarnessAttach, HarnessAttachAck}; use engram_harness_sdk::{ - serve_with, BoxedReader, BoxedWriter, Channels, ConnectionConfig, SUPERSEDED_TOKEN_GRACE, + serve_with, BoxedReader, BoxedWriter, Channels, ConnectionConfig, ENGINE_EXIT_GRACE, + SUPERSEDED_TOKEN_GRACE, }; use engram_ids::{SandboxId, SessionId}; @@ -216,3 +217,85 @@ async fn superseded_with_newer_token_file_redials_with_new_epoch() { async fn superseded_without_newer_token_exits_after_grace() { superseded_case(false).await; } + +/// A fenced harness exits even while another task still holds an event +/// sender (a hook connection in flight), so agentd can start a fresh one. +/// `engine_finishes = false`: the engine itself never finishes either. +async fn fenced_exit_with_a_stray_event_sender(engine_finishes: bool) -> (ExitCode, Duration) { + let _lock = ENV_LOCK.lock().await; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("token"); + let original = token(1); + let _env = TokenEnv::set(&path, original); + original.write_atomic(&path).unwrap(); + let channels = Channels::new(); + let mut commands = channels.command_rx; + let stray = channels.event_tx.clone(); + let _stray_task = tokio::spawn(async move { + let _held = stray; + std::future::pending::<()>().await; + }); + let events = channels.event_tx; + let engine = tokio::spawn(async move { + let _events = events; + if engine_finishes { + while commands.recv().await.is_some() {} + } else { + std::future::pending::<()>().await; + } + ExitCode::SUCCESS + }); + let (client, mut host) = tokio::io::duplex(4096); + let host_task = tokio::spawn(async move { + let _: HarnessAttach = read_msg(&mut host).await.unwrap(); + write_msg( + &mut host, + &HarnessAttachAck { + ok: false, + reject: Some(AttachReject::Superseded), + message: None, + }, + ) + .await + .unwrap(); + }); + let mut stream = Some(client); + let start = tokio::time::Instant::now(); + let served = tokio::time::timeout( + SUPERSEDED_TOKEN_GRACE + ENGINE_EXIT_GRACE + Duration::from_secs(60), + serve_with( + cfg(), + move || { + let stream = stream.take(); + Box::pin(async move { + stream.map(|s| { + let (r, w) = tokio::io::split(s); + (Box::new(r) as BoxedReader, Box::new(w) as BoxedWriter) + }) + }) + }, + engine, + channels.command_tx, + channels.event_rx, + channels.reattach, + ), + ) + .await + .expect("a fenced harness must exit while a stray event sender is alive"); + host_task.await.unwrap(); + (served, start.elapsed()) +} + +#[tokio::test(start_paused = true)] +async fn fenced_exit_does_not_wait_for_a_stray_event_sender() { + let (code, elapsed) = fenced_exit_with_a_stray_event_sender(true).await; + assert_eq!(code, ExitCode::SUCCESS); + assert_eq!(elapsed, SUPERSEDED_TOKEN_GRACE); +} + +#[tokio::test(start_paused = true)] +async fn fenced_exit_aborts_an_engine_that_does_not_finish() { + let (code, elapsed) = fenced_exit_with_a_stray_event_sender(false).await; + assert_eq!(code, ExitCode::FAILURE); + assert_eq!(elapsed, SUPERSEDED_TOKEN_GRACE + ENGINE_EXIT_GRACE); +}