Skip to content

[FIX] PeptideAndProteinQuant: O(1) sample-ID lookup (fixes IsobaricWorkflow "Quantifying peptides" hang) - #9672

Merged
timosachsenberg merged 1 commit into
developfrom
perf/quant-sample-id-lookup
Jun 26, 2026
Merged

timosachsenberg merged 1 commit into
developfrom
perf/quant-sample-id-lookup

Conversation

@timosachsenberg

Copy link
Copy Markdown
Contributor

Problem

IsobaricWorkflow (and ProteinQuantifier/ProteomicsLFQ) can hang for hours at the Quantifying peptides... step, with CPU usage sitting around ~5% — which looks like a deadlock but is actually one core pegged at 100% on a many-core machine (the code path is single-threaded).

Root cause

PeptideAndProteinQuant::getSampleIDFromFilenameAndChannel_() performed a linear scan over the experimental-design MS file section and recomputed File::stemName(entry.path) (a heap-allocating string operation) for every scanned row:

for (const auto& entry : ed.getMSFileSection())          // O(#files × #channels)
{
  std::string ed_filename = File::stemName(entry.path);  // string alloc, every row
  if (ed_filename == filename && entry.label == channel_or_label) return entry.sample;
}

It is called from the bottom of the 5-deep peptide aggregation loops (peptide × fraction × file × charge × channel) and a separate per-(file,charge) × label PSM-count loop. For a large isobaric experiment — e.g. 600 files × 18 channels → 10,800 MS-file-section rows — the step degenerates to roughly O(#observations × #channels × #ms_section_rows) with two heap allocations per inner step. That is on the order of 10¹¹ allocating string comparisons, i.e. hours of single-threaded wall time.

Additionally, the loop condition re-evaluated experimental_design_.getNumberOfLabels() every iteration, and that helper itself does an O(ms_section) std::max_element.

Fix

  1. Precompute a std::map<std::pair<std::string, UInt>, size_t> mapping (stemName(path), label) → sample, built once per readQuantData(). getSampleIDFromFilenameAndChannel_() now does a single map::find. emplace keeps the first occurrence of a (stem, label) pair, preserving the old "return first match" semantics. The cache is cleared in updateMembers_().
  2. Hoist getNumberOfLabels() into a const before the loops in quantifyPeptides() and annotateQuantificationsToProteins().

This takes the lookups from O(ms_section)-with-allocations down to O(log ms_section), turning the "Quantifying peptides" step from hours → seconds on large isobaric data. The number of lookups is unchanged, so results are bit-for-bit identical.

Correctness / behavior

No behavioral change. The mapping is built from the same getMSFileSection() in the same order, with identical first-match semantics and the identical Exception::MissingInformation on a miss. The consensus path already validated (basename, label) uniqueness upstream.

Testing

  • PeptideAndProteinQuant_test ✅
  • TOPP_ProteinQuantifier, TOPP_IsobaricWorkflow, TOPP_ProteomicsLFQ — 101/101 pass with identical reference output ✅
  • Adversarial static review (codex): no correctness regressions found; lifecycle (cache always built in readQuantData before any consumer) verified across all three TOPP drivers and the unit test.

🤖 Generated with Claude Code

…rkflow "Quantifying peptides" hang)

The "Quantifying peptides" step scaled ~quadratically with experiment size.
getSampleIDFromFilenameAndChannel_() linearly scanned the experimental-design
MS file section and recomputed File::stemName() (a heap-allocating string op)
for every scanned row, and it was called inside the per-peptide x fraction x
file x charge x channel aggregation loops (plus a per-(file,charge) x label
PSM-count loop). For a large isobaric run (e.g. 600 files x 18 channels =
10,800 MS-file-section rows) this becomes billions of allocating string
comparisons on a single thread -> hours of wall time at ~5% CPU (one pegged
core on a many-core box).

