Skip to content

Commit 489cd82

Browse files
authored
[BUG] Keep the curl retry deadline stable within an attempt (#4452)
1 parent e51997b commit 489cd82

4 files changed

Lines changed: 173 additions & 37 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,9 @@ Increment the:
8080
`AttributesProcessor`, matching `SyncMetricStorage`.
8181
[#1724](https://github.com/open-telemetry/opentelemetry-cpp/issues/1724)
8282

83+
* [BUG] Keep the curl retry deadline stable within each attempt
84+
[#4452](https://github.com/open-telemetry/opentelemetry-cpp/pull/4452)
85+
8386
## [1.29.0] 2026-09-13
8487

8588
* [RELEASE] Bump main branch to 1.29.0-dev (#4259)

‎ext/include/opentelemetry/ext/http/client/curl/http_operation_curl.h‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -294,8 +294,8 @@ class HttpOperation
294294
void Abort();
295295

296296
/**
297-
* Perform curl message, this function only can be called in the polling thread and it can only
298-
* be called when got a CURLMSG_DONE.
297+
* Process a completed curl message. This is called directly by synchronous requests or from the
298+
* polling thread after receiving CURLMSG_DONE.
299299
*
300300
* @param code CURLcode
301301
* @return true if the request was re-armed for a retry, false if the operation was cleaned up
@@ -330,6 +330,8 @@ class HttpOperation
330330

331331
const char *GetCurlErrorMessage(CURLcode code);
332332

333+
std::chrono::system_clock::time_point CalculateNextRetryTime();
334+
333335
std::atomic<bool> is_aborted_{false}; // Set to 'true' when async callback is aborted
334336
std::atomic<bool> is_finished_{false}; // Set to 'true' when async callback is finished.
335337
std::atomic<bool> is_cleaned_{false}; // Set to 'true' when async callback is cleaned.
@@ -362,7 +364,7 @@ class HttpOperation
362364
const RetryPolicy retry_policy_;
363365
decltype(RetryPolicy::max_attempts) retry_attempts_;
364366
std::chrono::system_clock::time_point last_attempt_time_;
365-
std::chrono::system_clock::time_point retry_after_time_point_{};
367+
std::chrono::system_clock::time_point next_retry_time_point_{};
366368

367369
// Processed response headers and body
368370
// See CURLINFO_RESPONSE_CODE, type is long

‎ext/src/http/client/curl/http_operation_curl.cc‎

Lines changed: 50 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -631,11 +631,16 @@ bool HttpOperation::IsRetryable()
631631

632632
std::chrono::system_clock::time_point HttpOperation::NextRetryTime()
633633
{
634-
if (retry_after_time_point_ != std::chrono::system_clock::time_point{})
634+
if (next_retry_time_point_ != std::chrono::system_clock::time_point{})
635635
{
636-
return retry_after_time_point_;
636+
return next_retry_time_point_;
637637
}
638638

639+
return CalculateNextRetryTime();
640+
}
641+
642+
std::chrono::system_clock::time_point HttpOperation::CalculateNextRetryTime()
643+
{
639644
// One engine per thread. Every HttpClient drives its own background thread, and drawing from
640645
// the engine advances its state, so a shared one is written by all of them at once.
641646
static thread_local std::mt19937 gen{std::random_device{}()};
@@ -1565,9 +1570,9 @@ void HttpOperation::Abort()
15651570
bool HttpOperation::PerformCurlMessage(CURLcode code)
15661571
{
15671572
++retry_attempts_;
1568-
last_attempt_time_ = std::chrono::system_clock::now();
1569-
last_curl_result_ = code;
1570-
retry_after_time_point_ = std::chrono::system_clock::time_point{};
1573+
last_attempt_time_ = std::chrono::system_clock::now();
1574+
last_curl_result_ = code;
1575+
next_retry_time_point_ = std::chrono::system_clock::time_point{};
15711576

15721577
if (code != CURLE_OK)
15731578
{
@@ -1598,34 +1603,15 @@ bool HttpOperation::PerformCurlMessage(CURLcode code)
15981603
curl_easy_getinfo(curl_resource_.easy_handle, CURLINFO_RESPONSE_CODE, &response_code_);
15991604
}
16001605

1601-
// Transform state
1602-
if (GetSessionState() == opentelemetry::ext::http::client::SessionState::Connecting)
1603-
{
1604-
DispatchEvent(opentelemetry::ext::http::client::SessionState::Connected);
1605-
}
1606-
1607-
if (GetSessionState() == opentelemetry::ext::http::client::SessionState::Connected)
1608-
{
1609-
DispatchEvent(opentelemetry::ext::http::client::SessionState::Sending);
1610-
}
1611-
1612-
if (GetSessionState() == opentelemetry::ext::http::client::SessionState::Sending)
1613-
{
1614-
DispatchEvent(opentelemetry::ext::http::client::SessionState::Response);
1615-
}
1616-
1617-
// A server-driven Retry-After may request a retry far beyond the retry
1618-
// policy's max_backoff (e.g. a malicious or misbehaving server returning
1619-
// "Retry-After: 2 years"). Such a session would linger in the pending retry
1620-
// list and block the FIFO drain in doRetrySessions(), so it must be closed
1621-
// rather than honored. Cap the requested delay at max_backoff; if the
1622-
// server-driven retry time still exceeds the maximum expected retry window,
1623-
// the session is closed below and not retried.
1606+
// Establish the deadline before dispatching Response. Event handlers run synchronously and may
1607+
// inspect it from the callback, so calculating it afterwards could expose a different jittered
1608+
// value from the one retained for scheduling this attempt.
16241609
const bool is_retryable = IsRetryable();
16251610
bool retry_after_exceeds_max_delay = false;
16261611

16271612
if (is_retryable)
16281613
{
1614+
bool has_valid_retry_after = false;
16291615
nostd::string_view retry_after;
16301616
if (FindRetryAfterValue(response_headers_, retry_after))
16311617
{
@@ -1636,23 +1622,55 @@ bool HttpOperation::PerformCurlMessage(CURLcode code)
16361622

16371623
if (parsed_delay || parsed_date)
16381624
{
1625+
has_valid_retry_after = true;
16391626
// Reuse the attempt timestamp instead of calling now() again, so the
16401627
// retry-after delay is measured from the attempt that produced this
16411628
// response and we avoid an extra system_clock syscall on the hot path.
1642-
retry_after_time_point_ = parsed_delay
1643-
? (last_attempt_time_ + delay)
1644-
: ((date > last_attempt_time_) ? date : last_attempt_time_);
1629+
next_retry_time_point_ = parsed_delay
1630+
? (last_attempt_time_ + delay)
1631+
: ((date > last_attempt_time_) ? date : last_attempt_time_);
16451632

16461633
const auto max_retry_time =
16471634
last_attempt_time_ +
16481635
std::chrono::duration_cast<std::chrono::milliseconds>(retry_policy_.max_backoff);
1649-
if (retry_after_time_point_ > max_retry_time)
1636+
if (next_retry_time_point_ > max_retry_time)
16501637
{
16511638
retry_after_exceeds_max_delay = true;
16521639
}
16531640
}
16541641
}
16551642

1643+
if (!has_valid_retry_after)
1644+
{
1645+
next_retry_time_point_ = CalculateNextRetryTime();
1646+
}
1647+
}
1648+
1649+
// Transform state
1650+
if (GetSessionState() == opentelemetry::ext::http::client::SessionState::Connecting)
1651+
{
1652+
DispatchEvent(opentelemetry::ext::http::client::SessionState::Connected);
1653+
}
1654+
1655+
if (GetSessionState() == opentelemetry::ext::http::client::SessionState::Connected)
1656+
{
1657+
DispatchEvent(opentelemetry::ext::http::client::SessionState::Sending);
1658+
}
1659+
1660+
if (GetSessionState() == opentelemetry::ext::http::client::SessionState::Sending)
1661+
{
1662+
DispatchEvent(opentelemetry::ext::http::client::SessionState::Response);
1663+
}
1664+
1665+
// A server-driven Retry-After may request a retry far beyond the retry
1666+
// policy's max_backoff (e.g. a malicious or misbehaving server returning
1667+
// "Retry-After: 2 years"). Such a session would linger in the pending retry
1668+
// list and block the FIFO drain in doRetrySessions(), so it must be closed
1669+
// rather than honored. Cap the requested delay at max_backoff; if the
1670+
// server-driven retry time still exceeds the maximum expected retry window,
1671+
// the session is closed below and not retried.
1672+
if (is_retryable)
1673+
{
16561674
if (!retry_after_exceeds_max_delay)
16571675
{
16581676
// Clear any response data received in previous attempt

‎ext/test/http/curl_http_test.cc‎

Lines changed: 115 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,26 @@ class RetryEventHandler : public CustomEventHandler
267267
}
268268
};
269269

270+
#ifdef ENABLE_OTLP_RETRY_PREVIEW
271+
class RetryDeadlineEventHandler : public RetryEventHandler
272+
{
273+
public:
274+
void OnEvent(http_client::SessionState state, nostd::string_view reason) noexcept override
275+
{
276+
CustomEventHandler::OnEvent(state, reason);
277+
if (state == http_client::SessionState::Response && operation_ != nullptr)
278+
{
279+
++response_event_count_;
280+
retry_time_during_response_ = operation_->NextRetryTime();
281+
}
282+
}
283+
284+
curl::HttpOperation *operation_{nullptr};
285+
int response_event_count_{0};
286+
std::chrono::system_clock::time_point retry_time_during_response_{};
287+
};
288+
#endif // ENABLE_OTLP_RETRY_PREVIEW
289+
270290
class BasicCurlHttpTests : public ::testing::Test, public HTTP_SERVER_NS::HttpRequestCallback
271291
{
272292
protected:
@@ -302,6 +322,7 @@ class BasicCurlHttpTests : public ::testing::Test, public HTTP_SERVER_NS::HttpRe
302322
server_.addHandler("/post/", *this);
303323
server_.addHandler("/retry/", *this);
304324
server_.addHandler("/retry-after/", *this);
325+
server_.addHandler("/retry-after-invalid/", *this);
305326
server_.addHandler("/close/", *this);
306327
server_.start();
307328
is_running_ = true;
@@ -335,12 +356,21 @@ class BasicCurlHttpTests : public ::testing::Test, public HTTP_SERVER_NS::HttpRe
335356
response.body = "{'k1':'v1', 'k2':'v2', 'k3':'v3'}";
336357
response_status = 200;
337358
}
338-
else if (request.uri == "/retry/")
359+
else if (request.uri == "/retry/" || request.uri == "/retry-after/" ||
360+
request.uri == "/retry-after-invalid/")
339361
{
340362
std::unique_lock<std::mutex> lk1(mtx_requests);
341363
received_requests_.push_back(request);
342364
response.headers["Content-Type"] = "text/plain";
343-
response_status = 429;
365+
if (request.uri == "/retry-after/")
366+
{
367+
response.headers["Retry-After"] = "2";
368+
}
369+
else if (request.uri == "/retry-after-invalid/")
370+
{
371+
response.headers["Retry-After"] = "invalid";
372+
}
373+
response_status = 429;
344374
}
345375
else if (request.uri == "/retry-after/")
346376
{
@@ -693,6 +723,89 @@ TEST_F(BasicCurlHttpTests, ExponentialBackoffRetry)
693723
ASSERT_FALSE(operation.IsRetryable());
694724
}
695725

726+
TEST_F(BasicCurlHttpTests, RetryDeadlineIsStableWithinAttempt)
727+
{
728+
RetryEventHandler handler;
729+
http_client::HttpSslOptions no_ssl;
730+
http_client::Body body;
731+
http_client::Headers headers;
732+
http_client::Compression compression = http_client::Compression::kNone;
733+
http_client::RetryPolicy retry_policy = {4, std::chrono::duration<float>{1.0f},
734+
std::chrono::duration<float>{5.0f}, 2.0f};
735+
736+
curl::HttpOperation operation(http_client::Method::Post, "http://127.0.0.1:19000/retry/", no_ssl,
737+
&handler, headers, body, compression, false,
738+
curl::kDefaultHttpConnTimeout, false, false, retry_policy);
739+
740+
ASSERT_EQ(CURLE_OK, operation.Send());
741+
ASSERT_TRUE(operation.IsRetryable());
742+
743+
const auto retry_time = operation.NextRetryTime();
744+
for (int i = 0; i < 8; ++i)
745+
{
746+
EXPECT_EQ(retry_time, operation.NextRetryTime());
747+
}
748+
}
749+
750+
TEST_F(BasicCurlHttpTests, RetryDeadlineIsReadyDuringResponseEvent)
751+
{
752+
RetryDeadlineEventHandler handler;
753+
http_client::HttpSslOptions no_ssl;
754+
http_client::Body body;
755+
http_client::Headers headers;
756+
http_client::Compression compression = http_client::Compression::kNone;
757+
http_client::RetryPolicy retry_policy = {4, std::chrono::duration<float>{1.0f},
758+
std::chrono::duration<float>{5.0f}, 2.0f};
759+
760+
curl::HttpOperation operation(http_client::Method::Post, "http://127.0.0.1:19000/retry-after/",
761+
no_ssl, &handler, headers, body, compression, false,
762+
curl::kDefaultHttpConnTimeout, false, false, retry_policy);
763+
handler.operation_ = &operation;
764+
765+
const auto before_send = std::chrono::system_clock::now();
766+
ASSERT_EQ(CURLE_OK, operation.Send());
767+
const auto after_send = std::chrono::system_clock::now();
768+
769+
ASSERT_TRUE(operation.IsRetryable());
770+
ASSERT_EQ(1, handler.response_event_count_);
771+
EXPECT_EQ(handler.retry_time_during_response_, operation.NextRetryTime());
772+
EXPECT_GE(handler.retry_time_during_response_.time_since_epoch().count(),
773+
(before_send + std::chrono::seconds{2}).time_since_epoch().count());
774+
EXPECT_LE(handler.retry_time_during_response_.time_since_epoch().count(),
775+
(after_send + std::chrono::seconds{2}).time_since_epoch().count());
776+
}
777+
778+
TEST_F(BasicCurlHttpTests, InvalidRetryAfterUsesStableBackoff)
779+
{
780+
RetryDeadlineEventHandler handler;
781+
http_client::HttpSslOptions no_ssl;
782+
http_client::Body body;
783+
http_client::Headers headers;
784+
http_client::Compression compression = http_client::Compression::kNone;
785+
http_client::RetryPolicy retry_policy = {4, std::chrono::duration<float>{1.0f},
786+
std::chrono::duration<float>{5.0f}, 2.0f};
787+
788+
curl::HttpOperation operation(
789+
http_client::Method::Post, "http://127.0.0.1:19000/retry-after-invalid/", no_ssl, &handler,
790+
headers, body, compression, false, curl::kDefaultHttpConnTimeout, false, false, retry_policy);
791+
handler.operation_ = &operation;
792+
793+
const auto before_send = std::chrono::system_clock::now();
794+
ASSERT_EQ(CURLE_OK, operation.Send());
795+
const auto after_send = std::chrono::system_clock::now();
796+
797+
ASSERT_TRUE(operation.IsRetryable());
798+
ASSERT_EQ(1, handler.response_event_count_);
799+
for (int i = 0; i < 8; ++i)
800+
{
801+
EXPECT_EQ(handler.retry_time_during_response_, operation.NextRetryTime());
802+
}
803+
EXPECT_GE(handler.retry_time_during_response_.time_since_epoch().count(),
804+
(before_send + std::chrono::milliseconds{750}).time_since_epoch().count());
805+
EXPECT_LE(handler.retry_time_during_response_.time_since_epoch().count(),
806+
(after_send + std::chrono::milliseconds{1250}).time_since_epoch().count());
807+
}
808+
696809
// A Retry-After beyond max_backoff closes the session. The IO loop used to queue it anyway, where
697810
// it held back later retries and the background thread until the server's time.
698811
TEST_F(BasicCurlHttpTests, RetryAfterBeyondMaxBackoffIsNotQueued)

0 commit comments

Comments
 (0)