Skip to content

[EXPORTER] OTLP ForceFlush waits for the requests it was called with - #4794

Draft
thc1006 wants to merge 1 commit into
open-telemetry:mainfrom
thc1006:fix/4339-forceflush-identity
Draft

thc1006 wants to merge 1 commit into
open-telemetry:mainfrom
thc1006:fix/4339-forceflush-identity

Conversation

@thc1006

@thc1006 thc1006 commented Nov 17, 2026 •

Copy link
Copy Markdown
Member

ForceFlush(timeout) 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 the issue: "ForceFlush(timeout) returns true only when all requests that were pending before the call have completed." The other two items from that comment landed in #4357, so this is what is left of it.

The issue also names the shared client case: one OtlpGrpcClient can be handed to the trace, metrics and log exporters, which then wait on the same counters. That is this defect across exporters rather than a separate one, and the sequence closes it. A flush still waits for sibling exporters' requests that were in flight when it was called, which preserves the existing client wide behaviour and is the conservative direction.

What changed

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 that meant moving the counter increment, which sat four lines before the insert: a flush reading the counter in between would have found a request counted and not present.

Ordering across a wrap is a distance and not a <. What has to stay under half the range is how many sequences are handed out while the request being asked about is alive, and the concurrency limit does not bound that. At size_t width on 32 bit it was reachable, and there the first version of this was worse than the code it replaced: a request holding sequence zero while another slot completes 2^31 requests falls one past the half range, so the predicate skips it and the flush reports success with it still in flight, where lifetime totals answer correctly. Confirmed at 32 bit width in a standalone program. The sequence is std::uint64_t for that reason.

Moving the flush onto the registry opened one window of its own. The gRPC completion callback erases the call inside running_calls_lock and dropped running_requests after releasing it, which was harmless while the flush read finished_request_counter, 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. The decrement now joins the erase.

finished_session_counter_ and finished_request_counter lose all their readers and are removed.

A snapshot of the registry keys would have been wrong, since an address freed by one session can later be handed to another. A snapshot of per request identifiers would carry no bound at all, at the cost of a container copy per flush. I took the sequence because the counter it derives from already existed; say so if you would rather have the version with nothing to reason about.

What to flag

The widening 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 ${OPENTELEMETRY_ATOMIC_LIB}, 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. No job here builds either path. I checked that both client .pc files gain -latomic when the detection reports one, not that its absence breaks a link.

Removing finished_session_counter_ and widening the counter change sizeof(OtlpHttpClient), and the new sequence field changes the size of the private nested HttpSessionData. Both are in an installed header. #4104 changed the same struct and Export's signature, so there is precedent, but say the word if you would rather keep the member. The gRPC side changes nothing visible: OtlpGrpcClientAsyncData is forward declared in its header and defined in the .cc, and the call data class is OPENTELEMETRY_LOCAL_SYMBOL.

Shutdown calls ForceFlush, so a request added during that flush is no longer waited for. The window predates this change, since createSession refuses once the shutdown flag is set, and Shutdown then cancels and finishes every session and drains the gc list. ~OtlpHttpClient also waits unconditionally for running_sessions_ to empty.

The gRPC half introduces a lock pairing the file did not have, session_waker_lock then running_calls_lock, because the two existing waits read only the running_requests atomic. Every site was checked: three running_calls_lock blocks hold it alone for an insert, an erase and a copy, and Shutdown calls ForceFlush and only afterwards, in a separate scope, takes it. Nothing takes the two in the opposite nesting.

Measured

Each case was also run against the unmodified client, restored from a snapshot rather than with git, so the before numbers come from the same test code that ships here.

without the change with it
ForceFlushDoesNotAcceptALaterRequestInPlaceOfItsOwn, HTTP 0 of 3 pass 3 of 3
the same case, gRPC 0 of 3 pass 3 of 3

Both fail on two assertions, the result and the duration. The HTTP case returns at 210 ms against a 500 ms deadline and the gRPC case at 200 ms against 1000 ms, which is the moment the later request completed. Both arrange their ordering with a sleep, which is safe for what they assert: a reordering enters the flush with both requests pending, it waits, and waiting is the assertion.

The opposite direction cannot be arranged that way, since 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. It is asked of the predicate directly instead, in two sequential cases with no threads, through the fixture OtlpHttpClient now friends, as otlp_http_exporter.h already does for this 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 is not cosmetic: a single sequence covering both survived a flush that waited for the whole registry to empty, because whichever request is completed first has left the registry for the other question. Split, that one dies. The gRPC predicate cannot be reached this way, being a free function in an anonymous namespace whose counter lives in a struct defined in the .cc, so that client is covered end to end only.

Both sequential cases finish whatever is still registered on the way out. The fatal assertions run while both requests are still pending, and ~OtlpHttpClient waits for the registry to empty with no deadline, so one of them firing would otherwise hang the case rather than fail it. With the predicate forced to report done, the case now fails in under a second and names the line.

Full suite green in three configurations: gRPC with OTELCPP_WITH_ASYNC_EXPORT_PREVIEW on and off, 1525 cases each, and an HTTP build without gRPC, 1479. The gRPC case sits in OtlpGrpcExporterFlushTestPeer rather than behind an #if, because gtest_add_tests registers by scanning source; in the default build it is registered and skipped. Clean under OTELCPP_MAINTAINER_MODE with -Werror. clang-tidy reports no new diagnostic on either client or either test file; I had measured only the clients at first and the preview jobs caught two in the HTTP test, a helper with external linkage and a missing in-class initializer, both now fixed. Neither was a runtime defect: the constructor already set both pointers.

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.

The Conan jobs fail on the base commit as well, at abseil/20250127.0, and are #4796.

Refs #4339 rather than Fixes, because I asked a scoping question on the issue on 5 August, before writing any of this, and it is still open: on a shared client, should a trace flush wait for a log request that was in flight when it was called? This change makes it wait. The answer decides whether the issue closes, so happy to switch the keyword either way.

Refs #4339

@codecov

codecov Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 86.70%. Comparing base (da57137) to head (6d71cc5).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #4794      +/-   ##
==========================================
+ Coverage   86.70%   86.70%   +0.01%     
==========================================
  Files         530      530              
  Lines       21204    21217      +13     
==========================================
+ Hits        18382    18395      +13     
  Misses       2822     2822              
Files with missing lines Coverage Δ
...de/opentelemetry/exporters/otlp/otlp_http_client.h 100.00% <ø> (ø)
exporters/otlp/src/otlp_grpc_client.cc 71.89% <100.00%> (+0.84%) ⬆️
exporters/otlp/src/otlp_http_client.cc 73.43% <100.00%> (+0.22%) ⬆️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@thc1006
thc1006 force-pushed the fix/4339-forceflush-identity branch 5 times, most recently from 1aa6953 to 11e6208 Compare November 19, 2026 14:04
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>
@thc1006
thc1006 force-pushed the fix/4339-forceflush-identity branch from 11e6208 to 6d71cc5 Compare November 20, 2026 13:13

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant