Skip to content

perf(QPXFile): single-pass metavalue iteration via metaBegin() with cached name lookup - #9692

Merged
timosachsenberg merged 1 commit into
developfrom
perf/qpxfile-metabegin-metavalue-iteration
Jun 30, 2026
Merged

timosachsenberg merged 1 commit into
developfrom
perf/qpxfile-metabegin-metavalue-iteration

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

What

Follow-on to #9689 (per @jpfeuffer's review): cut the MetaInfoRegistry lock traffic in the Parquet PSM export.

The Arrow export loops resolved each PSM's metavalues with getKeys(std::vector<std::string>) + getMetaValue(key). Both paths hit a #pragma omp critical (MetaInfoRegistry) lock — getName() inside getKeys() and getIndex() inside getMetaValue() — i.e. ~2 lock acquisitions per metavalue per PSM, plus a per-PSM vector<string> allocation and a redundant flat_map lookup.

Changes

src/openms/source/FORMAT/QPXFile.cpp — iterate metaBegin()/metaEnd() directly (no allocation, it->first = index, it->second = value) and resolve the UInt index → name through a function-local cache (cachedMetaName_), so the registry lock is paid at most once per unique key for the whole export. Applied to all four metavalue loops in exportToArrow and exportPSMsToQPXArrow, sharing one cache across all PSMs.

