Skip to content

[BUG] Prevent lost condition-variable wakeups during OTLP file, periodic metric, and batch span processor shutdown - #4365

Merged
dbarker merged 14 commits into
open-telemetry:mainfrom
mike-nugent-mongodb:exporter-shutdown-race
Sep 8, 2026
Merged

dbarker merged 14 commits into
open-telemetry:mainfrom
mike-nugent-mongodb:exporter-shutdown-race

Conversation

@mike-nugent-mongodb

Copy link
Copy Markdown
Contributor

Changes

The issue in each changed spot is that there is a race between the "shutdown" call and the worker thread, such that the worker thread might not actually shut down. The worker will eventually shut down on the next configured periodic export, but if this could be configured to be relatively long (e.g. 1 minute). There's no workaround for this:

  • ForceFlush will early-return after shutdown, so one can't use ForceFlush to un-stuck a worker thread.
  • Calling Shutdown more than once can lead to undefined behavior if it tries to join the worker thread from two different threads - at the very least, the return value of joinable is undefined, so a second thread trying to check if the worker is still joinable might see joinable as false if the thread has been joined but is stuck.

I did not update CHANGELOG.md since the change seems small, but let me know if I should. I did not add unit tests as they would need to be invasive and complicated to reliably catch these. AFAIK there is no existing bug/issue documenting this.

…dic metric, and batch span processor shutdown.
@mike-nugent-mongodb
mike-nugent-mongodb requested a review from a team as a code owner August 5, 2026 19:12
@linux-foundation-easycla

linux-foundation-easycla Bot commented Aug 5, 2026 •

Copy link
Copy Markdown

CLA Signed
The committers listed above are authorized under a signed CLA.

  • ✅ login: mike-nugent-mongodb / name: Mike Nugent (e35bb01)

@codecov

codecov Bot commented Aug 8, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 83.47%. Comparing base (a30be41) to head (c5c48b3).

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #4365      +/-   ##
==========================================
+ Coverage   83.45%   83.47%   +0.02%     
==========================================
  Files         522      522              
  Lines       20428    20440      +12     
==========================================
+ Hits        17047    17061      +14     
+ Misses       3381     3379       -2     
Files with missing lines Coverage Δ
exporters/otlp/src/otlp_file_client.cc 70.72% <100.00%> (+0.35%) ⬆️
...metrics/export/periodic_exporting_metric_reader.cc 74.14% <100.00%> (+0.93%) ⬆️

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@mateenali66 mateenali66 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reader and file exporter fixes look right. per the overlap discussion on #4382: dropping the batch_span_processor.cc hunk here would let both PRs land without conflict, the other two fixes aren't covered there at all. also needs a CHANGELOG entry

