Skip to content

Parallelize the streaming QPX feature Parquet export (OpenMP) - #9699

Merged
timosachsenberg merged 2 commits into
developfrom
perf/qpx-feature-streaming-parallel
Jul 2, 2026
Merged

timosachsenberg merged 2 commits into
developfrom
perf/qpx-feature-streaming-parallel

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #9698 (base branch perf/qpx-feature-streaming-export). Review/merge that one first; this PR's diff is only the parallelization delta.

Motivation

#9698 made the QPX feature export stream in batches so peak memory stays bounded (fixing the isobaric OOM where quantms.feature.parquet was never created). That version builds each batch serially. The per-feature build (ProForma + modifications + mass math) is the bulk of export time, so this follow-up ports the OpenMP parallel batch build that the merged PSM PR #9697 already uses — same pattern, applied to the feature path.

What this does

  • Parallel batch build. ConsensusMapArrowExport::exportToParquetStreaming gains n_threads (1 = serial default, 0 = all cores honoring OMP_NUM_THREADS, N = fixed). Each batch [b, e) is split into W contiguous sub-ranges built in parallel via #pragma omp parallel for and written in index order (the parquet::arrow::FileWriter stays serial). Worker exceptions are contained per partition via std::exception_ptr and surfaced as the existing bool failure. A pre-warm block touches the lazily-initialized singletons (ModificationsDB/ResidueDB/Scores/AASequence) before the parallel region so first-touch cannot race. Output rows and their order are identical for any thread count (deterministic); only the Parquet row-group layout may differ.
  • Lock-free metavalue reads. buildFeatureTableRange resolves the fixed dedicated-column metavalue names (target_decoy, predicted_RT/rt, ion_mobility/IM, spectrum_reference, missed_cleavages, start/stop_ion_mobility, rt_start/stop) to MetaInfoRegistry indices once per range and reads them via the lock-free UInt overloads behind a metaHas() sentinel guard; the dynamic PEP score name is resolved once per feature; and additional_scores switched from getKeys()+getMetaValue(string) to a single metaBegin()/metaEnd() pass with a cachedMetaName_ index→name cache. This removes the per-row omp critical MetaInfoRegistry lock that would otherwise serialize the parallel build. Same values, same iteration order.
  • IsobaricWorkflow opts the feature export into n_threads=0.

