Skip to content

Commit 6d71cc5

Browse files
committed
[EXPORTER] OTLP ForceFlush waits for the requests it was called with
ForceFlush on both OTLP clients compared two lifetime totals, started and finished, so it waited for a number of completions rather than for the requests it was called with. A request that starts after the call and finishes before a pending one supplies one of those completions, and the flush then reported success with the earlier request still in flight. owent stated the contract on issue 4339: ForceFlush(timeout) returns true only when all requests that were pending before the call have completed. Both clients already register every request, OtlpHttpClient in running_sessions_ and OtlpGrpcClient in async_data->running_calls, so only an order was missing. Each entry carries a sequence taken from the existing monotonic start counter, and the flush asks whether any entry still has a sequence below the one it was entered with. The same predicate ends the wait and produces the result. The sequence is assigned inside the critical section the predicate uses. On the gRPC side the counter increment moved into the same block as the insert, since a flush reading the counter between them would have found a request counted and not present. Ordering across a wrap is a distance and not a comparison, and what has to stay under half the range is how many sequences are handed out while the request being asked about is alive, which the concurrency limit does not bound. At size_t width that was reachable on 32 bit: a request holding sequence zero while another slot completes 2^31 requests falls one past the half range and is skipped, where comparing lifetime totals answers correctly. So the sequence is std::uint64_t, which makes the OTLP HTTP client a new user of 64 bit atomics. It now calls otel_link_libatomic, and its pkg-config file carries EXTRA_LIBS with the detected atomic library, both of which the gRPC client already had. The generator emits only what EXTRA_LIBS lists and does not read a target's link dependencies, so a consumer with curl disabled, linking through pkg-config --static, would otherwise be left with an undefined __atomic_fetch_add_8. The gRPC completion callback now drops running_requests under the same lock as the erase. While the flush read finished_request_counter that did not matter, because the counter is bumped after the decrement; once the erase is what a flush sees, a flush could report success in between while the next Export was still refused for capacity. finished_session_counter_ and finished_request_counter lose all their readers and are removed. One case per client drives the public ForceFlush: a later request finishing while the original is pending must not satisfy it. That fails three runs of three on main, on both the result and the duration, returning at 210 ms against a 500 ms deadline for HTTP and at 200 ms against 1000 ms for gRPC. Both arrange the ordering with a sleep, which is safe here: if it is reordered the flush is entered with both requests pending, it waits, and that is what the case asserts, so it passes without measuring rather than failing. The other direction cannot be arranged that way, because asserting success fails when a reordering puts the later request inside the snapshot, and nothing a test can observe says when the cutoff was read. So it is asked of the predicate directly, in two sequential cases with no threads, through the fixture that OtlpHttpClient now friends, as otlp_http_exporter.h already does for that same fixture. One completes the later request and asserts the snapshot is still not satisfied; the other completes the original while the later one is in flight and asserts that it is. The split matters: whichever request is completed first is no longer in the registry for the other question, and a single sequence covering both passed against a flush that waited for the whole registry to empty. With the split that mutant is killed. Both sequential cases finish whatever is still registered on the way out. Every assertion in them runs before either request completes, and ~OtlpHttpClient waits for the registry to empty with no deadline, so a fatal assertion would otherwise hang rather than fail. With the predicate forced to report done, the case fails in under a second and names the line. The guard lives in an anonymous namespace, since a helper in a test translation unit has no reason to have external linkage. The gRPC predicate cannot be reached the same way, since it is a free function in an anonymous namespace and its counter lives in a struct defined in the .cc, so only the end to end case covers that client. Full suite green with the async export preview on and off, 1525 cases each, and in an HTTP build without gRPC, 1479. Clean under OTELCPP_MAINTAINER_MODE with -Werror. ThreadSanitizer reports the same four warnings before and after on the gRPC side, all inside libgrpc and libabsl, with no frame in this change and no lock order inversion. Refs open-telemetry/opentelemetry-cpp issue 4339 Signed-off-by: thc1006 <84045975+thc1006@users.noreply.github.com>
1 parent da57137 commit 6d71cc5

7 files changed

Lines changed: 451 additions & 34 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,14 @@ Increment the:
1515

1616
## [Unreleased]
1717

