diff --git a/CHANGELOG.md b/CHANGELOG.md index 740c3d3337..13b4ef2e54 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,14 @@ Increment the: ## [Unreleased] +* [EXPORTER] `OtlpHttpClient::ForceFlush`, and `OtlpGrpcClient::ForceFlush` + under the async export preview, now wait for the requests that were pending + when they were called, instead of for as many completions as there were + requests started. A request begun after the call could supply one of those + completions, so the flush reported success with an earlier request still in + flight + [#4339](https://github.com/open-telemetry/opentelemetry-cpp/issues/4339) + * [SDK] Restore the check in `DoubleHistogram::Record` that drops NaN and +Inf measurements, so they no longer reach the histogram aggregations diff --git a/exporters/otlp/CMakeLists.txt b/exporters/otlp/CMakeLists.txt index 4f1c5933fa..004ecab05a 100644 --- a/exporters/otlp/CMakeLists.txt +++ b/exporters/otlp/CMakeLists.txt @@ -368,6 +368,7 @@ if(OTELCPP_WITH_OTLP_HTTP) opentelemetry_exporter_otlp_http_client PUBLIC opentelemetry_http_client PRIVATE opentelemetry_common) + otel_link_libatomic(opentelemetry_exporter_otlp_http_client) target_include_directories( opentelemetry_exporter_otlp_http_client @@ -529,7 +530,8 @@ if(OTELCPP_WITH_OTLP_HTTP) endif() opentelemetry_add_pkgconfig( exporter_otlp_http_client "OpenTelemetry OTLP - HTTP Client" - "HTTP client for OTLP protocol." "${_otlp_http_client_pc_requires}") + "HTTP client for OTLP protocol." "${_otlp_http_client_pc_requires}" + EXTRA_LIBS ${OPENTELEMETRY_ATOMIC_LIB}) opentelemetry_add_pkgconfig( exporter_otlp_http diff --git a/exporters/otlp/include/opentelemetry/exporters/otlp/otlp_http_client.h b/exporters/otlp/include/opentelemetry/exporters/otlp/otlp_http_client.h index da28fbfdec..c0e26ab107 100644 --- a/exporters/otlp/include/opentelemetry/exporters/otlp/otlp_http_client.h +++ b/exporters/otlp/include/opentelemetry/exporters/otlp/otlp_http_client.h @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -244,6 +245,12 @@ class OtlpHttpClient std::unique_ptr arena; google::protobuf::Message *response = nullptr; + // Where this session falls in the order sessions were started, taken from + // start_session_counter_ before it is incremented. ForceFlush waits for the sessions below + // the sequence it was entered with, rather than for a number of completions that a session + // started after the call could supply. + std::uint64_t sequence = 0; + HttpSessionData() noexcept; HttpSessionData(std::shared_ptr &&input_session, std::shared_ptr &&input_handle, @@ -286,6 +293,15 @@ class OtlpHttpClient */ bool cleanupGCSessions() noexcept; + /** + * @brief Whether every session started before the given sequence has finished. + * + * Reads running_sessions_ under session_manager_lock_, so it answers for the moment it is + * called. A session started after the call has a sequence at or above the given one, so it + * does not hold the answer back. + */ + bool allSessionsBeforeFinished(std::uint64_t sequence) noexcept; + // Stores if this HTTP client had its Shutdown() method called std::atomic is_shutdown_; @@ -308,8 +324,11 @@ class OtlpHttpClient // Condition variable and mutex to control the concurrency count of running sessions std::mutex session_waker_lock_; std::condition_variable session_waker_; - std::atomic start_session_counter_; - std::atomic finished_session_counter_; + std::atomic start_session_counter_; + + // For testing. Reaches start_session_counter_ and allSessionsBeforeFinished, so that the + // sequence a flush would take as its cutoff can be asked about without racing a real flush. + friend class OtlpHttpExporterCustomClientTestPeer; }; } // namespace otlp } // namespace exporter diff --git a/exporters/otlp/src/otlp_grpc_client.cc b/exporters/otlp/src/otlp_grpc_client.cc index cd8f4a3b96..2aa0f1a75e 100644 --- a/exporters/otlp/src/otlp_grpc_client.cc +++ b/exporters/otlp/src/otlp_grpc_client.cc @@ -67,6 +67,11 @@ class OPENTELEMETRY_LOCAL_SYMBOL OtlpGrpcAsyncCallDataBase opentelemetry::sdk::common::ExportResult::kFailure; GrpcAsyncCallback grpc_async_callback = nullptr; + // Where this call falls in the order calls were started, taken from start_request_counter + // before it is incremented. ForceFlush waits for the calls below the sequence it was entered + // with, rather than for a number of completions that a call started after it could supply. + std::uint64_t sequence = 0; + OtlpGrpcAsyncCallDataBase() = default; virtual ~OtlpGrpcAsyncCallDataBase() = default; OtlpGrpcAsyncCallDataBase(const OtlpGrpcAsyncCallDataBase &) = delete; @@ -114,8 +119,7 @@ struct OtlpGrpcClientAsyncData // Running requests, this is used to limit the number of concurrent requests. std::atomic running_requests{0}; // Request counter is used to record ForceFlush. - std::atomic start_request_counter{0}; - std::atomic finished_request_counter{0}; + std::atomic start_request_counter{0}; std::size_t max_concurrent_requests = 64; // Condition variable and mutex to control the concurrency count of running requests. @@ -205,10 +209,12 @@ static sdk::common::ExportResult InternalDelegateAsyncExport( return true; }; - ++async_data->start_request_counter; ++async_data->running_requests; { std::lock_guard lock{async_data->running_calls_lock}; + // Counted inside the lock the flush predicate takes, so a ForceFlush cannot read a sequence + // that includes this call and then fail to find the call itself. + call_data->sequence = async_data->start_request_counter.fetch_add(1, std::memory_order_release); async_data->running_calls.insert( std::static_pointer_cast(call_data)); } @@ -225,11 +231,12 @@ static sdk::common::ExportResult InternalDelegateAsyncExport( std::lock_guard lock{async_data->running_calls_lock}; async_data->running_calls.erase( std::static_pointer_cast(call_data)); + // Dropped under the same lock as the erase. ForceFlush answers from the + // registry now, so releasing the lock first would leave a window where a + // flush reports success and the next Export is still refused for capacity. + --async_data->running_requests; } - --async_data->running_requests; - ++async_data->finished_request_counter; - call_data->grpc_status = grpc_status; if (call_data->grpc_status.ok()) { @@ -719,6 +726,52 @@ bool OtlpGrpcClient::IsShutdown() const noexcept return is_shutdown_.load(std::memory_order_acquire); } +#ifdef ENABLE_ASYNC_EXPORT +namespace +{ +/// Whether \p sequence was handed out before \p cutoff, across a wrap of the counter. +/// +/// The counter is finite, so this is a distance and not a comparison. cutoff - sequence is +/// evaluated in unsigned arithmetic: it is small for a request that started before the cutoff, +/// including when the counter has since wrapped past zero, and close to the whole range for one +/// that started after it. Half the range is the dividing line, so the answer holds while fewer +/// than 2^63 sequences are handed out during the lifetime of the request being asked about. +/// Nothing bounds that from the number of requests in flight at once, which is why the sequence +/// is 64 bits wide rather than size_t: at a thousand registrations a second the boundary is a few +/// hundred million years away, and at 32 bits it was twenty five days. +bool StartedBefore(std::uint64_t sequence, std::uint64_t cutoff) noexcept +{ + const std::uint64_t distance = cutoff - sequence; + return distance != 0U && distance <= ((~static_cast(0)) >> 1); +} +} // namespace + +namespace +{ +/// Whether every call started before the given sequence has finished. +/// +/// A call started after the flush has a sequence at or above the given one, so it does not hold +/// the answer back. Takes running_calls_lock. The check on the way into ForceFlush holds nothing +/// else; the loop condition and the result hold session_waker_lock too, and that nesting, waker +/// then calls, is the only one in this file. Nothing takes the two the other way round. +bool AllCallsBeforeFinished(const std::shared_ptr &async_data, + std::uint64_t sequence) noexcept +{ + std::lock_guard lock{async_data->running_calls_lock}; + + for (const auto &call_data : async_data->running_calls) + { + if (call_data && StartedBefore(call_data->sequence, sequence)) + { + return false; + } + } + + return true; +} +} // namespace +#endif + bool OtlpGrpcClient::ForceFlush( OPENTELEMETRY_MAYBE_UNUSED std::chrono::microseconds timeout) noexcept { @@ -728,8 +781,12 @@ bool OtlpGrpcClient::ForceFlush( } #ifdef ENABLE_ASYNC_EXPORT - std::size_t request_counter = async_data_->start_request_counter.load(std::memory_order_acquire); - if (request_counter <= async_data_->finished_request_counter.load(std::memory_order_acquire)) + // The calls to wait for are the ones already started, so the sequence is read once and the + // predicate is about those. A request that starts after this point cannot satisfy the flush and + // cannot hold it back either. + const std::uint64_t wait_sequence = + async_data_->start_request_counter.load(std::memory_order_acquire); + if (AllCallsBeforeFinished(async_data_, wait_sequence)) { return true; } @@ -750,7 +807,7 @@ bool OtlpGrpcClient::ForceFlush( } while (timeout_steady > std::chrono::steady_clock::duration::zero() && - request_counter > async_data_->finished_request_counter.load(std::memory_order_acquire)) + !AllCallsBeforeFinished(async_data_, wait_sequence)) { // A completion can land between the loop condition and the wait, so the wait is bounded and the // condition re-read on every wakeup. Never wait past the caller's deadline. @@ -765,7 +822,7 @@ bool OtlpGrpcClient::ForceFlush( timeout_steady -= std::chrono::steady_clock::now() - start_timepoint; } - return request_counter <= async_data_->finished_request_counter.load(std::memory_order_acquire); + return AllCallsBeforeFinished(async_data_, wait_sequence); #else return true; #endif diff --git a/exporters/otlp/src/otlp_http_client.cc b/exporters/otlp/src/otlp_http_client.cc index 7a09e3762c..18121e6dec 100644 --- a/exporters/otlp/src/otlp_http_client.cc +++ b/exporters/otlp/src/otlp_http_client.cc @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -709,8 +710,7 @@ OtlpHttpClient::OtlpHttpClient(OtlpHttpClientOptions &&options, : is_shutdown_(false), options_(std::move(options)), http_client_(std::move(http_client)), - start_session_counter_(0), - finished_session_counter_(0) + start_session_counter_(0) { http_client_->SetMaxSessionsPerConnection(options_.max_requests_per_connection); } @@ -829,16 +829,16 @@ bool OtlpHttpClient::ForceFlush(std::chrono::microseconds timeout) noexcept timeout_steady = (std::chrono::steady_clock::duration::max)(); } - size_t wait_counter = start_session_counter_.load(std::memory_order_acquire); + // The sessions to wait for are the ones already started, so the sequence is read once and the + // predicate is about those. A request that starts after this point cannot satisfy the flush and + // cannot hold it back either. + const std::uint64_t wait_sequence = start_session_counter_.load(std::memory_order_acquire); while (timeout_steady > std::chrono::steady_clock::duration::zero()) { + if (allSessionsBeforeFinished(wait_sequence)) { - std::lock_guard guard{session_manager_lock_}; - if (running_sessions_.empty()) - { - break; - } + break; } // When changes of running_sessions_ and notify_one/notify_all happen between predicate // 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 { cleanupGCSessions(); } - else if (finished_session_counter_.load(std::memory_order_acquire) >= wait_counter) - { - break; - } timeout_steady -= std::chrono::steady_clock::now() - start_timepoint; } - // What the wait was for, rather than what is left of the deadline. A session that finishes - // between the last check and the last wait takes its notification with it, and the flush it was - // holding up has happened. - return finished_session_counter_.load(std::memory_order_acquire) >= wait_counter; + // The same question the loop asked, so the result and the reason the wait ended agree. A session + // that finishes between the last check and the last wait takes its notification with it, and the + // flush it was holding up has happened. + return allSessionsBeforeFinished(wait_sequence); } bool OtlpHttpClient::Shutdown(std::chrono::microseconds timeout) noexcept @@ -902,7 +898,6 @@ void OtlpHttpClient::ReleaseSession( gc_sessions_.emplace_back(std::move(session_iter->second)); running_sessions_.erase(session_iter); - finished_session_counter_.fetch_add(1, std::memory_order_release); has_session = true; } @@ -1076,13 +1071,49 @@ void OtlpHttpClient::addSession(HttpSessionData &&session_data) noexcept HttpSessionData &store_session_data = running_sessions_[session.get()]; store_session_data = std::move(session_data); + // Assigned after the move, which would otherwise overwrite it, and inside the lock the + // predicate takes, so a concurrent ForceFlush never reads an entry without a sequence. + store_session_data.sequence = start_session_counter_.fetch_add(1, std::memory_order_release); } - start_session_counter_.fetch_add(1, std::memory_order_release); // Send request after the session is added session->SendRequest(handle); } +namespace +{ +/// Whether \p sequence was handed out before \p cutoff, across a wrap of the counter. +/// +/// The counter is finite, so this is a distance and not a comparison. cutoff - sequence is +/// evaluated in unsigned arithmetic: it is small for a request that started before the cutoff, +/// including when the counter has since wrapped past zero, and close to the whole range for one +/// that started after it. Half the range is the dividing line, so the answer holds while fewer +/// than 2^63 sequences are handed out during the lifetime of the request being asked about. +/// Nothing bounds that from the number of requests in flight at once, which is why the sequence +/// is 64 bits wide rather than size_t: at a thousand registrations a second the boundary is a few +/// hundred million years away, and at 32 bits it was twenty five days. +bool StartedBefore(std::uint64_t sequence, std::uint64_t cutoff) noexcept +{ + const std::uint64_t distance = cutoff - sequence; + return distance != 0U && distance <= ((~static_cast(0)) >> 1); +} +} // namespace + +bool OtlpHttpClient::allSessionsBeforeFinished(std::uint64_t sequence) noexcept +{ + std::lock_guard guard{session_manager_lock_}; + + for (const auto &running_session : running_sessions_) + { + if (StartedBefore(running_session.second.sequence, sequence)) + { + return false; + } + } + + return true; +} + bool OtlpHttpClient::cleanupGCSessions() noexcept { std::lock_guard guard{session_manager_lock_}; diff --git a/exporters/otlp/test/otlp_grpc_exporter_test.cc b/exporters/otlp/test/otlp_grpc_exporter_test.cc index ce923a32f1..44ed1b1516 100644 --- a/exporters/otlp/test/otlp_grpc_exporter_test.cc +++ b/exporters/otlp/test/otlp_grpc_exporter_test.cc @@ -166,6 +166,25 @@ class OtlpMockTraceServiceStub : public proto::collector::trace::v1::MockTraceSe return true; } + // Completes whichever deferred request arrived last, false when there is none. A flush entered + // while an earlier request was pending must not be satisfied by this one. + bool CompleteLatestDeferred() + { + std::function callback; + { + std::lock_guard guard(deferred_lock_); + if (deferred_.empty()) + { + return false; + } + callback = std::move(deferred_.back()); + deferred_.pop_back(); + } + + callback(::grpc::Status::OK); + return true; + } + void CompleteAllDeferred() { while (CompleteOneDeferred()) @@ -405,6 +424,51 @@ TEST_F(OtlpGrpcExporterFlushTestPeer, ForceFlushKeepsWaitingWhenAnotherRequestCo EXPECT_GE(elapsed.count(), 500); EXPECT_EQ(1u, mock_stub->DeferredCount()); } + +// The result came from two lifetime totals, started and finished, so the question was how many +// requests had finished and not which ones. A request that starts after the flush and finishes +// before the pending one supplies one of those completions, and the flush then reported success +// with the earlier request still in flight. +TEST_F(OtlpGrpcExporterFlushTestPeer, ForceFlushDoesNotAcceptALaterRequestInPlaceOfItsOwn) +{ + auto *mock_stub = new OtlpMockTraceServiceStub(); + mock_stub->DeferCompletions(); + std::unique_ptr stub_interface( + mock_stub); + auto exporter = GetExporter(stub_interface); + DrainDeferredCompletions drain{mock_stub}; + + auto first = exporter->MakeRecordable(); + first->SetName("Test span 1"); + nostd::span> first_batch(&first, 1); + exporter->Export(first_batch); + ASSERT_EQ(1u, mock_stub->DeferredCount()); + + // Both started and completed once the flush below is parked, so the flush was entered with the + // first request pending and nothing else. + std::thread later([mock_stub, &exporter] { + std::this_thread::sleep_for(std::chrono::milliseconds{200}); + + auto second = exporter->MakeRecordable(); + second->SetName("Test span 2"); + nostd::span> second_batch(&second, 1); + exporter->Export(second_batch); + mock_stub->CompleteLatestDeferred(); + }); + + const auto started = std::chrono::steady_clock::now(); + const bool flushed = exporter->ForceFlush(std::chrono::milliseconds{1000}); + const auto elapsed = std::chrono::duration_cast( + std::chrono::steady_clock::now() - started); + later.join(); + + EXPECT_FALSE(flushed) << "reported success while the request pending when it was entered was " + "still in flight"; + // Ran its own deadline down rather than ending on the later request's completion. + EXPECT_GE(elapsed.count(), 500); + EXPECT_EQ(1u, mock_stub->DeferredCount()); +} + } // namespace // Create spans, let processor call Export() diff --git a/exporters/otlp/test/otlp_http_exporter_custom_client_test.cc b/exporters/otlp/test/otlp_http_exporter_custom_client_test.cc index b9c0157508..58cf9d1de7 100644 --- a/exporters/otlp/test/otlp_http_exporter_custom_client_test.cc +++ b/exporters/otlp/test/otlp_http_exporter_custom_client_test.cc @@ -4,9 +4,12 @@ #include #include #include +#include +#include #include #include #include +#include #include #include "gmock/gmock.h" @@ -131,8 +134,25 @@ class OtlpHttpExporterCustomClientTestPeer : public ::testing::Test 1); } + // Friendship is granted to this fixture and does not extend to the class TEST_F derives from + // it, so the two private things a case needs are read through these. + static std::uint64_t FlushCutoff(const OtlpHttpClient &otlp_client) + { + return otlp_client.start_session_counter_.load(std::memory_order_acquire); + } + + static bool SnapshotSatisfied(OtlpHttpClient &otlp_client, std::uint64_t cutoff) + { + return otlp_client.allSessionsBeforeFinished(cutoff); + } + // A non-zero request budget keeps the export asynchronous, so it returns while the session runs. - static void ExportOneRequest(OtlpHttpClient &otlp_client) + // The budget has to cover every session still registered, not just this one: Export registers + // first and then waits for the registry to fall back inside the budget, so too small a budget + // makes the call run the client timeout down and report failure. + static opentelemetry::sdk::common::ExportResult ExportOneRequest( + OtlpHttpClient &otlp_client, + std::size_t max_running_requests = 1) { auto arena = std::make_unique(); auto *request = @@ -142,10 +162,10 @@ class OtlpHttpExporterCustomClientTestPeer : public ::testing::Test google::protobuf::Arena::Create( arena.get()); - otlp_client.Export( + return otlp_client.Export( *request, std::move(arena), response, [](opentelemetry::sdk::common::ExportResult, google::protobuf::Message *) { return true; }, - 1); + max_running_requests); } }; @@ -275,6 +295,222 @@ TEST_F(OtlpHttpExporterCustomClientTestPeer, ForceFlushReportsSuccessOnceTheSess EXPECT_TRUE(otlp_client.ForceFlush(std::chrono::milliseconds{50})); } +// ForceFlush reports on two lifetime totals, started and finished, so it asks whether as many +// requests have finished as had started when it was entered, not whether the ones it is waiting +// for are among them. A request that starts after the call and finishes before the pending one +// satisfies that count and the flush reports success with the first request still in flight. +// +// Nothing between starting the flush thread and joining it may assert. A gtest failure returns +// from the case, a joinable std::thread terminates the process on destruction, and +// ~OtlpHttpClient waits for the registry to empty with no deadline. So both cases below complete +// every request and join, and only then assert. +TEST_F(OtlpHttpExporterCustomClientTestPeer, ForceFlushDoesNotAcceptALaterRequestInPlaceOfItsOwn) +{ + auto client = http_client::HttpClientTestFactory::Create(); + auto no_send_client = std::static_pointer_cast(client); + auto first = std::static_pointer_cast(no_send_client->session_); + + std::shared_ptr first_pending; + EXPECT_CALL(*first, SendRequest) + .WillRepeatedly( + [&first_pending](std::shared_ptr cb) { + first_pending = std::move(cb); + }); + + // A short client timeout, so the bounded wait re-reads its predicate often. + OtlpHttpClient otlp_client(MakeOtlpHttpClientOptions(std::chrono::milliseconds{10}), client); + + const auto first_result = ExportOneRequest(otlp_client, 2); + + // Entered with the first request pending, so this is the request it has to wait for. How long it + // waits is the other half of the answer: ending early is what accepting the wrong completion + // looks like, so the duration is asserted as well as the result. + bool flushed = true; + std::chrono::steady_clock::duration waited{}; + std::thread flusher([&otlp_client, &flushed, &waited] { + const auto entered = std::chrono::steady_clock::now(); + flushed = otlp_client.ForceFlush(std::chrono::milliseconds{500}); + waited = std::chrono::steady_clock::now() - entered; + }); + std::this_thread::sleep_for(std::chrono::milliseconds{200}); + + // A second request, started after the flush. The nosend client hands out one session, and the + // running sessions are keyed by session pointer, so a second session object is what makes this a + // second entry rather than an overwrite of the first. + auto second = std::make_shared(*no_send_client); + std::shared_ptr second_pending; + EXPECT_CALL(*second, SendRequest) + .WillRepeatedly( + [&second_pending](std::shared_ptr cb) { + second_pending = std::move(cb); + }); + no_send_client->session_ = second; + + const auto second_result = ExportOneRequest(otlp_client, 2); + + if (second_pending) + { + http_client::nosend::Response second_sent; + second_sent.Finish(*second_pending); + } + + flusher.join(); + if (first_pending) + { + http_client::nosend::Response first_sent; + first_sent.Finish(*first_pending); + } + + const auto waited_ms = std::chrono::duration_cast(waited).count(); + EXPECT_EQ(opentelemetry::sdk::common::ExportResult::kSuccess, first_result); + EXPECT_EQ(opentelemetry::sdk::common::ExportResult::kSuccess, second_result); + EXPECT_NE(first_pending, nullptr); + EXPECT_NE(second_pending, nullptr); + EXPECT_FALSE(flushed) << "reported success while the request pending when it was entered was " + "still in flight"; + EXPECT_GE(waited_ms, 400) << "ended on the second request's completion rather than waiting for " + "the first"; +} + +// Finishes whatever a case left registered, so that a fatal assertion ends the case instead of +// hanging it. ~OtlpHttpClient waits for the registry to empty with no deadline, and the nosend +// client delivers no completion of its own, so an early return with a session still registered +// never comes back. Finishing an already finished handler does nothing, since ResponseHandler +// clears its owner and session before releasing. Declare after the client, so this runs first. +namespace +{ +class FinishPendingOnExit +{ +public: + FinishPendingOnExit( + std::shared_ptr &first, + std::shared_ptr &second) noexcept + : handlers_{&first, &second} + {} + + ~FinishPendingOnExit() + { + for (auto *handler : handlers_) + { + if (*handler) + { + http_client::nosend::Response done; + done.Finish(**handler); + } + } + } + + FinishPendingOnExit(const FinishPendingOnExit &) = delete; + FinishPendingOnExit &operator=(const FinishPendingOnExit &) = delete; + FinishPendingOnExit(FinishPendingOnExit &&) = delete; + FinishPendingOnExit &operator=(FinishPendingOnExit &&) = delete; + +private: + std::shared_ptr *handlers_[2]{}; +}; +} // namespace + +// The cutoff a flush takes on entry, asked about directly. Driving these through ForceFlush needs +// the second request to register after the flush has read the cutoff, and nothing a test can +// observe says when that happened, so the order here is sequential rather than arranged with a +// sleep. Two cases, because the two directions cannot share one sequence: whichever request is +// completed first is no longer in the registry for the other question. +TEST_F(OtlpHttpExporterCustomClientTestPeer, ACompletionFromALaterRequestDoesNotSatisfyTheSnapshot) +{ + auto client = http_client::HttpClientTestFactory::Create(); + auto no_send_client = std::static_pointer_cast(client); + auto first = std::static_pointer_cast(no_send_client->session_); + + std::shared_ptr first_pending; + std::shared_ptr second_pending; + EXPECT_CALL(*first, SendRequest) + .WillRepeatedly( + [&first_pending](std::shared_ptr cb) { + first_pending = std::move(cb); + }); + + OtlpHttpClient otlp_client(MakeOtlpHttpClientOptions(std::chrono::milliseconds{10}), client); + FinishPendingOnExit finish_pending{first_pending, second_pending}; + + ASSERT_EQ(opentelemetry::sdk::common::ExportResult::kSuccess, ExportOneRequest(otlp_client, 2)); + ASSERT_NE(first_pending, nullptr); + + // What ForceFlush would read on entry, with the first request already registered. + const std::uint64_t cutoff = FlushCutoff(otlp_client); + + auto second = std::make_shared(*no_send_client); + EXPECT_CALL(*second, SendRequest) + .WillRepeatedly( + [&second_pending](std::shared_ptr cb) { + second_pending = std::move(cb); + }); + no_send_client->session_ = second; + + ASSERT_EQ(opentelemetry::sdk::common::ExportResult::kSuccess, ExportOneRequest(otlp_client, 2)); + ASSERT_NE(second_pending, nullptr); + + ASSERT_FALSE(SnapshotSatisfied(otlp_client, cutoff)) + << "the request below the cutoff is still in flight"; + + http_client::nosend::Response second_sent; + second_sent.Finish(*second_pending); + EXPECT_FALSE(SnapshotSatisfied(otlp_client, cutoff)) + << "a completion from a request started after the cutoff satisfied the snapshot"; + + http_client::nosend::Response first_sent; + first_sent.Finish(*first_pending); +} + +// The direction that a flush waiting for the whole registry to empty would get wrong, which is why +// the later request is left in flight for the assertion rather than completed first. +TEST_F(OtlpHttpExporterCustomClientTestPeer, ALaterRequestStillInFlightDoesNotHoldTheSnapshotBack) +{ + auto client = http_client::HttpClientTestFactory::Create(); + auto no_send_client = std::static_pointer_cast(client); + auto first = std::static_pointer_cast(no_send_client->session_); + + std::shared_ptr first_pending; + std::shared_ptr second_pending; + EXPECT_CALL(*first, SendRequest) + .WillRepeatedly( + [&first_pending](std::shared_ptr cb) { + first_pending = std::move(cb); + }); + + OtlpHttpClient otlp_client(MakeOtlpHttpClientOptions(std::chrono::milliseconds{10}), client); + FinishPendingOnExit finish_pending{first_pending, second_pending}; + + ASSERT_EQ(opentelemetry::sdk::common::ExportResult::kSuccess, ExportOneRequest(otlp_client, 2)); + ASSERT_NE(first_pending, nullptr); + + // What ForceFlush would read on entry, with the first request already registered. + const std::uint64_t cutoff = FlushCutoff(otlp_client); + + auto second = std::make_shared(*no_send_client); + EXPECT_CALL(*second, SendRequest) + .WillRepeatedly( + [&second_pending](std::shared_ptr cb) { + second_pending = std::move(cb); + }); + no_send_client->session_ = second; + + ASSERT_EQ(opentelemetry::sdk::common::ExportResult::kSuccess, ExportOneRequest(otlp_client, 2)); + ASSERT_NE(second_pending, nullptr); + + ASSERT_FALSE(SnapshotSatisfied(otlp_client, cutoff)) + << "the request below the cutoff is still in flight"; + + http_client::nosend::Response first_sent; + first_sent.Finish(*first_pending); + EXPECT_TRUE(SnapshotSatisfied(otlp_client, cutoff)) + << "the snapshot was not satisfied once the request below the cutoff finished, with a later " + "one still in flight"; + EXPECT_NE(second_pending, nullptr); + + http_client::nosend::Response second_sent; + second_sent.Finish(*second_pending); +} + // A client that finishes a transfer on ReadError, WriteError or Destroyed ends the request: the // result callback runs once, and ForceFlush returns rather than waiting out its deadline. TEST_F(OtlpHttpExporterCustomClientTestPeer, ATerminalClientEventEndsTheRequest)