{
// Acquiring cv_m_ guarantees that the next time the worker thread checks the wait condition
// on cv_ (either from notify below or any other reason) it will see IsShutdown() return true.
std::lock_guard<std::mutex> cv_guard{cv_m_};

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fence is right, the wait predicate checks IsShutdown() under cv_m_. the force flush path below has the same store-then-notify shape (the "must not wait for ever" workaround), in scope here or follow-up?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since it's in the same vein, I've added the change to ForceFlush as well.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ForceFlush change looks right, and no lock-order problem with it: this path takes force_flush_m_ then cv_m_ inside the predicate, and the worker's cv_m_ lock is scoped to the do-while body so it is released before CollectAndExportOnce runs.

One direction is still open though. This fixes the waker side (cv_). The completion side is unchanged: CollectAndExportOnce CASes force_flush_notified_sequence_ and calls force_flush_cv_.notify_all() holding nothing, so an OnForceFlush caller can evaluate the predicate, miss the notify, then wait. That is what the "must not wait for ever" chunked wait is compensating for, so the chunked loop has to stay as long as that store-then-notify is unguarded. Same bucket as the wait_for race you described, fine as a follow-up, just noting why that workaround can't come out yet.

Comment thread exporters/otlp/src/otlp_file_client.cc Outdated
// Even though is_shutdown is atomic, the lock guarantees that either a change to
// is_shutdown will be observed, or background_thread_waker_cv will see the notification
// at shutdown.
if (concurrency_file->is_shutdown.load(std::memory_order_acquire))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

with the early check gone, shutdown is observed only after one more flush pass, intended? fine if it's deliberate flush-on-shutdown, just checking

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The check on is_shutdown occurs at almost the same time as previously, the only difference is that the check now occurs while holding concurrency_file->background_thread_waker_lock instead of prior to acquiring it. In both cases, if a flush is occurring while is_shutdown is set then the code will break prior to the next wait_for. Does that make sense or am I misunderstanding?

While looking into this I do notice there is an issue where a ForceFlush may not cause an additional flush and make take the full flush interval if file_->background_thread_waker_cv.notify_all(); happens just before the background thread blocks on concurrency_file->background_thread_waker_cv.wait_for(lk, flush_interval);. Fixing this would require a more involved change, so I'd prefer that to be separate. Some details on that: if you just add a variable to cause background_thread_waker_cv.wait_for to exit when it's set (e.g. is_force_background_thread_wake), the problem is that ForceFlush waits on background_thread_waiter_cv , so it could miss the notification from the background thread unless there is some additional synchronization (e.g., acquire the waiter lock before releasing the waker lock).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-read the loop against the head commit, the only thing between the old check position and the new one is the BeforeWait() hook, so no extra flush pass. Agreed.

That hook is the one thing the move does change. On the shutdown path BeforeWait() now fires and AfterWait() never does, because the break is inside the lock scope. Before this PR the shutdown break came ahead of BeforeWait(), so the pair stayed balanced. thread_instrumentation.h documents the two as bracketing a blocking wait, so an app that flips thread state in BeforeWait and restores it in AfterWait leaves it set at thread exit. Hoisting the break out of the lock scope keeps both the fence and the pairing:

bool shutdown_requested = false;
{
  std::unique_lock<std::mutex> lk(concurrency_file->background_thread_waker_lock);
  shutdown_requested = concurrency_file->is_shutdown.load(std::memory_order_acquire);
  if (!shutdown_requested)
  {
    concurrency_file->background_thread_waker_cv.wait_for(lk, flush_interval);
  }
}

then break after the AfterWait() block. Agreed the ForceFlush / wait_for race is a separate change.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  std::unique_lock<std::mutex> lk(concurrency_file->background_thread_waker_lock);
  concurrency_file->background_thread_waker_cv.wait_for(lk, flush_interval, [concurrency_file]() {
    return concurrency_file->is_shutdown.load(std::memory_order_acquire);
  });

Is these codes more clear? We also use conditional wait_for in other components.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, I've moved the break to after AfterWait.

As far as using the conditional wait_for, I don't think it would be a lot clearer right now because is_shutdown has to kept outside the function, so the code would be more like

  std::unique_lock<std::mutex> lk(concurrency_file->background_thread_waker_lock);
  concurrency_file->background_thread_waker_cv.wait_for(lk, flush_interval, [concurrency_file, &is_shutdown]() {
    return is_shutdown = concurrency_file->is_shutdown.load(std::memory_order_acquire);
  });

but let me know if this is preferred.

Comment thread exporters/otlp/src/otlp_file_client.cc Resolved
if (worker_thread_.joinable())
{
synchronization_data_->is_force_wakeup_background_worker.store(true, std::memory_order_release);
{

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we drop the BatchSpanProcessor changes from this PR? #4382 contains the more complete fix for this path, including ForceFlush, completion notification, and regression coverage. Keeping the trace fix there avoids overlapping changes between the two PRs.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, I've removed BatchSpanProcessor changes.

@mike-nugent-mongodb mike-nugent-mongodb left a comment •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've removed the BatchSpanProcessor and added the change to CHANGELOG in addition to addressing the comments.

if (worker_thread_.joinable())
{
synchronization_data_->is_force_wakeup_background_worker.store(true, std::memory_order_release);
{

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, I've removed BatchSpanProcessor changes.

Comment thread exporters/otlp/src/otlp_file_client.cc Resolved
{
// Acquiring cv_m_ guarantees that the next time the worker thread checks the wait condition
// on cv_ (either from notify below or any other reason) it will see IsShutdown() return true.
std::lock_guard<std::mutex> cv_guard{cv_m_};

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since it's in the same vein, I've added the change to ForceFlush as well.

Comment thread exporters/otlp/src/otlp_file_client.cc Outdated
// Even though is_shutdown is atomic, the lock guarantees that either a change to
// is_shutdown will be observed, or background_thread_waker_cv will see the notification
// at shutdown.
if (concurrency_file->is_shutdown.load(std::memory_order_acquire))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The check on is_shutdown occurs at almost the same time as previously, the only difference is that the check now occurs while holding concurrency_file->background_thread_waker_lock instead of prior to acquiring it. In both cases, if a flush is occurring while is_shutdown is set then the code will break prior to the next wait_for. Does that make sense or am I misunderstanding?

While looking into this I do notice there is an issue where a ForceFlush may not cause an additional flush and make take the full flush interval if file_->background_thread_waker_cv.notify_all(); happens just before the background thread blocks on concurrency_file->background_thread_waker_cv.wait_for(lk, flush_interval);. Fixing this would require a more involved change, so I'd prefer that to be separate. Some details on that: if you just add a variable to cause background_thread_waker_cv.wait_for to exit when it's set (e.g. is_force_background_thread_wake), the problem is that ForceFlush waits on background_thread_waiter_cv , so it could miss the notification from the background thread unless there is some additional synchronization (e.g., acquire the waiter lock before releasing the waker lock).

@mateenali66

Copy link
Copy Markdown
Member

branch is conflicting against main now that #4382 has landed, needs a rebase before CI can give a clean signal here

owent added a commit to owent/opentelemetry-cpp-contrib that referenced this pull request Aug 20, 2026
Comment thread exporters/otlp/src/otlp_file_client.cc Resolved

@mike-nugent-mongodb mike-nugent-mongodb left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

branch is conflicting against main now that #4382 has landed, needs a rebase before CI can give a clean signal here

I have added merge commits with main, so #4382 changes are included. The only conflict was from CHANGELOG.

Comment thread exporters/otlp/src/otlp_file_client.cc Resolved
Comment thread exporters/otlp/src/otlp_file_client.cc Outdated
// Even though is_shutdown is atomic, the lock guarantees that either a change to
// is_shutdown will be observed, or background_thread_waker_cv will see the notification
// at shutdown.
if (concurrency_file->is_shutdown.load(std::memory_order_acquire))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, I've moved the break to after AfterWait.

As far as using the conditional wait_for, I don't think it would be a lot clearer right now because is_shutdown has to kept outside the function, so the code would be more like

  std::unique_lock<std::mutex> lk(concurrency_file->background_thread_waker_lock);
  concurrency_file->background_thread_waker_cv.wait_for(lk, flush_interval, [concurrency_file, &is_shutdown]() {
    return is_shutdown = concurrency_file->is_shutdown.load(std::memory_order_acquire);
  });

but let me know if this is preferred.

Comment thread exporters/otlp/src/otlp_file_client.cc Resolved

@marcalff marcalff left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks for the fix.

@dbarker
dbarker merged commit 30322cf into open-telemetry:main Sep 8, 2026
77 checks passed
owent added a commit to owent/opentelemetry-cpp-contrib that referenced this pull request Sep 18, 2026
owent added a commit to owent/opentelemetry-cpp-contrib that referenced this pull request Sep 18, 2026
^ Conflicts:
^	exporters/prometheus/MODULE.bazel

Update bazel modules

Fixes bazel and cmake support

Fixes prometheus linking

Fixes document

Fixes compatibility

Fixes compatibility of  localtime_s usage

Make all variables in ResetLogFile atomic

Add unit test for PrometheusFileExporter

Merge concunrrency fixes from <open-telemetry/opentelemetry-cpp#4365>

Update otel-cpp to 1.29.0

Limit max value for wait interval
owent added a commit to owent/opentelemetry-cpp-contrib that referenced this pull request Sep 18, 2026
^ Conflicts:
^	exporters/prometheus/MODULE.bazel

Update bazel modules

Fixes bazel and cmake support

Fixes prometheus linking

Fixes document

Fixes compatibility

Fixes compatibility of  localtime_s usage

Make all variables in ResetLogFile atomic

Add unit test for PrometheusFileExporter

Merge concunrrency fixes from <open-telemetry/opentelemetry-cpp#4365>

Update otel-cpp to 1.29.0

Limit max value for wait interval

^ Conflicts:
^	exporters/prometheus/MODULE.bazel
owent added a commit to owent/opentelemetry-cpp-contrib that referenced this pull request Sep 22, 2026
^ Conflicts:
^	exporters/prometheus/MODULE.bazel

Update bazel modules

Fixes bazel and cmake support

Fixes prometheus linking

Fixes document

Fixes compatibility

Fixes compatibility of  localtime_s usage

Make all variables in ResetLogFile atomic

Add unit test for PrometheusFileExporter

Merge concunrrency fixes from <open-telemetry/opentelemetry-cpp#4365>

Update otel-cpp to 1.29.0

Limit max value for wait interval

^ Conflicts:
^	exporters/prometheus/MODULE.bazel

^ Conflicts:
^	.github/workflows/prometheus.yml
^	exporters/prometheus/.bazelversion
^	exporters/prometheus/CMakeLists.txt
^	exporters/prometheus/MODULE.bazel
^	exporters/prometheus/repository.bzl
owent added a commit to owent/opentelemetry-cpp-contrib that referenced this pull request Sep 24, 2026
^ Conflicts:
^	exporters/prometheus/MODULE.bazel

Update bazel modules

Fixes bazel and cmake support

Fixes prometheus linking

Fixes document

Fixes compatibility

Fixes compatibility of  localtime_s usage

Make all variables in ResetLogFile atomic

Add unit test for PrometheusFileExporter

Merge concunrrency fixes from <open-telemetry/opentelemetry-cpp#4365>

Update otel-cpp to 1.29.0

Limit max value for wait interval

^ Conflicts:
^	exporters/prometheus/MODULE.bazel

^ Conflicts:
^	.github/workflows/prometheus.yml
^	exporters/prometheus/.bazelversion
^	exporters/prometheus/CMakeLists.txt
^	exporters/prometheus/MODULE.bazel
^	exporters/prometheus/repository.bzl
owent added a commit to owent/opentelemetry-cpp-contrib that referenced this pull request Oct 9, 2026
Update bazel modules

Fixes bazel and cmake support

Fixes prometheus linking

Fixes document

Fixes compatibility

Fixes compatibility of  localtime_s usage

Make all variables in ResetLogFile atomic

Add unit test for PrometheusFileExporter

Merge concunrrency fixes from <open-telemetry/opentelemetry-cpp#4365>

Update otel-cpp to 1.29.0

Limit max value for wait interval
owent added a commit to owent/opentelemetry-cpp-contrib that referenced this pull request Oct 28, 2026
Update bazel modules

Fixes bazel and cmake support

Fixes prometheus linking

Fixes document

Fixes compatibility

Fixes compatibility of  localtime_s usage

Make all variables in ResetLogFile atomic

Add unit test for PrometheusFileExporter

Merge concunrrency fixes from <open-telemetry/opentelemetry-cpp#4365>

Update otel-cpp to 1.29.0

Limit max value for wait interval
owent added a commit to owent/opentelemetry-cpp-contrib that referenced this pull request Oct 28, 2026
Update bazel modules

Fixes bazel and cmake support

Fixes prometheus linking

Fixes document

Fixes compatibility

Fixes compatibility of  localtime_s usage

Make all variables in ResetLogFile atomic

Add unit test for PrometheusFileExporter

Merge concunrrency fixes from <open-telemetry/opentelemetry-cpp#4365>

Update otel-cpp to 1.29.0

Limit max value for wait interval

Add prometheus file exporter's output document and samples.

Fixes conan building

Fixes dependency of conan

Upgrade to otel 1.29 in vcpkg.json
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.

6 participants