18+
* [EXPORTER] `OtlpHttpClient::ForceFlush`, and `OtlpGrpcClient::ForceFlush`
19+
under the async export preview, now wait for the requests that were pending
20+
when they were called, instead of for as many completions as there were
21+
requests started. A request begun after the call could supply one of those
22+
completions, so the flush reported success with an earlier request still in
23+
flight
24+
[#4339](https://github.com/open-telemetry/opentelemetry-cpp/issues/4339)
25+
1826
* [SDK] Restore the check in `DoubleHistogram::Record` that drops NaN and +Inf
1927
measurements, so they no longer reach the histogram aggregations
2028

‎exporters/otlp/CMakeLists.txt‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -368,6 +368,7 @@ if(OTELCPP_WITH_OTLP_HTTP)
368368
opentelemetry_exporter_otlp_http_client
369369
PUBLIC opentelemetry_http_client
370370
PRIVATE opentelemetry_common)
371+
otel_link_libatomic(opentelemetry_exporter_otlp_http_client)
371372

372373
target_include_directories(
373374
opentelemetry_exporter_otlp_http_client
@@ -529,7 +530,8 @@ if(OTELCPP_WITH_OTLP_HTTP)
529530
endif()
530531
opentelemetry_add_pkgconfig(
531532
exporter_otlp_http_client "OpenTelemetry OTLP - HTTP Client"
532-
"HTTP client for OTLP protocol." "${_otlp_http_client_pc_requires}")
533+
"HTTP client for OTLP protocol." "${_otlp_http_client_pc_requires}"
534+
EXTRA_LIBS ${OPENTELEMETRY_ATOMIC_LIB})
533535

534536
opentelemetry_add_pkgconfig(
535537
exporter_otlp_http

‎exporters/otlp/include/opentelemetry/exporters/otlp/otlp_http_client.h‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
#include <chrono>
88
#include <condition_variable>
99
#include <cstddef>
10+
#include <cstdint>
1011
#include <functional>
1112
#include <list>
1213
#include <memory>
@@ -244,6 +245,12 @@ class OtlpHttpClient
244245
std::unique_ptr<google::protobuf::Arena> arena;
245246
google::protobuf::Message *response = nullptr;
246247

248+
// Where this session falls in the order sessions were started, taken from
249+
// start_session_counter_ before it is incremented. ForceFlush waits for the sessions below
250+
// the sequence it was entered with, rather than for a number of completions that a session
251+
// started after the call could supply.
252+
std::uint64_t sequence = 0;
253+
247254
HttpSessionData() noexcept;
248255
HttpSessionData(std::shared_ptr<opentelemetry::ext::http::client::Session> &&input_session,
249256
std::shared_ptr<opentelemetry::ext::http::client::EventHandler> &&input_handle,
@@ -286,6 +293,15 @@ class OtlpHttpClient
286293
*/
287294
bool cleanupGCSessions() noexcept;
288295

296+
/**
297+
* @brief Whether every session started before the given sequence has finished.
298+
*
299+
* Reads running_sessions_ under session_manager_lock_, so it answers for the moment it is
300+
* called. A session started after the call has a sequence at or above the given one, so it
301+
* does not hold the answer back.
302+
*/
303+
bool allSessionsBeforeFinished(std::uint64_t sequence) noexcept;
304+
289305
// Stores if this HTTP client had its Shutdown() method called
290306
std::atomic<bool> is_shutdown_;
291307

@@ -308,8 +324,11 @@ class OtlpHttpClient
308324
// Condition variable and mutex to control the concurrency count of running sessions
309325
std::mutex session_waker_lock_;
310326
std::condition_variable session_waker_;
311-
std::atomic<size_t> start_session_counter_;
312-
std::atomic<size_t> finished_session_counter_;
327+
std::atomic<std::uint64_t> start_session_counter_;
328+
329+
// For testing. Reaches start_session_counter_ and allSessionsBeforeFinished, so that the
330+
// sequence a flush would take as its cutoff can be asked about without racing a real flush.
331+
friend class OtlpHttpExporterCustomClientTestPeer;
313332
};
314333
} // namespace otlp
315334
} // namespace exporter

‎exporters/otlp/src/otlp_grpc_client.cc‎

Lines changed: 67 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,11 @@ class OPENTELEMETRY_LOCAL_SYMBOL OtlpGrpcAsyncCallDataBase
6767
opentelemetry::sdk::common::ExportResult::kFailure;
6868
GrpcAsyncCallback grpc_async_callback = nullptr;
6969

