Skip to content

(osw): Speed up OpenSwathWorkflow for Large Libraries - #9190

Merged
timosachsenberg merged 131 commits into
OpenMS:developfrom
singjc:profile/osw
Apr 26, 2026
Merged

timosachsenberg merged 131 commits into
OpenMS:developfrom
singjc:profile/osw

Conversation

@singjc

@singjc singjc commented Apr 20, 2026 •

Copy link
Copy Markdown
Contributor

Description

This PR improves OpenSwathWorkflow performance for large transition libraries and high-SWATH-count DIA data. The main changes are:

  • Faster PQP transition-library loading for large predicted libraries.
  • A memory-aware SWATH wave scheduler that keeps scoring threads busy while bounding resident SWATH data.
  • Buffered OSW output writing to reduce SQLite/write-side stalls.
  • Lower allocation pressure in peak picking, scoring, DIA scoring, and IPF/identification transition scoring.
  • Better multi-run memory cleanup so sequential runs do not retain large run-local data structures.
  • Updated TOPP parameter help for batchSize, innerBatchSize, maxConcurrentSwaths, and outer_loop_threads.

The default batchSize is now 0, which enables automatic scheduling. With in-memory reads, this uses the SWATH wave scheduler; positive batchSize values still force the legacy per-SWATH batch path.

Main Changes

PQP loading

  • Optimized SQLite access for read-only PQP loads.
  • Avoided unnecessary query paths when compound or peptidoform mapping tables are absent or empty.
  • Reworked transition/protein/gene joins to avoid duplicated transition rows from multi-gene mappings.
  • Reduced extra COUNT scans and cold-cache passes.
  • Streamed rows directly into the light targeted experiment representation with better reserve/deduplication behavior.

Extraction and scoring

  • Added a SWATH wave scheduler that plans concurrent SWATH windows from memory budget, spectra count, transition density, writer-buffer reserve, and scoring-thread count.
  • Added innerBatchSize and maxConcurrentSwaths controls.
  • Kept the legacy scheduler available by setting a positive batchSize.

Output writing

  • Added buffered OSW row writing with a bounded queue and a single writer thread.
  • Reused prepared SQLite statements and typed row buffers.
  • Reduced temporary score-list materialization during OSW output preparation.

Allocation and scoring hot paths

  • Reused transition-group picker buffers for picked/smoothed chromatograms, features, edge vectors, and peak-boundary temporaries.
  • Cached native ID lookups, chromatogram pointers, total XICs, largest peak indices, and MetaInfo IDs.
  • Added reusable scoring buffers in MRMScoring, OpenSwathScoring, DIA scoring, ion mobility scoring, and IPF/identification transition scoring.
  • Reused target/decoy score pools in the IPF path and explicitly cleared them between uses.

Multi-run memory lifetime

  • Avoided retaining OSW peak groups in cross-run feature maps.
  • Kept run-local feature maps local to OSW writing.
  • Scoped run-level workflow objects so MS1 maps and internal run state are destructed before post-run output.
  • Cleared SWATH maps after extraction to release raw data before processing the next input run.

Benchmarks

Benchmarks were run on the profile/osw branch and compared against develop before these optimizations on a fairly idle machine with 186Gb of Ram and 36 threads.

Initial profiling diagnostics

The first diagnostic runs used temporary -Debugging:profile instrumentation with -threads 34 and -readOptions cacheWorkingInMemory on the HeLa Evosep diaPASEF dataset. The profiling output reported both wall time and summed worker phase time. The summed worker time is useful for attribution across threads, but is not expected to equal wall time.

Input summary for the focused diagnostic run: 24 SWATH windows, 129,754 compounds, 778,524 scored transitions, 519,016 MS1 chromatograms, and 778,524 MS2 chromatograms.

A representative phase breakdown from the temporary profiler showed why the work focused on scoring and output materialization rather than raw extraction:

Phase bucket Summed worker time Interpretation
SWATH load + MS1/MS2 extraction + conversion about 2:07 min Extraction was not the dominant cost.
Total scoring phase 2:26:53 h Scoring dominated the profiled worker time.
picker + score_peakgroups 1:53:19 h Peak picking and peakgroup scoring were the largest CPU buckets.
dia + chrom 29:06 min DIA and chromatographic score families were high-volume scoring costs.
score_output + osw_prepare 45:06 min OSW row preparation and feature metadata extraction were major overheads.
osw_write 55.8 s Actual SQLite writes were much smaller than row preparation.

