Skip to content

Speed up Parquet identification I/O (single-pass metavalue write, hoisted reads) - #9689

Merged
timosachsenberg merged 1 commit into
OpenMS:developfrom
jonasscheid:feature/parquet-xml-io-speedup
Jun 30, 2026
Merged

timosachsenberg merged 1 commit into
OpenMS:developfrom
jonasscheid:feature/parquet-xml-io-speedup

Conversation

@jonasscheid

@jonasscheid jonasscheid commented Jun 30, 2026 •

Copy link
Copy Markdown
Collaborator

What

Reduces the CPU cost of OpenMS's Parquet identification I/O (QPXFile / ArrowIOHelpers), which back the idparquet format and the PSM bundle embedded in featureparquet/consensusparquet.

Motivation: idparquet files are ~10x smaller than idXML, yet writing them was slower. Profiling showed the write cost is Arrow table construction, not compression (ZSTD is only ~11% of write time), and the per-PSM metavalue handling did redundant work.

Changes

  • Write (QPXFile::exportToArrow): build the additional_scores and psm_metavalues columns in a single pass over each PeptideHit's metavalues instead of two (they are complementary partitions of the same key set), removing a duplicate getKeys() allocation and isKnownScoreType()/getMetaValue() sweep per PSM.
  • Read (ArrowIOHelpers::readMetaValues): index the shared child struct via value_offset/value_length instead of value_slice(row), which allocated a sliced array per row.
  • Read (QPXFile::importFromArrow): hoist loop-invariant GetFieldByName child-array lookups (protein_accessions/additional_scores) out of the row loop.

Benchmarks

idparquet write of a 143 MB / 18,294-PSM (metavalue-heavy) file, in-process, 9 reps:

baseline this PR
min 2.57 s 2.03 s (-21%)
median 2.83 s 2.06 s (-27%)