70+
// Where this call falls in the order calls were started, taken from start_request_counter
71+
// before it is incremented. ForceFlush waits for the calls below the sequence it was entered
72+
// with, rather than for a number of completions that a call started after it could supply.
73+
std::uint64_t sequence = 0;
74+
7075
OtlpGrpcAsyncCallDataBase() = default;
7176
virtual ~OtlpGrpcAsyncCallDataBase() = default;
7277
OtlpGrpcAsyncCallDataBase(const OtlpGrpcAsyncCallDataBase &) = delete;
@@ -114,8 +119,7 @@ struct OtlpGrpcClientAsyncData
114119
// Running requests, this is used to limit the number of concurrent requests.
115120
std::atomic<std::size_t> running_requests{0};
116121
// Request counter is used to record ForceFlush.
117-
std::atomic<std::size_t> start_request_counter{0};
118-
std::atomic<std::size_t> finished_request_counter{0};
122+
std::atomic<std::uint64_t> start_request_counter{0};
119123
std::size_t max_concurrent_requests = 64;
120124

121125
// Condition variable and mutex to control the concurrency count of running requests.
@@ -205,10 +209,12 @@ static sdk::common::ExportResult InternalDelegateAsyncExport(
205209
return true;
206210
};
207211

208-
++async_data->start_request_counter;
209212
++async_data->running_requests;
210213
{
211214
std::lock_guard<std::mutex> lock{async_data->running_calls_lock};
215+
// Counted inside the lock the flush predicate takes, so a ForceFlush cannot read a sequence
216+
// that includes this call and then fail to find the call itself.
217+
call_data->sequence = async_data->start_request_counter.fetch_add(1, std::memory_order_release);
212218
async_data->running_calls.insert(
213219
std::static_pointer_cast<OtlpGrpcAsyncCallDataBase>(call_data));
214220
}
@@ -225,11 +231,12 @@ static sdk::common::ExportResult InternalDelegateAsyncExport(
225231
std::lock_guard<std::mutex> lock{async_data->running_calls_lock};
226232
async_data->running_calls.erase(
227233
std::static_pointer_cast<OtlpGrpcAsyncCallDataBase>(call_data));
234+
// Dropped under the same lock as the erase. ForceFlush answers from the
235+
// registry now, so releasing the lock first would leave a window where a
236+
// flush reports success and the next Export is still refused for capacity.
237+
--async_data->running_requests;
228238
}
229239

230-
--async_data->running_requests;
231-
++async_data->finished_request_counter;
232-
233240
call_data->grpc_status = grpc_status;
234241
if (call_data->grpc_status.ok())
235242
{
@@ -719,6 +726,52 @@ bool OtlpGrpcClient::IsShutdown() const noexcept
719726
return is_shutdown_.load(std::memory_order_acquire);
720727
}
721728