These diagnostics drove the main implementation choices in this PR: memory-aware wave scheduling for better CPU utilization, pooled temporary buffers in picker/scoring hot paths, ScoreValueList and OSW row-buffer changes for output preparation, and run-local cleanup for multi-run workflows.

HeLa Evosep diaPASEF DDA empirical library, 24 SWATH windows, 1 run

Input summary: 14,216 proteins, 146,788 compounds with 880,728 transitions.

Values are means from running the same OpenSwathWorkflow Command 20 times.

Configuration Overall wall Extract/score wall Overall CPU Peak memory Speedup vs baseline
Baseline 447.3 s 383.4 s 5,796.0 s 23.6 GB N/A
Optimized 182.6 s 120.4 s 3,371.8 s 25.1 GB 2.45x overall, 3.18x extract/score
Optimized + jemalloc 169.2 s 106.8 s 2,874.6 s 20.9 GB 2.64x overall, 3.59x extract/score

Astral predicted library, 300 SWATH windows, 2 runs

Input summary: 40,787 proteins, 5,550,339 compounds, 33,302,034 transitions loaded. The run-specific evidence filter retained 37,914 target precursors for run 1 and 57,564 target precursors for run 2.

Configuration Run 1 extract/score Run 2 extract/score Total wall Total CPU Peak memory
Baseline 23:40:02 h 19:45:12 h 43:43:50 h 6d 10:55:44 h 41.3 GB
Optimized 1:17:44 h 1:17:51 h 2:46:18 h 3d 11:35:13 h 126.6 GB

This is a 15.8x end-to-end wall-clock speedup for the two-run Astral benchmark. Extraction/scoring improved by 18.3x for run 1 and 15.2x for run 2.

The optimized Astral path intentionally uses more memory because the wave scheduler keeps multiple SWATH windows resident to improve CPU utilization. The scheduler now accounts for memory budget and maxConcurrentSwaths can be used to cap concurrency on smaller machines.

This PR should not change scoring semantics. The changes are intended to reduce I/O overhead, allocation overhead, scheduling imbalance, and retained run-local memory.

Checklist

  • Make sure that you are listed in the AUTHORS file
  • Add relevant changes and new features to the CHANGELOG file
  • I have commented my code, particularly in hard-to-understand areas
  • New and existing unit tests pass locally with my changes
  • Updated or added python bindings for changed or new classes (Tick if no updates were necessary.)

How can I get additional information on failed tests during CI

Click to expand If your PR is failing you can check out

Advanced commands (admins / reviewer only)

Click to expand
  • /reformat (experimental) applies the clang-format style changes as additional commit. Note: your branch must have a different name (e.g., yourrepo:feature/XYZ) than the receiving branch (e.g., OpenMS:develop). Otherwise, reformat fails to push.
  • setting the label "NoJenkins" will skip tests for this PR on jenkins (saves resources e.g., on edits that do not affect tests)
  • commenting with rebuild jenkins will retrigger Jenkins-based CI builds

⚠️ Note: Once you opened a PR try to minimize the number of pushes to it as every push will trigger CI (automated builds and test) and is rather heavy on our infrastructure (e.g., if several pushes per day are performed).

Summary by CodeRabbit

  • New Features

    • Debugging profile flag to log per-batch and per-SWATH timings.
    • Wave scheduler for automatic, memory-aware concurrent SWATH processing; new innerBatchSize and maxConcurrentSwaths controls.
    • Buffered, typed OSW row writing with transactional bulk commits and deferred write buffering.
  • Improvements

    • Reduced allocations via pooled/thread-local caches for faster scoring.
    • Automatic system-memory detection to size scheduling and write buffers.
    • More deterministic PQP output ordering and safer CLI defaults (batchSize now defaults to automatic).
  • Bug Fixes

    • Fixed transition duplication from multiple gene mappings; improved SQLite/OSW persistence reliability.