The write fix also feeds featureparquet/consensusparquet (they embed the PSM bundle): ~6% faster feature round-trip. The read changes are correctness-neutral on this data (Arrow's value_slice is near-zero-copy) but remove allocations on evidence/row-heavy inputs.

Correctness

Output is round-trip identical (idXML -> idparquet -> idXML byte-identical; feature/PSM counts preserved). All Arrow-IO class tests pass: QPXFile, PSMArrowIO, FeatureMapArrowIO, ConsensusMapArrowIO, ConsensusMapArrowExport, ProteinIdentificationArrowIO, ArrowIOHelpers.

Summary by CodeRabbit

  • Chores
    • Improved Arrow-based import/export performance, especially for identification data with many metadata fields.
    • Exported results now build score-related and metadata-related columns in a single pass, reducing processing overhead.
    • Import processing now reuses shared array lookups and avoids extra slicing, making reads faster.
    • Output remains round-trip identical.

…es/psm_metavalues write passes and remove per-row value_slice/GetFieldByName work on read (~20-25% faster idparquet writes, output identical).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01A7Z3YRNpFx521tmdYWib1v
@jonasscheid
jonasscheid force-pushed the feature/parquet-xml-io-speedup branch from 67ee5aa to 3278525 Compare June 30, 2026 13:09
@github-actions

Copy link
Copy Markdown
Contributor

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

  • jonasscheid

Please consider applying the following patch:

--- AUTHORS	2026-06-30 13:09:53.121352847 +0000
+++ AUTHORS.new	2026-06-30 13:09:58.732282366 +0000
@@ -61,6 +61,7 @@
  - Johannes Veit
  - Johannes von Kleist
  - Johan Teleman
+ - jonasscheid
  - Joshua Charkow
  - Juliane Schmachtenberg
  - Julianus Pfeuffer

@coderabbitai

coderabbitai Bot commented Jun 30, 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: 238af7c7-4532-4b14-a4b3-0d34cb05b522

📥 Commits

Reviewing files that changed from the base of the PR and between 9cffb90 and 3278525.

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

📝 Walkthrough

Walkthrough

Performance optimizations for Arrow/Parquet identification I/O: QPXFile::exportToArrow merges two metavalue passes into one, QPXFile::importFromArrow hoists child array lookups outside the row loop, and readMetaValues replaces per-row array slicing with offset/length indexing.

Changes

Parquet I/O Performance

Layer / File(s) Summary
Single-pass exportToArrow column building
src/openms/source/FORMAT/QPXFile.cpp
Removes the standalone additional_scores loop; a single metavalue iteration now dispatches known numeric score keys into additional_scores and all others into psm_metavalues.
Hoisted child arrays in importFromArrow
src/openms/source/FORMAT/QPXFile.cpp
protein_accessions and additional_scores struct field arrays are extracted once before the row loop; per-row decoding uses the cached arrays with value_offset/value_length.
readMetaValues offset/length indexing
src/openms/source/FORMAT/ArrowIOHelpers.cpp
Replaces value_slice(row) and full-length struct iteration with explicit off/len indexing into the shared child StructArray.
CHANGELOG
CHANGELOG
Adds a performance note for the idparquet single-pass column building change.

🐇 One loop where two once ran,
Offsets replace the slice-and-scan,
Child arrays hoisted, cached with care,
Parquet reads fly through the air—
Round-trip identical, I declare! ✨

🚥 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 summarizes the main performance-focused Parquet I/O changes, including single-pass metavalue writing and hoisted reads.
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 unit tests (beta)
  • Create PR with unit tests

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.

@jpfeuffer

jpfeuffer commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Nice, I wonder if the whole metavalue iteration can be sped up by not doing useless roundtrips in getMetaValue.

AI-review on this:

The getKeys(std::vector<std::string>) + getMetaValue(key) pattern currently pays two #pragma omp critical registry lock acquisitions per metavalue per PSM: one getName(idx) in getKeys() and one getIndex(key) inside getMetaValue(). For a metavalue-heavy file with ~20 keys × 18k PSMs that's ~720k lock round-trips.

A much cheaper approach: iterate via metaBegin()/metaEnd() (direct flat_map traversal, no allocation) and resolve UInt indices through a std::vector<std::string> cache built lazily before/during the loop — lock taken at most once per unique key across all PSMs:

// Before the PSM loop — one vector, lock taken at most once per unique index ever seen
std::vector<std::string> idx_to_name; // direct index by UInt, O(1) lookup
const auto& reg = MetaInfoInterface::metaRegistry();

auto cachedName = [&](UInt idx) -> const std::string& {
  if (idx >= idx_to_name.size()) idx_to_name.resize(idx + 1);
  if (idx_to_name[idx].empty()) idx_to_name[idx] = reg.getName(idx); // lock once per unique key
  return idx_to_name[idx];
};

// In the hit loop — no vector allocation, no getMetaValue() call:
for (auto it = hit.metaBegin(); it != hit.metaEnd(); ++it)
{
  const std::string& key = cachedName(it->first); // O(1), lock-free after first encounter
  if (excluded_hit_mvs_psm.contains(key)) continue;
  const DataValue& val = it->second; // already have it — no flat_map lookup
  // ... dispatch to additional_scores / psm_metavalues
}

Per-PSM cost in steady state: zero lock acquisitions, zero registry round-trips, zero flat_map lookups — just flat_map iteration + a vector bounds check. The vector itself stays small (~1024 + number of search engine-specific keys, typically < 1100 entries × 32 bytes = ~35 KB, well within L1/L2).

This also directly unblocks future parallelisation of the export loop — the cache is local to the function, so there's no shared mutable state between threads.

Ideally, the MetaInfoRegistry would support iteration so you could just build a lock-free vector-based lookup cache in a single iteration before the loop over PSMs but this is a separate improvement.

@jpfeuffer

Copy link
Copy Markdown
Contributor

Also a certain degree of parallelization should be feasible since you say that ArrowTable construction is the bottleneck.

AI-review on this:

Yes, this is very feasible, and Arrow's parquet::arrow::FileWriter — which MSChromatogramParquetConsumer already uses in this codebase — is exactly the right tool. It supports incremental row-group writes, so you can feed it batches as they finish.

Here's the architecture:

Pipeline design

Thread pool (N workers)
  ├── Worker 0: PSMs [0, B)   → builds Arrow table chunk → queue
  ├── Worker 1: PSMs [B, 2B)  → builds Arrow table chunk → queue
  ├── Worker 2: PSMs [2B, 3B) → builds Arrow table chunk → queue
  └── ...

Writer thread (single)
  └── dequeues chunks in order → FileWriter::WriteTable() per chunk (= one row group each)

Each chunk is an independent arrow::Table built by one thread. The writer thread calls FileWriter::WriteTable() for each, which appends a row group to the single open Parquet file. Order is preserved by an ordered queue indexed by chunk number.

The key blockers

1. MetaInfoRegistry lock — as we just discussed, getKeys(std::vector<std::string>) takes the #pragma omp critical lock per key per PSM. With N threads all calling getKeys() simultaneously, this becomes a thundering herd on a single global mutex. The fix is to use getKeys(std::vector<UInt>&) (no lock, just copies integers from the flat_map) and resolve names separately — or pre-warm a thread-local UInt→string cache before each batch.

2. IDScoreSwitcherAlgorithm idsa — currently one instance shared across all PSMs in the loop. Would need to be per-thread.

3. Arrow builders are not thread-safe — already fine since each worker has its own independent set of builders.

4. FileWriter::WriteTable() is single-threaded — the writer thread serializes this, which is correct. parquet::arrow::FileWriter itself is not thread-safe for concurrent writes.

Rough sketch

// Pre-split PSMs into batches
const size_t batch_size = 1000; // tune per row_group_size
std::vector<std::span<const PeptideIdentification>> batches = splitIntoBatches(peptide_identifications, batch_size);

// Ordered result queue
std::vector<std::future<std::shared_ptr<arrow::Table>>> futures;
futures.reserve(batches.size());

// Build each batch in parallel
// Use getKeys(UInt) to avoid registry lock contention
for (auto& batch : batches)
{
  futures.push_back(std::async(std::launch::async, [&, batch]() {
    return buildBatchTable(protein_identifications, batch);
  }));
}

// Open FileWriter once
auto writer = openFileWriter(filename, schema, config);

// Drain futures in order -> write row groups sequentially
for (auto& fut : futures)
{
  auto chunk = fut.get();
  writer->WriteTable(*chunk, chunk->num_rows());
}
writer->Close();

Is it worth it?

From the PR's own benchmarks, the bottleneck is Arrow table construction (not I/O or compression). That's exactly the CPU-bound work you'd parallelize. For the 18k-PSM benchmark file, with batch_size=1000 you'd get ~18 parallel tasks — on a machine with ≥4 cores that should translate to roughly linear speedup for the build phase, with the writer thread never starved since construction is the bottleneck.

The main caveat is the registry lock. For a metavalue-heavy file it could serialize most of the gain away. The getKeys(UInt) + deferred name resolution approach is the prerequisite for this to actually scale.

This would be a meaningful follow-on PR — probably worth filing as an issue linked to this one rather than stacking it here.

@timosachsenberg

Copy link
Copy Markdown
Contributor

cool. I think this is good to merge... open for more optimizations

@timosachsenberg
timosachsenberg merged commit 7de1a8d into OpenMS:develop Jun 30, 2026
38 checks passed
timosachsenberg added a commit that referenced this pull request Jun 30, 2026
…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]>
timosachsenberg added a commit that referenced this pull request Jun 30, 2026
…okup (#9692)

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

3 participants