Correctness / determinism

  • Workers share only const state (cmap, id_lut); Arrow builders, IDScoreSwitcherAlgorithm, and the meta_name_cache are per buildFeatureTableRange() call. No shared mutable state.
  • The index-based reads preserve the string-keyed semantics exactly (UInt(-1) guarded; same object per site; predicted_RT/predicted_rt etc. variants kept). getKeys() and metaBegin() both iterate the same index-sorted MetaInfo map, so additional_scores order is unchanged.
  • Every lazy singleton reachable from the parallel region is pre-warmed (the same set Speed up & bound memory of QPX PSM Parquet export (streaming + parallel build) #9697 warms; SpectrumNativeIDParser/boost::regex and ProForma resolve through those chemistry DBs).

Tests

The streaming↔one-shot equivalence now runs across n_threads {1, 2, 8} plus a single all-threads batch (full Table::Equals over combined chunks, order-sensitive via unique RT). A new section pins the exact exported values of every index-resolved dedicated column and the additional_scores struct fields, and asserts non-score / non-numeric metavalues are filtered out. ConsensusMapArrowExport_test passes locally.

🤖 Generated with Claude Code

https://claude.ai/code/session_01HcY3LMYuUDF2psYat9uUYN

Summary by CodeRabbit

  • New Features
    • Parquet streaming export of consensus feature data now supports an n_threads setting to parallelize batch preparation (Parquet writing remains serial).
  • Bug Fixes
    • Improved metadata handling during export using more reliable field resolution (including alternate-name fallbacks) for better nullness and value selection.
    • Ensures deterministic row order matches standard export across thread counts.
  • Tests
    • Streaming export tests now verify deterministic results across multiple n_threads values and strengthen column/row equivalence checks.
    • Added Arrow export coverage for dedicated metavalue and score columns, including filtering and exact value validation.

@timosachsenberg
timosachsenberg force-pushed the perf/qpx-feature-streaming-parallel branch from d3db402 to 8285bae Compare July 1, 2026 15:09
Base automatically changed from perf/qpx-feature-streaming-export to develop July 1, 2026 17:52
Follow-up to the serial streaming feature export: port the OpenMP
parallel batch build that #9697 added for the PSM export to the
feature export, so the per-feature build (~one row per PSM for
isobaric data; ProForma + modifications + mass math, ~93% of export
time) uses all cores while peak memory stays batch-bounded.

- exportToParquetStreaming() gains an n_threads parameter (1 = serial
  default, 0 = all cores honoring OMP_NUM_THREADS, N = fixed). Each
  batch [b, e) is split into W contiguous sub-ranges built in parallel
  via OpenMP and written in index order (the FileWriter stays serial).
  Worker exceptions are contained per partition via std::exception_ptr
  and surfaced as the existing bool failure. Output rows and their order
  are identical for any thread count (deterministic); only the Parquet
  row-group layout may differ. A pre-warm block touches the lazily
  initialized singletons (ModificationsDB/ResidueDB/Scores/AASequence)
  before the parallel region so first-touch cannot race.

- buildFeatureTableRange() now reads metavalues lock-free: the fixed
  dedicated-column names are resolved to MetaInfoRegistry indices once
  per range and read via the UInt overloads behind a metaHas() sentinel
  guard; the dynamic PEP score name is resolved once per feature; and
  additional_scores switched from getKeys()+getMetaValue(string) to a
  single metaBegin()/metaEnd() pass with a cachedMetaName_ index->name
  cache. This removes the per-row omp-critical MetaInfoRegistry lock
  that would otherwise cap parallel scaling. Same values, same order.

- IsobaricWorkflow opts the feature export into n_threads=0.

Tests: the streaming<->one-shot equivalence now runs across n_threads
{1,2,8} plus a single all-threads batch (full Table::Equals, order-
sensitive via unique RT). A new section pins the exact exported values
of every index-resolved dedicated column (is_decoy, posterior_error_
probability, predicted_rt, ion_mobility, ion_mobility_start/stop,
rt_start/stop, missed_cleavages, pg_global_qvalue) and the
additional_scores struct fields, and asserts non-score / non-numeric
metavalues are filtered out.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HcY3LMYuUDF2psYat9uUYN
@timosachsenberg
timosachsenberg force-pushed the perf/qpx-feature-streaming-parallel branch from 8285bae to 46c41f0 Compare July 1, 2026 19:53
@coderabbitai

coderabbitai Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 23a5f271-81f8-4a7e-89fd-c646d974f3e5

📥 Commits

Reviewing files that changed from the base of the PR and between 46c41f0 and 6001224.

📒 Files selected for processing (1)
  • src/tests/class_tests/openms/source/ConsensusMapArrowExport_test.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/tests/class_tests/openms/source/ConsensusMapArrowExport_test.cpp

📝 Walkthrough

Walkthrough

The PR adds n_threads to ConsensusMapArrowExport::exportToParquetStreaming, parallelizes per-batch partition construction with OpenMP while keeping Parquet writes serial, switches MetaInfo access to cached indices in the exporter, updates one caller, and extends export tests.

Changes

Parquet Streaming Export Parallelization and Index-based MetaInfo Access

Layer / File(s) Summary
Streaming export API and documentation for n_threads
src/openms/include/OpenMS/FORMAT/ConsensusMapArrowExport.h
Adds n_threads to exportToParquetStreaming and documents parallel batch construction with serial, order-preserving Parquet writing.
Cached index-based MetaInfo resolution helper
src/openms/source/FORMAT/ConsensusMapArrowExport.cpp
Adds MetaInfo/OpenMP-related includes and introduces cachedMetaName_ for cached registry-name lookup by index.
Index-based metavalue extraction across feature fields
src/openms/source/FORMAT/ConsensusMapArrowExport.cpp
Pre-resolves fixed MetaInfo names into indices and reworks decoy, PEP score, additional scores, predicted RT, spectrum reference, ion mobility, missed cleavages, and rt_start/rt_stop extraction to use index-based access.
OpenMP-parallel batch partition build and serial writing
src/openms/source/FORMAT/ConsensusMapArrowExport.cpp
Adds thread-count handling and replaces serial batch-table construction with parallel partition building, exception capture, and ordered serial writing.
Caller update in IsobaricWorkflow
src/topp/IsobaricWorkflow.cpp
Passes explicit batch_size and n_threads=0 to streaming export.
Tests for deterministic streaming output and dedicated metavalue export
src/tests/class_tests/openms/source/ConsensusMapArrowExport_test.cpp
Updates boolean assertions, validates streaming output across thread counts against a reference table, and adds dedicated metavalue export coverage.

Sequence Diagram(s)

sequenceDiagram
  participant IsobaricWorkflow
  participant exportToParquetStreaming
  participant OpenMPThreads
  participant ParquetWriter
  IsobaricWorkflow->>exportToParquetStreaming: call with batch_size, n_threads=0
  exportToParquetStreaming->>exportToParquetStreaming: resolve thread count, pre-warm singletons
  exportToParquetStreaming->>OpenMPThreads: build batch partitions in parallel
  OpenMPThreads-->>exportToParquetStreaming: return subtables or exceptions
  exportToParquetStreaming->>ParquetWriter: write partitions serially in order
  ParquetWriter-->>IsobaricWorkflow: parquet file written
Loading

Possibly related PRs

  • OpenMS/OpenMS#9692: Both PRs change metavalue serialization to iterate directly via metaBegin()/metaEnd() and use a cached MetaInfo index→name resolver instead of getKeys()/getMetaValue(), affecting Arrow/Parquet export output.

Suggested reviewers: jpfeuffer

Poem

A rabbit hops through threads anew,
Batching Parquet rows in queue,
Indexes hum, names cached tight,
Writes stay serial, order right,
Hoppy tests now all shine through,
Deterministic, crisp, and true 🐇

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: parallelizing the streaming feature Parquet export with OpenMP.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch perf/qpx-feature-streaming-parallel

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.

@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

🧹 Nitpick comments (2)
src/openms/source/FORMAT/ConsensusMapArrowExport.cpp (2)

1113-1131: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Use '\n' instead of std::endl in new logs.

std::endl forces a flush on these error paths. As per coding guidelines, **/*.cpp: “Avoid std::endl and use \n instead for performance reasons”.

♻️ Proposed fix
-        catch (const std::exception& ex) { OPENMS_LOG_ERROR << "ConsensusMapArrowExport: feature batch build threw: " << ex.what() << std::endl; }
-        catch (...)                      { OPENMS_LOG_ERROR << "ConsensusMapArrowExport: feature batch build threw (unknown exception)" << std::endl; }
+        catch (const std::exception& ex) { OPENMS_LOG_ERROR << "ConsensusMapArrowExport: feature batch build threw: " << ex.what() << '\n'; }
+        catch (...)                      { OPENMS_LOG_ERROR << "ConsensusMapArrowExport: feature batch build threw (unknown exception)" << '\n'; }
...
-        OPENMS_LOG_ERROR << "ConsensusMapArrowExport: Failed to build feature batch partition " << t << std::endl;
+        OPENMS_LOG_ERROR << "ConsensusMapArrowExport: Failed to build feature batch partition " << t << '\n';
...
-                         << st.ToString() << std::endl;
+                         << st.ToString() << '\n';
🤖 Prompt for 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.

In `@src/openms/source/FORMAT/ConsensusMapArrowExport.cpp` around lines 1113 -
1131, The new logging in ConsensusMapArrowExport should avoid using std::endl
because it forces an unnecessary flush on error paths. Update the affected log
statements in the relevant export/error handling code to use '\n' instead, and
keep the change localized to the logging calls in ConsensusMapArrowExport.

Source: Coding guidelines


535-536: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Cache dynamic PEP score indices per range.

This still calls MetaInfoRegistry::getIndex() once per feature for repeated result.score_name values, so the registry critical section can remain a parallel hotspot. Cache score-name-to-index alongside the fixed-name indices.

♻️ Proposed refactor
+  std::unordered_map<std::string, UInt> meta_index_cache;
+  auto cachedMetaIndex = [&](const std::string& name) -> UInt
+  {
+    if (name.empty())
+    {
+      return static_cast<UInt>(-1);
+    }
+    const auto it = meta_index_cache.find(name);
+    if (it != meta_index_cache.end())
+    {
+      return it->second;
+    }
+    const UInt idx = mreg.getIndex(name);
+    meta_index_cache.emplace(name, idx);
+    return idx;
+  };
+
   const UInt idx_target_decoy       = mreg.getIndex("target_decoy");
-      const UInt idx_pep = result.score_name.empty() ? static_cast<UInt>(-1) : mreg.getIndex(result.score_name);
+      const UInt idx_pep = cachedMetaIndex(result.score_name);
🤖 Prompt for 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.

In `@src/openms/source/FORMAT/ConsensusMapArrowExport.cpp` around lines 535 - 536,
The per-feature lookup in ConsensusMapArrowExport still repeatedly calls
MetaInfoRegistry::getIndex() for the same result.score_name values, leaving the
registry lock as a hotspot. Update the score-index handling in the export logic
to cache dynamic score-name-to-index mappings alongside the existing fixed-name
indices, and reuse that cached index for all features in the same range instead
of querying MetaInfoRegistry on every iteration.
🤖 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/ConsensusMapArrowExport_test.cpp`:
- Line 450: Replace the boolean assertions in ConsensusMapArrowExport_test with
the dedicated macros: in the affected test cases and helper checks, swap every
TEST_EQUAL(expr, true) to TEST_TRUE(expr) and every TEST_EQUAL(expr, false) to
TEST_FALSE(expr). Use the existing assertion locations around the
ConsensusMapArrowExport tests to update all boolean checks consistently,
including the repeated assertions in the later test block, so the test code
follows the coding guideline and remains easy to read.

---

Nitpick comments:
In `@src/openms/source/FORMAT/ConsensusMapArrowExport.cpp`:
- Around line 1113-1131: The new logging in ConsensusMapArrowExport should avoid
using std::endl because it forces an unnecessary flush on error paths. Update
the affected log statements in the relevant export/error handling code to use
'\n' instead, and keep the change localized to the logging calls in
ConsensusMapArrowExport.
- Around line 535-536: The per-feature lookup in ConsensusMapArrowExport still
repeatedly calls MetaInfoRegistry::getIndex() for the same result.score_name
values, leaving the registry lock as a hotspot. Update the score-index handling
in the export logic to cache dynamic score-name-to-index mappings alongside the
existing fixed-name indices, and reuse that cached index for all features in the
same range instead of querying MetaInfoRegistry on every iteration.
🪄 Autofix (Beta)

✅ Autofix completed


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3c324d07-7d66-4452-8bd6-cb4dd5cb2a4a

📥 Commits

Reviewing files that changed from the base of the PR and between 0fe9ffb and 46c41f0.

📒 Files selected for processing (4)
  • src/openms/include/OpenMS/FORMAT/ConsensusMapArrowExport.h
  • src/openms/source/FORMAT/ConsensusMapArrowExport.cpp
  • src/tests/class_tests/openms/source/ConsensusMapArrowExport_test.cpp
  • src/topp/IsobaricWorkflow.cpp

@coderabbitai

coderabbitai Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Note

Autofix is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it.

Fixes Applied Successfully

Fixed 1 file(s) based on 1 unresolved review comment.

Files modified:

  • src/tests/class_tests/openms/source/ConsensusMapArrowExport_test.cpp

Commit: 6001224bdfea311b1ce6e9f605514806714f1795

The changes have been pushed to the perf/qpx-feature-streaming-parallel branch.

Time taken: 4m 16s

Fixed 1 file(s) based on 1 unresolved review comment.

Co-authored-by: CodeRabbit <[email protected]>
@timosachsenberg
timosachsenberg merged commit 508d9b5 into develop Jul 2, 2026
41 checks passed
@timosachsenberg
timosachsenberg deleted the perf/qpx-feature-streaming-parallel branch July 2, 2026 05:09
timosachsenberg added a commit that referenced this pull request Jul 4, 2026
Routine changelog sweep found three merged develop PRs without changelog
coverage: FileInfo progress-logging restoration (#9707), a pyOpenMS enum
binding completeness fix (#9705), and OpenMP parallelization of the QPX
feature Parquet export (#9699, extending #9698). Also updated the #9698
entry's now-inaccurate "Serial only" note to point at #9699.


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

Co-authored-by: Claude <[email protected]>
timosachsenberg added a commit that referenced this pull request Jul 6, 2026
Three recently merged PRs landed on develop without changelog coverage:
the OpenMP parallelization of the QPX feature Parquet export (#9699,
follow-up to #9698), the pyOpenMS enum-binding drift fix restoring
several inaccessible NASFragmentType/ProteomicsPkaScale/OSWHierarchy/
LPWrapper::SOLVER enumerators (#9705), and the re-added FileInfo
progress logging exposed to pyOpenMS via Options.log_type (#9707).


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

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

1 participant