singjc added 30 commits April 10, 2026 23:51
…onst reference in prepareScoredFeatureOutput_
…nters for feature finders and transition group pickers
…ce extraction process with new scoring management
- Updated the handling of RUN.ID to ensure it is stored as INTEGER instead of BLOB, addressing a type mismatch that caused JOIN queries to return 0 rows.
- Refactored the regression test to insert a minimal FEATURE row using the prepared-row writer path instead of direct SQL statements, improving test clarity and maintainability.
- Added verification for the type of RUN_ID in the FEATURE table to ensure it is correctly stored as INTEGER.
…g job management

- Introduced a new lambda function `finalize_context` to handle the finalization of scoring contexts.
- Added `remaining_score_jobs` and `finalized` flags to track the state of scoring jobs within each context.
- Updated the scoring job processing loop to finalize contexts when all jobs are completed.
- Improved thread safety with OpenMP critical sections around context finalization and OSW writing.
- Simplified the handling of OSW output and feature writing by consolidating logic into the new finalization function.
…e flush trigger for improved memory management
…ragine isotope distributions to improve performance

@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: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/openms/source/ANALYSIS/OPENSWATH/OpenSwathWorkflow.cpp`:
- Around line 301-304: performExtraction() sets the global
suppress_resampling_spacing_warning flag to true and never restores it, which
silences resampling warnings for the entire process; change performExtraction()
to save the previous value of suppress_resampling_spacing_warning, set it to
true for the extraction, and then restore the saved value on all exit paths
(normal return or exceptions). Implement this by adding a small RAII guard
(e.g., ScopedBoolGuard) or by using a try/finally pattern inside
performExtraction(): read old = suppress_resampling_spacing_warning.load(),
store(true), and ensure suppress_resampling_spacing_warning.store(old) in the
guard's destructor or finally block so LinearResamplerAlign warnings are only
suppressed during the extraction scope. Ensure you reference
suppress_resampling_spacing_warning and performExtraction() when adding the
guard.
- Around line 1519-1524: The call to OpenSwath::LightCompound() and nullptr
loses assay/transition context; replace those placeholders in the
prepareRowsInto(...) call so it receives the actual assay compound and the
detection transition pointer you used earlier (e.g., pass the assay's compound
object instead of OpenSwath::LightCompound() and pass a pointer/reference to the
transition/filter instead of nullptr), keeping the other arguments
(to_osw_output, output, id) unchanged so prepareRowsInto(id, to_osw_output,
<assay_compound>, <transition_ptr>, output) preserves OSW row context.
🪄 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: 91eefa96-4eca-4692-a5b5-5719428de6f7

📥 Commits

Reviewing files that changed from the base of the PR and between ba7d211 and afc672d.

📒 Files selected for processing (4)
  • src/openms/include/OpenMS/PROCESSING/RESAMPLING/LinearResamplerAlign.h
  • src/openms/source/ANALYSIS/OPENSWATH/OpenSwathScoring.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/OpenSwathWorkflow.cpp
  • src/topp/OpenSwathWorkflow.cpp

Comment on lines +1519 to +1524
// Compound and transition are currently unused by the OSW row writer.
osw_writer.prepareRowsInto(to_osw_output,
OpenSwath::LightCompound(),
nullptr,
output,
id);

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.

⚠️ Potential issue | 🟠 Major

Pass the assay compound and detection transition into OSW row preparation.

prepareRowsInto() is documented to receive the compound and optional transition filter; passing an empty LightCompound and nullptr can drop or mis-associate OSW row context, especially for transition/IPF-related output.

🐛 Preserve OSW row context
-        // Compound and transition are currently unused by the OSW row writer.
+        const OpenSwath::LightCompound& compound =
+          transition_exp.getCompounds()[assay_peptide_map[id]];
         osw_writer.prepareRowsInto(to_osw_output,
-                                   OpenSwath::LightCompound(),
-                                   nullptr,
+                                   compound,
+                                   detection_assay_it,
                                    output,
                                    id);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/source/ANALYSIS/OPENSWATH/OpenSwathWorkflow.cpp` around lines 1519
- 1524, The call to OpenSwath::LightCompound() and nullptr loses
assay/transition context; replace those placeholders in the prepareRowsInto(...)
call so it receives the actual assay compound and the detection transition
pointer you used earlier (e.g., pass the assay's compound object instead of
OpenSwath::LightCompound() and pass a pointer/reference to the transition/filter
instead of nullptr), keeping the other arguments (to_osw_output, output, id)
unchanged so prepareRowsInto(id, to_osw_output, <assay_compound>,
<transition_ptr>, output) preserves OSW row context.