729+
#ifdef ENABLE_ASYNC_EXPORT
730+
namespace
731+
{
732+
/// Whether \p sequence was handed out before \p cutoff, across a wrap of the counter.
733+
///
734+
/// The counter is finite, so this is a distance and not a comparison. cutoff - sequence is
735+
/// evaluated in unsigned arithmetic: it is small for a request that started before the cutoff,
736+
/// including when the counter has since wrapped past zero, and close to the whole range for one
737+
/// that started after it. Half the range is the dividing line, so the answer holds while fewer
738+
/// than 2^63 sequences are handed out during the lifetime of the request being asked about.
739+
/// Nothing bounds that from the number of requests in flight at once, which is why the sequence
740+
/// is 64 bits wide rather than size_t: at a thousand registrations a second the boundary is a few
741+
/// hundred million years away, and at 32 bits it was twenty five days.
742+
bool StartedBefore(std::uint64_t sequence, std::uint64_t cutoff) noexcept
743+
{
744+
const std::uint64_t distance = cutoff - sequence;
745+
return distance != 0U && distance <= ((~static_cast<std::uint64_t>(0)) >> 1);
746+
}
747+
} // namespace
748+
749+
namespace
750+
{
751+
/// Whether every call started before the given sequence has finished.
752+
///
753+
/// A call started after the flush has a sequence at or above the given one, so it does not hold
754+
/// the answer back. Takes running_calls_lock. The check on the way into ForceFlush holds nothing
755+
/// else; the loop condition and the result hold session_waker_lock too, and that nesting, waker
756+
/// then calls, is the only one in this file. Nothing takes the two the other way round.
757+
bool AllCallsBeforeFinished(const std::shared_ptr<OtlpGrpcClientAsyncData> &async_data,
758+
std::uint64_t sequence) noexcept
759+
{
760+
std::lock_guard<std::mutex> lock{async_data->running_calls_lock};
761+
762+
for (const auto &call_data : async_data->running_calls)
763+
{
764+
if (call_data && StartedBefore(call_data->sequence, sequence))
765+
{
766+
return false;
767+
}
768+
}
769+
770+
return true;
771+
}
772+
} // namespace
773+
#endif
774+
722775
bool OtlpGrpcClient::ForceFlush(
723776
OPENTELEMETRY_MAYBE_UNUSED std::chrono::microseconds timeout) noexcept
724777
{
@@ -728,8 +781,12 @@ bool OtlpGrpcClient::ForceFlush(
728781
}
729782

730783
#ifdef ENABLE_ASYNC_EXPORT
731-
std::size_t request_counter = async_data_->start_request_counter.load(std::memory_order_acquire);
732-
if (request_counter <= async_data_->finished_request_counter.load(std::memory_order_acquire))
784+
// The calls to wait for are the ones already started, so the sequence is read once and the
785+
// predicate is about those. A request that starts after this point cannot satisfy the flush and
786+
// cannot hold it back either.
787+
const std::uint64_t wait_sequence =
788+
async_data_->start_request_counter.load(std::memory_order_acquire);
789+
if (AllCallsBeforeFinished(async_data_, wait_sequence))
733790
{
734791
return true;
735792
}
@@ -750,7 +807,7 @@ bool OtlpGrpcClient::ForceFlush(
750807
}
751808

752809
while (timeout_steady > std::chrono::steady_clock::duration::zero() &&
753-
request_counter > async_data_->finished_request_counter.load(std::memory_order_acquire))
810+
!AllCallsBeforeFinished(async_data_, wait_sequence))
754811
{
755812
// A completion can land between the loop condition and the wait, so the wait is bounded and the
756813
// condition re-read on every wakeup. Never wait past the caller's deadline.
@@ -765,7 +822,7 @@ bool OtlpGrpcClient::ForceFlush(
765822
timeout_steady -= std::chrono::steady_clock::now() - start_timepoint;
766823
}
767824

768-
return request_counter <= async_data_->finished_request_counter.load(std::memory_order_acquire);
825+
return AllCallsBeforeFinished(async_data_, wait_sequence);
769826
#else
770827
return true;
771828
#endif

‎exporters/otlp/src/otlp_http_client.cc‎

Lines changed: 49 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
#include <chrono>
77
#include <condition_variable>
88
#include <cstddef>
9+
#include <cstdint>
910
#include <functional>
1011
#include <iostream>
1112
#include <list>
@@ -709,8 +710,7 @@ OtlpHttpClient::OtlpHttpClient(OtlpHttpClientOptions &&options,
709710
: is_shutdown_(false),
710711
options_(std::move(options)),
711712
http_client_(std::move(http_client)),
712-
start_session_counter_(0),
713-
finished_session_counter_(0)
713+
start_session_counter_(0)
714714
{
715715
http_client_->SetMaxSessionsPerConnection(options_.max_requests_per_connection);
716716
}
@@ -829,16 +829,16 @@ bool OtlpHttpClient::ForceFlush(std::chrono::microseconds timeout) noexcept
829829
timeout_steady = (std::chrono::steady_clock::duration::max)();
830830
}
831831

832-
size_t wait_counter = start_session_counter_.load(std::memory_order_acquire);
832+
// The sessions to wait for are the ones already started, so the sequence is read once and the
833+
// predicate is about those. A request that starts after this point cannot satisfy the flush and
834+
// cannot hold it back either.
835+
const std::uint64_t wait_sequence = start_session_counter_.load(std::memory_order_acquire);
833836

834837
while (timeout_steady > std::chrono::steady_clock::duration::zero())
835838
{
839+
if (allSessionsBeforeFinished(wait_sequence))
836840
{
837-
std::lock_guard<std::recursive_mutex> guard{session_manager_lock_};
838-
if (running_sessions_.empty())
839-
{
840-
break;
841-
}
841+
break;
842842
}
843843
// When changes of running_sessions_ and notify_one/notify_all happen between predicate
844844
// checking and waiting, we should not wait forever.We should cleanup gc sessions here as soon
@@ -852,18 +852,14 @@ bool OtlpHttpClient::ForceFlush(std::chrono::microseconds timeout) noexcept
852852
{
853853
cleanupGCSessions();
854854
}
855-
else if (finished_session_counter_.load(std::memory_order_acquire) >= wait_counter)
856-
{
857-
break;
858-
}
859855

860856
timeout_steady -= std::chrono::steady_clock::now() - start_timepoint;
861857
}
862858

863-
// What the wait was for, rather than what is left of the deadline. A session that finishes
864-
// between the last check and the last wait takes its notification with it, and the flush it was
865-
// holding up has happened.
866-
return finished_session_counter_.load(std::memory_order_acquire) >= wait_counter;
859+
// The same question the loop asked, so the result and the reason the wait ended agree. A session
860+
// that finishes between the last check and the last wait takes its notification with it, and the
861+
// flush it was holding up has happened.
862+
return allSessionsBeforeFinished(wait_sequence);
867863
}
868864

