Repository navigation
Speed up & bound memory of QPX PSM Parquet export (streaming + parallel build) - #9697
Conversation
…rkflow Build and flush the QPX PSM table in row-batches through a persistent parquet::arrow::FileWriter (QPXFile::exportToParquetStreaming) instead of materializing the entire table in memory, and pass non-owning pointers from IsobaricWorkflow instead of deep-copying all PeptideIdentifications. This caps peak memory for very large PSM counts (millions), which was driving multi-hour PSM Parquet writes into swap. - exportPSMsToQPXArrow refactored to delegate to a file-local buildQPXPSMTableRange over a pointer range (behavior unchanged) - QPX PSM metadata factored into qpxPsmMetadata(), built once per file and reused per batch via ReplaceSchemaMetadata - IsobaricWorkflow collects const PeptideIdentification* (no deep copy); pointers reference into the ConsensusMap that outlives the export - tests: streaming-vs-one-shot equivalence + empty/single/non-multiple/0-batch edge cases (chunk-aware readback) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Build each batch's rows in parallel by splitting the batch into contiguous sub-ranges, building each via buildQPXPSMTableRange on its own OpenMP thread, then writing them in index order through the (serial) FileWriter. The per-row build is ~93% of export time and is embarrassingly parallel; peak memory stays batch-bounded (the sub-tables together hold one batch's rows). - exportToParquetStreaming gains an n_threads param (1 = serial default, 0 = all cores, N = fixed); IsobaricWorkflow opts into n_threads=0 - exceptions are contained per worker via std::exception_ptr and surfaced as a logged failure (never thrown across the OpenMP boundary) - singletons pre-warmed before the parallel region; writer stays serial - output is byte-identical in row content/order for any n_threads - tests: n_threads=1/2/8 equivalence vs one-shot, export_all_psms with variable hits across partitions, non-empty-zero-rows, and M=0/M=1/rows<threads edges Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…dedicated columns) The dedicated-column reads in buildQPXPSMTableRange still resolved metavalues by string name (target_decoy, predicted_RT/predicted_rt, ion_mobility/IM, missed_cleavages, reference_file_name/run_file_name, and the PEP score name), each taking the MetaInfoRegistry omp-critical lock twice via getIndex(). Under the parallel build this serialized every partition on one global lock. Resolve those fixed names to registry indices ONCE per range (plus the dynamic PEP score name once per identification) and use the lock-free index overloads of metaValueExists(UInt)/getMetaValue(UInt) in the per-row body. UInt(-1) (unregistered name) is explicitly guarded to match the string overload's sentinel behaviour, and the alias precedence (predicted_RT > predicted_rt; ion_mobility > IM; reference_file_name > run_file_name) is preserved, so output is byte-identical. Complements #9692, which already removed the lock from the additional_scores iteration. exportToArrow (serial PSMSchema path) is intentionally left unchanged. Also document that n_threads=0 honours OMP_NUM_THREADS and that on hyper-threaded CPUs the physical-core count is the sweet spot (the build is memory-bandwidth bound). - new test: dedicated-column exact values + alias precedence, streaming(n_threads=4) == one-shot Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds a batched ChangesQPX Streaming Export
Sequence Diagram(s)sequenceDiagram
participant IsobaricWorkflow
participant QPXFile
participant OpenMPWorkers
participant ParquetWriter
IsobaricWorkflow->>QPXFile: exportToParquetStreaming(peptide_identification_ptrs, batch_size=1000000, n_threads=0)
QPXFile->>QPXFile: partition batch into contiguous subranges
QPXFile->>OpenMPWorkers: buildQPXPSMTableRange(subrange) in parallel
OpenMPWorkers-->>QPXFile: sub-tables built
QPXFile->>ParquetWriter: write row groups sequentially
ParquetWriter-->>IsobaricWorkflow: close writer/output stream
Possibly related PRs
Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
src/openms/source/FORMAT/QPXFile.cpp (1)
1564-1565: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse
\ninstead ofstd::endlin new log messages.These paths do not need forced flushing.
♻️ Proposed logging cleanup
- << file_result.status().ToString() << std::endl; + << file_result.status().ToString() << "\n"; ... - << writer_result.status().ToString() << std::endl; + << writer_result.status().ToString() << "\n"; ... - catch (const std::exception& ex) { OPENMS_LOG_ERROR << "QPXFile: PSM batch build threw: " << ex.what() << std::endl; } - catch (...) { OPENMS_LOG_ERROR << "QPXFile: PSM batch build threw (unknown exception)" << std::endl; } + catch (const std::exception& ex) { OPENMS_LOG_ERROR << "QPXFile: PSM batch build threw: " << ex.what() << "\n"; } + catch (...) { OPENMS_LOG_ERROR << "QPXFile: PSM batch build threw (unknown exception)" << "\n"; } ... - << st.ToString() << std::endl; + << st.ToString() << "\n"; ... - << writer_close.ToString() << std::endl; + << writer_close.ToString() << "\n"; ... - << outfile_close.ToString() << std::endl; + << outfile_close.ToString() << "\n";As per coding guidelines, “Avoid
std::endland use\ninstead for performance reasons.”Also applies to: 1577-1578, 1620-1621, 1638-1639, 1665-1673
🤖 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/QPXFile.cpp` around lines 1564 - 1565, The new QPXFile log messages currently use std::endl, which forces an unnecessary flush; update the affected OPENMS_LOG_ERROR statements in QPXFile to use '\n' instead. Check the logging spots around the file-open, write, and related error paths in QPXFile::write and nearby methods, and replace std::endl consistently while keeping the existing message text and context intact.Source: Coding guidelines
src/openms/include/OpenMS/FORMAT/QPXFile.h (1)
146-148: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse OpenMS primitive types in the new public signature.
Prefer
Size/Inthere and mirror the same types in the.cppdefinition, keeping the exported API aligned with OpenMS conventions.♻️ Proposed type cleanup
- size_t batch_size = 1000000, + Size batch_size = 1000000, const ParquetWriteConfig& config = ParquetWriteConfig{}, - int n_threads = 1); + Int n_threads = 1);As per coding guidelines, “Use OpenMS primitive types from
OpenMS/CONCEPT/Types.hinstead of standard C++ types.”🤖 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/include/OpenMS/FORMAT/QPXFile.h` around lines 146 - 148, The public QPXFile API currently exposes standard C++ types in the new signature, so update the declaration in QPXFile and the matching .cpp definition to use OpenMS primitive types from OpenMS/CONCEPT/Types.h instead. Replace the batch size and thread count parameters in the relevant QPXFile write function with Size and Int respectively, and keep the default values and parameter names aligned between the header and implementation to preserve the exported interface.Source: Coding guidelines
🤖 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/openms/source/FORMAT/QPXFile.cpp`:
- Around line 1197-1207: The `QPXFile::` run file lookup is dropping
parent-level `run_file_name` metadata because the `PeptideIdentification`
fallback only checks `idx_reference_file_name`. Update the fallback chain in
this block to also try `pep_id`’s `idx_run_file_name` before giving up,
mirroring the hit-level handling. Keep the existing
`metaHas(...)`/`getMetaValue(...)` pattern and preserve the current precedence
between hit-level and parent-level values.
In `@src/tests/class_tests/openms/source/QPXFile_test.cpp`:
- Around line 832-850: The equivalence check in the QPXFile tests is still
vulnerable to row reordering because it only compares repeated fields in the
loop. Update the streaming-vs-reference comparisons in the test block that
iterates over `st_table` and `ref_table` to also compare a row-unique column
such as `rt` or `scan` on each iteration. Apply the same hardening to the
related comparison blocks in the other affected test sections so the assertions
fail when partition order changes.
---
Nitpick comments:
In `@src/openms/include/OpenMS/FORMAT/QPXFile.h`:
- Around line 146-148: The public QPXFile API currently exposes standard C++
types in the new signature, so update the declaration in QPXFile and the
matching .cpp definition to use OpenMS primitive types from
OpenMS/CONCEPT/Types.h instead. Replace the batch size and thread count
parameters in the relevant QPXFile write function with Size and Int
respectively, and keep the default values and parameter names aligned between
the header and implementation to preserve the exported interface.
In `@src/openms/source/FORMAT/QPXFile.cpp`:
- Around line 1564-1565: The new QPXFile log messages currently use std::endl,
which forces an unnecessary flush; update the affected OPENMS_LOG_ERROR
statements in QPXFile to use '\n' instead. Check the logging spots around the
file-open, write, and related error paths in QPXFile::write and nearby methods,
and replace std::endl consistently while keeping the existing message text and
context intact.
🪄 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: 0ccf7f0d-dbf0-4700-a01c-a9d49e538c9b
📒 Files selected for processing (4)
src/openms/include/OpenMS/FORMAT/QPXFile.hsrc/openms/source/FORMAT/QPXFile.cppsrc/tests/class_tests/openms/source/QPXFile_test.cppsrc/topp/IsobaricWorkflow.cpp
Address CodeRabbit review (#9697): the streaming-vs-one-shot comparisons only checked columns whose values repeat across rows, so a partition-reordering regression could pass unnoticed. Also compare the per-row-unique `rt` value (100.0 + i) so the checks now fail if row order is not preserved. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
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
) * Stream QPX feature Parquet export in batches to bound peak memory For isobaric labeling there is ~one consensus feature per PSM, so the ConsensusMap feature table can be millions of rows. The old ConsensusMapArrowExport::exportToArrow built the entire Arrow table in memory before a single write, so on large runs peak memory drove the process into swap/OOM and quantms.feature.parquet was never created (it is written first in IsobaricWorkflow, before the PSM/pg exports). Port the streaming approach already used for the PSM export (#9697) to the feature export, serial only: - Refactor the per-row build into an anonymous-namespace range builder buildFeatureTableRange(cmap, id_lut, [begin, end)); hoist the per-map protein-group/gene lookups into buildFeatureIdLookups and the Parquet writer properties into makeFeatureWriterProperties. Each feature row is independent, so any contiguous sub-range yields a self-contained, schema-valid table. - exportToArrow() now delegates over the whole range (output unchanged). - Add exportToParquetStreaming(): build and flush one batch_size-sized range at a time through a persistent parquet::arrow::FileWriter, so peak memory stays bounded by one batch instead of the whole table. - IsobaricWorkflow uses the streaming path for the feature export. Written rows and their order are identical to the one-shot path; only the Parquet row-group layout may differ. A new class-test asserts streaming<->one-shot equivalence (full Table::Equals over combined chunks, order-sensitive via unique RT) across multiple batches, the single-batch and batch_size==0 cases, and the empty-map edge. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_01HcY3LMYuUDF2psYat9uUYN * Update src/tests/class_tests/openms/source/ConsensusMapArrowExport_test.cpp Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> --------- Co-authored-by: Claude Opus 4.8 <[email protected]> Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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
* Parallelize the streaming QPX feature Parquet export (OpenMP) 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 * fix: apply CodeRabbit auto-fixes Fixed 1 file(s) based on 1 unresolved review comment. Co-authored-by: CodeRabbit <[email protected]> --------- Co-authored-by: Claude Opus 4.8 <[email protected]> Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> Co-authored-by: CodeRabbit <[email protected]>
Three recently merged PRs landed on develop without changelog coverage: the PeptideIdentification::base_name removal (breaking API change routed through the run-level primary MS run path) and the two QPX Parquet streaming-export performance fixes (PSM export in #9697, feature export in #9698) that bound peak memory for large isobaric-labeling runs. Claude-Session: https://claude.ai/code/session_0167xb6udbdqvWLcUsNeZf4r Co-authored-by: Claude <[email protected]>
Motivation
Writing
quantms.psm.parquetfromIsobaricWorkflowfor ~7M PSMs took hours. Root cause was peak memory → swap: the export held the data three times at once (the ConsensusMap, a redundant deep copy of everyPeptideIdentificationinto a flat list, and the whole Arrow table built in memory before a single write).What this does (3 commits)
Stream + eliminate the copy —
QPXFile::exportToParquetStreamingbuilds and flushes the QPX PSM table in row-batches through a persistentparquet::arrow::FileWriterinstead of one monolithic in-memory table, and takes non-owningconst PeptideIdentification*soIsobaricWorkflowno longer deep-copies all PSMs.exportPSMsToQPXArrowwas refactored to delegate to a shared file-local range builder (behavior unchanged). Peak memory becomes batch-bounded.Parallel build (OpenMP) — the per-row build is ~93% of export time and is embarrassingly parallel. Each batch is split into contiguous sub-ranges built in parallel and written in index order (the
FileWriterstays serial). Deterministic, byte-identical output for any thread count; exceptions are contained per worker viastd::exception_ptr. Newn_threadsparam:1=serial (default),0=auto (honorsOMP_NUM_THREADS),N=fixed;IsobaricWorkflowopts into0.Remove the residual per-row registry lock — the dedicated-column reads still resolved metavalues by string name, each taking the
MetaInfoRegistryomp-critical lock; those names are now resolved to indices once per range and read via the lock-freeUIntoverloads (guarding theUInt(-1)sentinel, preserving alias precedence). Complements perf(QPXFile): single-pass metavalue iteration via metaBegin() with cached name lookup #9692.Measured (3M PSMs, 4-core/8-thread laptop, Release)
Peak RSS is flat across thread counts (memory-neutral). The hours→minutes win at production scale comes from keeping peak memory below the swap threshold; the parallel build adds throughput on many-core servers. (On this hyper-threaded laptop 4 threads is the sweet spot; all-logical-cores is memory-bandwidth bound — documented.)
Tests
QPXFile_testextended: streaming↔one-shot equivalence acrossn_threads1/2/8,export_all_psmswith variable hit counts across partition boundaries, non-empty-zero-rows,M=0/M=1/rows<threadsedges, and exact dedicated-column values + alias precedence across a multi-partition run. All QPX/Arrow class tests pass locally.Notes
develop(includes perf(QPXFile): single-pass metavalue iteration via metaBegin() with cached name lookup #9692); the metavalue-cache merged cleanly into the shared range builder.exportToArrow; precompute PEP-candidate indices infindScoreType; same streaming treatment for the features/protein-group exports.🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
batch_sizeand parallel batch processing.Bug Fixes
Tests