Fix:
- Precompute a map<(stemName, label) -> sample> once per readQuantData();
  getSampleIDFromFilenameAndChannel_() now does a single map::find. emplace
  keeps the first occurrence, matching the previous "return first match"
  semantics. Cache is cleared in updateMembers_().
- Hoist getNumberOfLabels() (itself an O(ms_section) max_element) out of the
  loop conditions in quantifyPeptides() and annotateQuantificationsToProteins().

Behavior is unchanged: the PeptideAndProteinQuant unit test and all
TOPP_ProteinQuantifier, TOPP_IsobaricWorkflow and TOPP_ProteomicsLFQ
integration tests pass with identical reference output.

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

coderabbitai Bot commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@timosachsenberg, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 18 minutes and 25 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: da1a2df7-37f6-4eda-9503-7c9d4ef7fc0b

📥 Commits

Reviewing files that changed from the base of the PR and between 1b23de1 and c8bde53.

📒 Files selected for processing (2)
  • src/openms/include/OpenMS/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.h
  • src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch perf/quant-sample-id-lookup

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.

@timosachsenberg

Copy link
Copy Markdown
Contributor Author

Self-review

Read through the final diff line by line. The change is tight and well-scoped (2 files, +61/−26); semantics are preserved and verified by the unit test plus 101 passing TOPP reference-output tests. A few notes for reviewers, none blocking:

Verified correct

  • First-match semantics preserved. buildSampleIDLookup_() iterates getMSFileSection() in the same order the old linear scan did and uses emplace, so on a duplicate (stem, label) the first row wins — identical to the old return entry.sample. (The consensus readQuantData already rejects conflicting (basename, label) rows upstream.)
  • Lifecycle is safe. experimental_design_ is private with no setter; it is assigned only in the three readQuantData() overloads, each of which now calls buildSampleIDLookup_() immediately after. Every TOPP driver (ProteinQuantifier, IsobaricWorkflow, ProteomicsLFQ) and the unit test call readQuantData() before quantifyPeptides()/quantifyProteins()/annotate…. updateMembers_() clears the cache. So the cache is never stale or empty at a consumer (an empty cache would throw MissingInformation, exactly as the old empty-scan did).
  • Types line up exactly. MSFileSectionEntry::label and ::sample are both unsigned (= UInt); the std::pair<std::string, UInt> key and size_t value involve no narrowing.
  • n_labels hoist is invariant. Neither quantifyPeptides() nor annotateQuantificationsToProteins() mutates the design mid-loop.

Nits (non-blocking, intentionally left as-is)

  1. sample_id_lookup_.find({filename, channel_or_label}) materializes a temporary pair (one string copy) per lookup. That's one allocation per call vs the old ~ms_section/2 allocating stemName() calls — a ~4 order-of-magnitude reduction — so not worth heterogeneous-lookup machinery here.
  2. Chose std::map over std::unordered_map to match the existing in-file idiom (the consensus path already builds a std::map<FileAndLabel, …>). O(log n) over ~10⁴ rows keeps the whole step in the low seconds; an unordered_map would shave a bit more but isn't needed.

Approach and result look correct to me. Ready for CI / a second pair of eyes.

@timosachsenberg
timosachsenberg merged commit 83aa20b into develop Jun 26, 2026
44 checks passed
@timosachsenberg
timosachsenberg deleted the perf/quant-sample-id-lookup branch June 26, 2026 11:21
timosachsenberg added a commit that referenced this pull request Jun 27, 2026
Documents four PRs that landed on 2026-06-26 after the last CHANGELOG
update (#9667):

- #9668: fix platform-dependent float formatting in scientific notation
- #9669: feat(PIPECHO) cap SVM training-set size (max_training_points)
- #9670: fix SimpleSVM constant-predictor crashes in predict()/setup()
- #9672: perf PeptideAndProteinQuant O(1) sample-ID lookup (fixes IsobaricWorkflow hang)

GitHub Actions version bump (#9673) carries no CHANGELOG entry per the
PR author's own checklist.


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

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