Skip to content

[INTERNAL,FIX] UniqueIdGenerator: one mutex per draw, exclude zero ids - #10538

Merged
timosachsenberg merged 2 commits into
OpenMS:developfrom
timosachsenberg:perf/10520-buffered-unique-ids
Oct 13, 2026
Merged

timosachsenberg merged 2 commits into
OpenMS:developfrom
timosachsenberg:perf/10520-buffered-unique-ids

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Description

getUniqueId() currently enters two OpenMP critical sections per draw. This makes bulk generation contend between workers and leaves the shared RNG unprotected in builds without OpenMP. setSeed() uses a different critical section than the draw, so a concurrent reseed races with it.

Guard the shared std::mt19937_64 with one std::mutex, taken on every draw and in setSeed()/getSeed(). Skip zero engine outputs, which UniqueIdInterface reserves for an invalid id.

Keep the implementation small: one private state object owns the seed, engine and mutex; the engine is stored by value. Remove the old singleton bookkeeping, redundant test buffers and unused includes. There is no new public API or configuration. Add explicit standard-thread linkage, regression coverage and a changelog entry.

An earlier revision of this PR cached 1024 ids per thread. It was faster under contention, but seeded runs with more than one thread stopped being reproducible: the ids drawn in a parallel region, and every id drawn serially after it, depended on thread count and scheduling. For example, ProteomicsLFQ -test wrote different consensusXML ids at 2, 4 and 8 threads than at 1. The second commit replaces the cache with the per-draw mutex.

Related to #10520. This excludes zero and makes generation thread-safe without OpenMP; it does not implement the broader map-ID lifecycle changes in that issue.

Compatibility and tradeoffs

  • The seeded sequence is preserved, except zero outputs are skipped.
  • For a given seed, the ids drawn up to any point are the same set however many threads drew them, as on develop. Which thread receives which id still depends on scheduling.
  • setSeed() may run while other threads draw; each draw comes from either the old or the new seed.
  • Every draw takes the mutex, so tight multi-threaded generation loops still serialize. The per-thread cache of the earlier revision was 2.5–5.5x faster in such loops, at the cost of the reproducibility described above.

