Skip to content

Guard null dereferences in TargetedExperiment::get*ByRef and ReactionMonitoringTransition::getPrediction - #9492

Merged
timosachsenberg merged 4 commits into
OpenMS:developfrom
timosachsenberg:pols-fix-guards-openswath
Jul 16, 2026
Merged

timosachsenberg merged 4 commits into
OpenMS:developfrom
timosachsenberg:pols-fix-guards-openswath

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

POLS audit fixes (#9488), systemic pattern: guard degenerate input. Both methods were guarded only by OPENMS_PRECONDITION (a no-op in release builds), so an unknown key dereferenced a null/invalid pointer.

  • TargetedExperiment::getProteinByRef / getPeptideByRef / getCompoundByRef returned *(map_[ref]). operator[] on the unordered_map<string, const T*> inserts a null pointer for an unknown ref, then dereferences it (UB). Now uses find() and throws Exception::ElementNotFound.
  • ReactionMonitoringTransition::getPrediction checked the wrong predicate (hasPrecursorCVTerms() instead of hasPrediction()) and dereferenced a possibly-null prediction_. Now checks hasPrediction() and throws Exception::MissingInformation when no Prediction is set.

Tests

Regression tests added (getProteinByRef/getPrediction throw on missing data, return correctly when present); both pass locally. No reference files touched.

Part of #9488. ABI-safe (no signature changes).

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved robustness when accessing prediction data: missing predictions now trigger a clear exception instead of risking a null dereference.
    • Improved robustness for reference-based lookups (protein/peptide/compound): unknown references now throw a not-found exception rather than creating invalid entries.
  • Tests
    • Added/expanded unit test coverage to verify the new exception behavior for missing prediction and missing reference lookups.

@github-actions

Copy link
Copy Markdown
Contributor

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

  • Timo Sachsenberg

Please consider applying the following patch:

--- AUTHORS	2026-06-12 11:43:09.083679327 +0000
+++ AUTHORS.new	2026-06-12 11:43:13.991243938 +0000
@@ -22,8 +22,8 @@
  - Chirag Dave
  - Chris Bauer
  - Chris Bielow
- - Christie Mathews
  - Christian Ehrlich
+ - Christie Mathews
  - Clemens Groepl
  - Cornelia Friedle
  - Daniel Jameson

@coderabbitai

coderabbitai Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

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

Next review available in: 31 seconds

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

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

How do review 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 refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a2dec24c-97bb-4ae6-a135-65097b27b1d6

📥 Commits

Reviewing files that changed from the base of the PR and between 2579e66 and 5c0090e.

📒 Files selected for processing (1)
  • src/openms/source/ANALYSIS/TARGETED/TargetedExperiment.cpp
📝 Walkthrough

Walkthrough

This PR hardens two OpenMS data-structure accessors against null-pointer dereferences and unsafe lookups. ReactionMonitoringTransition::getPrediction() now validates the prediction state and throws Exception::MissingInformation instead of dereferencing a null pointer. Three TargetedExperiment lookup methods (getProteinByRef, getPeptideByRef, getCompoundByRef) replace unsafe operator[] calls with safe std::map::find() and throw Exception::ElementNotFound on missing references. Unit tests cover both the success and exception paths.

Changes

Null-safety exception improvements for accessor methods

Layer / File(s) Summary
ReactionMonitoringTransition getPrediction null-guard
src/openms/source/ANALYSIS/MRM/ReactionMonitoringTransition.cpp, src/tests/class_tests/openms/source/ReactionMonitoringTransition_test.cpp
Exception header is included and getPrediction() now checks hasPrediction() before access, throwing Exception::MissingInformation if the prediction pointer is null. Unit test verifies the exception is raised for unset predictions and valid data is returned when set.
TargetedExperiment lookup methods safe-access
src/openms/source/ANALYSIS/TARGETED/TargetedExperiment.cpp, src/tests/class_tests/openms/source/TargetedExperiment_test.cpp
Exception header is included and three lookup methods (getProteinByRef, getPeptideByRef, getCompoundByRef) replace unsafe operator[] with std::map::find(), throwing Exception::ElementNotFound when a reference is missing. Unit tests verify correct retrieval and exception behavior for unknown references.

Suggested reviewers

  • singjc

Poem

🐰 A rabbit hops through null pointers with care,
No more unsafe lookups, no derefs despair!
With exception guards tight and safe finds in place,
Each accessor now dances with pride and with grace.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.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 directly and accurately describes the main purpose of the changeset: guarding against null dereferences in two specific functions across two OpenMS files.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

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

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/openms/source/ANALYSIS/TARGETED/TargetedExperiment.cpp (1)

401-415: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

The cached *_reference_map_ state can still hand back dangling pointers.

Lines 409/471/486 only fix the lookup primitive. The backing maps are never cleared in createProteinReferenceMap_(), createPeptideReferenceMap_(), or createCompoundReferenceMap_(), so a call sequence like getProteinByRef("p1"), setProteins({}), getProteinByRef("p1") can still find a removed id and dereference freed vector storage. setCompounds() and addCompound() also never set compound_reference_map_dirty_, so getCompoundByRef() can consult a stale cache after the first lookup.

Suggested fix
 void TargetedExperiment::setCompounds(const std::vector<Compound> & compounds)
 {
+  compound_reference_map_dirty_ = true;
   compounds_ = compounds;
 }

 void TargetedExperiment::addCompound(const Compound & rhs)
 {
+  compound_reference_map_dirty_ = true;
   compounds_.push_back(rhs);
 }

 void TargetedExperiment::createProteinReferenceMap_() const
 {
+  protein_reference_map_.clear();
   for (Size i = 0; i < getProteins().size(); i++)
   {
     protein_reference_map_[getProteins()[i].id] = &getProteins()[i];
   }
   protein_reference_map_dirty_ = false;
 }

 void TargetedExperiment::createPeptideReferenceMap_() const
 {
+  peptide_reference_map_.clear();
   for (Size i = 0; i < getPeptides().size(); i++)
   {
     peptide_reference_map_[getPeptides()[i].id] = &getPeptides()[i];
   }
   peptide_reference_map_dirty_ = false;
 }

 void TargetedExperiment::createCompoundReferenceMap_() const
 {
+  compound_reference_map_.clear();
   for (Size i = 0; i < getCompounds().size(); i++)
   {
     compound_reference_map_[getCompounds()[i].id] = &getCompounds()[i];
   }
   compound_reference_map_dirty_ = false;
 }

Also applies to: 432-445, 464-492, 695-719

🤖 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/ANALYSIS/TARGETED/TargetedExperiment.cpp` around lines 401
- 415, The cached reference maps can return dangling pointers because
createProteinReferenceMap_(), createPeptideReferenceMap_(), and
createCompoundReferenceMap_() never clear the previous maps before rebuilding
and some mutators (notably setCompounds() and addCompound(), and analogues for
peptides/proteins) never mark the corresponding *_reference_map_dirty_ flags;
fix by clearing the backing maps at the start of each create*ReferenceMap_()
(e.g. call clear() on protein_reference_map_, peptide_reference_map_,
compound_reference_map_) and then repopulate from the current vectors, and
ensure all mutators that change the underlying vectors (setCompounds,
addCompound, setPeptides, addPeptide, setProteins, addProtein, etc.) set the
appropriate *_reference_map_dirty_ = true so subsequent lookups rebuild a fresh
map.
🤖 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/ANALYSIS/MRM/ReactionMonitoringTransition.cpp`:
- Around line 323-329: Remove the OPENMS_PRECONDITION call so the function
consistently throws Exception::MissingInformation in all builds: delete the
OPENMS_PRECONDITION(hasPrediction(), ...) line and rely on the runtime null
check of prediction_ (the existing if (prediction_ == nullptr) { throw
Exception::MissingInformation(...); }) so callers of
getPrediction()/hasPrediction() always get the MissingInformation exception
rather than an assertion failure; update any related comments referencing the
old precondition to reflect the runtime contract.

In `@src/tests/class_tests/openms/source/TargetedExperiment_test.cpp`:
- Around line 221-230: Extend the existing regression test block that verifies
getProteinByRef to also assert that getPeptideByRef and getCompoundByRef throw
Exception::ElementNotFound for unknown refs: inside the same TEST_SECTION (where
TargetedExperiment t and a Protein p are created), add two TEST_EXCEPTION
assertions calling t.getPeptideByRef("does_not_exist") and
t.getCompoundByRef("does_not_exist") respectively so the changed behavior of
getPeptideByRef and getCompoundByRef is covered alongside getProteinByRef (use
the same Exception::ElementNotFound matcher and do not modify the existing
protein assertions).

---

Outside diff comments:
In `@src/openms/source/ANALYSIS/TARGETED/TargetedExperiment.cpp`:
- Around line 401-415: The cached reference maps can return dangling pointers
because createProteinReferenceMap_(), createPeptideReferenceMap_(), and
createCompoundReferenceMap_() never clear the previous maps before rebuilding
and some mutators (notably setCompounds() and addCompound(), and analogues for
peptides/proteins) never mark the corresponding *_reference_map_dirty_ flags;
fix by clearing the backing maps at the start of each create*ReferenceMap_()
(e.g. call clear() on protein_reference_map_, peptide_reference_map_,
compound_reference_map_) and then repopulate from the current vectors, and
ensure all mutators that change the underlying vectors (setCompounds,
addCompound, setPeptides, addPeptide, setProteins, addProtein, etc.) set the
appropriate *_reference_map_dirty_ = true so subsequent lookups rebuild a fresh
map.
🪄 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: 0b55211f-4286-48dc-b291-d9a5a9bc7ccc

📥 Commits

Reviewing files that changed from the base of the PR and between 28de924 and bf6b2bf.

📒 Files selected for processing (4)
  • src/openms/source/ANALYSIS/MRM/ReactionMonitoringTransition.cpp
  • src/openms/source/ANALYSIS/TARGETED/TargetedExperiment.cpp
  • src/tests/class_tests/openms/source/ReactionMonitoringTransition_test.cpp
  • src/tests/class_tests/openms/source/TargetedExperiment_test.cpp

timosachsenberg and others added 2 commits June 15, 2026 10:05
…MonitoringTransition::getPrediction

POLS audit (OpenMS#9488) findings, systemic pattern "guard degenerate input". Both were
guarded only by OPENMS_PRECONDITION (a no-op in release builds), so an unknown key
dereferenced a null/invalid pointer:

- TargetedExperiment::getProteinByRef / getPeptideByRef / getCompoundByRef returned
  *(map_[ref]). operator[] on the unordered_map<string, const T*> inserts a null
  pointer for an unknown ref, which was then dereferenced (UB). Now uses find() and
  throws Exception::ElementNotFound for an unknown ref.

- ReactionMonitoringTransition::getPrediction checked the wrong predicate
  (hasPrecursorCVTerms() instead of hasPrediction()) and dereferenced a possibly-null
  prediction_. Now checks hasPrediction() and throws Exception::MissingInformation
  when no Prediction is set.

Regression tests added (getProteinByRef and getPrediction throw on missing data,
return correctly when present); both pass. ABI-safe (no signature changes).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…d get*ByRef

- ReactionMonitoringTransition::getPrediction: remove the OPENMS_PRECONDITION (it would
  short-circuit before the runtime throw in assertion-enabled builds); rely on the null
  check so MissingInformation is thrown consistently across build configurations.
- TargetedExperiment_test: also assert getPeptideByRef/getCompoundByRef throw
  ElementNotFound on unknown refs (the PR changed all three accessors).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@timosachsenberg
timosachsenberg force-pushed the pols-fix-guards-openswath branch from c9a52f3 to 2579e66 Compare June 15, 2026 08:09
…nd clear() stale pointers on rebuild

Completes the get*ByRef hardening: setCompounds/addCompound now set
compound_reference_map_dirty_ (matching the protein/peptide mutators), and
create{Protein,Peptide,Compound}ReferenceMap_ clear() the map before rebuilding
so a removed id cannot survive as a dangling pointer into freed vector storage.
Adds a mutate-after-lookup regression test.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@timosachsenberg
timosachsenberg requested a review from jcharkow June 16, 2026 15:06

Copy link
Copy Markdown
Contributor Author

Adversarial review result: I did not find a blocking issue in this targeted-reference fix. The by-ref accessors now avoid map operator[] insertion on missing keys, clear stale pointer caches on rebuild, and mark compound caches dirty on mutation; the added tests cover the stale-cache and unknown-ref cases.

No whitespace errors or source/test comments with tracker-style issue references stood out in this diff.

I did not build or run the tests locally.

@timosachsenberg
timosachsenberg merged commit 84ec342 into OpenMS:develop Jul 16, 2026
38 checks passed
timosachsenberg added a commit that referenced this pull request Jul 17, 2026
* docs(changelog): add entries for #9492, #9752

Backfills two CHANGELOG entries for recently merged PRs that landed
without their own entry:
- #9752: new BUILD_TOPP_TOOLS / INSTALL_OPENMS_EXAMPLES CMake options
  enabling a core-only OpenMS SDK build
- #9492: null-dereference guards in TargetedExperiment::get*ByRef and
  ReactionMonitoringTransition::getPrediction

All other PRs merged since the last CHANGELOG update (#9613, #9750,
#9738) already carried their own entries; #9572 is test-only and
follows the existing convention of not adding a changelog entry for
test-only PRs in this series.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QcFv1tmBLzroCNJFjoqhZt

* Update CHANGELOG

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

---------

Co-authored-by: Claude <[email protected]>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
jcharkow pushed a commit to jcharkow/OpenMS that referenced this pull request Aug 12, 2026
…S#9753)

* docs(changelog): add entries for OpenMS#9492, OpenMS#9752

Backfills two CHANGELOG entries for recently merged PRs that landed
without their own entry:
- OpenMS#9752: new BUILD_TOPP_TOOLS / INSTALL_OPENMS_EXAMPLES CMake options
  enabling a core-only OpenMS SDK build
- OpenMS#9492: null-dereference guards in TargetedExperiment::get*ByRef and
  ReactionMonitoringTransition::getPrediction

All other PRs merged since the last CHANGELOG update (OpenMS#9613, OpenMS#9750,
OpenMS#9738) already carried their own entries; OpenMS#9572 is test-only and
follows the existing convention of not adding a changelog entry for
test-only PRs in this series.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QcFv1tmBLzroCNJFjoqhZt

* Update CHANGELOG

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

---------

Co-authored-by: Claude <[email protected]>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
jcharkow added a commit to jcharkow/OpenMS that referenced this pull request Oct 9, 2026
…S#9753)

* docs(changelog): add entries for OpenMS#9492, OpenMS#9752

Backfills two CHANGELOG entries for recently merged PRs that landed
without their own entry:
- OpenMS#9752: new BUILD_TOPP_TOOLS / INSTALL_OPENMS_EXAMPLES CMake options
  enabling a core-only OpenMS SDK build
- OpenMS#9492: null-dereference guards in TargetedExperiment::get*ByRef and
  ReactionMonitoringTransition::getPrediction

All other PRs merged since the last CHANGELOG update (OpenMS#9613, OpenMS#9750,
follows the existing convention of not adding a changelog entry for
test-only PRs in this series.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QcFv1tmBLzroCNJFjoqhZt

* Update CHANGELOG

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

---------

Co-authored-by: Claude <[email protected]>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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