Skip to content

Fix LogStreamBuf thread-safety: shared static buffer, sink & Colorizer (#9515) - #9583

Merged
timosachsenberg merged 1 commit into
developfrom
fix/9515-logstream-thread-safety
Jun 17, 2026
Merged

timosachsenberg merged 1 commit into
developfrom
fix/9515-logstream-thread-safety

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #9515.

Problem

OPENMS_LOG_* resolves to thread-local LogStream/LogStreamBuf instances (#8620 / #8596), so per-stream state (incomplete_line_, log_cache_, …) is no longer raced. But three shared resources survived the refactor and corrupt the heap when warnings are emitted from inside an OpenMP parallel region (0xC0000374 / STATUS_HEAP_CORRUPTION on Windows). This was hit in practice by the imzML reader in #9454, whose populateSpectraWithData_() logs a per-array warning for every spectrum inside a #pragma omp parallel for.

Root cause & fix

  1. Shared static line buffer. LogStreamBuf::syncLF_() assembled lines through a function-local static char buf[BUFFER_LENGTH] shared across all threads (strncpy/memcpy in, C-string read back out). A racing overwrite of the trailing '\0' could also drive incomplete_line_ += &buf[0] past the array.
    → Removed the scratch buffer entirely: append directly into incomplete_line_ / outstring with std::string::append(ptr, len).

  2. Unsynchronized shared sink and shared global Colorizer. distribute_() wrote *(stream) << … << std::endl to the shared std::cerr/std::cout and called (*colorizer_)() / .undo() on the shared global Colorizer (yellow/red/magenta) from multiple threads. The colorizer mutates a heap-backed std::stringstream (input_) unconditionally (independent of TTY redirection), which is itself a genuine data race and a direct heap-corruption source on the default cerr path.
    → Serialized the entire distribute_() body with a single global std::mutex (covers the stream writes, the Colorizer state mutation, and prefix expansion). The mutex is intentionally leaked so it stays valid during static teardown — unlike the former OpenMP critical section, a std::mutex does not depend on the OpenMP runtime, so locking in the destructor path is safe. Notifier callbacks are invoked after the lock is released so a notifier that logs cannot self-deadlock.

  3. Non-reentrant localtime. expandPrefix_() used std::localtime (shared static tm), which races when a time-format prefix (%T/%t/%D/…) is configured.
    → Replaced with localtime_r / localtime_s.

Also fixes the stale class doc in LogStream.h, which claimed the macros are "protected by a OPENMS_THREAD_CRITICAL directive". They are not — thread-safety comes from the thread-local buffers plus the new sink mutex.

Testing

  • New regression section in LogStream_test.cpp: logs 5000 unique messages from an 8-thread OpenMP region (capturing cerr, which carries the yellow colorizer) and asserts every message arrives exactly once and intact (count == 5000). Passes locally.
  • Full LogStream_test suite passes.
  • Recommended for reviewers: also run this section under TSan on Linux and as a Release smoke test on Windows (TSan flags the static buf and Colorizer stringstream races; the heap-verifier catches the OOB path).

Notes

  • Behavioral side effect of the thread-local refactor (pre-existing, documented here for completeness): the "…occurred N times" de-dup cache is per-thread, so identical warnings from N threads can print up to N times.

🤖 Generated with Claude Code

Summary by CodeRabbit

Bug Fixes

  • Improved thread-safety of log emission to prevent corrupted or missing messages when multiple threads log concurrently.
  • Made timestamp formatting and output dispatch more reliable under parallel execution.

Documentation

  • Updated logging macro documentation to reflect the current thread-local logging model and safe configuration guidance.

Tests

  • Added a regression test that validates warning messages emitted inside an OpenMP parallel region are captured exactly once per expected id.

@github-actions

Copy link
Copy Markdown
Contributor

@timosachsenberg The following names might be missing from the AUTHORS file:

  • Timo Sachsenberg

Please consider applying the following patch:

--- AUTHORS	2026-06-16 06:36:25.687693644 +0000
+++ AUTHORS.new	2026-06-16 06:36:30.814822240 +0000
@@ -23,8 +23,8 @@
  - Chirag Dave
  - Chris Bauer
  - Chris Bielow
- - Christie Mathews
  - Christian Ehrlich
+ - Christie Mathews
  - Clemens Groepl
  - Cornelia Friedle
  - Daniel Jameson

@timosachsenberg
timosachsenberg marked this pull request as ready for review June 16, 2026 06:38
@coderabbitai

coderabbitai Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@timosachsenberg, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 6 minutes and 27 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 5496a3c6-64d2-48a5-a33f-152716374792

📥 Commits

Reviewing files that changed from the base of the PR and between 564a411 and 389b45f.

📒 Files selected for processing (3)
  • src/openms/include/OpenMS/CONCEPT/LogStream.h
  • src/openms/source/CONCEPT/LogStream.cpp
  • src/tests/class_tests/openms/source/LogStream_test.cpp
📝 Walkthrough

Walkthrough

Thread-safety of OPENMS_LOG_* macro logging is improved by introducing a global leaked mutex to serialize final sink writes and Colorizer state in LogStreamBuf::distribute_(), deferring logNotify() calls until after the lock is released, removing a static scratch buffer from syncLF_(), and replacing non-reentrant localtime with localtime_s/localtime_r. The header documentation is updated and an OpenMP parallel regression test is added.

Changes

LogStream thread-safety hardening

Layer / File(s) Summary
Global mutex and reentrant time helper
src/openms/source/CONCEPT/LogStream.cpp
Adds <ctime>, <mutex>, <vector> headers and defines an anonymous-namespace leaked global mutex accessor and a toLocalTime_() reentrant helper used throughout the new implementation.
Thread-safe distribute_() and syncLF_() rewrite
src/openms/source/CONCEPT/LogStream.cpp
Locks the global mutex around all sink writes and Colorizer state in distribute_(), defers logNotify() until after the lock is released, removes the static scratch buffer from syncLF_(), and appends partial lines directly into incomplete_line_.
Reentrant timestamp formatting
src/openms/source/CONCEPT/LogStream.cpp
Replaces all non-reentrant localtime calls in prefix expansion with toLocalTime_() and strftime for all timestamp format variants.
Threading docs update and OpenMP regression test
src/openms/include/OpenMS/CONCEPT/LogStream.h, src/tests/class_tests/openms/source/LogStream_test.cpp
Updates OPENMS_LOG_* Doxygen note to describe thread-local buffers, mutex-serialized sink dispatch, and getGlobalLog*() configuration-only semantics; adds a parallel OpenMP test that captures and validates OPENMS_LOG_WARN output integrity across concurrent iterations.

Possibly related issues

Poem

🐇 Hop hop, no more races to dread,
A mutex now guards what threads once shred.
localtime_r keeps timestamps in line,
No static scratch buffer to corrupt by design.
The log flows safely, each message aligned — ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main changes: fixing LogStreamBuf thread-safety by addressing the shared static buffer, sink, and Colorizer issues, all referenced with the issue number #9515.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/9515-logstream-thread-safety

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/tests/class_tests/openms/source/LogStream_test.cpp`:
- Around line 139-147: The current loop logic only counts total occurrences of
"racing_line_" to verify the count matches num_iterations, which is insufficient
because a dropped message and a duplicated message would cancel out and still
pass. Instead of just counting occurrences in the for loop starting at the
out.find("racing_line_") call, extract and track the individual message IDs from
the captured output by parsing each "racing_line_" occurrence along with its
associated numeric ID, then assert that each ID from 0 to num_iterations-1
appears exactly once by checking that no IDs are duplicated and none are
missing.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 4d80ce00-c2a2-4f70-92c2-7dc621882b26

📥 Commits

Reviewing files that changed from the base of the PR and between a1ca62b and df9e523.

📒 Files selected for processing (3)
  • src/openms/include/OpenMS/CONCEPT/LogStream.h
  • src/openms/source/CONCEPT/LogStream.cpp
  • src/tests/class_tests/openms/source/LogStream_test.cpp

@timosachsenberg
timosachsenberg force-pushed the fix/9515-logstream-thread-safety branch from df9e523 to 564a411 Compare June 16, 2026 07:12
#9515)

OPENMS_LOG_* routes through thread-local LogStream/LogStreamBuf instances,
but three shared resources survived the thread-local refactor (#8620/#8596)
and corrupt the heap when logging from OpenMP parallel regions (0xC0000374
on Windows; hit in practice by the imzML reader in #9454):

1. syncLF_() assembled lines through a function-local
   `static char buf[BUFFER_LENGTH]` shared across every thread. Replaced
   with direct std::string::append into incomplete_line_/outstring, so there
   is no scratch buffer (and no out-of-bounds read when a racing thread
   overwrites the trailing NUL).

2. distribute_() wrote to the shared sink (std::cerr/std::cout) and mutated
   the shared global Colorizer (yellow/red/magenta -- its std::stringstream
   and flags) from multiple threads without synchronization. Both are now
   serialized by a single global std::mutex held around the whole
   distribute_() body. The mutex is intentionally leaked so it stays valid
   during static teardown (a std::mutex, unlike the former OpenMP critical
   section, does not depend on the OpenMP runtime). Notifier callbacks run
   after the lock is released to avoid self-deadlock.

3. expandPrefix_() used non-reentrant std::localtime (shared static tm).
   Replaced with localtime_r/localtime_s.

Also corrects the stale LogStream.h note that claimed the macros are
protected by OPENMS_THREAD_CRITICAL (they are not -- safety comes from
thread-local buffers plus the new sink mutex), and adds a regression test
that logs 5000 unique messages from an 8-thread OpenMP region and asserts
each arrives exactly once and intact.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@timosachsenberg
timosachsenberg force-pushed the fix/9515-logstream-thread-safety branch from 564a411 to 389b45f Compare June 16, 2026 08:19
@timosachsenberg
timosachsenberg merged commit 5e727b1 into develop Jun 17, 2026
41 checks passed
@timosachsenberg
timosachsenberg deleted the fix/9515-logstream-thread-safety branch June 17, 2026 08:35
timosachsenberg added a commit that referenced this pull request Jun 19, 2026
Add entries for all substantive non-test PRs merged since the last
changelog update:

- #9623 ThermoRawFile full mzML metadata extraction + polarity fix
- #9602 New FileInfo library class usable from C++ and pyOpenMS
- #9521 IMAGING multi-region support (add missing PR reference)
- #9620 Deisotoper::isToleranceSupported + ProSE/SSE crash fix on low-res data
- #9610 DistanceMatrix::setValue cached-minimum guard fix
- #9497 DistanceMatrix::operator==, ClusteringGrid, File path guard fixes
- #9583 LogStreamBuf thread-safety fix
- #9514 CI Windows migration to Visual Studio 2026


Claude-Session: https://claude.ai/code/session_01YLg6pWyjyTxpWAU6mgrDzC

Co-authored-by: Claude <[email protected]>
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.

LogStreamBuf is not thread-safe: shared static buffer + unsynchronized sink corrupt the heap when logging from OpenMP regions

1 participant