Validation

  • Full configured Debug build passed with GCC 13.4/C++23, assertions and OpenMP enabled. GUI, pyOpenMS, OpenTIMS and Thermo RAW were disabled.
  • Full CTest run: 2,997 passed, 12 failed, 5 skipped out of 3,014 tests. The same 12 fail when develop's generator is interposed into the same binaries via LD_PRELOAD: six CometAdapter output comparisons (for CometAdapter_1, the reference idXML records a calibration_tolerance parameter that this build's output lacks), five ProSE rescoring tests/comparisons (vendored Percolator's BaseSpline.cpp:236 assertion), and one external Percolator output comparison.
  • Generator tests cover the original golden values; 100,000 exact serial draws against std::mt19937_64 for each of three seeds; 100,000 ids drawn by eight OpenMP workers and by eight standard threads, each asserted to equal the first engine outputs for the seed, with the next id following them; and UUID and integer ids sharing the sequence. The multi-threaded assertions fail against the earlier per-thread cache.
  • Seeded reproducibility: a probe that draws ids in a dynamically scheduled OpenMP region and then one serial id gave one distinct result over 30 runs at each of 1, 2, 4 and 8 threads, identical to develop's generator. The TOPP_ProteomicsLFQ_1 command wrote byte-identical consensusXML at 1, 2, 4 and 8 threads, and its two reference comparisons passed at each.
  • The actual generator source passed a probe with eight threads drawing ids and UUIDs from a cold start during 200 concurrent reseeds under ThreadSanitizer and ASan/UBSan. This instruments the generator probe rather than the full library; ASan leak detection was disabled.
  • clang-format --dry-run -Werror and git diff --check passed.

Generator microbenchmark, this implementation versus unchanged develop source, built as a shared library with -O3 -fPIC -fopenmp, tight loop of 2,000,000 ids per thread, best of three:

Threads Develop Single mutex Speedup
1 24.9 M ids/s 42.4 M ids/s 1.7x
2 6.5 M ids/s 13.9 M ids/s 2.1x
4 3.0 M ids/s 14.8 M ids/s 4.9x
8 1.9 M ids/s 11.6 M ids/s 6.1x

In a process that has not started another thread, a draw costs 9.2 ns versus 38.5 ns on develop. These are generator timings, not end-to-end workflow speedups.

Checklist

  • Listed in AUTHORS
  • CHANGELOG updated
  • Comments explain the synchronization
  • New and existing unit tests pass locally; integration-suite limitations are documented above
  • Python bindings need no changes because the public API is unchanged

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Unique IDs are now generated safely across concurrent calls, including when OpenMP is unavailable.
    • Generated integer IDs exclude zero. If the random generator produces zero, another value is drawn instead.
  • Improvements
    • Seeded ID generation follows a consistent sequence, skipping zero values while preserving the sequence of other generated values.
    • UUIDs and integer IDs continue to draw from the same generator.

Amortize shared Mersenne Twister synchronization across batches of 1024
nonzero IDs. Keep the seeded single-thread sequence, and invalidate caches
on every seed reset. Protect refills in builds with and without OpenMP.

Consolidate private generator state and cover serial stream compatibility,
million-ID parallel generation, persistent-worker reseeding and UUID batch
boundaries. Document the changed parallel allocation and idle-worker
requirement for reseeding.

Related to OpenMS#10520.

Copilot AI 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.

🟢 Approval recommended

The implementation is internally consistent, correctly synchronized under its documented contract, and comprehensively tested.

0 open findings

What changed in this PR

Improves UniqueIdGenerator concurrency and performance while ensuring generated IDs are nonzero.

Changes:

  • Adds thread-local buffering with synchronized batch refills and reseed invalidation.
  • Expands serial, OpenMP, standard-thread, reseeding, and UUID tests.
  • Adds thread linkage, API documentation, and changelog coverage.
File Description
CHANGELOG Documents behavior and compatibility changes.
src/​openms/​CMakeLists.txt Links OpenMS with thread support.
src/​openms/​include/​OpenMS/​CONCEPT/​UniqueIdGenerator.h Documents buffering and reseeding semantics.
src/​openms/​source/​CONCEPT/​UniqueIdGenerator.cpp Implements synchronized batch generation.
src/​tests/​class_tests/​openms/​CMakeLists.txt Links generator tests with thread support.
src/​tests/​class_tests/​openms/​source/​UniqueIdGenerator_test.cpp Adds comprehensive concurrency and sequence tests.

🧠 Review effort: Balanced


💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

…stead of buffering per thread

The per-thread 1024-id buffer made seeded runs with more than one thread
irreproducible: the set of ids drawn in a parallel region, and every id drawn
serially after it, depended on thread count and scheduling. For example,
ProteomicsLFQ -test produced different consensusXML ids at 2, 4 and 8 threads
than at 1 thread.

Take the shared mutex on every draw instead. All threads advance the one
engine, so for a given seed the ids drawn up to any point are the same set
however many threads drew them, as before the buffer was introduced. This
still replaces the two OpenMP critical sections per id with a single lock and
still protects callers that do not use OpenMP.

Removes the buffer, the generation counter, the cache-line alignment and the
setSeed() precondition that no other thread may be generating ids.

Tests: the multi-threaded sections now assert that the ids drawn by eight
OpenMP or standard threads are exactly the first outputs of the seeded engine
and that the next id follows them. The batch-boundary and cache-invalidation
cases are dropped with the buffer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: b00d3896-4958-4743-b129-d779c655b00a

📥 Commits

Reviewing files that changed from the base of the PR and between 4df2bef and 1142e7f.


📒 Files selected for processing (4)
  • CHANGELOG
  • src/openms/include/OpenMS/CONCEPT/UniqueIdGenerator.h
  • src/openms/source/CONCEPT/UniqueIdGenerator.cpp
  • src/tests/class_tests/openms/source/UniqueIdGenerator_test.cpp

🚧 Files skipped from review as they are similar to previous changes (1)
  • CHANGELOG

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.



📝 Walkthrough
📝 Walkthrough

Walkthrough

UniqueIdGenerator now uses a shared random engine protected by a mutex. Integer ID generation skips zero outputs, and UUID generation continues to use two draws. Seed access and reseeding use the same synchronized state. Tests cover deterministic sequences and concurrent generation.

Changes

UniqueIdGenerator

Layer / File(s) Summary
Generator contract and state
src/openms/include/OpenMS/CONCEPT/UniqueIdGenerator.h, src/openms/source/CONCEPT/UniqueIdGenerator.cpp, src/openms/CMakeLists.txt
The documentation describes shared process-lifetime generation and nonzero IDs. The implementation initializes shared state using clock time and process ID, and removes the static singleton and RNG pointers. OpenMS links Threads privately.
Synchronized generation and seed access
src/openms/source/CONCEPT/UniqueIdGenerator.cpp
Integer ID draws, UUID draws, seed reads, and reseeding use the shared mutex-protected engine. Integer generation retries zero outputs.
Build integration and generator tests
src/tests/class_tests/openms/CMakeLists.txt, src/tests/class_tests/openms/source/UniqueIdGenerator_test.cpp, CHANGELOG
The test target links Threads. Tests check seeded sequences, seed retrieval, UUID and integer stream sharing, and concurrent generation. The changelog records the generator changes.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant UniqueIdGenerator
  participant SharedGeneratorState
  participant Mutex
  participant mt19937_64
  Caller->>UniqueIdGenerator: Request an integer ID
  UniqueIdGenerator->>Mutex: Lock shared generator state
  UniqueIdGenerator->>mt19937_64: Draw an ID
  alt Draw is zero
    UniqueIdGenerator->>mt19937_64: Draw again
  else Draw is nonzero
    UniqueIdGenerator-->>Caller: Return ID
  end
  UniqueIdGenerator->>Mutex: Unlock shared generator state
Loading

Priority: ⬇️ Low

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 1142e

Unique ID generation now uses one shared, mutex-protected engine and skips zero IDs. No actionable merge-blocking risk was found. Update the PR description to match the implemented design.

Pre-merge checks | Passed 4 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 3 files. (1 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title accurately identifies the main changes: mutex protection for each ID draw and exclusion of zero IDs. It is specific and concise.

Full details: Docstring Coverage

Explanation

Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 3 files. (1 skipped: 1 unsupported.)


  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR


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

A rabbit checks the numbers as they hop,
Zero turns around and makes a stop.
Two draws shape a UUID bright,
The mutex keeps the stream in sight.
Seeds return, and threads share the trail.

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

@timosachsenberg timosachsenberg changed the title [INTERNAL,FIX] Buffer unique ID generation per thread [INTERNAL,FIX] UniqueIdGenerator: one mutex per draw, exclude zero ids Oct 12, 2026
@timosachsenberg

Copy link
Copy Markdown
Contributor Author

could be improved if we accept different orders on different threads

@timosachsenberg
timosachsenberg merged commit f62a011 into OpenMS:develop Oct 13, 2026
31 checks passed
timosachsenberg pushed a commit that referenced this pull request Oct 13, 2026
…ProSE)

Only CHANGELOG conflicted (both entries kept). The new PeptDeep rescoring works
on PeptideIdentification lists, which this branch keeps.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01B51nRFoHvZuVXD7cT8XZav
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.

2 participants