From d4014cb19d23614be39c0cf57d981e042ba0763a Mon Sep 17 00:00:00 2001 From: Benjamin Carlsson Date: Sat, 21 Nov 2026 23:20:01 +0000 Subject: [PATCH] Keep Cloud reply stream recovery retryable after transient failures (#63058) ## Why Repeated disconnects could exhaust the active recovery attempt limit. A shared deadline also let time spent in the worker queue or waiting to reattach cut into the time available to fetch history and install the replacement stream. ## What changed - Replace the active recovery attempt limit with exponential backoff capped at 30 seconds. - Give worker dispatch, reattachment, recovery history reads, and stream installation separate timeout budgets. Wait for the caller to release the held stream before starting the installation timeout. - Surface transient failures and timeouts as transport errors so callers can retry recovery. Continue to enforce sign-in and network policy checks during recovery. ## Testing Cover dispatch delays and expired queued requests, recovery after repeated transient attach failures, history read timeouts, and rejection of a replacement stream that closes before installation. GitOrigin-RevId: aa1757e01b5cd32b1c4bd38bad97c2650904edd8 --- codex-rs/app-server-client/src/cloud.rs | 63 ++++++---- .../src/cloud_backend/connection_tests.rs | 39 +++--- .../src/cloud_backend/idle.rs | 118 +++++++++++------- .../src/cloud_backend/mod.rs | 62 +++++---- codex-rs/app-server-client/src/cloud_tests.rs | 43 +++++++ 5 files changed, 213 insertions(+), 112 deletions(-) diff --git a/codex-rs/app-server-client/src/cloud.rs b/codex-rs/app-server-client/src/cloud.rs index 0f93c99a25..bc682902ef 100644 --- a/codex-rs/app-server-client/src/cloud.rs +++ b/codex-rs/app-server-client/src/cloud.rs @@ -23,15 +23,16 @@ use std::sync::MutexGuard; use std::sync::PoisonError; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; +use std::time::Duration; use tokio::sync::mpsc; use tokio::sync::oneshot; -use tokio::time::Instant; -use tokio::time::timeout_at; /// Rejection from the original network policy during Cloud recovery. pub const CLOUD_RECOVERY_NETWORK_BLOCKED: &str = "The current network policy blocks cloud reconnection."; +pub(super) const MAX_RECOVERY_BACKOFF: Duration = Duration::from_secs(30); + /// Operations the cloud worker must handle without forwarding to another backend. /// Unsupported operations must return an explicit error; they must not claim success. pub enum CloudOperation { @@ -56,8 +57,9 @@ pub enum CloudOperation { ResumeDisconnectedThread { thread_id: String, require_history: bool, - deadline: Instant, - release: oneshot::Receiver>>, + timeout: Duration, + dispatched: oneshot::Sender<()>, + release: oneshot::Receiver>>, }, Notify(ClientNotification), Resolve { @@ -90,24 +92,23 @@ pub struct CloudCommand { /// Allows the worker to install a held stream after the caller reads its history. /// Dropping the token cancels that replacement. pub struct CloudRecoveryRelease { - release: oneshot::Sender>>, - deadline: Instant, + release: oneshot::Sender>>, + timeout: Duration, } impl CloudRecoveryRelease { - pub async fn install(self) -> Result<(), &'static str> { + pub async fn install(self) -> io::Result<()> { let (ack, mut installed) = oneshot::channel(); - self.release - .send(ack) - .map_err(|_| "Cloud reconnection expired.")?; - let response = match timeout_at(self.deadline, &mut installed).await { - Ok(result) => result.ok(), + let closed = || io::Error::new(io::ErrorKind::BrokenPipe, "Cloud reconnection expired."); + self.release.send(ack).map_err(|_| closed())?; + let response = match tokio::time::timeout(self.timeout, &mut installed).await { + Ok(result) => return result.map_err(|_| closed())?, Err(_) => { installed.close(); installed.try_recv().ok() } }; - response.unwrap_or(Err("Cloud reconnection expired.")) + response.unwrap_or_else(|| Err(io::ErrorKind::TimedOut.into())) } } @@ -348,24 +349,32 @@ impl CloudRequestHandle { &self, thread_id: String, require_history: bool, - deadline: Instant, + timeout: Duration, ) -> Result<(Option, CloudRecoveryRelease), TypedRequestError> { let (release, held) = oneshot::channel(); - let response = timeout_at( - deadline, - self.send(CloudOperation::ResumeDisconnectedThread { - thread_id, - require_history, - deadline, - release: held, - }), - ) - .await - .map_err(io::Error::from) - .and_then(std::convert::identity); + let (dispatched, dispatch) = oneshot::channel(); + let request = self.send(CloudOperation::ResumeDisconnectedThread { + thread_id, + require_history, + timeout, + dispatched, + release: held, + }); + // Bound time in the queue separately so it cannot eat into the + // worker's backoff and Attach budget. Prefer a ready response on expiry. + let watchdog = async { + if tokio::time::timeout(timeout, dispatch).await.is_ok() { + tokio::time::sleep(timeout.saturating_add(MAX_RECOVERY_BACKOFF)).await; + } + }; + let response = tokio::select! { + biased; + result = request => result, + () = watchdog => Err(io::ErrorKind::TimedOut.into()), + }; let settings: Option = crate::decode_typed_response("thread/resume", response)?; - Ok((settings, CloudRecoveryRelease { release, deadline })) + Ok((settings, CloudRecoveryRelease { release, timeout })) } /// Whether a completed model read still belongs to the bound Cloud account. diff --git a/codex-rs/app-server-client/src/cloud_backend/connection_tests.rs b/codex-rs/app-server-client/src/cloud_backend/connection_tests.rs index dcbb7e8631..013c560027 100644 --- a/codex-rs/app-server-client/src/cloud_backend/connection_tests.rs +++ b/codex-rs/app-server-client/src/cloud_backend/connection_tests.rs @@ -257,7 +257,7 @@ async fn failed_archive_loaded_list_tracks_attachment_not_cached_metadata() -> R let mut recovery = idle::Recovery::new(state, Arc::clone(&requests.client), login.clone()); recovery.held = Some(( "t".into(), - tokio::time::Instant::now() + std::time::Duration::from_secs(8), + std::time::Duration::from_secs(8), Box::pin(async move { let idle: &[u8] = b"\x1a\x09\x12\x07\x0a\x02\x12\x00\x12\x01t"; Some(idle::Opened { @@ -272,7 +272,7 @@ async fn failed_archive_loaded_list_tracks_attachment_not_cached_metadata() -> R replies.idle = Some(recovery); requests.warned_partial_history = Some("t".into()); replies.next_event(&output).await; - assert_eq!(installed.await?, Ok(())); + installed.await??; let AppServerEvent::ServerNotification(notification) = notifications.try_recv()? else { panic!("expected held first event"); }; @@ -296,6 +296,7 @@ async fn failed_archive_loaded_list_tracks_attachment_not_cached_metadata() -> R (true, &["7"][..], "install"), (false, &["14", "7"][..], "install"), (false, &["14", "busy"][..], "install"), + (false, &["14", "14", "14", "busy"][..], "outage"), (true, &["busy"][..], "install"), (true, &["busy"][..], "cancel"), (true, &["busy", "busy"][..], "retry"), @@ -340,6 +341,10 @@ async fn failed_archive_loaded_list_tracks_attachment_not_cached_metadata() -> R login.clone() }, ); + if outcome == "outage" { + // Two replacements have already disconnected in quick succession. + recovery.attempts = 2; + } recovery.observed_idle = Some(idle); let mut worker_replies = Replies { idle: Some(recovery), @@ -355,13 +360,16 @@ async fn failed_archive_loaded_list_tracks_attachment_not_cached_metadata() -> R run_worker(commands, &mut worker_requests, &mut worker_replies, &events).await; }); let budget = std::time::Duration::from_secs(if outcome == "slow-history" { 2 } else { 8 }); - let result = handle - .resume_disconnected_thread( - "t".into(), - /*require_history*/ false, - tokio::time::Instant::now() + budget, - ) - .await; + let restore = || { + handle.resume_disconnected_thread("t".into(), /*require_history*/ false, budget) + }; + if outcome == "outage" { + let Err(crate::TypedRequestError::Transport { source, .. }) = restore().await else { + panic!("expected a retryable attach failure"); + }; + assert_eq!(source.kind(), std::io::ErrorKind::ConnectionAborted); + } + let result = restore().await; if outcome == "pat" || statuses.last() == Some(&"7") { let Err(crate::TypedRequestError::Server { source, .. }) = result else { panic!("expected recovery to reject this authentication mode or access denial"); @@ -453,10 +461,10 @@ async fn failed_archive_loaded_list_tracks_attachment_not_cached_metadata() -> R .all(|request| !request.url.path().ends_with("/ListItems")) ); } else if outcome == "slow-history" { - let Err(crate::TypedRequestError::Server { source, .. }) = history else { - panic!("expected the recovery deadline to withhold the page"); + let Err(crate::TypedRequestError::Transport { source, .. }) = history else { + panic!("expected the request timeout to withhold the page"); }; - assert_eq!(source, idle::recovery_error(idle::RECOVERY_TIMEOUT)); + assert_eq!(source.kind(), std::io::ErrorKind::TimedOut); } else { assert_eq!( history?, @@ -490,7 +498,7 @@ async fn failed_archive_loaded_list_tracks_attachment_not_cached_metadata() -> R .resume_disconnected_thread( "t".into(), /*require_history*/ true, - tokio::time::Instant::now() + std::time::Duration::from_secs(8), + std::time::Duration::from_secs(8), ) .await?; assert_eq!(settings.as_ref(), Some(cached.as_ref())); @@ -506,7 +514,10 @@ async fn failed_archive_loaded_list_tracks_attachment_not_cached_metadata() -> R assert!(client.next_event().now_or_never().is_none()); } else { // The wiremock response is finite: it must never ACK a live installation. - assert!(release.install().await.is_err()); + assert_eq!( + release.install().await.unwrap_err().kind(), + std::io::ErrorKind::ConnectionAborted, + ); assert!(client.next_event().now_or_never().is_none()); } } diff --git a/codex-rs/app-server-client/src/cloud_backend/idle.rs b/codex-rs/app-server-client/src/cloud_backend/idle.rs index 3ae171dc07..74d6118180 100644 --- a/codex-rs/app-server-client/src/cloud_backend/idle.rs +++ b/codex-rs/app-server-client/src/cloud_backend/idle.rs @@ -1,11 +1,13 @@ //! Restores Cloud reply streams under the original login and network permit. //! An active recovery holds its stream until the caller has read history. +use super::CloudRecoverySignInChanged; use super::ReplyStream; use super::check_reply_stream; use crate::CLOUD_RECOVERY_NETWORK_BLOCKED; use crate::RequestResult; use crate::cloud::IdleReconnect; +use crate::cloud::MAX_RECOVERY_BACKOFF; use codex_app_server_protocol::JSONRPCErrorError; use codex_app_server_protocol::ThreadResumeResponse; use codex_cloud_client as cloud; @@ -50,8 +52,12 @@ pub(super) struct Login { } impl Login { + pub(super) fn supports_recovery(&self) -> bool { + matches!(self.mode, AuthMode::Chatgpt | AuthMode::ChatgptAuthTokens) + } + pub(super) async fn current(&self) -> bool { - if !matches!(self.mode, AuthMode::Chatgpt | AuthMode::ChatgptAuthTokens) { + if !self.supports_recovery() { return false; } let Ok(Some(auth)) = self @@ -73,11 +79,12 @@ impl Login { }) } + /// A missing reason means all attempts failed transiently. async fn attach( &self, client: &cloud::Client, thread_id: &str, - ) -> Result<(ReplyStream, Option), &'static str> { + ) -> Result<(ReplyStream, Option), Option<&'static str>> { for delay in [ Duration::ZERO, Duration::from_millis(500), @@ -87,7 +94,7 @@ impl Login { tokio::time::sleep(delay).await; } if !self.current().await { - return Err(SIGN_IN_AGAIN); + return Err(Some(SIGN_IN_AGAIN)); } match client .attach(thread_id) @@ -99,27 +106,26 @@ impl Login { }) { Ok(attachment) => { if !self.current().await { - return Err(SIGN_IN_AGAIN); + return Err(Some(SIGN_IN_AGAIN)); } return Ok(attachment); } Err(Some(error)) if !transient(Some(&error)) => { - return Err(blocked_recovery(&error).unwrap_or(RECOVERY_FAILED)); + return Err(Some(blocked_recovery(&error).unwrap_or(RECOVERY_FAILED))); } Err(_) => {} } } - Err("Cloud did not restore the reply stream after several attempts.") + Err(None) } } -pub(super) const RECOVERY_TIMEOUT: &str = "Cloud could not restore the reply stream in time."; -type Release = oneshot::Receiver>>; +type Release = oneshot::Receiver>>; pub(super) struct Opened { pub(super) stream: ReplyStream, pub(super) first: Option, - pub(super) ack: oneshot::Sender>, + pub(super) ack: oneshot::Sender>, } type Open = BoxFuture<'static, Result<(ReplyStream, Option), Option<&'static str>>>; @@ -128,7 +134,7 @@ pub(super) struct Recovery { pub(super) state: watch::Sender, pub(super) pending: Option<(Arc, Open)>, pub(super) installed: Option, - pub(super) held: Option<(String, Instant, BoxFuture<'static, Option>)>, + pub(super) held: Option<(String, Duration, BoxFuture<'static, Option>)>, pub(super) attempts: u8, // None until either the initial Attach event or the activation snapshot establishes status. pub(super) observed_idle: Option, @@ -144,6 +150,22 @@ pub(super) fn transient(error: Option<&cloud::Error>) -> bool { } } +pub(super) fn reply_stream_error(error: Option<&cloud::Error>) -> io::Error { + match error { + Some(cloud::Error::Timeout) => io::ErrorKind::TimedOut.into(), + Some(cloud::Error::Rpc(status)) if status.code == 4 => io::ErrorKind::TimedOut.into(), + error if transient(error) => io::ErrorKind::ConnectionAborted.into(), + error => io::Error::other(error.and_then(blocked_recovery).unwrap_or(RECOVERY_FAILED)), + } +} + +fn recovery_backoff(attempts: u8) -> Duration { + if attempts == 0 { + return Duration::ZERO; + } + Duration::from_millis(500 << (attempts - 1).min(6)).min(MAX_RECOVERY_BACKOFF) +} + impl Recovery { pub(super) fn check_permit(&self) -> Result<(), &'static str> { self.login @@ -152,11 +174,11 @@ impl Recovery { .map_err(|_| CLOUD_RECOVERY_NETWORK_BLOCKED) } - pub(super) fn history_login(&self, thread_id: &str) -> Option<(Arc, Instant)> { + pub(super) fn history_login(&self, thread_id: &str) -> Option<(Arc, Duration)> { self.held .as_ref() .filter(|(root, _, _)| root == thread_id) - .map(|(_, deadline, _)| (Arc::clone(&self.login), *deadline)) + .map(|(_, timeout, _)| (Arc::clone(&self.login), *timeout)) } pub(super) fn start( @@ -164,7 +186,7 @@ impl Recovery { thread_id: String, cached: Box, _require_history: bool, - deadline: Instant, + timeout: Duration, release: Release, mut response: oneshot::Sender>, ) { @@ -177,35 +199,35 @@ impl Recovery { )))); return; } - let attempts = self.attempts; - if attempts >= 3 { - let _ = response.send(Ok(Err(recovery_error( - "The cloud reply stream keeps disconnecting. Your transcript and draft are still here.", - )))); - return; - } self.cancel(); + let backoff = recovery_backoff(self.attempts); + self.attempts = self.attempts.saturating_add(1); let client = Arc::clone(&self.client); let login = Arc::clone(&self.login); let root = thread_id.clone(); let open = async move { - let attempt = login.permit.run(async { - tokio::time::sleep(Duration::from_millis(500 * u64::from(attempts))).await; - login.attach(&client, &root).await - }); + let attach = login.permit.run(login.attach(&client, &root)); + let attempt = async { + if !backoff.is_zero() { + tokio::time::sleep(backoff).await; + } + tokio::time::timeout(timeout, attach).await + }; let opened = tokio::select! { biased; _ = response.closed() => return None, - result = tokio::time::timeout_at(deadline, attempt) => match result { - Ok(Ok(result)) => result, - Ok(Err(_)) => Err(CLOUD_RECOVERY_NETWORK_BLOCKED), - Err(_) => Err(RECOVERY_TIMEOUT), + result = attempt => match result { + Ok(Ok(Ok(attachment))) => Ok(attachment), + Ok(Ok(Err(None))) => Err(Err(io::ErrorKind::ConnectionAborted.into())), + Ok(Ok(Err(Some(reason)))) => Err(Ok(Err(recovery_error(reason)))), + Ok(Err(_)) => Err(Ok(Err(recovery_error(CLOUD_RECOVERY_NETWORK_BLOCKED)))), + Err(error) => Err(Err(error.into())), }, }; let (stream, first) = match opened { Ok(opened) => opened, - Err(reason) => { - let _ = response.send(Ok(Err(recovery_error(reason)))); + Err(failure) => { + let _ = response.send(failure); return None; } }; @@ -221,19 +243,18 @@ impl Recovery { } }; response.send(Ok(Ok(value))).ok()?; - let ack = tokio::time::timeout_at(deadline, release) - .await - .ok()? - .ok()?; + let mut ack = release.await.ok()?; let checked = login.permit.run(login.current()); - let authorized = match tokio::time::timeout_at(deadline, checked).await { - Ok(Ok(true)) => login - .permit - .check() - .map_err(|_| CLOUD_RECOVERY_NETWORK_BLOCKED), - Ok(Ok(false)) => Err(SIGN_IN_AGAIN), - Ok(Err(_)) => Err(CLOUD_RECOVERY_NETWORK_BLOCKED), - Err(_) => Err(RECOVERY_TIMEOUT), + let authorized = tokio::select! { + biased; + _ = ack.closed() => return None, + result = tokio::time::timeout(timeout, checked) => match result { + Ok(Ok(true)) => login.permit.check() + .map_err(|_| io::Error::other(CLOUD_RECOVERY_NETWORK_BLOCKED)), + Ok(Ok(false)) => Err(io::Error::other(CloudRecoverySignInChanged)), + Ok(Err(_)) => Err(io::Error::other(CLOUD_RECOVERY_NETWORK_BLOCKED)), + Err(error) => Err(error.into()), + }, }; if let Err(reason) = authorized { let _ = ack.send(Err(reason)); @@ -241,7 +262,7 @@ impl Recovery { } Some(Opened { stream, first, ack }) }; - self.held = Some((thread_id, deadline, open.boxed())); + self.held = Some((thread_id, timeout, open.boxed())); } pub(super) fn cancel(&mut self) -> Option> { @@ -315,10 +336,7 @@ impl Recovery { pub(super) fn offer(&mut self, id: &str) { // Only OAuth credentials can be rechecked locally. PATs use ordinary explicit reopen. - if !matches!( - self.login.mode, - AuthMode::Chatgpt | AuthMode::ChatgptAuthTokens - ) { + if !self.login.supports_recovery() { return; } let root: Arc = Arc::from(id); @@ -342,7 +360,11 @@ impl Recovery { .await .map_err(|_| None)? .map_err(|_| None)? - .map_err(Some) + .map_err(|reason| { + Some(reason.unwrap_or( + "Cloud did not restore the reply stream after several attempts.", + )) + }) }; self.pending = Some((root, open.boxed())); } diff --git a/codex-rs/app-server-client/src/cloud_backend/mod.rs b/codex-rs/app-server-client/src/cloud_backend/mod.rs index 4bbc7bd4b7..9befeaef8c 100644 --- a/codex-rs/app-server-client/src/cloud_backend/mod.rs +++ b/codex-rs/app-server-client/src/cloud_backend/mod.rs @@ -24,6 +24,7 @@ use futures::FutureExt; use futures::StreamExt; use futures::stream::BoxStream; use serde_json::Value; +use std::io; use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; @@ -95,22 +96,23 @@ impl Replies { recovery.held = None; if let Some(opened) = opened { if let Err(reason) = recovery.check_permit() { - let _ = opened.ack.send(Err(reason)); + let _ = opened.ack.send(Err(io::Error::other(reason))); return; } - let Ok((stream, first)) = check_prepared_stream((opened.stream, opened.first)) - else { - let _ = opened - .ack - .send(Err("Cloud reply stream disconnected again.")); - return; + let (stream, first) = match check_prepared_stream((opened.stream, opened.first)) { + Ok(attachment) => attachment, + Err(error) => { + let _ = opened + .ack + .send(Err(idle::reply_stream_error(error.as_ref()))); + return; + } }; // Commit through the acknowledgement. If the caller timed out // and closed it first, leave the stream held and drop it here. if opened.ack.send(Ok(())).is_err() { return; } - recovery.attempts += 1; recovery.installed = Some(tokio::time::Instant::now()); recovery.observed_idle = None; self.stream_losses.supersede(&root); @@ -242,7 +244,7 @@ impl Replies { return Ok(None); } let mut stream = self.while_listening(open, output).await?; - let first = probe_reply_stream(&mut stream)?; + let first = check_reply_stream(&mut stream).map_err(activation_stream_error)?; Ok(Some((stream, first))) } @@ -335,12 +337,8 @@ impl Replies { } } -fn probe_reply_stream(stream: &mut ReplyStream) -> Result> { - check_reply_stream(stream).map_err(|_| { - eyre!( - "Cloud conversation activated but its stream did not connect. Reopen it before sending." - ) - }) +fn activation_stream_error(_: Option) -> color_eyre::Report { + eyre!("Cloud conversation activated but its stream did not connect. Reopen it before sending.") } /// Opens an app-server client backed by the authenticated native Cloud client. @@ -493,9 +491,13 @@ async fn run_worker_with_prepared( CloudOperation::ResumeDisconnectedThread { thread_id, require_history, - deadline, + timeout, + dispatched, release, } => { + if dispatched.send(()).is_err() { + continue; + } // Retire canceled holds, but commit a ready handoff through its normal ACK. if replies .idle @@ -518,7 +520,7 @@ async fn run_worker_with_prepared( thread_id, cached.clone(), require_history, - deadline, + timeout, release, command.response, ); @@ -563,6 +565,7 @@ async fn run_worker_with_prepared( let is_read = history_thread.is_some() || matches!(&request, protocol::ClientRequest::ThreadList { .. }); let login = history_thread.and_then(|id| replies.idle.as_ref()?.history_login(id)); + let recovery_read = login.is_some(); // When closure and the handshake are both ready, cancel before // the handshake can replace the active attachment. let result = tokio::select! { @@ -576,10 +579,10 @@ async fn run_worker_with_prepared( } result = async { let read = handle_request(request, mode, environment, requests, replies, output); - let Some((login, deadline)) = login else { + let Some((login, timeout)) = login else { return read.await; }; - tokio::time::timeout_at(deadline, login.permit.run(async { + tokio::time::timeout(timeout, login.permit.run(async { if !login.current().await { return Err(eyre!(CloudRecoverySignInChanged)); } @@ -589,10 +592,19 @@ async fn run_worker_with_prepared( } login.permit.check().map_err(|_| eyre!(CLOUD_RECOVERY_NETWORK_BLOCKED))?; result - })).await.map_err(|_| eyre!(idle::RECOVERY_TIMEOUT))? + })).await.map_err(|_| cloud::Error::Timeout)? .map_err(|_| eyre!(CLOUD_RECOVERY_NETWORK_BLOCKED))? } => result, }; + if recovery_read + && let Err(error) = &result + && let Some(cause) = error.downcast_ref::() + { + let _ = command + .response + .send(Err(idle::reply_stream_error(Some(cause)))); + continue; + } if unloads && result.is_ok() && let Some(root) = prepared @@ -649,11 +661,13 @@ struct PreparedResume { const PREPARED_EVENT_LIMIT: usize = 8; -fn check_prepared_stream((mut stream, first): OpenReplyStream) -> Result { +fn check_prepared_stream( + (mut stream, first): OpenReplyStream, +) -> Result> { let mut prefix = Vec::new(); // The regular stream path forwards the prefix and unread tail in order. for _ in usize::from(first.is_some())..PREPARED_EVENT_LIMIT { - let Some(event) = probe_reply_stream(&mut stream)? else { + let Some(event) = check_reply_stream(&mut stream)? else { break; }; prefix.push(Ok(event)); @@ -720,7 +734,9 @@ async fn advance_prepared_resume( match operation { CloudOperation::CommitPreparedResume => { let ready = match candidate.opened { - Some(opened) => check_prepared_stream(opened).map(Some), + Some(opened) => check_prepared_stream(opened) + .map(Some) + .map_err(activation_stream_error), None if replies.admit_turn(id, output).is_ok() && replies.generation == candidate.generation => { diff --git a/codex-rs/app-server-client/src/cloud_tests.rs b/codex-rs/app-server-client/src/cloud_tests.rs index 2f093f95bb..f5ab8cb50f 100644 --- a/codex-rs/app-server-client/src/cloud_tests.rs +++ b/codex-rs/app-server-client/src/cloud_tests.rs @@ -103,6 +103,49 @@ async fn cloud_shutdown_times_out_when_owner_does_not_respond() { assert!(commands.recv().await.is_none()); } +#[tokio::test(start_paused = true)] +async fn cloud_recovery_dispatch_wait_does_not_use_the_attach_budget() { + let (client, mut commands, _events) = CloudClient::channel(/*capacity*/ 1); + let handle = client.request_handle(); + let budget = Duration::from_secs(15); + let one_second = Duration::from_secs(1); + + let start = tokio::time::Instant::now(); + let Err(TypedRequestError::Transport { source, .. }) = handle + .resume_disconnected_thread("t".into(), /*require_history*/ false, budget) + .await + else { + panic!("an undispatched request must time out"); + }; + assert!(start.elapsed() < budget + one_second); + assert_eq!(source.kind(), io::ErrorKind::TimedOut); + let expired = commands.try_recv().unwrap(); + let CloudOperation::ResumeDisconnectedThread { dispatched, .. } = expired.operation else { + panic!("expected the expired recovery command"); + }; + assert!(dispatched.send(()).is_err()); + assert!(expired.response.is_closed()); + + let retry = + handle.resume_disconnected_thread("t".into(), /*require_history*/ false, budget); + let worker = async { + tokio::time::sleep(budget - one_second).await; + let command = commands.recv().await.unwrap(); + let CloudOperation::ResumeDisconnectedThread { dispatched, .. } = command.operation else { + panic!("expected a new recovery command"); + }; + dispatched.send(()).unwrap(); + tokio::time::sleep(MAX_RECOVERY_BACKOFF + budget - one_second).await; + command + .response + .send(Ok(Ok(serde_json::Value::Null))) + .unwrap(); + }; + let (result, ()) = tokio::join!(retry, worker); + let (settings, _release) = result.unwrap(); + assert!(settings.is_none()); +} + #[tokio::test] async fn native_model_list_bypasses_the_cloud_command_queue() -> color_eyre::Result<()> { use codex_app_server_protocol::ModelListResponse;