From 9ca5747611cde2090bb96f85928288b9639131bb Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 3 Dec 2026 11:35:52 -0800 Subject: [PATCH 1/8] fix(extension-core): report a refused retry at the deadline as a transport failure Bound each retry by the deadline, or the fixed window when there is none, in a single loop, and abandon it with the earlier transport failure. The first attempt stays the caller's to cut short. Signed-off-by: Matthew Grossman --- .../openshell-extension-core/src/transport.rs | 64 ++++++++++++++++++- 1 file changed, 61 insertions(+), 3 deletions(-) diff --git a/crates/openshell-extension-core/src/transport.rs b/crates/openshell-extension-core/src/transport.rs index 8895b7f261..9d2a49edca 100644 --- a/crates/openshell-extension-core/src/transport.rs +++ b/crates/openshell-extension-core/src/transport.rs @@ -205,8 +205,12 @@ fn call_was_not_processed(status: &Status) -> bool { /// /// `call` builds and sends one attempt. No attempt starts after `deadline`, /// or after a fixed window when there is none, and the failure of the last -/// attempt is returned. An attempt still running at `deadline` is the -/// caller's to cut short. +/// attempt is returned. The first attempt still running at `deadline` is the +/// caller's to cut short. A retry still running at `deadline`, or at the end +/// of the fixed window, is abandoned and the failure before it is returned, +/// so a service that keeps refusing the call is not reported as one that +/// timed out. The inner `timeout_at` must stay inside the caller's: both fire +/// at `deadline`, and the inner one is polled first. pub async fn call_with_retries( deadline: Option, mut call: F, @@ -218,8 +222,13 @@ where let give_up = deadline.unwrap_or_else(|| tokio::time::Instant::now() + UNPROCESSED_RETRY_WINDOW); let mut pause = UNPROCESSED_RETRY_FIRST_PAUSE; + let mut previous = None; loop { - let status = match call().await { + let outcome = match previous.take() { + None => call().await, + Some(failure) => retry_until(give_up, failure, call()).await, + }; + let status = match outcome { Ok(response) => return Ok(response), Err(status) => status, }; @@ -228,9 +237,23 @@ where } tokio::time::sleep(pause).await; pause = (pause * 2).min(UNPROCESSED_RETRY_MAX_PAUSE); + previous = Some(status); } } +/// Runs a retry, giving up at `give_up` with the failure that prompted it. +/// The caller's own deadline is the same instant, so an abandoned retry must +/// be settled here: left running, it loses the race and reads as a timeout. +async fn retry_until( + give_up: tokio::time::Instant, + failure: Status, + retry: impl Future>, +) -> Result { + tokio::time::timeout_at(give_up, retry) + .await + .unwrap_or(Err(failure)) +} + fn validate_config(config: &ExtensionChannelConfig) -> Result<(), TransportError> { if config.endpoint.is_empty() { return Err(TransportError::EmptyEndpoint); @@ -546,6 +569,41 @@ mod tests { } } + /// Callers cut the call short at the same deadline. A refused retry that + /// is still connecting then must not turn the failure into a timeout. + #[tokio::test(start_paused = true)] + async fn a_retry_running_at_the_deadline_returns_the_transport_failure() { + for latency_ms in 1..=20 { + let latency = Duration::from_millis(latency_ms); + let deadline = tokio::time::Instant::now() + Duration::from_millis(500); + let result: Result<(), Status> = tokio::time::timeout_at( + deadline, + call_with_retries(Some(deadline), || async move { + tokio::time::sleep(latency).await; + Err(connect_failure(io::ErrorKind::ConnectionRefused)) + }), + ) + .await + .unwrap_or_else(|_| panic!("timed out with {latency:?} per attempt")); + assert!(call_was_not_processed(&result.unwrap_err())); + } + } + + /// The first attempt is not bounded here: a slow service is a timeout. + #[tokio::test(start_paused = true)] + async fn a_first_attempt_running_at_the_deadline_is_left_to_the_caller() { + let deadline = tokio::time::Instant::now() + Duration::from_millis(500); + let result = tokio::time::timeout_at( + deadline, + call_with_retries(Some(deadline), || async { + tokio::time::sleep(Duration::from_secs(10)).await; + Err::<(), _>(connect_failure(io::ErrorKind::ConnectionRefused)) + }), + ) + .await; + assert!(result.is_err()); + } + #[test] fn a_stream_error_this_side_raised_does_not_prove_the_call_was_not_processed() { for reason in [ From b15c1be4564ec875692a1c0f9f443dbff7ec3418 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 3 Dec 2026 12:36:21 -0800 Subject: [PATCH 2/8] test(extension-core): cover a retry that starts just before the deadline The backoff wakes in time, but the refusal arrives after the deadline, so the caller's timeout would otherwise win the race. Signed-off-by: Matthew Grossman --- .../openshell-extension-core/src/transport.rs | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/openshell-extension-core/src/transport.rs b/crates/openshell-extension-core/src/transport.rs index 9d2a49edca..a217a07b86 100644 --- a/crates/openshell-extension-core/src/transport.rs +++ b/crates/openshell-extension-core/src/transport.rs @@ -589,6 +589,27 @@ mod tests { } } + /// With instant refusals the retries run at 0, 5, 15, 35, 75, 155, 255 and + /// 355 ms. The deadline leaves the last one 1 ms, which a refusal that + /// takes 5 ms to arrive overruns, even though the backoff woke in time. + #[tokio::test(start_paused = true)] + async fn a_retry_started_just_before_the_deadline_returns_the_transport_failure() { + let start = tokio::time::Instant::now(); + let deadline = start + Duration::from_millis(356); + let result: Result<(), Status> = tokio::time::timeout_at( + deadline, + call_with_retries(Some(deadline), || async move { + if start.elapsed() >= Duration::from_millis(300) { + tokio::time::sleep(Duration::from_millis(5)).await; + } + Err(connect_failure(io::ErrorKind::ConnectionRefused)) + }), + ) + .await + .expect("timed out instead of reporting the transport failure"); + assert!(call_was_not_processed(&result.unwrap_err())); + } + /// The first attempt is not bounded here: a slow service is a timeout. #[tokio::test(start_paused = true)] async fn a_first_attempt_running_at_the_deadline_is_left_to_the_caller() { From 2efabde42bd4cd68f8e237b7ff527d529c7fed71 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 3 Dec 2026 12:38:35 -0800 Subject: [PATCH 3/8] fix(extension-core): do not start a retry once the backoff reaches the deadline The doc comment promises no attempt starts after the deadline, but a backoff that woke at or after it still started one. Signed-off-by: Matthew Grossman --- .../openshell-extension-core/src/transport.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/crates/openshell-extension-core/src/transport.rs b/crates/openshell-extension-core/src/transport.rs index a217a07b86..5285502034 100644 --- a/crates/openshell-extension-core/src/transport.rs +++ b/crates/openshell-extension-core/src/transport.rs @@ -236,6 +236,9 @@ where return Err(status); } tokio::time::sleep(pause).await; + if tokio::time::Instant::now() >= give_up { + return Err(status); + } pause = (pause * 2).min(UNPROCESSED_RETRY_MAX_PAUSE); previous = Some(status); } @@ -610,6 +613,20 @@ mod tests { assert!(call_was_not_processed(&result.unwrap_err())); } + /// A backoff that ends at the deadline leaves no time for another attempt. + #[tokio::test(start_paused = true)] + async fn no_attempt_starts_once_the_backoff_reaches_the_deadline() { + let deadline = tokio::time::Instant::now() + UNPROCESSED_RETRY_FIRST_PAUSE; + let mut attempts = 0; + let result: Result<(), Status> = call_with_retries(Some(deadline), || { + attempts += 1; + async { Err(connect_failure(io::ErrorKind::ConnectionRefused)) } + }) + .await; + assert!(call_was_not_processed(&result.unwrap_err())); + assert_eq!(attempts, 1); + } + /// The first attempt is not bounded here: a slow service is a timeout. #[tokio::test(start_paused = true)] async fn a_first_attempt_running_at_the_deadline_is_left_to_the_caller() { From 58d8cb882c8e9a5fd19418d3c02a1bb1312123d2 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 3 Dec 2026 12:44:37 -0800 Subject: [PATCH 4/8] refactor(extension-core): let call_before own the deadline Replace call_with_retries with call_before, which bounds every attempt by the deadline itself and returns Elapsed only for a first attempt that runs out of time. Callers no longer wrap it in a second timeout_at at the same instant, so the result no longer depends on which timer is polled first. The fail-open choice moves in as Unprocessed::Fail, the deadline is required, and the fixed retry window is gone. Signed-off-by: Matthew Grossman --- crates/openshell-extension-core/src/lib.rs | 2 +- .../openshell-extension-core/src/transport.rs | 210 +++++++++--------- .../src/plan.rs | 27 +-- .../src/profile_source.rs | 21 +- .../src/runtime.rs | 23 +- .../src/lib.rs | 33 +-- .../src/remote.rs | 26 ++- 7 files changed, 157 insertions(+), 185 deletions(-) diff --git a/crates/openshell-extension-core/src/lib.rs b/crates/openshell-extension-core/src/lib.rs index 3b1701bc94..ecb0642d6e 100644 --- a/crates/openshell-extension-core/src/lib.rs +++ b/crates/openshell-extension-core/src/lib.rs @@ -18,6 +18,6 @@ pub use jwt::{ }; pub use store::ExtensionCredentialStore; pub use transport::{ - ExtensionChannelConfig, ExtensionServerTrust, TransportError, call_with_retries, + ExtensionChannelConfig, ExtensionServerTrust, TransportError, Unprocessed, call_before, connect_channel, }; diff --git a/crates/openshell-extension-core/src/transport.rs b/crates/openshell-extension-core/src/transport.rs index 5285502034..d470dc4583 100644 --- a/crates/openshell-extension-core/src/transport.rs +++ b/crates/openshell-extension-core/src/transport.rs @@ -21,8 +21,6 @@ use tower::service_fn; const CONNECT_TIMEOUT: Duration = Duration::from_secs(5); const KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(10); const KEEP_ALIVE_TIMEOUT: Duration = Duration::from_secs(20); -/// Longest time a call without a deadline keeps being sent again. -const UNPROCESSED_RETRY_WINDOW: Duration = Duration::from_secs(5); const UNPROCESSED_RETRY_FIRST_PAUSE: Duration = Duration::from_millis(5); const UNPROCESSED_RETRY_MAX_PAUSE: Duration = Duration::from_millis(100); @@ -194,8 +192,17 @@ fn call_was_not_processed(status: &Status) -> bool { false } -/// Sends a unary extension call, and sends it again while the failure proves -/// the service never started processing it. +/// Whether a call the service did not process is sent again before the deadline. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Unprocessed { + Retry, + /// For a fail-open binding, which is skipped on its first failure so a + /// service that is down does not delay the request. + Fail, +} + +/// Sends a unary extension call before `deadline`, and sends it again while +/// the failure proves the service never started processing it. /// /// An extension service that restarts or hands over to another instance /// closes its connections. Calls caught by that close fail in the transport @@ -203,58 +210,46 @@ fn call_was_not_processed(status: &Status) -> bool { /// Failures with an unknown outcome and every answer from the service are /// returned as they are. /// -/// `call` builds and sends one attempt. No attempt starts after `deadline`, -/// or after a fixed window when there is none, and the failure of the last -/// attempt is returned. The first attempt still running at `deadline` is the -/// caller's to cut short. A retry still running at `deadline`, or at the end -/// of the fixed window, is abandoned and the failure before it is returned, -/// so a service that keeps refusing the call is not reported as one that -/// timed out. The inner `timeout_at` must stay inside the caller's: both fire -/// at `deadline`, and the inner one is polled first. -pub async fn call_with_retries( - deadline: Option, - mut call: F, -) -> Result +/// `call` builds and sends one attempt. No attempt starts at or after +/// `deadline`. The outer result tracks the local timer and the inner result +/// preserves the service status: +/// +/// - A first attempt still running at `deadline` is `Err(Elapsed)`: the +/// service was slow. +/// - A retry still running at `deadline` is abandoned, and the failure that +/// prompted it is returned as `Ok(Err(_))`. The retry may have connected, +/// so the failure is the earlier one, not necessarily this one. +pub async fn call_before( + deadline: tokio::time::Instant, + unprocessed: Unprocessed, + mut call: impl FnMut() -> Fut, +) -> Result, tokio::time::error::Elapsed> where - F: FnMut() -> Fut, Fut: Future>, { - let give_up = - deadline.unwrap_or_else(|| tokio::time::Instant::now() + UNPROCESSED_RETRY_WINDOW); + let mut status = match tokio::time::timeout_at(deadline, call()).await? { + Ok(response) => return Ok(Ok(response)), + Err(status) => status, + }; let mut pause = UNPROCESSED_RETRY_FIRST_PAUSE; - let mut previous = None; - loop { - let outcome = match previous.take() { - None => call().await, - Some(failure) => retry_until(give_up, failure, call()).await, - }; - let status = match outcome { - Ok(response) => return Ok(response), - Err(status) => status, - }; - if !call_was_not_processed(&status) || tokio::time::Instant::now() + pause > give_up { - return Err(status); - } + while unprocessed == Unprocessed::Retry + && call_was_not_processed(&status) + && tokio::time::Instant::now() + pause < deadline + { tokio::time::sleep(pause).await; - if tokio::time::Instant::now() >= give_up { - return Err(status); + // A timer that wakes late must not start an attempt: `timeout_at` + // polls its future once even when the deadline has passed. + if tokio::time::Instant::now() >= deadline { + break; } pause = (pause * 2).min(UNPROCESSED_RETRY_MAX_PAUSE); - previous = Some(status); + match tokio::time::timeout_at(deadline, call()).await { + Ok(Ok(response)) => return Ok(Ok(response)), + Ok(Err(next)) => status = next, + Err(_) => break, + } } -} - -/// Runs a retry, giving up at `give_up` with the failure that prompted it. -/// The caller's own deadline is the same instant, so an abandoned retry must -/// be settled here: left running, it loses the race and reads as a timeout. -async fn retry_until( - give_up: tokio::time::Instant, - failure: Status, - retry: impl Future>, -) -> Result { - tokio::time::timeout_at(give_up, retry) - .await - .unwrap_or(Err(failure)) + Ok(Err(status)) } fn validate_config(config: &ExtensionChannelConfig) -> Result<(), TransportError> { @@ -502,10 +497,14 @@ mod tests { } } + fn in_five_seconds() -> tokio::time::Instant { + tokio::time::Instant::now() + Duration::from_secs(5) + } + #[tokio::test(start_paused = true)] async fn an_unprocessed_call_is_sent_again_until_it_is_answered() { let mut attempts = 0; - let answer = call_with_retries(None, || { + let answer = call_before(in_five_seconds(), Unprocessed::Retry, || { attempts += 1; let refused = attempts < 4; async move { @@ -517,6 +516,7 @@ mod tests { } }) .await + .unwrap() .unwrap(); assert_eq!(answer, "answer"); assert_eq!(attempts, 4); @@ -532,38 +532,42 @@ mod tests { let code = status.code(); let mut status = Some(status); let mut attempts = 0; - let result: Result<(), Status> = call_with_retries(None, || { - attempts += 1; - let status = status.take().expect("one attempt"); - async move { Err(status) } - }) - .await; + let result: Result<(), Status> = + call_before(in_five_seconds(), Unprocessed::Retry, || { + attempts += 1; + let status = status.take().expect("one attempt"); + async move { Err(status) } + }) + .await + .unwrap(); assert_eq!(result.unwrap_err().code(), code); assert_eq!(attempts, 1); } } #[tokio::test(start_paused = true)] - async fn sending_again_stops_at_the_window() { - let started = tokio::time::Instant::now(); - let result: Result<(), Status> = call_with_retries(None, || async { - Err(connect_failure(io::ErrorKind::ConnectionRefused)) + async fn a_refused_call_is_sent_once_when_retries_are_off() { + let mut attempts = 0; + let result: Result<(), Status> = call_before(in_five_seconds(), Unprocessed::Fail, || { + attempts += 1; + async { Err(connect_failure(io::ErrorKind::ConnectionRefused)) } }) - .await; + .await + .unwrap(); assert!(call_was_not_processed(&result.unwrap_err())); - let elapsed = started.elapsed(); - assert!(elapsed <= UNPROCESSED_RETRY_WINDOW); - assert!(elapsed + UNPROCESSED_RETRY_MAX_PAUSE > UNPROCESSED_RETRY_WINDOW); + assert_eq!(attempts, 1); } #[tokio::test(start_paused = true)] async fn sending_again_stops_at_the_deadline_with_the_transport_failure() { for timeout in [Duration::from_millis(500), Duration::from_secs(20)] { let started = tokio::time::Instant::now(); - let result: Result<(), Status> = call_with_retries(Some(started + timeout), || async { - Err(connect_failure(io::ErrorKind::ConnectionRefused)) - }) - .await; + let result: Result<(), Status> = + call_before(started + timeout, Unprocessed::Retry, || async { + Err(connect_failure(io::ErrorKind::ConnectionRefused)) + }) + .await + .unwrap(); let status = result.unwrap_err(); assert!(status.to_string().contains("connect failure"), "{status}"); let elapsed = started.elapsed(); @@ -572,72 +576,68 @@ mod tests { } } - /// Callers cut the call short at the same deadline. A refused retry that - /// is still connecting then must not turn the failure into a timeout. - #[tokio::test(start_paused = true)] - async fn a_retry_running_at_the_deadline_returns_the_transport_failure() { - for latency_ms in 1..=20 { - let latency = Duration::from_millis(latency_ms); - let deadline = tokio::time::Instant::now() + Duration::from_millis(500); - let result: Result<(), Status> = tokio::time::timeout_at( - deadline, - call_with_retries(Some(deadline), || async move { - tokio::time::sleep(latency).await; - Err(connect_failure(io::ErrorKind::ConnectionRefused)) - }), - ) - .await - .unwrap_or_else(|_| panic!("timed out with {latency:?} per attempt")); - assert!(call_was_not_processed(&result.unwrap_err())); - } - } - /// With instant refusals the retries run at 0, 5, 15, 35, 75, 155, 255 and /// 355 ms. The deadline leaves the last one 1 ms, which a refusal that /// takes 5 ms to arrive overruns, even though the backoff woke in time. #[tokio::test(start_paused = true)] async fn a_retry_started_just_before_the_deadline_returns_the_transport_failure() { let start = tokio::time::Instant::now(); - let deadline = start + Duration::from_millis(356); - let result: Result<(), Status> = tokio::time::timeout_at( - deadline, - call_with_retries(Some(deadline), || async move { + let result: Result<(), Status> = call_before( + start + Duration::from_millis(356), + Unprocessed::Retry, + || async move { if start.elapsed() >= Duration::from_millis(300) { tokio::time::sleep(Duration::from_millis(5)).await; } Err(connect_failure(io::ErrorKind::ConnectionRefused)) - }), + }, ) .await .expect("timed out instead of reporting the transport failure"); assert!(call_was_not_processed(&result.unwrap_err())); } - /// A backoff that ends at the deadline leaves no time for another attempt. + /// A backoff that would end at the deadline leaves no time for another + /// attempt. #[tokio::test(start_paused = true)] - async fn no_attempt_starts_once_the_backoff_reaches_the_deadline() { + async fn no_attempt_starts_when_the_backoff_would_reach_the_deadline() { let deadline = tokio::time::Instant::now() + UNPROCESSED_RETRY_FIRST_PAUSE; let mut attempts = 0; - let result: Result<(), Status> = call_with_retries(Some(deadline), || { + let result: Result<(), Status> = call_before(deadline, Unprocessed::Retry, || { attempts += 1; async { Err(connect_failure(io::ErrorKind::ConnectionRefused)) } }) - .await; + .await + .unwrap(); assert!(call_was_not_processed(&result.unwrap_err())); assert_eq!(attempts, 1); } - /// The first attempt is not bounded here: a slow service is a timeout. + /// The caller's timer wakes the backoff after the deadline, as a loaded + /// runner can: the sleep is still pending when the clock jumps past it. + #[tokio::test(start_paused = true)] + async fn no_attempt_starts_when_the_backoff_wakes_after_the_deadline() { + let timeout = Duration::from_millis(50); + let deadline = tokio::time::Instant::now() + timeout; + let mut attempts = 0; + let call = call_before(deadline, Unprocessed::Retry, || { + attempts += 1; + async { Err::<(), _>(connect_failure(io::ErrorKind::ConnectionRefused)) } + }); + // Poll the call into its backoff, then move the clock to the deadline. + let (result, ()) = tokio::join!(biased; call, tokio::time::advance(timeout)); + assert!(call_was_not_processed(&result.unwrap().unwrap_err())); + assert_eq!(attempts, 1); + } + + /// A slow first attempt is a timeout, not the failure of an attempt. #[tokio::test(start_paused = true)] - async fn a_first_attempt_running_at_the_deadline_is_left_to_the_caller() { + async fn a_first_attempt_running_at_the_deadline_is_a_timeout() { let deadline = tokio::time::Instant::now() + Duration::from_millis(500); - let result = tokio::time::timeout_at( - deadline, - call_with_retries(Some(deadline), || async { - tokio::time::sleep(Duration::from_secs(10)).await; - Err::<(), _>(connect_failure(io::ErrorKind::ConnectionRefused)) - }), - ) + let result = call_before(deadline, Unprocessed::Retry, || async { + tokio::time::sleep(Duration::from_secs(10)).await; + Err::<(), _>(connect_failure(io::ErrorKind::ConnectionRefused)) + }) .await; assert!(result.is_err()); } diff --git a/crates/openshell-gateway-interceptors/src/plan.rs b/crates/openshell-gateway-interceptors/src/plan.rs index a6802bd665..37f9dc5183 100644 --- a/crates/openshell-gateway-interceptors/src/plan.rs +++ b/crates/openshell-gateway-interceptors/src/plan.rs @@ -19,7 +19,7 @@ use openshell_core::proto::gateway_interceptor::v1::{ }; use openshell_extension_core::{ BearerTokenInterceptor, BearerTokenSlot, ExtensionChannelConfig, ExtensionServerTrust, - call_with_retries, connect_channel, + Unprocessed, call_before, connect_channel, }; use tonic::Request; use tracing::{info, warn}; @@ -215,20 +215,17 @@ impl ExecutionPlan { ); let gateway = gateway_metadata(ExtensionFamily::GatewayInterceptor); let deadline = tokio::time::Instant::now() + timeout; - let manifest = tokio::time::timeout_at( - deadline, - call_with_retries(Some(deadline), || { - let mut client = client.clone(); - let gateway = gateway.clone(); - async move { - client - .describe(Request::new(DescribeRequest { - gateway: Some(gateway), - })) - .await - } - }), - ) + let manifest = call_before(deadline, Unprocessed::Retry, || { + let mut client = client.clone(); + let gateway = gateway.clone(); + async move { + client + .describe(Request::new(DescribeRequest { + gateway: Some(gateway), + })) + .await + } + }) .await .map_err(|_| { InterceptorError::Transport(format!("Describe timed out for '{}'", config.name)) diff --git a/crates/openshell-gateway-interceptors/src/profile_source.rs b/crates/openshell-gateway-interceptors/src/profile_source.rs index 306fabbd62..8c633fd08d 100644 --- a/crates/openshell-gateway-interceptors/src/profile_source.rs +++ b/crates/openshell-gateway-interceptors/src/profile_source.rs @@ -10,7 +10,7 @@ use openshell_core::proto::ProviderProfile; use openshell_core::proto::gateway_interceptor::v1::{ ProviderProfileSnapshotRequest, gateway_interceptor_client::GatewayInterceptorClient, }; -use openshell_extension_core::call_with_retries; +use openshell_extension_core::{Unprocessed, call_before}; use prost::Message as _; use sha2::Digest as _; use tonic::Request; @@ -53,17 +53,14 @@ impl GatewayInterceptorProfileSource { pub async fn snapshot(&self) -> Result { let deadline = tokio::time::Instant::now() + self.timeout; - let response = tokio::time::timeout_at( - deadline, - call_with_retries(Some(deadline), || { - let mut client = self.client.clone(); - async move { - client - .snapshot_provider_profiles(Request::new(ProviderProfileSnapshotRequest {})) - .await - } - }), - ) + let response = call_before(deadline, Unprocessed::Retry, || { + let mut client = self.client.clone(); + async move { + client + .snapshot_provider_profiles(Request::new(ProviderProfileSnapshotRequest {})) + .await + } + }) .await .map_err(|_| { InterceptorError::Transport(format!( diff --git a/crates/openshell-gateway-interceptors/src/runtime.rs b/crates/openshell-gateway-interceptors/src/runtime.rs index a92391e9e6..654c9fd95d 100644 --- a/crates/openshell-gateway-interceptors/src/runtime.rs +++ b/crates/openshell-gateway-interceptors/src/runtime.rs @@ -15,7 +15,7 @@ use openshell_core::proto::gateway_interceptor::v1::{ InterceptorEvaluation, InterceptorResult, JsonPatch, ModifyOperationEvaluation, PostCommitEvaluation, ValidateEvaluation, interceptor_evaluation, }; -use openshell_extension_core::{BearerTokenSlot, call_with_retries}; +use openshell_extension_core::{BearerTokenSlot, Unprocessed, call_before}; use prost::Message as _; use prost_types::Struct; use serde_json::{Map, Value}; @@ -335,18 +335,15 @@ async fn evaluate_plan( let request = Request::new(request.clone()); async move { client.evaluate(request).await } }; - // A fail-open binding is bypassed on its first failure, so a service - // that is down does not delay the operation. - let result = tokio::time::timeout_at(deadline, async { - match plan.failure_policy { - FailurePolicy::FailClosed => call_with_retries(Some(deadline), evaluate).await, - FailurePolicy::FailOpen => evaluate().await, - } - }) - .await - .map_err(|_| InterceptorError::Transport("evaluation timed out".to_string()))? - .map_err(|status| InterceptorError::Transport(status.to_string()))? - .into_inner(); + let unprocessed = match plan.failure_policy { + FailurePolicy::FailClosed => Unprocessed::Retry, + FailurePolicy::FailOpen => Unprocessed::Fail, + }; + let result = call_before(deadline, unprocessed, evaluate) + .await + .map_err(|_| InterceptorError::Transport("evaluation timed out".to_string()))? + .map_err(|status| InterceptorError::Transport(status.to_string()))? + .into_inner(); let encoded_len = result.encoded_len(); histogram!("openshell_gateway_interceptor_latency_seconds") .record(start.elapsed().as_secs_f64()); diff --git a/crates/openshell-supervisor-middleware/src/lib.rs b/crates/openshell-supervisor-middleware/src/lib.rs index 9e355209e6..64c39ab42c 100644 --- a/crates/openshell-supervisor-middleware/src/lib.rs +++ b/crates/openshell-supervisor-middleware/src/lib.rs @@ -917,34 +917,7 @@ impl MiddlewareServiceState { } } -/// Whether a call the service did not process is sent again before `timeout`. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Unprocessed { - Retry, - /// For a fail-open binding, which is skipped on its first failure so a - /// service that is down does not delay the request. - Fail, -} - -/// The outer result tracks the local timer. The inner result preserves the service status. -async fn call_before_deadline( - deadline: tokio::time::Instant, - unprocessed: Unprocessed, - mut call: impl FnMut() -> Fut, -) -> std::result::Result, tokio::time::error::Elapsed> -where - Fut: Future>, -{ - tokio::time::timeout_at(deadline, async { - match unprocessed { - Unprocessed::Retry => { - openshell_extension_core::call_with_retries(Some(deadline), call).await - } - Unprocessed::Fail => call().await, - } - }) - .await -} +use openshell_extension_core::Unprocessed; async fn call_with_timeout( timeout: Duration, @@ -956,7 +929,7 @@ where F: FnMut() -> Fut, Fut: Future, tonic::Status>>, { - call_before_deadline(tokio::time::Instant::now() + timeout, unprocessed, call) + openshell_extension_core::call_before(tokio::time::Instant::now() + timeout, unprocessed, call) .await .map_err(|_| { tonic::Status::deadline_exceeded(format!("middleware {operation} timed out")) @@ -2368,7 +2341,7 @@ impl ChainRunner { } } } - let evaluated = match call_before_deadline( + let evaluated = match openshell_extension_core::call_before( now + entry.timeout.min(remaining), match entry.on_error() { OnError::FailClosed => Unprocessed::Retry, diff --git a/crates/openshell-supervisor-middleware/src/remote.rs b/crates/openshell-supervisor-middleware/src/remote.rs index ca8e3d6ae3..07119a8606 100644 --- a/crates/openshell-supervisor-middleware/src/remote.rs +++ b/crates/openshell-supervisor-middleware/src/remote.rs @@ -284,7 +284,7 @@ mod tests { http_preflight_result, http_request_hook_event, http_request_hook_result, http_response_hook_event, http_response_hook_result, }; - use openshell_extension_core::call_with_retries; + use openshell_extension_core::{Unprocessed, call_before}; use tokio::net::TcpListener; use tokio::sync::{mpsc, oneshot}; use tokio_stream::wrappers::TcpListenerStream; @@ -572,12 +572,17 @@ mod tests { tokio::spawn(async move { let mut answered = 0_usize; while !stop.load(Ordering::SeqCst) { - call_with_retries(None, || { - client.evaluate_http_request(Request::new( - HttpRequestEvaluation::default(), - )) - }) + call_before( + tokio::time::Instant::now() + std::time::Duration::from_secs(5), + Unprocessed::Retry, + || { + client.evaluate_http_request(Request::new( + HttpRequestEvaluation::default(), + )) + }, + ) .await + .expect("the call did not time out") .expect("call answered across a hand-over"); answered += 1; } @@ -664,10 +669,13 @@ mod tests { .await .expect("connect"); let call = tokio::spawn(async move { - call_with_retries(None, || { - client.evaluate_http_request(Request::new(HttpRequestEvaluation::default())) - }) + call_before( + tokio::time::Instant::now() + std::time::Duration::from_secs(5), + Unprocessed::Retry, + || client.evaluate_http_request(Request::new(HttpRequestEvaluation::default())), + ) .await + .expect("the call did not time out") }); received From 10de71fd7deb3d899177438cb1db6a309ef5b896 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 3 Dec 2026 12:46:13 -0800 Subject: [PATCH 5/8] revert: refactor(extension-core): let call_before own the deadline Out of scope for the flake fix in #6196. The one-file fix before it covers both races; the wider restructure can be proposed separately. Signed-off-by: Matthew Grossman --- crates/openshell-extension-core/src/lib.rs | 2 +- .../openshell-extension-core/src/transport.rs | 210 +++++++++--------- .../src/plan.rs | 27 ++- .../src/profile_source.rs | 21 +- .../src/runtime.rs | 23 +- .../src/lib.rs | 33 ++- .../src/remote.rs | 26 +-- 7 files changed, 185 insertions(+), 157 deletions(-) diff --git a/crates/openshell-extension-core/src/lib.rs b/crates/openshell-extension-core/src/lib.rs index ecb0642d6e..3b1701bc94 100644 --- a/crates/openshell-extension-core/src/lib.rs +++ b/crates/openshell-extension-core/src/lib.rs @@ -18,6 +18,6 @@ pub use jwt::{ }; pub use store::ExtensionCredentialStore; pub use transport::{ - ExtensionChannelConfig, ExtensionServerTrust, TransportError, Unprocessed, call_before, + ExtensionChannelConfig, ExtensionServerTrust, TransportError, call_with_retries, connect_channel, }; diff --git a/crates/openshell-extension-core/src/transport.rs b/crates/openshell-extension-core/src/transport.rs index d470dc4583..5285502034 100644 --- a/crates/openshell-extension-core/src/transport.rs +++ b/crates/openshell-extension-core/src/transport.rs @@ -21,6 +21,8 @@ use tower::service_fn; const CONNECT_TIMEOUT: Duration = Duration::from_secs(5); const KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(10); const KEEP_ALIVE_TIMEOUT: Duration = Duration::from_secs(20); +/// Longest time a call without a deadline keeps being sent again. +const UNPROCESSED_RETRY_WINDOW: Duration = Duration::from_secs(5); const UNPROCESSED_RETRY_FIRST_PAUSE: Duration = Duration::from_millis(5); const UNPROCESSED_RETRY_MAX_PAUSE: Duration = Duration::from_millis(100); @@ -192,17 +194,8 @@ fn call_was_not_processed(status: &Status) -> bool { false } -/// Whether a call the service did not process is sent again before the deadline. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Unprocessed { - Retry, - /// For a fail-open binding, which is skipped on its first failure so a - /// service that is down does not delay the request. - Fail, -} - -/// Sends a unary extension call before `deadline`, and sends it again while -/// the failure proves the service never started processing it. +/// Sends a unary extension call, and sends it again while the failure proves +/// the service never started processing it. /// /// An extension service that restarts or hands over to another instance /// closes its connections. Calls caught by that close fail in the transport @@ -210,46 +203,58 @@ pub enum Unprocessed { /// Failures with an unknown outcome and every answer from the service are /// returned as they are. /// -/// `call` builds and sends one attempt. No attempt starts at or after -/// `deadline`. The outer result tracks the local timer and the inner result -/// preserves the service status: -/// -/// - A first attempt still running at `deadline` is `Err(Elapsed)`: the -/// service was slow. -/// - A retry still running at `deadline` is abandoned, and the failure that -/// prompted it is returned as `Ok(Err(_))`. The retry may have connected, -/// so the failure is the earlier one, not necessarily this one. -pub async fn call_before( - deadline: tokio::time::Instant, - unprocessed: Unprocessed, - mut call: impl FnMut() -> Fut, -) -> Result, tokio::time::error::Elapsed> +/// `call` builds and sends one attempt. No attempt starts after `deadline`, +/// or after a fixed window when there is none, and the failure of the last +/// attempt is returned. The first attempt still running at `deadline` is the +/// caller's to cut short. A retry still running at `deadline`, or at the end +/// of the fixed window, is abandoned and the failure before it is returned, +/// so a service that keeps refusing the call is not reported as one that +/// timed out. The inner `timeout_at` must stay inside the caller's: both fire +/// at `deadline`, and the inner one is polled first. +pub async fn call_with_retries( + deadline: Option, + mut call: F, +) -> Result where + F: FnMut() -> Fut, Fut: Future>, { - let mut status = match tokio::time::timeout_at(deadline, call()).await? { - Ok(response) => return Ok(Ok(response)), - Err(status) => status, - }; + let give_up = + deadline.unwrap_or_else(|| tokio::time::Instant::now() + UNPROCESSED_RETRY_WINDOW); let mut pause = UNPROCESSED_RETRY_FIRST_PAUSE; - while unprocessed == Unprocessed::Retry - && call_was_not_processed(&status) - && tokio::time::Instant::now() + pause < deadline - { + let mut previous = None; + loop { + let outcome = match previous.take() { + None => call().await, + Some(failure) => retry_until(give_up, failure, call()).await, + }; + let status = match outcome { + Ok(response) => return Ok(response), + Err(status) => status, + }; + if !call_was_not_processed(&status) || tokio::time::Instant::now() + pause > give_up { + return Err(status); + } tokio::time::sleep(pause).await; - // A timer that wakes late must not start an attempt: `timeout_at` - // polls its future once even when the deadline has passed. - if tokio::time::Instant::now() >= deadline { - break; + if tokio::time::Instant::now() >= give_up { + return Err(status); } pause = (pause * 2).min(UNPROCESSED_RETRY_MAX_PAUSE); - match tokio::time::timeout_at(deadline, call()).await { - Ok(Ok(response)) => return Ok(Ok(response)), - Ok(Err(next)) => status = next, - Err(_) => break, - } + previous = Some(status); } - Ok(Err(status)) +} + +/// Runs a retry, giving up at `give_up` with the failure that prompted it. +/// The caller's own deadline is the same instant, so an abandoned retry must +/// be settled here: left running, it loses the race and reads as a timeout. +async fn retry_until( + give_up: tokio::time::Instant, + failure: Status, + retry: impl Future>, +) -> Result { + tokio::time::timeout_at(give_up, retry) + .await + .unwrap_or(Err(failure)) } fn validate_config(config: &ExtensionChannelConfig) -> Result<(), TransportError> { @@ -497,14 +502,10 @@ mod tests { } } - fn in_five_seconds() -> tokio::time::Instant { - tokio::time::Instant::now() + Duration::from_secs(5) - } - #[tokio::test(start_paused = true)] async fn an_unprocessed_call_is_sent_again_until_it_is_answered() { let mut attempts = 0; - let answer = call_before(in_five_seconds(), Unprocessed::Retry, || { + let answer = call_with_retries(None, || { attempts += 1; let refused = attempts < 4; async move { @@ -516,7 +517,6 @@ mod tests { } }) .await - .unwrap() .unwrap(); assert_eq!(answer, "answer"); assert_eq!(attempts, 4); @@ -532,42 +532,38 @@ mod tests { let code = status.code(); let mut status = Some(status); let mut attempts = 0; - let result: Result<(), Status> = - call_before(in_five_seconds(), Unprocessed::Retry, || { - attempts += 1; - let status = status.take().expect("one attempt"); - async move { Err(status) } - }) - .await - .unwrap(); + let result: Result<(), Status> = call_with_retries(None, || { + attempts += 1; + let status = status.take().expect("one attempt"); + async move { Err(status) } + }) + .await; assert_eq!(result.unwrap_err().code(), code); assert_eq!(attempts, 1); } } #[tokio::test(start_paused = true)] - async fn a_refused_call_is_sent_once_when_retries_are_off() { - let mut attempts = 0; - let result: Result<(), Status> = call_before(in_five_seconds(), Unprocessed::Fail, || { - attempts += 1; - async { Err(connect_failure(io::ErrorKind::ConnectionRefused)) } + async fn sending_again_stops_at_the_window() { + let started = tokio::time::Instant::now(); + let result: Result<(), Status> = call_with_retries(None, || async { + Err(connect_failure(io::ErrorKind::ConnectionRefused)) }) - .await - .unwrap(); + .await; assert!(call_was_not_processed(&result.unwrap_err())); - assert_eq!(attempts, 1); + let elapsed = started.elapsed(); + assert!(elapsed <= UNPROCESSED_RETRY_WINDOW); + assert!(elapsed + UNPROCESSED_RETRY_MAX_PAUSE > UNPROCESSED_RETRY_WINDOW); } #[tokio::test(start_paused = true)] async fn sending_again_stops_at_the_deadline_with_the_transport_failure() { for timeout in [Duration::from_millis(500), Duration::from_secs(20)] { let started = tokio::time::Instant::now(); - let result: Result<(), Status> = - call_before(started + timeout, Unprocessed::Retry, || async { - Err(connect_failure(io::ErrorKind::ConnectionRefused)) - }) - .await - .unwrap(); + let result: Result<(), Status> = call_with_retries(Some(started + timeout), || async { + Err(connect_failure(io::ErrorKind::ConnectionRefused)) + }) + .await; let status = result.unwrap_err(); assert!(status.to_string().contains("connect failure"), "{status}"); let elapsed = started.elapsed(); @@ -576,68 +572,72 @@ mod tests { } } + /// Callers cut the call short at the same deadline. A refused retry that + /// is still connecting then must not turn the failure into a timeout. + #[tokio::test(start_paused = true)] + async fn a_retry_running_at_the_deadline_returns_the_transport_failure() { + for latency_ms in 1..=20 { + let latency = Duration::from_millis(latency_ms); + let deadline = tokio::time::Instant::now() + Duration::from_millis(500); + let result: Result<(), Status> = tokio::time::timeout_at( + deadline, + call_with_retries(Some(deadline), || async move { + tokio::time::sleep(latency).await; + Err(connect_failure(io::ErrorKind::ConnectionRefused)) + }), + ) + .await + .unwrap_or_else(|_| panic!("timed out with {latency:?} per attempt")); + assert!(call_was_not_processed(&result.unwrap_err())); + } + } + /// With instant refusals the retries run at 0, 5, 15, 35, 75, 155, 255 and /// 355 ms. The deadline leaves the last one 1 ms, which a refusal that /// takes 5 ms to arrive overruns, even though the backoff woke in time. #[tokio::test(start_paused = true)] async fn a_retry_started_just_before_the_deadline_returns_the_transport_failure() { let start = tokio::time::Instant::now(); - let result: Result<(), Status> = call_before( - start + Duration::from_millis(356), - Unprocessed::Retry, - || async move { + let deadline = start + Duration::from_millis(356); + let result: Result<(), Status> = tokio::time::timeout_at( + deadline, + call_with_retries(Some(deadline), || async move { if start.elapsed() >= Duration::from_millis(300) { tokio::time::sleep(Duration::from_millis(5)).await; } Err(connect_failure(io::ErrorKind::ConnectionRefused)) - }, + }), ) .await .expect("timed out instead of reporting the transport failure"); assert!(call_was_not_processed(&result.unwrap_err())); } - /// A backoff that would end at the deadline leaves no time for another - /// attempt. + /// A backoff that ends at the deadline leaves no time for another attempt. #[tokio::test(start_paused = true)] - async fn no_attempt_starts_when_the_backoff_would_reach_the_deadline() { + async fn no_attempt_starts_once_the_backoff_reaches_the_deadline() { let deadline = tokio::time::Instant::now() + UNPROCESSED_RETRY_FIRST_PAUSE; let mut attempts = 0; - let result: Result<(), Status> = call_before(deadline, Unprocessed::Retry, || { + let result: Result<(), Status> = call_with_retries(Some(deadline), || { attempts += 1; async { Err(connect_failure(io::ErrorKind::ConnectionRefused)) } }) - .await - .unwrap(); + .await; assert!(call_was_not_processed(&result.unwrap_err())); assert_eq!(attempts, 1); } - /// The caller's timer wakes the backoff after the deadline, as a loaded - /// runner can: the sleep is still pending when the clock jumps past it. - #[tokio::test(start_paused = true)] - async fn no_attempt_starts_when_the_backoff_wakes_after_the_deadline() { - let timeout = Duration::from_millis(50); - let deadline = tokio::time::Instant::now() + timeout; - let mut attempts = 0; - let call = call_before(deadline, Unprocessed::Retry, || { - attempts += 1; - async { Err::<(), _>(connect_failure(io::ErrorKind::ConnectionRefused)) } - }); - // Poll the call into its backoff, then move the clock to the deadline. - let (result, ()) = tokio::join!(biased; call, tokio::time::advance(timeout)); - assert!(call_was_not_processed(&result.unwrap().unwrap_err())); - assert_eq!(attempts, 1); - } - - /// A slow first attempt is a timeout, not the failure of an attempt. + /// The first attempt is not bounded here: a slow service is a timeout. #[tokio::test(start_paused = true)] - async fn a_first_attempt_running_at_the_deadline_is_a_timeout() { + async fn a_first_attempt_running_at_the_deadline_is_left_to_the_caller() { let deadline = tokio::time::Instant::now() + Duration::from_millis(500); - let result = call_before(deadline, Unprocessed::Retry, || async { - tokio::time::sleep(Duration::from_secs(10)).await; - Err::<(), _>(connect_failure(io::ErrorKind::ConnectionRefused)) - }) + let result = tokio::time::timeout_at( + deadline, + call_with_retries(Some(deadline), || async { + tokio::time::sleep(Duration::from_secs(10)).await; + Err::<(), _>(connect_failure(io::ErrorKind::ConnectionRefused)) + }), + ) .await; assert!(result.is_err()); } diff --git a/crates/openshell-gateway-interceptors/src/plan.rs b/crates/openshell-gateway-interceptors/src/plan.rs index 37f9dc5183..a6802bd665 100644 --- a/crates/openshell-gateway-interceptors/src/plan.rs +++ b/crates/openshell-gateway-interceptors/src/plan.rs @@ -19,7 +19,7 @@ use openshell_core::proto::gateway_interceptor::v1::{ }; use openshell_extension_core::{ BearerTokenInterceptor, BearerTokenSlot, ExtensionChannelConfig, ExtensionServerTrust, - Unprocessed, call_before, connect_channel, + call_with_retries, connect_channel, }; use tonic::Request; use tracing::{info, warn}; @@ -215,17 +215,20 @@ impl ExecutionPlan { ); let gateway = gateway_metadata(ExtensionFamily::GatewayInterceptor); let deadline = tokio::time::Instant::now() + timeout; - let manifest = call_before(deadline, Unprocessed::Retry, || { - let mut client = client.clone(); - let gateway = gateway.clone(); - async move { - client - .describe(Request::new(DescribeRequest { - gateway: Some(gateway), - })) - .await - } - }) + let manifest = tokio::time::timeout_at( + deadline, + call_with_retries(Some(deadline), || { + let mut client = client.clone(); + let gateway = gateway.clone(); + async move { + client + .describe(Request::new(DescribeRequest { + gateway: Some(gateway), + })) + .await + } + }), + ) .await .map_err(|_| { InterceptorError::Transport(format!("Describe timed out for '{}'", config.name)) diff --git a/crates/openshell-gateway-interceptors/src/profile_source.rs b/crates/openshell-gateway-interceptors/src/profile_source.rs index 8c633fd08d..306fabbd62 100644 --- a/crates/openshell-gateway-interceptors/src/profile_source.rs +++ b/crates/openshell-gateway-interceptors/src/profile_source.rs @@ -10,7 +10,7 @@ use openshell_core::proto::ProviderProfile; use openshell_core::proto::gateway_interceptor::v1::{ ProviderProfileSnapshotRequest, gateway_interceptor_client::GatewayInterceptorClient, }; -use openshell_extension_core::{Unprocessed, call_before}; +use openshell_extension_core::call_with_retries; use prost::Message as _; use sha2::Digest as _; use tonic::Request; @@ -53,14 +53,17 @@ impl GatewayInterceptorProfileSource { pub async fn snapshot(&self) -> Result { let deadline = tokio::time::Instant::now() + self.timeout; - let response = call_before(deadline, Unprocessed::Retry, || { - let mut client = self.client.clone(); - async move { - client - .snapshot_provider_profiles(Request::new(ProviderProfileSnapshotRequest {})) - .await - } - }) + let response = tokio::time::timeout_at( + deadline, + call_with_retries(Some(deadline), || { + let mut client = self.client.clone(); + async move { + client + .snapshot_provider_profiles(Request::new(ProviderProfileSnapshotRequest {})) + .await + } + }), + ) .await .map_err(|_| { InterceptorError::Transport(format!( diff --git a/crates/openshell-gateway-interceptors/src/runtime.rs b/crates/openshell-gateway-interceptors/src/runtime.rs index 654c9fd95d..a92391e9e6 100644 --- a/crates/openshell-gateway-interceptors/src/runtime.rs +++ b/crates/openshell-gateway-interceptors/src/runtime.rs @@ -15,7 +15,7 @@ use openshell_core::proto::gateway_interceptor::v1::{ InterceptorEvaluation, InterceptorResult, JsonPatch, ModifyOperationEvaluation, PostCommitEvaluation, ValidateEvaluation, interceptor_evaluation, }; -use openshell_extension_core::{BearerTokenSlot, Unprocessed, call_before}; +use openshell_extension_core::{BearerTokenSlot, call_with_retries}; use prost::Message as _; use prost_types::Struct; use serde_json::{Map, Value}; @@ -335,15 +335,18 @@ async fn evaluate_plan( let request = Request::new(request.clone()); async move { client.evaluate(request).await } }; - let unprocessed = match plan.failure_policy { - FailurePolicy::FailClosed => Unprocessed::Retry, - FailurePolicy::FailOpen => Unprocessed::Fail, - }; - let result = call_before(deadline, unprocessed, evaluate) - .await - .map_err(|_| InterceptorError::Transport("evaluation timed out".to_string()))? - .map_err(|status| InterceptorError::Transport(status.to_string()))? - .into_inner(); + // A fail-open binding is bypassed on its first failure, so a service + // that is down does not delay the operation. + let result = tokio::time::timeout_at(deadline, async { + match plan.failure_policy { + FailurePolicy::FailClosed => call_with_retries(Some(deadline), evaluate).await, + FailurePolicy::FailOpen => evaluate().await, + } + }) + .await + .map_err(|_| InterceptorError::Transport("evaluation timed out".to_string()))? + .map_err(|status| InterceptorError::Transport(status.to_string()))? + .into_inner(); let encoded_len = result.encoded_len(); histogram!("openshell_gateway_interceptor_latency_seconds") .record(start.elapsed().as_secs_f64()); diff --git a/crates/openshell-supervisor-middleware/src/lib.rs b/crates/openshell-supervisor-middleware/src/lib.rs index 64c39ab42c..9e355209e6 100644 --- a/crates/openshell-supervisor-middleware/src/lib.rs +++ b/crates/openshell-supervisor-middleware/src/lib.rs @@ -917,7 +917,34 @@ impl MiddlewareServiceState { } } -use openshell_extension_core::Unprocessed; +/// Whether a call the service did not process is sent again before `timeout`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Unprocessed { + Retry, + /// For a fail-open binding, which is skipped on its first failure so a + /// service that is down does not delay the request. + Fail, +} + +/// The outer result tracks the local timer. The inner result preserves the service status. +async fn call_before_deadline( + deadline: tokio::time::Instant, + unprocessed: Unprocessed, + mut call: impl FnMut() -> Fut, +) -> std::result::Result, tokio::time::error::Elapsed> +where + Fut: Future>, +{ + tokio::time::timeout_at(deadline, async { + match unprocessed { + Unprocessed::Retry => { + openshell_extension_core::call_with_retries(Some(deadline), call).await + } + Unprocessed::Fail => call().await, + } + }) + .await +} async fn call_with_timeout( timeout: Duration, @@ -929,7 +956,7 @@ where F: FnMut() -> Fut, Fut: Future, tonic::Status>>, { - openshell_extension_core::call_before(tokio::time::Instant::now() + timeout, unprocessed, call) + call_before_deadline(tokio::time::Instant::now() + timeout, unprocessed, call) .await .map_err(|_| { tonic::Status::deadline_exceeded(format!("middleware {operation} timed out")) @@ -2341,7 +2368,7 @@ impl ChainRunner { } } } - let evaluated = match openshell_extension_core::call_before( + let evaluated = match call_before_deadline( now + entry.timeout.min(remaining), match entry.on_error() { OnError::FailClosed => Unprocessed::Retry, diff --git a/crates/openshell-supervisor-middleware/src/remote.rs b/crates/openshell-supervisor-middleware/src/remote.rs index 07119a8606..ca8e3d6ae3 100644 --- a/crates/openshell-supervisor-middleware/src/remote.rs +++ b/crates/openshell-supervisor-middleware/src/remote.rs @@ -284,7 +284,7 @@ mod tests { http_preflight_result, http_request_hook_event, http_request_hook_result, http_response_hook_event, http_response_hook_result, }; - use openshell_extension_core::{Unprocessed, call_before}; + use openshell_extension_core::call_with_retries; use tokio::net::TcpListener; use tokio::sync::{mpsc, oneshot}; use tokio_stream::wrappers::TcpListenerStream; @@ -572,17 +572,12 @@ mod tests { tokio::spawn(async move { let mut answered = 0_usize; while !stop.load(Ordering::SeqCst) { - call_before( - tokio::time::Instant::now() + std::time::Duration::from_secs(5), - Unprocessed::Retry, - || { - client.evaluate_http_request(Request::new( - HttpRequestEvaluation::default(), - )) - }, - ) + call_with_retries(None, || { + client.evaluate_http_request(Request::new( + HttpRequestEvaluation::default(), + )) + }) .await - .expect("the call did not time out") .expect("call answered across a hand-over"); answered += 1; } @@ -669,13 +664,10 @@ mod tests { .await .expect("connect"); let call = tokio::spawn(async move { - call_before( - tokio::time::Instant::now() + std::time::Duration::from_secs(5), - Unprocessed::Retry, - || client.evaluate_http_request(Request::new(HttpRequestEvaluation::default())), - ) + call_with_retries(None, || { + client.evaluate_http_request(Request::new(HttpRequestEvaluation::default())) + }) .await - .expect("the call did not time out") }); received From 76ba46323cf7378394457d99c7997957dd0171d4 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 3 Dec 2026 12:52:42 -0800 Subject: [PATCH 6/8] fix(extension-core): settle a retry at the deadline in one place Run each retry under timeout_at(give_up) in a single loop, with a strict pre-sleep bound, so a retry that overruns the deadline reports the failure before it instead of racing the caller's timeout. Drop the overlapping latency sweep test. Signed-off-by: Matthew Grossman --- .../openshell-extension-core/src/transport.rs | 76 +++++-------------- 1 file changed, 18 insertions(+), 58 deletions(-) diff --git a/crates/openshell-extension-core/src/transport.rs b/crates/openshell-extension-core/src/transport.rs index 5285502034..c241c1a6fa 100644 --- a/crates/openshell-extension-core/src/transport.rs +++ b/crates/openshell-extension-core/src/transport.rs @@ -203,14 +203,10 @@ fn call_was_not_processed(status: &Status) -> bool { /// Failures with an unknown outcome and every answer from the service are /// returned as they are. /// -/// `call` builds and sends one attempt. No attempt starts after `deadline`, -/// or after a fixed window when there is none, and the failure of the last -/// attempt is returned. The first attempt still running at `deadline` is the -/// caller's to cut short. A retry still running at `deadline`, or at the end -/// of the fixed window, is abandoned and the failure before it is returned, -/// so a service that keeps refusing the call is not reported as one that -/// timed out. The inner `timeout_at` must stay inside the caller's: both fire -/// at `deadline`, and the inner one is polled first. +/// `call` builds and sends one attempt. No retry runs past `deadline`, or past +/// a fixed window when there is none, and the failure of the last attempt is +/// returned. The first attempt is the caller's to cut short; a retry still +/// running at the deadline is abandoned and the failure before it is returned. pub async fn call_with_retries( deadline: Option, mut call: F, @@ -222,39 +218,23 @@ where let give_up = deadline.unwrap_or_else(|| tokio::time::Instant::now() + UNPROCESSED_RETRY_WINDOW); let mut pause = UNPROCESSED_RETRY_FIRST_PAUSE; - let mut previous = None; - loop { - let outcome = match previous.take() { - None => call().await, - Some(failure) => retry_until(give_up, failure, call()).await, - }; - let status = match outcome { - Ok(response) => return Ok(response), - Err(status) => status, - }; - if !call_was_not_processed(&status) || tokio::time::Instant::now() + pause > give_up { - return Err(status); - } + let mut status = match call().await { + Ok(response) => return Ok(response), + Err(status) => status, + }; + while call_was_not_processed(&status) && tokio::time::Instant::now() + pause < give_up { tokio::time::sleep(pause).await; - if tokio::time::Instant::now() >= give_up { - return Err(status); - } pause = (pause * 2).min(UNPROCESSED_RETRY_MAX_PAUSE); - previous = Some(status); + // The caller's timeout fires at the same instant as this one. A + // `Timeout` polls its future before its timer, so the caller's sees + // this settled failure instead of timing out. + status = match tokio::time::timeout_at(give_up, call()).await { + Ok(Ok(response)) => return Ok(response), + Ok(Err(status)) => status, + Err(_) => break, + }; } -} - -/// Runs a retry, giving up at `give_up` with the failure that prompted it. -/// The caller's own deadline is the same instant, so an abandoned retry must -/// be settled here: left running, it loses the race and reads as a timeout. -async fn retry_until( - give_up: tokio::time::Instant, - failure: Status, - retry: impl Future>, -) -> Result { - tokio::time::timeout_at(give_up, retry) - .await - .unwrap_or(Err(failure)) + Err(status) } fn validate_config(config: &ExtensionChannelConfig) -> Result<(), TransportError> { @@ -572,26 +552,6 @@ mod tests { } } - /// Callers cut the call short at the same deadline. A refused retry that - /// is still connecting then must not turn the failure into a timeout. - #[tokio::test(start_paused = true)] - async fn a_retry_running_at_the_deadline_returns_the_transport_failure() { - for latency_ms in 1..=20 { - let latency = Duration::from_millis(latency_ms); - let deadline = tokio::time::Instant::now() + Duration::from_millis(500); - let result: Result<(), Status> = tokio::time::timeout_at( - deadline, - call_with_retries(Some(deadline), || async move { - tokio::time::sleep(latency).await; - Err(connect_failure(io::ErrorKind::ConnectionRefused)) - }), - ) - .await - .unwrap_or_else(|_| panic!("timed out with {latency:?} per attempt")); - assert!(call_was_not_processed(&result.unwrap_err())); - } - } - /// With instant refusals the retries run at 0, 5, 15, 35, 75, 155, 255 and /// 355 ms. The deadline leaves the last one 1 ms, which a refusal that /// takes 5 ms to arrive overruns, even though the backoff woke in time. From b2d17c5e2569c7c8ab0b0a8ed859a6c261634a3d Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 3 Dec 2026 15:01:14 -0800 Subject: [PATCH 7/8] fix(extension-core): start a retry only if it has room to answer Drop the per-retry timeout_at. A retry now starts only when at least the pause it waited remains before the deadline, so every retry runs to completion and reports what happened: a refusal is a transport failure, and a retry that connected and hangs is a timeout, as for a first attempt. Calls without a deadline are no longer cut at the fixed window. Signed-off-by: Matthew Grossman --- .../openshell-extension-core/src/transport.rs | 91 ++++++++++++++----- 1 file changed, 67 insertions(+), 24 deletions(-) diff --git a/crates/openshell-extension-core/src/transport.rs b/crates/openshell-extension-core/src/transport.rs index c241c1a6fa..820c0772fd 100644 --- a/crates/openshell-extension-core/src/transport.rs +++ b/crates/openshell-extension-core/src/transport.rs @@ -203,10 +203,12 @@ fn call_was_not_processed(status: &Status) -> bool { /// Failures with an unknown outcome and every answer from the service are /// returned as they are. /// -/// `call` builds and sends one attempt. No retry runs past `deadline`, or past -/// a fixed window when there is none, and the failure of the last attempt is -/// returned. The first attempt is the caller's to cut short; a retry still -/// running at the deadline is abandoned and the failure before it is returned. +/// `call` builds and sends one attempt. A retry starts only if it leaves at +/// least the pause it waited to answer before `deadline` (or before a fixed +/// window when there is none), so a service that keeps refusing the call is +/// reported as such and not as one that timed out. The failure of the last +/// attempt is returned. An attempt still running at `deadline` is the caller's +/// to cut short. pub async fn call_with_retries( deadline: Option, mut call: F, @@ -218,23 +220,18 @@ where let give_up = deadline.unwrap_or_else(|| tokio::time::Instant::now() + UNPROCESSED_RETRY_WINDOW); let mut pause = UNPROCESSED_RETRY_FIRST_PAUSE; - let mut status = match call().await { - Ok(response) => return Ok(response), - Err(status) => status, - }; - while call_was_not_processed(&status) && tokio::time::Instant::now() + pause < give_up { + loop { + let status = match call().await { + Ok(response) => return Ok(response), + Err(status) => status, + }; + // The retry starts one `pause` from now and keeps one more to answer. + if !call_was_not_processed(&status) || tokio::time::Instant::now() + 2 * pause > give_up { + return Err(status); + } tokio::time::sleep(pause).await; pause = (pause * 2).min(UNPROCESSED_RETRY_MAX_PAUSE); - // The caller's timeout fires at the same instant as this one. A - // `Timeout` polls its future before its timer, so the caller's sees - // this settled failure instead of timing out. - status = match tokio::time::timeout_at(give_up, call()).await { - Ok(Ok(response)) => return Ok(response), - Ok(Err(status)) => status, - Err(_) => break, - }; } - Err(status) } fn validate_config(config: &ExtensionChannelConfig) -> Result<(), TransportError> { @@ -533,7 +530,7 @@ mod tests { assert!(call_was_not_processed(&result.unwrap_err())); let elapsed = started.elapsed(); assert!(elapsed <= UNPROCESSED_RETRY_WINDOW); - assert!(elapsed + UNPROCESSED_RETRY_MAX_PAUSE > UNPROCESSED_RETRY_WINDOW); + assert!(elapsed + 2 * UNPROCESSED_RETRY_MAX_PAUSE > UNPROCESSED_RETRY_WINDOW); } #[tokio::test(start_paused = true)] @@ -548,13 +545,14 @@ mod tests { assert!(status.to_string().contains("connect failure"), "{status}"); let elapsed = started.elapsed(); assert!(elapsed <= timeout); - assert!(elapsed + UNPROCESSED_RETRY_MAX_PAUSE > timeout); + assert!(elapsed + 2 * UNPROCESSED_RETRY_MAX_PAUSE > timeout); } } - /// With instant refusals the retries run at 0, 5, 15, 35, 75, 155, 255 and - /// 355 ms. The deadline leaves the last one 1 ms, which a refusal that - /// takes 5 ms to arrive overruns, even though the backoff woke in time. + /// With instant refusals the retries would run at 0, 5, 15, 35, 75, 155, + /// 255 and 355 ms. The 355 ms retry is not started, because it would have + /// 1 ms to answer before the 356 ms deadline: a refusal that takes 5 ms to + /// arrive would overrun it and read as a timeout. #[tokio::test(start_paused = true)] async fn a_retry_started_just_before_the_deadline_returns_the_transport_failure() { let start = tokio::time::Instant::now(); @@ -573,7 +571,52 @@ mod tests { assert!(call_was_not_processed(&result.unwrap_err())); } - /// A backoff that ends at the deadline leaves no time for another attempt. + /// A retry that connected and then hangs is a slow service, not a + /// refusal: the caller's timeout reports it, as it does for a first attempt. + #[tokio::test(start_paused = true)] + async fn a_retry_that_hangs_is_left_to_the_caller() { + let deadline = tokio::time::Instant::now() + Duration::from_millis(500); + let mut attempts = 0; + let result = tokio::time::timeout_at( + deadline, + call_with_retries(Some(deadline), || { + attempts += 1; + let hangs = attempts > 1; + async move { + if hangs { + std::future::pending().await + } + Err::<(), _>(connect_failure(io::ErrorKind::ConnectionRefused)) + } + }), + ) + .await; + assert!(result.is_err()); + assert_eq!(attempts, 2); + } + + /// Without a deadline the window only limits when a retry starts. + #[tokio::test(start_paused = true)] + async fn a_retry_started_inside_the_window_may_answer_after_it() { + let mut attempts = 0; + let answer = call_with_retries(None, || { + attempts += 1; + let slow = attempts > 1; + async move { + if slow { + tokio::time::sleep(UNPROCESSED_RETRY_WINDOW + Duration::from_secs(1)).await; + Ok("answer") + } else { + Err(connect_failure(io::ErrorKind::ConnectionRefused)) + } + } + }) + .await + .unwrap(); + assert_eq!(answer, "answer"); + } + + /// A backoff that leaves no room to answer starts no retry. #[tokio::test(start_paused = true)] async fn no_attempt_starts_once_the_backoff_reaches_the_deadline() { let deadline = tokio::time::Instant::now() + UNPROCESSED_RETRY_FIRST_PAUSE; From f5111d03626494193d17a95055b167f073d17314 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 3 Dec 2026 15:53:00 -0800 Subject: [PATCH 8/8] test(extension-core): end the hanging retry statement with a semicolon Signed-off-by: Matthew Grossman --- crates/openshell-extension-core/src/transport.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/openshell-extension-core/src/transport.rs b/crates/openshell-extension-core/src/transport.rs index 820c0772fd..07746c99f7 100644 --- a/crates/openshell-extension-core/src/transport.rs +++ b/crates/openshell-extension-core/src/transport.rs @@ -584,7 +584,7 @@ mod tests { let hangs = attempts > 1; async move { if hangs { - std::future::pending().await + std::future::pending::<()>().await; } Err::<(), _>(connect_failure(io::ErrorKind::ConnectionRefused)) }