869865
bool OtlpHttpClient::Shutdown(std::chrono::microseconds timeout) noexcept
@@ -902,7 +898,6 @@ void OtlpHttpClient::ReleaseSession(
902898
gc_sessions_.emplace_back(std::move(session_iter->second));
903899
running_sessions_.erase(session_iter);
904900

905-
finished_session_counter_.fetch_add(1, std::memory_order_release);
906901
has_session = true;
907902
}
908903

@@ -1076,13 +1071,49 @@ void OtlpHttpClient::addSession(HttpSessionData &&session_data) noexcept
10761071

10771072
HttpSessionData &store_session_data = running_sessions_[session.get()];
10781073
store_session_data = std::move(session_data);
1074+
// Assigned after the move, which would otherwise overwrite it, and inside the lock the
1075+
// predicate takes, so a concurrent ForceFlush never reads an entry without a sequence.
1076+
store_session_data.sequence = start_session_counter_.fetch_add(1, std::memory_order_release);
10791077
}
10801078

1081-
start_session_counter_.fetch_add(1, std::memory_order_release);
10821079
// Send request after the session is added
10831080
session->SendRequest(handle);
10841081
}
10851082

1083+
namespace
1084+
{
1085+
/// Whether \p sequence was handed out before \p cutoff, across a wrap of the counter.
1086+
///
1087+
/// The counter is finite, so this is a distance and not a comparison. cutoff - sequence is
1088+
/// evaluated in unsigned arithmetic: it is small for a request that started before the cutoff,
1089+
/// including when the counter has since wrapped past zero, and close to the whole range for one
1090+
/// that started after it. Half the range is the dividing line, so the answer holds while fewer
1091+
/// than 2^63 sequences are handed out during the lifetime of the request being asked about.
1092+
/// Nothing bounds that from the number of requests in flight at once, which is why the sequence
1093+
/// is 64 bits wide rather than size_t: at a thousand registrations a second the boundary is a few
1094+
/// hundred million years away, and at 32 bits it was twenty five days.
1095+
bool StartedBefore(std::uint64_t sequence, std::uint64_t cutoff) noexcept
1096+
{
1097+
const std::uint64_t distance = cutoff - sequence;
1098+
return distance != 0U && distance <= ((~static_cast<std::uint64_t>(0)) >> 1);
1099+
}
1100+
} // namespace
1101+
1102+
bool OtlpHttpClient::allSessionsBeforeFinished(std::uint64_t sequence) noexcept
1103+
{
1104+
std::lock_guard<std::recursive_mutex> guard{session_manager_lock_};
1105+
1106+
for (const auto &running_session : running_sessions_)
1107+
{
1108+
if (StartedBefore(running_session.second.sequence, sequence))
1109+
{
1110+
return false;
1111+
}
1112+
}
1113+
1114+
return true;
1115+
}
1116+
10861117
bool OtlpHttpClient::cleanupGCSessions() noexcept
10871118
{
10881119
std::lock_guard<std::recursive_mutex> guard{session_manager_lock_};

0 commit comments

Comments
 (0)