This also removes the dominant global lock that would otherwise serialize a future parallelised export (jpfeuffer's Idea 2).

Correctness

Iteration order is unchanged (same sorted flat_map), so output is round-trip identical:

  • QPXFile_test passes.
  • Verified on a real 827 MB consensusXML → QPX conversion (139,891 PSMs): the exported Arrow table is content-identical to the pre-change output (pyarrow Table.equals() = True, same schema, same row count).

Benchmark

Controlled A/B on that conversion, write-step only (Arrow build + ZSTD), 5 reps each, same machine/file:

median write step
baseline (getKeys+getMetaValue) 2.089 s
this PR (metaBegin+cache) 2.017 s

~3.5% on this metavalue-light TMT data (few keys per PSM, so little lock traffic to remove). The win scales with metavalues-per-PSM; on metavalue-heavy inputs (cf. #9689's ~20-keys/PSM benchmark) the per-PSM lock count dominates write time and the improvement is correspondingly larger. The primary value here is correctness-neutral lock removal that unblocks parallel export.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved export of metadata in Arrow/QPX outputs so additional values and spectrum details are serialized more reliably.
    • Preserved existing column handling while making excluded metadata filtering more consistent during export.
    • Reduced repeated lookup work during export, which may improve performance for large result sets.

…okup

The Arrow export loops resolved per-PSM metavalues via getKeys(vector<string>)
+ getMetaValue(key), which takes a MetaInfoRegistry omp-critical lock twice per
metavalue per PSM (getName() in getKeys, getIndex() in getMetaValue). Iterate
metaBegin()/metaEnd() directly instead and resolve UInt index->name through a
function-local cache, so the lock is paid at most once per unique key for the
whole export. Applied to both exportToArrow and exportPSMsToQPXArrow.

Iteration order is unchanged (same sorted flat_map), so output is round-trip
identical. Also removes the dominant global lock that would otherwise serialize
a future parallel export. Idea by Julianus Pfeuffer (PR #9689 review).

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

coderabbitai Bot commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

QPXFile.cpp gains a cachedMetaName_ inline helper that resolves MetaInfo registry indices to names via a lazily-grown cache vector. All three metavalue serialization loops in exportToArrow and exportPSMsToQPXArrow are updated to iterate metaBegin()/metaEnd() and resolve names through this cache, replacing the previous getKeys()/getMetaValue() two-step approach.

Changes

Cached MetaInfo name resolution in QPXFile

Layer / File(s) Summary
cachedMetaName_ helper and cache vector initialization
src/openms/source/FORMAT/QPXFile.cpp
Adds anonymous-namespace cachedMetaName_ that lazily resolves MetaInfoInterface::metaRegistry().getName(index) into a resizable cache vector; adds meta_name_cache locals in both exportToArrow and exportPSMsToQPXArrow.
Metavalue loop replacement with cached iterator traversal
src/openms/source/FORMAT/QPXFile.cpp
Replaces getKeys()/getMetaValue() two-step iteration with metaBegin()/metaEnd() traversal plus cachedMetaName_ resolution in PSM metavalue export, spectrum metavalue export, and additional-scores metavalue export; excluded-key and dedicated-column filtering logic is preserved.

🐇 No more keys fetched twice in a row,
The cache now speeds up every show.
metaBegin to metaEnd we glide,
With names resolved on the first ride.
Hoppy code, efficient and bright! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% 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 clearly describes the main performance change: single-pass metavalue iteration with cached name lookup in QPXFile.
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/qpxfile-metabegin-metavalue-iteration

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.

🧹 Nitpick comments (1)
src/openms/source/FORMAT/QPXFile.cpp (1)

60-66: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Defensive: returning a reference into a self-resizing cache is fragile.

cachedMetaName_ returns const std::string& into cache, but a subsequent call can resize() and invalidate that reference. The current callers bind key once per iteration and use it before the next call, so it is safe today. However, this is an easy footgun for future edits (e.g., binding two keys, or holding key across another cachedMetaName_ call). Consider documenting the constraint or returning by value to be resize-safe.

🤖 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 60 - 66, The cached
reference returned by cachedMetaName_ is fragile because cache.resize() can
invalidate previously held references; update cachedMetaName_ to avoid exposing
a reference into the self-resizing vector, either by returning a std::string by
value or by documenting and enforcing that callers in QPXFile.cpp must not hold
the result across another cachedMetaName_ call. Keep the fix centered on
cachedMetaName_ and the call sites that use the key variable so future edits
can’t accidentally retain an invalidated reference.
🤖 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.

Nitpick comments:
In `@src/openms/source/FORMAT/QPXFile.cpp`:
- Around line 60-66: The cached reference returned by cachedMetaName_ is fragile
because cache.resize() can invalidate previously held references; update
cachedMetaName_ to avoid exposing a reference into the self-resizing vector,
either by returning a std::string by value or by documenting and enforcing that
callers in QPXFile.cpp must not hold the result across another cachedMetaName_
call. Keep the fix centered on cachedMetaName_ and the call sites that use the
key variable so future edits can’t accidentally retain an invalidated reference.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 125babbb-6030-46a8-a2c6-9833be769dba

📥 Commits

Reviewing files that changed from the base of the PR and between 7de1a8d and 70a3d10.

📒 Files selected for processing (1)
  • src/openms/source/FORMAT/QPXFile.cpp

@timosachsenberg
timosachsenberg merged commit 52aad4d into develop Jun 30, 2026
16 checks passed
@timosachsenberg
timosachsenberg deleted the perf/qpxfile-metabegin-metavalue-iteration branch June 30, 2026 15:42
timosachsenberg added a commit that referenced this pull request Jul 1, 2026
… (#9694)

Four recently merged PRs landed on develop without changelog coverage:
the QPXConverter removal was documented but missing its PR reference,
and the QPXFile metavalue-iteration perf fix, the cross-codebase
expensive-copy cleanup, and the EmgFitter1D robustness fix had no
entry at all.


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

Co-authored-by: Claude <[email protected]>
timosachsenberg added a commit that referenced this pull request Jul 1, 2026
…el build) (#9697)

* Stream QPX PSM Parquet export in batches; drop PSM copy in IsobaricWorkflow

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]>

* Parallelize QPX PSM build with OpenMP (per-batch partitions)

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]>

* Remove per-row MetaInfoRegistry lock from QPX PSM build (index-based 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]>

* Harden QPX streaming equivalence tests with an order-sensitive column

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]>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
timosachsenberg added a commit that referenced this pull request Aug 6, 2026
…feature (#9881)

The 3.6 section had grown to 217 KB (22x the 3.5 section), mostly because
recent entries were appended verbatim as PR-body-style root-cause writeups,
with newest entries prepended to "General:" regardless of topic.

Collapse incremental/superseded PR chains into one entry per feature:

  - QPX Parquet export: ~30 entries across #9692-#9878 (long-format
    conversion, run_file_name resolution, validation, transactional writes,
    streaming/parallel build) reduced to a 6-item block. The export is new in
    3.6, so the intermediate fixes never shipped to users.
  - ProteinQuantifier/PeptideAndProteinQuant: the per-assay grain change,
    fractions:aggregate, best_charge rename, the same undetected-peptide
    aggregation defect fixed at three levels, and the perf work bundled.
  - pyOpenMS nanobind lifetime/use-after-free work (#9792, #9794, #9795).
  - ProSE: 30 entries down to 17, grouped by search modes, calibration,
    FDR, Percolator and FragmentIndex.
  - Bruker TimsTOF, IMAGING, ThermoRawFile and the native Parquet formats
    each get one nested block instead of scattered entries.
  - ~20 near-identical per-tool ".idparquet/.featureparquet support" and
    "Thermo .raw input" entries folded into "TOPP tools > all:".

Remove exact duplicates (ProteinQuantifier -ratios removal, Annotation1DItem
DLLAPI, ConsensusMapArrowExport streaming, macOS pkg notarization, Qt removal
steps duplicated between General/Dependencies/Build System, IsoelectricPoint
and IMAGING multi-region duplicated between General and OpenMS Library).

File misplaced entries into the sections they belong to and add a GUI tools
section, matching the structure used by 3.5 and earlier releases.

Net: 217 KB -> 82 KB with all 440 distinct PR references preserved; the five
dropped refs are CI-internal test guards and a historical bug reference.


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

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.

1 participant