@timosachsenberg

timosachsenberg commented Apr 21, 2026 •

Copy link
Copy Markdown
Contributor

Did a multi-agent review pass on this and want to sanity-check 4 concrete blockers + 2 reframings with you before they harden into review demands. Most of the original "critical regression" findings melted under empirical inspection — but a few items still look real. Could you confirm/push back on each?

Blockers (would like verification)

B1 — featureXML byte-determinism. OpenSwathWorkflow.cpp ~L8112 accumulates features under omp critical (osw_scheduler_context) via context.feature_file.push_back(...). Order depends on thread arrival. The existing topp tests don't catch this (small inputs → max_concurrent_swaths=1 → effectively serial), but on real multi-SWATH inputs with >1 thread the featureXML output order varies run-to-run. Cheap fix: add out_featureFile.sortByPosition() before buffered_osw_writer->finish() (~L912). OSW row-order isn't a problem (FEATURE_IDs were already random per run via the time-seeded UniqueIdGenerator, and pyprophet uses ORDER BY queries).

B2 — suppress_resampling_spacing_warning is a process-global atomic that's never reset. Set in OpenSwathWorkflow.cpp:7703 (lib) and OpenSwathWorkflow.cpp:9723 (TOPP), declared inline std::atomic<bool> in LinearResamplerAlign.h:22. After OpenSwath runs once in a process (e.g. pyOpenMS, test harnesses, downstream tools sharing the same process), every later use of LinearResamplerAlign silently has the warning suppressed. Suggest RAII-scope it. The 18× perf justification is fine, just needs a save/restore wrapper.

B3 — Memory budget undercounts ~3×. Astral 41.3 → 126.6 GB peak isn't fully explained by "wave scheduler keeps multiple SWATHs resident". The dominant unaccounted item is context.chrom_exp per active context (~1.6 GB/swath × concurrency = ~50 GB). Adding FeatureMap scratch + thread_local pools across 32 workers + writer-queue undercount, the composed estimate lands at ~120 GB, matching the measured peak. Risk: users on 64 GB boxes will OOM silently. Cheapest mitigation: drop default OpenSwathWorkflowScheduler::Options::memory_usage_fraction from 0.90 → 0.50 in OpenSwathWorkflowScheduler.h, plus a 2-3× safety divisor in estimateAvailableMemoryForScoring. Tier-2 fix (account for FeatureMap+OSW scratch in the per-swath estimate) and Tier-3 fix (post-wave-1 RSS feedback via the existing SysInfo::getProcessMemoryConsumption) can land in follow-ups.

Two findings I'd like to confirm aren't actually regressions

R1 — IM/resample merge change. fetchSpectrumSwath RESAMPLE+IM path now calls mergeSpectraForScoring_ → concatenateDriftFilteredSpectra_ instead of addUpSpectra(spectra, im_range, sr, true). Reading the code path: OLD addUpSpectra(2D) after filterByDrift dropped the IM array, which means IonMobilityScoring::computeIonMobilogram's getDriftTimeArray() != nullptr precondition (IonMobilityScoring.cpp:165) was violated on the merged-spectrum path → IM scoring silently no-op'd. NEW path preserves IM via concat, and all other downstream scorers use tolerance-window integration (DIAHelpers::integrateWindow) which is concat-safe. So this looks like a fix for IM scoring on diaPASEF, not a regression. Is that right? If yes, the CHANGELOG entry should be "Fix: IonMobility scores now correctly computed for diaPASEF data in RESAMPLE merge mode (previously silently skipped)".

R2 — Multi-gene PQP dedup. Removing the raw PEPTIDE_GENE_MAPPING join in TransitionPQPFile.cpp looks like it can't change scores, because OLD code didn't produce different scores for multi-gene libraries — it produced N duplicate transition rows that hit Exception::InvalidValue in MRMTransitionGroup::addTransition's emplace unique-key check. Multi-gene libraries were therefore unusable before. CHANGELOG should phrase this as "Fix: PQP libraries with peptides mapped to multiple genes no longer crash during loading". Is that consistent with what you observed in benchmarks?

