mirror of
https://github.com/openai/codex.git
synced 2026-11-29 00:00:54 +00:00
Honor Retry-After and preserve server retry deadlines (#47641)
## Why HTTP retries used local backoff even when the server supplied `Retry-After`. Relative retry delays also failed to account for time spent propagating errors or reporting retries. ## What changed - Parse `Retry-After` delay seconds and HTTP dates into a monotonic deadline captured when response headers arrive. - Honor that deadline for HTTP retries, falling back to local backoff when valid advice is absent. - Preserve deadlines through API and Bedrock error mapping, stream retries, and exhausted retry state. Expired advice remains a zero delay instead of triggering local backoff. ## Testing Add coverage for header parsing, deadline countdown and expiry, error mapping after exhausted HTTP retries, and delayed stream retry notifications. Update Responses and remote compaction tests to verify that HTTP retries honor `Retry-After`. GitOrigin-RevId: a2eff02946e5524f29e06f7ba1431e3d339261a4
This commit is contained in:
committed by
copyberry
parent
ab021e9f13
commit
9d8de19674
@@ -10,6 +10,7 @@ codex-utils-rustls-provider = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
http = { workspace = true }
|
||||
http-body = "1.0.1"
|
||||
httpdate = { workspace = true }
|
||||
native-tls = "0.2"
|
||||
opentelemetry = { workspace = true }
|
||||
reqwest = { workspace = true, features = ["json", "rustls-tls-native-roots", "stream"] }
|
||||
@@ -45,6 +46,7 @@ opentelemetry_sdk = { workspace = true }
|
||||
pretty_assertions = { workspace = true }
|
||||
rcgen = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
tracing-subscriber = { workspace = true }
|
||||
|
||||
[lib]
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Errors returned by the shared Codex HTTP transport.
|
||||
|
||||
use crate::client::HttpError;
|
||||
use crate::retry_after::RetryAfter;
|
||||
use http::HeaderMap;
|
||||
use http::StatusCode;
|
||||
use thiserror::Error;
|
||||
@@ -15,6 +16,7 @@ pub enum TransportError {
|
||||
url: Option<String>,
|
||||
headers: Option<HeaderMap>,
|
||||
body: Option<String>,
|
||||
retry_after: Option<RetryAfter>,
|
||||
},
|
||||
#[error("retry limit reached")]
|
||||
RetryLimit,
|
||||
@@ -30,6 +32,22 @@ pub enum TransportError {
|
||||
ResponseTooLarge { max_bytes: usize },
|
||||
}
|
||||
|
||||
impl TransportError {
|
||||
/// Returns retry advice captured when this error response arrived.
|
||||
pub fn retry_after(&self) -> Option<RetryAfter> {
|
||||
match self {
|
||||
Self::Http { retry_after, .. } => *retry_after,
|
||||
Self::Policy(_)
|
||||
| Self::RetryLimit
|
||||
| Self::Timeout
|
||||
| Self::Connection(_)
|
||||
| Self::Network(_)
|
||||
| Self::Build(_)
|
||||
| Self::ResponseTooLarge { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum StreamError {
|
||||
#[error("stream failed: {0}")]
|
||||
|
||||
@@ -11,6 +11,7 @@ mod request;
|
||||
mod request_builder;
|
||||
mod request_draft;
|
||||
mod response;
|
||||
mod retry_after;
|
||||
mod route_aware_client_pool;
|
||||
mod route_aware_redirect;
|
||||
mod tls_backend_fallback;
|
||||
@@ -61,6 +62,7 @@ pub use crate::request::RequestCompression;
|
||||
pub use crate::request::Response;
|
||||
pub use crate::request_builder::RequestBuilder;
|
||||
pub use crate::response::HttpResponse;
|
||||
pub use crate::retry_after::RetryAfter;
|
||||
pub use crate::route_aware_client_pool::RouteAwareClientPool;
|
||||
pub use crate::route_aware_client_pool::RouteAwareClientPoolError;
|
||||
pub use crate::route_aware_client_pool::RouteAwareRequestError;
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
//! Server retry advice captured once so passing an error between callers does not restart it.
|
||||
|
||||
use http::HeaderMap;
|
||||
use http::header::RETRY_AFTER;
|
||||
use std::time::Duration;
|
||||
use std::time::SystemTime;
|
||||
use tokio::time::Instant;
|
||||
|
||||
/// The earliest time a server advised making a follow-up request.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct RetryAfter(Instant);
|
||||
|
||||
impl RetryAfter {
|
||||
/// Captures an interval measured from receipt of the server's advice.
|
||||
pub fn from_delay(delay: Duration) -> Option<Self> {
|
||||
Instant::now().checked_add(delay).map(Self)
|
||||
}
|
||||
|
||||
/// Reads either nonnegative delay seconds or an HTTP date from `Retry-After`.
|
||||
pub fn from_headers(headers: &HeaderMap) -> Option<Self> {
|
||||
Self::from_header(headers.get(RETRY_AFTER)?.to_str().ok()?)
|
||||
}
|
||||
|
||||
/// Reads a `Retry-After` value, including values carried inside a streamed error.
|
||||
pub fn from_header(value: &str) -> Option<Self> {
|
||||
// Sample wall time first so a scheduling pause cannot shorten the server's deadline.
|
||||
let now = SystemTime::now();
|
||||
let received_at = Instant::now();
|
||||
let value = value.trim();
|
||||
let delay = if !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()) {
|
||||
Duration::from_secs(value.parse().ok()?)
|
||||
} else {
|
||||
httpdate::parse_http_date(value)
|
||||
.ok()?
|
||||
.duration_since(now)
|
||||
.unwrap_or_default()
|
||||
};
|
||||
received_at.checked_add(delay).map(Self)
|
||||
}
|
||||
|
||||
/// Returns the original deadline for callers that pass advice on or sleep until it.
|
||||
pub fn deadline(self) -> Instant {
|
||||
self.0
|
||||
}
|
||||
|
||||
/// Returns the remaining delay, or zero after the deadline has passed.
|
||||
pub fn remaining_delay(self) -> Duration {
|
||||
self.0.saturating_duration_since(Instant::now())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "retry_after_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,45 @@
|
||||
use super::*;
|
||||
use http::HeaderValue;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
/// Delta seconds start at receipt and remain present once their deadline expires.
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn delta_seconds_count_down_to_zero() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(RETRY_AFTER, HeaderValue::from_static("10"));
|
||||
let advice = RetryAfter::from_headers(&headers).expect("valid advice");
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
assert_eq!(advice.deadline(), deadline);
|
||||
assert_eq!(advice.remaining_delay(), Duration::from_secs(10));
|
||||
tokio::time::advance(Duration::from_secs(4)).await;
|
||||
assert_eq!(advice.remaining_delay(), Duration::from_secs(6));
|
||||
tokio::time::advance(Duration::from_secs(7)).await;
|
||||
assert_eq!(advice.remaining_delay(), Duration::ZERO);
|
||||
}
|
||||
|
||||
/// HTTP dates share the monotonic clock; expired dates and explicit zero are still advice.
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn http_dates_and_invalid_advice() {
|
||||
let value = httpdate::fmt_http_date(SystemTime::now() + Duration::from_secs(60));
|
||||
let date = httpdate::parse_http_date(&value).expect("formatted date");
|
||||
let before = SystemTime::now();
|
||||
let advice = RetryAfter::from_header(&value).expect("valid date");
|
||||
let after = SystemTime::now();
|
||||
let remaining = advice.remaining_delay();
|
||||
assert!(
|
||||
(date.duration_since(after).unwrap()..=date.duration_since(before).unwrap())
|
||||
.contains(&remaining)
|
||||
);
|
||||
tokio::time::advance(Duration::from_secs(3)).await;
|
||||
assert_eq!(advice.remaining_delay(), remaining - Duration::from_secs(3));
|
||||
|
||||
for value in ["0", "Thu, 01 Jan 1970 00:00:00 GMT"] {
|
||||
assert_eq!(
|
||||
RetryAfter::from_header(value).map(RetryAfter::remaining_delay),
|
||||
Some(Duration::ZERO)
|
||||
);
|
||||
}
|
||||
for value in ["", "-1", "+1", "1.5", "invalid", "18446744073709551615"] {
|
||||
assert_eq!(RetryAfter::from_header(value), None, "{value}");
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ use crate::request::Request;
|
||||
use crate::request::RequestBody;
|
||||
use crate::request::Response;
|
||||
use crate::request_draft::RequestDraft;
|
||||
use crate::retry_after::RetryAfter;
|
||||
use bytes::Bytes;
|
||||
use bytes::BytesMut;
|
||||
use futures::StreamExt;
|
||||
@@ -179,6 +180,7 @@ impl HttpTransport for ReqwestTransport {
|
||||
let resp = self.send(req).await?;
|
||||
let status = resp.status();
|
||||
let headers = resp.headers().clone();
|
||||
let retry_after = RetryAfter::from_headers(&headers);
|
||||
let bytes = match response_body_limit_bytes {
|
||||
Some(max_bytes) => bounded_response_bytes(resp, max_bytes).await,
|
||||
None => resp.bytes().await.map_err(Self::map_error),
|
||||
@@ -191,6 +193,8 @@ impl HttpTransport for ReqwestTransport {
|
||||
) => return Err(error),
|
||||
// Keep bounded diagnostic-body failures from hiding HTTP auth/retry status.
|
||||
Err(_) if response_body_limit_bytes.is_some() => None,
|
||||
// TODO(anp): Preserve retry advice on body failures without changing their
|
||||
// network/timeout classification to HTTP status handling.
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
return Err(TransportError::Http {
|
||||
@@ -198,6 +202,7 @@ impl HttpTransport for ReqwestTransport {
|
||||
url: Some(url),
|
||||
headers: Some(headers),
|
||||
body,
|
||||
retry_after,
|
||||
});
|
||||
}
|
||||
Ok(Response {
|
||||
@@ -216,6 +221,7 @@ impl HttpTransport for ReqwestTransport {
|
||||
let status = resp.status();
|
||||
let headers = resp.headers().clone();
|
||||
if !status.is_success() {
|
||||
let retry_after = RetryAfter::from_headers(&headers);
|
||||
let body = match response_body_limit_bytes {
|
||||
Some(max_bytes) => match bounded_response_bytes(resp, max_bytes).await {
|
||||
Ok(bytes) => {
|
||||
@@ -242,6 +248,7 @@ impl HttpTransport for ReqwestTransport {
|
||||
url: Some(url),
|
||||
headers: Some(headers),
|
||||
body,
|
||||
retry_after,
|
||||
});
|
||||
}
|
||||
let bytes = match response_body_limit_bytes {
|
||||
|
||||
Reference in New Issue
Block a user