Comment on lines +125 to +135
std::shared_ptr<FeatureWrapperList_> features_;
std::shared_ptr<FeatureWrapperList_> precursor_features_;
const std::vector<Feature>* direct_features_ = nullptr;
FeaturePointerList_ feature_ptrs_;
FeaturePointerList_ precursor_feature_ptrs_;
FeatureIndexList_ feature_index_;
FeatureIndexList_ precursor_feature_index_;
std::vector<std::string> feature_ids_storage_;
std::vector<std::string> precursor_feature_ids_storage_;
const std::vector<std::string>* feature_ids_ = nullptr;
const std::vector<std::string>* precursor_feature_ids_ = nullptr;

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.

this class get's quite chubby ;)
I think some generate comments that put all those new members into context would help.

Stores precomputed theoretical m/z and intensity arrays plus rescaling
bounds for repeated scoring of the same transition group.
*/
struct OPENMS_DLLAPI PreparedSpectrum

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.

don't 100% like the name. maybe something more telling? TransitionGroupTheoreticalSpectrum ? not a beauty though...

@param[in] lt Library transitions for the transition group
@param[out] prepared Precomputed theoretical spectrum
*/
void prepare(const std::vector<OpenSwath::LightTransition>& lt,

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.

the name "prepare" could potentially be replaced...

PreparedSpectrum& prepared) const;

/**
@brief Score an observed spectrum against a precomputed theoretical DIA spectrum.

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.

improve description:
it should be clear that it considers multiple spectra. (are those MS2 windows / frames?)

Comment on lines +271 to +275
/** @brief Return pooled normalized library intensities (uses internal pool)
*
* Fills and returns a reference to an internal thread-local buffer. Callers
* that want to avoid per-call allocations can use this to obtain a
* reference to pooled normalized intensities.

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.

hmm this sounds a bit complex... is there a simpler design?

singjc added 9 commits April 25, 2026 14:31
…to anonymous namespace for better encapsulation
…reticalSpectrumCache and update related methods for clarity
…ter warning management during processing

B1: performExtraction() now sorts the accumulated FeatureMap once at the end of feature-producing paths, including the wave-scheduler branch before buffered OSW finalization, so feature-based output order is deterministic after parallel accumulation.
B2: the resampling warning suppression is now scoped with an RAII guard instead of being left enabled process-wide. I wired that into both the library workflow path and the TOPP tool entrypoint.
R1: kept the current IM/resample merge behavior and added a code comment explaining that concatenation is intentional because IM scoring needs drift-time arrays preserved.
R2: kept the aggregated PQP gene join and strengthened the inline comment to state that the raw join duplicates transition rows and later breaks transition-group construction.
…inistic output after parallel scoring

fix(TransitionPQPFile_test): update test to check for transition existence and correct size
@singjc
singjc requested a review from timosachsenberg April 26, 2026 14:47
@singjc

singjc commented Apr 26, 2026

Copy link
Copy Markdown
Contributor Author

@timosachsenberg , I think I've addressed most/all the comments. The pyopenms wheel for MacOS seems to be failing though because it can't find a suitable arrow version?

@timosachsenberg
timosachsenberg merged commit 5da4322 into OpenMS:develop Apr 26, 2026
19 of 20 checks passed
timosachsenberg pushed a commit that referenced this pull request Apr 27, 2026
Add CHANGELOG entries for OpenSwathWorkflow speed-up for large libraries
(PR #9190):
- TOPP: document new wave scheduler parameters (batchSize=0 auto,
  innerBatchSize, maxConcurrentSwaths, outer_loop_threads) and
  memory-aware buffered OSW writer
- TOPP: document RUN.ID INTEGER fix
- Library: document SysInfo::getFreeSystemMemory(), new
  OpenSwathWorkflowScheduler class, and OpenSwathOSWWriter additions

Co-authored-by: GitHub Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
timosachsenberg added a commit that referenced this pull request Apr 27, 2026
- Add OpenSwathWorkflow SWATH wave scheduler performance improvement and
  new parameters (innerBatchSize, maxConcurrentSwaths, batchSize=0 default)
- Add Fix for RUN.ID stored as BLOB instead of INTEGER in OSW output
  (fixes downstream PyProphet JOIN queries returning 0 rows)
  Both entries reference #9190.

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

2 participants