Skip to content

[FIX] 14 boundary/serialization/state-consistency fixes from the #9767 audit - #9790

Merged
timosachsenberg merged 1 commit into
developfrom
fix/9767-easy-boundary-fixes
Jul 24, 2026
Merged

timosachsenberg merged 1 commit into
developfrom
fix/9767-easy-boundary-fixes

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR fixes 14 of the "no-doubt, easy" boundary/serialization/state-consistency defects catalogued in the implementation-consistency audit #9767. Each fix is small and localized, and ships with a focused regression test that fails (crashes / hangs / asserts) before the fix and passes after. Behavior on valid inputs is preserved; only the buggy edge cases change.

Line numbers in #9767 were pinned to an old commit and have drifted — every fix below was re-verified against current develop. The change set was additionally reviewed with Codex, and its findings are incorporated (see the per-fix notes).

Fixes (issue #9767 finding numbers)

Boundary / crash / underflow

  • 4 QTClusterFinder / FeatureGroupingAlgorithmKD: two feature-empty input maps produced an empty mass range that was then dereferenced (front()/back()/size()-1). Added an empty-range guard. (Codex:) the KD path still runs postprocess_() before returning so per-map protein / unassigned-peptide IDs are preserved, and the QT guard is placed inside the partition branch so the nr_partitions==1 / two-map validation is unchanged.
  • 5 TheoreticalSpectrumGenerator::addInternalFragmentPeaks_: l < peptide.size() - 1 - 2 (unsigned) underflows for peptides shorter than 4, giving an effectively infinite loop when add_internal_fragments is on. Rewritten to the additive, non-underflowing l + 3 < peptide.size() (identical iteration set for length ≥ 4).
  • 18 MzTab IDMzTabStream/CMMzTabStream::nextPSMRow: current_psm_idx_ == getHits().size()-1 underflows for an empty hit list, so with export_all_psms the caller looped forever -> use current_psm_idx_ + 1 >= getHits().size().
  • 30 OMSSACSVFile::load: an unmatched quote let the quote-skipping loop run past line.end() (OOB read). Loop is now bounded; malformed lines are rejected by the existing 14-column check with a clean ParseError.

Correctness (wrong field / sentinel / flag)

  • 3 IDScoreGetterSetter::addToPeptideScoreMap_: the try_emplace "inserted" flag was misused, so a duplicated peptide sequence never had its stored score replaced by a later, better one. Now keeps the best score per sequence, independent of input order. (Codex:) it now updates both the score and its target/decoy label together, so a better target no longer inherits an earlier decoy label.
  • 6 MRMFeatureFilter::calculateFilterValuesPercRSD: the component-group retention_time_u %RSD was computed from the retention_time_l mean/variance (copy-paste). Now reads its own _u fields.
  • 12 ConsensusFeature::getPositionRange/getIntensityRange: the running max was seeded with minPositive() (smallest positive value), so all-negative coordinates/intensities reported a bogus ~2.2e-308 max. Seeded with minNegative() (== lowest()).
  • 35 TIC::Result::operator==: omitted relative_intensities; now included.

Serialization round-trip

  • 17 Base64::decodeStrings: the emit guard required length ≥ 2 and silently dropped single-character strings. Now accepts length ≥ 1. (This also flips the malformed "====" corrupted-input case from 0 to 1 string — "====" decodes to a single placeholder byte that was previously masked by the same over-strict guard; the test is updated with a root-cause comment.)
  • 19 ArrowIOHelpers::readMetaValues: integer meta values were parsed with std::stol and cast to 32-bit int, truncating values above INT32_MAX (DataValue stores SignedSize). Now std::stoll → SignedSize.
  • 20 FeatureMapArrowIO::importPSMsFromArrow: PSM rows were grouped into PeptideIdentifications by row adjacency, so an externally sorted/filtered Parquet with interleaved rows split one logical ID. Now grouped by P_ID value (first-seen), matching QPXFile/ConsensusMapArrowIO.

Stale-state on reload / clear

  • 27 QcMLFile::load: cleared the data maps but not the derived run_Name_ID_map_/set_Name_ID_map_, so a second load resolved stale names. Both are now cleared.
  • 32 CalibrationData::clear: left groups_ populated (phantom groups drove getNrOfGroups()); now cleared with the data.
  • 33 KDTreeFeatureMaps: num_maps_ was uninitialized and clear() did not clear the rt_ cache. Now num_maps_{0} and rt_ is cleared.

Deliberately NOT included

  • 1 (SNE random-scan sampling) — this is POLS API audit: 827 Principle-of-Least-Surprise findings (62 high) — tracking + fix guide #9488 PROC-23, already fixed by the open PR [FIX] IDFilter typed peptide-score filter, MorphologicalFilter thread safety, random-scan noise sampling #9616; including it here would duplicate/conflict.
  • 2 (pooled split-charge FDR upper bound, .first→.second) — the one-token fix is correct, but the surrounding pooled split-charge path has order-dependent side effects (setScores_ removes decoys across charge iterations), so a robust failing-before/passing-after test can't be written without also addressing those unrelated issues. Deferred to a focused FDR cleanup.
  • 7 (percentile index) — verified NOT a bug. The original p / 100.0 * diffs.size() - 1 is a double expression; for small N the negative value truncates toward zero to 0 (well-defined, since 0 is representable), so there is no unsigned underflow. Both the change and its test were reverted.
  • 38 (peak-erase desyncs auxiliary data arrays in FileFilter/AssayGeneratorMetabo) — real bug with a clean select()-based fix, but it touches two TOPP tools and warrants a CLI/round-trip test; deferred to keep this PR to self-contained library fixes.

All remaining audit items were reviewed and left out because they require an API/behavior policy decision (wire-up vs deprecate) or a larger redesign.

Testing

14 focused regression tests added across the corresponding *_test.cpp files (plus 3 small data fixtures: QcMLFile_reload_{A,B}.qcML, OMSSACSVFile_test_unbalanced_quote.csv). Each was confirmed to exercise the corrected path; where a fix could otherwise pass trivially, the test's fail-before behavior was verified by reverting the fix. Verified no reference churn: the three fixes with any downstream reach (#3 peptide-level FDR, #6 %RSD, #12 ranges) are either unexercised by existing TOPP tests (FDR_type=PSM+peptide is not the default and no test sets it) or have no production callers.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved stability for empty inputs and very short peptides (prevents invalid range/loop behavior and hangs).
    • Corrected best-hit target/decoy label handling and tightened TIC result equality to include relative intensities.
    • Fixed retention-time statistics (%RSD), consensus range computation, calibration and QCML reload state resets, and cleared stale KD-tree caches.
    • Improved Arrow import robustness for non-contiguous PSM rows and preserved large integer metadata; fixed Base64, MzTab export boundary handling, and safer CSV quoting.
  • Tests
    • Added/expanded regression coverage for empty inputs, stale data, ordering-independence, negative ranges, large metadata, and malformed files.

@coderabbitai

coderabbitai Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR fixes state initialization and reset behavior, empty-input handling, identification grouping, numeric parsing, iterator bounds, range calculations, equality checks, and format-specific edge cases. Regression tests and fixtures cover the corrected behaviors.

Changes

OpenMS correctness fixes

Layer / File(s) Summary
State and empty-input handling
src/openms/include/OpenMS/ANALYSIS/QUANTITATION/KDTreeFeatureMaps.h, src/openms/source/ANALYSIS/QUANTITATION/KDTreeFeatureMaps.cpp, src/openms/source/ANALYSIS/MAPMATCHING/*, src/tests/class_tests/openms/source/*
KD-tree counters and caches are initialized and cleared correctly, while empty feature-map inputs avoid invalid mass-range access and preserve grouping metadata.
Identification and QC statistics
src/openms/source/ANALYSIS/ID/IDScoreGetterSetter.cpp, src/openms/source/ANALYSIS/OPENSWATH/MRMFeatureFilter.cpp, src/tests/class_tests/openms/source/FalseDiscoveryRate_test.cpp, src/tests/class_tests/openms/source/MRMFeatureFilter_test.cpp
Best peptide score replacements now update target/decoy labels, and upper retention-time %RSD uses the upper mean with updated statistical assertions.
Format parsing and serialization
src/openms/source/FORMAT/*, src/tests/class_tests/openms/source/*, src/tests/class_tests/openms/data/QcMLFile_reload_*
Integer metadata parsing, non-contiguous PSM grouping, MzTab boundaries, quote scanning, qcML reload state, and Base64 segment handling are corrected and tested.
Numeric and container correctness
src/openms/source/CHEMISTRY/TheoreticalSpectrumGenerator.cpp, src/openms/source/DATASTRUCTURES/CalibrationData.cpp, src/openms/source/KERNEL/ConsensusFeature.cpp, src/openms/source/QC/TIC.cpp, src/tests/class_tests/openms/source/*
Short-peptide loop bounds, calibration group clearing, negative-only ranges, TIC equality, and corresponding regression tests are updated.

Possibly related issues

Possibly related PRs

  • OpenMS/OpenMS#9689: Both PRs modify Arrow metadata handling in ArrowIOHelpers::readMetaValues.

Suggested reviewers: cbielow

Poem

I’m a rabbit with a tidy code trail,
Patching empty maps where crashes might prevail.
Scores wear labels, ranges turn true,
Formats keep every value in view.
Hop through the tests—each bug says goodbye!

🚥 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
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the PR’s main theme: 14 fixes covering boundary, serialization, and state-consistency issues from the audit.
✨ 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 fix/9767-easy-boundary-fixes

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: 3

Caution

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

⚠️ Outside diff range comments (3)
src/openms/source/ANALYSIS/QUANTITATION/KDTreeFeatureMaps.cpp (1)

72-78: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Reset the map count when clearing KDTreeFeatureMaps.

clear() removes feature state but preserves the old num_maps_, so a cleared object reports stale map-count information.

  • src/openms/source/ANALYSIS/QUANTITATION/KDTreeFeatureMaps.cpp#L72-L78: assign num_maps_ = 0 in clear().
  • src/tests/class_tests/openms/source/KDTreeFeatureMaps_test.cpp#L139-L152: assert numMaps() == 0 immediately after clear().
🤖 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/QUANTITATION/KDTreeFeatureMaps.cpp` around lines
72 - 78, Update KDTreeFeatureMaps::clear() to reset num_maps_ to zero alongside
the other cleared state. In
src/openms/source/ANALYSIS/QUANTITATION/KDTreeFeatureMaps.cpp lines 72-78, add
this reset; in src/tests/class_tests/openms/source/KDTreeFeatureMaps_test.cpp
lines 139-152, assert numMaps() equals zero immediately after clear().
src/openms/source/FORMAT/OMSSACSVFile.cpp (1)

68-78: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Reject unterminated quoted fields explicitly.

When no closing quote exists, the loop exits with it == line.end(), but parsing continues and offset is still used. The column-count check can therefore accept malformed rows or parse shifted fields, contradicting the new regression test’s expected Exception::ParseError.

         while (++it != line.end() && *it != '"')
         {
           if (*it == ',')
           {
             offset++;
           }
         }
+        if (it == line.end())
+        {
+          throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
+                                      line, "unterminated quoted field");
+        }
🤖 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/OMSSACSVFile.cpp` around lines 68 - 78, Update the
quoted-field scanning logic before StringUtils::split in the OMSSACSV parsing
flow to detect when the iterator reaches line.end() without finding a closing
quote and throw Exception::ParseError immediately. Only use offset for rows with
properly terminated quoted fields, while preserving the existing column-count
validation for valid input.
src/openms/source/FORMAT/QcMLFile.cpp (1)

770-776: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Clear the set-member name accumulator at reparse boundaries.

names_ is populated from MS:1000577 set members and copied into setQualityQPs_members_ by registerSet(...), but it is not reset by load() or at the setQuality boundary. Reusing the parser can carry over stale set members across reloads or multiple sets in one file. Add names_.clear() with the other cleared per-load/per-set state.

🤖 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/QcMLFile.cpp` around lines 770 - 776, Update the
parser reset logic in load() and at the setQuality boundary to clear names_
alongside runQualityQPs_, setQualityQPs_, and setQualityQPs_members_. Ensure
each reload and new set starts with an empty set-member name accumulator before
registerSet(...) populates it.
🧹 Nitpick comments (3)
src/tests/class_tests/openms/source/KDTreeFeatureMaps_test.cpp (1)

139-152: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert that clear() resets the map count.

Add TEST_EQUAL(kd_data_3.numMaps(), 0) immediately after clear() so this regression also detects stale num_maps_ state.

🤖 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/tests/class_tests/openms/source/KDTreeFeatureMaps_test.cpp` around lines
139 - 152, Update the clear() test for kd_data_3 by adding an assertion
immediately after kd_data_3.clear() that kd_data_3.numMaps() equals 0, while
preserving the existing size, treeSize, and RT reset assertions.
src/tests/class_tests/openms/source/QTClusterFinder_test.cpp (1)

226-241: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Cover the single-partition empty-input path.

This test only exercises the default multi-partition branch. Add a case configured with nr_partitions == 1; otherwise the remaining empty-input failure through run_internal_() is not detected.

🤖 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/tests/class_tests/openms/source/QTClusterFinder_test.cpp` around lines
226 - 241, Add a second regression case in the QTClusterFinder run() tests using
two empty FeatureMaps and configuring nr_partitions to 1 before invoking run().
Assert that the resulting ConsensusMap remains empty, ensuring the
single-partition run_internal_() path is covered alongside the existing default
multi-partition case.
src/openms/source/FORMAT/ArrowIOHelpers.cpp (1)

234-235: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use the required multiline brace style for the changed exception handling.

Proposed fix
-      try { target.setMetaValue(name, static_cast<SignedSize>(std::stoll(value_str))); }
-      catch (...) { target.setMetaValue(name, value_str); }
+      try
+      {
+        target.setMetaValue(name, static_cast<SignedSize>(std::stoll(value_str)));
+      }
+      catch (...)
+      {
+        target.setMetaValue(name, value_str);
+      }

As per coding guidelines, “Place opening and closing braces on their own lines, aligned with the surrounding code.”

🤖 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/ArrowIOHelpers.cpp` around lines 234 - 235, Update
the exception handling around the stoll conversion in the metadata assignment so
the try and catch blocks use multiline braces, placing each opening and closing
brace on its own line and aligning them with the surrounding code. Preserve the
existing numeric conversion and string fallback behavior.

Source: Coding guidelines

🤖 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/ID/IDScoreGetterSetter.cpp`:
- Around line 71-74: Update the score replacement logic in the surrounding ID
score getter/setter flow so equal scores between target and decoy entries
deterministically retain the target label, matching getPickedProteinScores_.
Preserve the existing isFirstBetterScore_ behavior for unequal scores and update
the stored score/label only when the score is better or the tie-break favors
is_target.

In `@src/openms/source/ANALYSIS/MAPMATCHING/QTClusterFinder.cpp`:
- Around line 267-275: In
src/openms/source/ANALYSIS/MAPMATCHING/QTClusterFinder.cpp:267-275, make the
empty massrange check return before the nr_partitions_ == 1 branch, so
run_internal_ is never called with empty input; preserve the existing result_map
clearing behavior. In
src/tests/class_tests/openms/source/QTClusterFinder_test.cpp:226-241, add
coverage configuring nr_partitions to 1 and verifying empty input completes
without throwing.

In `@src/tests/class_tests/openms/source/OMSSACSVFile_test.cpp`:
- Around line 57-66: Replace tab indentation with two spaces in the added
regression test block for OMSSACSVFile, including its comments, declarations,
and TEST_EXCEPTION call; do not alter the test behavior or surrounding code.

---

Outside diff comments:
In `@src/openms/source/ANALYSIS/QUANTITATION/KDTreeFeatureMaps.cpp`:
- Around line 72-78: Update KDTreeFeatureMaps::clear() to reset num_maps_ to
zero alongside the other cleared state. In
src/openms/source/ANALYSIS/QUANTITATION/KDTreeFeatureMaps.cpp lines 72-78, add
this reset; in src/tests/class_tests/openms/source/KDTreeFeatureMaps_test.cpp
lines 139-152, assert numMaps() equals zero immediately after clear().

In `@src/openms/source/FORMAT/OMSSACSVFile.cpp`:
- Around line 68-78: Update the quoted-field scanning logic before
StringUtils::split in the OMSSACSV parsing flow to detect when the iterator
reaches line.end() without finding a closing quote and throw
Exception::ParseError immediately. Only use offset for rows with properly
terminated quoted fields, while preserving the existing column-count validation
for valid input.

In `@src/openms/source/FORMAT/QcMLFile.cpp`:
- Around line 770-776: Update the parser reset logic in load() and at the
setQuality boundary to clear names_ alongside runQualityQPs_, setQualityQPs_,
and setQualityQPs_members_. Ensure each reload and new set starts with an empty
set-member name accumulator before registerSet(...) populates it.

---

Nitpick comments:
In `@src/openms/source/FORMAT/ArrowIOHelpers.cpp`:
- Around line 234-235: Update the exception handling around the stoll conversion
in the metadata assignment so the try and catch blocks use multiline braces,
placing each opening and closing brace on its own line and aligning them with
the surrounding code. Preserve the existing numeric conversion and string
fallback behavior.

In `@src/tests/class_tests/openms/source/KDTreeFeatureMaps_test.cpp`:
- Around line 139-152: Update the clear() test for kd_data_3 by adding an
assertion immediately after kd_data_3.clear() that kd_data_3.numMaps() equals 0,
while preserving the existing size, treeSize, and RT reset assertions.

In `@src/tests/class_tests/openms/source/QTClusterFinder_test.cpp`:
- Around line 226-241: Add a second regression case in the QTClusterFinder run()
tests using two empty FeatureMaps and configuring nr_partitions to 1 before
invoking run(). Assert that the resulting ConsensusMap remains empty, ensuring
the single-partition run_internal_() path is covered alongside the existing
default multi-partition case.
🪄 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 Plus

Run ID: 4755b1e3-bddb-48c9-8f5f-6e287edd7e49

📥 Commits

Reviewing files that changed from the base of the PR and between e7a4612 and 22a2fea.

⛔ Files ignored due to path filters (1)
  • src/tests/class_tests/openms/data/OMSSACSVFile_test_unbalanced_quote.csv is excluded by !**/*.csv
📒 Files selected for processing (32)
  • src/openms/include/OpenMS/ANALYSIS/QUANTITATION/KDTreeFeatureMaps.h
  • src/openms/source/ANALYSIS/ID/IDScoreGetterSetter.cpp
  • src/openms/source/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmKD.cpp
  • src/openms/source/ANALYSIS/MAPMATCHING/QTClusterFinder.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMFeatureFilter.cpp
  • src/openms/source/ANALYSIS/QUANTITATION/KDTreeFeatureMaps.cpp
  • src/openms/source/CHEMISTRY/TheoreticalSpectrumGenerator.cpp
  • src/openms/source/DATASTRUCTURES/CalibrationData.cpp
  • src/openms/source/FORMAT/ArrowIOHelpers.cpp
  • src/openms/source/FORMAT/Base64.cpp
  • src/openms/source/FORMAT/FeatureMapArrowIO.cpp
  • src/openms/source/FORMAT/MzTab.cpp
  • src/openms/source/FORMAT/OMSSACSVFile.cpp
  • src/openms/source/FORMAT/QcMLFile.cpp
  • src/openms/source/KERNEL/ConsensusFeature.cpp
  • src/openms/source/QC/TIC.cpp
  • src/tests/class_tests/openms/data/QcMLFile_reload_A.qcML
  • src/tests/class_tests/openms/data/QcMLFile_reload_B.qcML
  • src/tests/class_tests/openms/source/Base64_test.cpp
  • src/tests/class_tests/openms/source/CalibrationData_test.cpp
  • src/tests/class_tests/openms/source/ConsensusFeature_test.cpp
  • src/tests/class_tests/openms/source/FalseDiscoveryRate_test.cpp
  • src/tests/class_tests/openms/source/FeatureGroupingAlgorithmKD_test.cpp
  • src/tests/class_tests/openms/source/FeatureMapArrowIO_test.cpp
  • src/tests/class_tests/openms/source/KDTreeFeatureMaps_test.cpp
  • src/tests/class_tests/openms/source/MRMFeatureFilter_test.cpp
  • src/tests/class_tests/openms/source/MzTab_test.cpp
  • src/tests/class_tests/openms/source/OMSSACSVFile_test.cpp
  • src/tests/class_tests/openms/source/QTClusterFinder_test.cpp
  • src/tests/class_tests/openms/source/QcMLFile_test.cpp
  • src/tests/class_tests/openms/source/TIC_test.cpp
  • src/tests/class_tests/openms/source/TheoreticalSpectrumGenerator_test.cpp

…audit

Fixes 14 of the "no-doubt, easy" defects catalogued in the implementation-
consistency audit #9767. Each fix is small and localized, ships with a focused
regression test that fails (crash/hang/assert) before and passes after, and
preserves behavior on valid inputs (only the buggy edge cases change). The set
was reviewed with Codex and CodeRabbit; their findings are incorporated below.

Boundary / crash / underflow:
- #4  QTClusterFinder / FeatureGroupingAlgorithmKD: guard the empty mass range so
      feature-empty input maps don't dereference front()/back()/size()-1. The
      guards run before the linking work: KD calls postprocess_() first so per-map
      protein/unassigned-peptide IDs survive; QT returns before the single-partition
      branch, whose setParameters_() otherwise throws on the empty maps' invalid
      max m/z (the <2-maps case is validated by the caller).
- #5  TheoreticalSpectrumGenerator: internal-fragment loop bound underflowed for
      peptides shorter than 4 (l < size-1-2) -> use additive l+3 < size.
- #18 MzTab nextPSMRow (both streams): empty hit list underflowed size()-1 and
      looped forever with export_all_psms -> use current_psm_idx_+1 >= size().
- #30 OMSSACSVFile::load: bound the quote-skipping scan by line.end().

Correctness (wrong field / sentinel / flag):
- #3  IDScoreGetterSetter::addToPeptideScoreMap_: the try_emplace "inserted" flag
      was misused, so a duplicated sequence never kept a later better score. Now
      updates BOTH the score and its target/decoy label, and resolves equal-score
      target/decoy ties to the target (matching getPickedProteinScores_), so the
      peptide-level representative is deterministic and input-order independent.
- #6  MRMFeatureFilter: group retention_time_u %RSD read the _l mean/variance.
- #12 ConsensusFeature range max sentinel minPositive() -> minNegative().
- #35 TIC::Result::operator== now includes relative_intensities.

Serialization round-trip:
- #17 Base64::decodeStrings: keep length-1 segments (dropped single-char strings).
      Also updates the malformed "====" corrupted-input expectation (now decodes
      to one placeholder byte instead of being silently dropped).
- #19 ArrowIOHelpers: parse int meta with stoll -> SignedSize (was 32-bit).
- #20 FeatureMapArrowIO::importPSMsFromArrow: group PSM rows by P_ID value, not by
      row adjacency (matches QPXFile/ConsensusMapArrowIO).

Stale-state on reload / clear:
- #27 QcMLFile::load: also clear derived run_/set_Name_ID_map_.
- #32 CalibrationData::clear: also clear groups_.
- #33 KDTreeFeatureMaps: init num_maps_{0}; clear() also clears rt_ cache.

Not included: #1 (=#9488 PROC-23, already in open PR #9616); #2 (correct but the
pooled split-charge FDR path has order-dependent side effects that preclude a
clean regression test in isolation); #7 (percentile index -- verified NOT a bug:
the "-1" is part of the double expression, so the negative value truncates to 0,
no underflow); #38 (TOPP-tool aux-array desync, needs a CLI test). Remaining audit
items need an API/deprecate decision.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@timosachsenberg
timosachsenberg force-pushed the fix/9767-easy-boundary-fixes branch from 22a2fea to 4f3e0f5 Compare July 24, 2026 12:53
@timosachsenberg

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Addressed all three inline findings in the latest push (4f3e0f5f25):

  • IDScoreGetterSetter (Major, equal-score tie-break): the peptide-score map now resolves equal-score target/decoy ties to the target (matching getPickedProteinScores_), so the representative is fully input-order independent. Added a tie-case (equal-score decoy-vs-target) order-independence assertion to FalseDiscoveryRate_test.
  • QTClusterFinder (Major, empty input + nr_partitions == 1): you're right — run_internal_() -> setParameters_() throws on the empty maps' invalid max m/z. Moved the empty-massrange guard to return before the nr_partitions_ == 1 branch (the <2-maps case is validated upstream in FeatureGroupingAlgorithmQT::group_). Added a nr_partitions=1 empty-input case to the test.
  • OMSSACSVFile_test (Minor, tabs): converted the added block to 2-space indentation per .clang-format (UseTab: Never).

All 14 fix-tests still pass locally.

@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/FeatureMapArrowIO.cpp (1)

1546-1550: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use OpenMS primitive types for the new lookup state.

The added std::unordered_map<int32_t, size_t>, int64_t row, int32_t p_id, and size_t gidx should use Int32, Int64, and Size from OpenMS/CONCEPT/Types.h.

Proposed fix
-  std::unordered_map<int32_t, size_t> p_id_to_idx;
+  std::unordered_map<Int32, Size> p_id_to_idx;

-  for (int64_t row = 0; row < num_rows; ++row)
+  for (Int64 row = 0; row < num_rows; ++row)
...
-    int32_t p_id = getInt32Value_(col_p_id, row, -1);
+    Int32 p_id = getInt32Value_(col_p_id, row, -1);
...
-    const size_t gidx = pid_it->second;
+    const Size gidx = pid_it->second;

As per coding guidelines, use OpenMS primitive types from OpenMS/CONCEPT/Types.h instead of standard C++ types.

Also applies to: 1621-1621

🤖 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/FeatureMapArrowIO.cpp` around lines 1546 - 1550,
Replace the new lookup-state types in the surrounding FeatureMapArrowIO logic
with OpenMS aliases: use Int32 for p_id and the map key, Int64 for row, and Size
for gidx and the map value. Ensure the relevant declarations consistently use
these types from OpenMS/CONCEPT/Types.h.

Source: Coding guidelines

🤖 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/FeatureMapArrowIO.cpp`:
- Around line 1546-1550: Replace the new lookup-state types in the surrounding
FeatureMapArrowIO logic with OpenMS aliases: use Int32 for p_id and the map key,
Int64 for row, and Size for gidx and the map value. Ensure the relevant
declarations consistently use these types from OpenMS/CONCEPT/Types.h.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 360301a9-4703-4223-8cac-c7682c3f2da4

📥 Commits

Reviewing files that changed from the base of the PR and between 22a2fea and 4f3e0f5.

⛔ Files ignored due to path filters (1)
  • src/tests/class_tests/openms/data/OMSSACSVFile_test_unbalanced_quote.csv is excluded by !**/*.csv
📒 Files selected for processing (32)
  • src/openms/include/OpenMS/ANALYSIS/QUANTITATION/KDTreeFeatureMaps.h
  • src/openms/source/ANALYSIS/ID/IDScoreGetterSetter.cpp
  • src/openms/source/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmKD.cpp
  • src/openms/source/ANALYSIS/MAPMATCHING/QTClusterFinder.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMFeatureFilter.cpp
  • src/openms/source/ANALYSIS/QUANTITATION/KDTreeFeatureMaps.cpp
  • src/openms/source/CHEMISTRY/TheoreticalSpectrumGenerator.cpp
  • src/openms/source/DATASTRUCTURES/CalibrationData.cpp
  • src/openms/source/FORMAT/ArrowIOHelpers.cpp
  • src/openms/source/FORMAT/Base64.cpp
  • src/openms/source/FORMAT/FeatureMapArrowIO.cpp
  • src/openms/source/FORMAT/MzTab.cpp
  • src/openms/source/FORMAT/OMSSACSVFile.cpp
  • src/openms/source/FORMAT/QcMLFile.cpp
  • src/openms/source/KERNEL/ConsensusFeature.cpp
  • src/openms/source/QC/TIC.cpp
  • src/tests/class_tests/openms/data/QcMLFile_reload_A.qcML
  • src/tests/class_tests/openms/data/QcMLFile_reload_B.qcML
  • src/tests/class_tests/openms/source/Base64_test.cpp
  • src/tests/class_tests/openms/source/CalibrationData_test.cpp
  • src/tests/class_tests/openms/source/ConsensusFeature_test.cpp
  • src/tests/class_tests/openms/source/FalseDiscoveryRate_test.cpp
  • src/tests/class_tests/openms/source/FeatureGroupingAlgorithmKD_test.cpp
  • src/tests/class_tests/openms/source/FeatureMapArrowIO_test.cpp
  • src/tests/class_tests/openms/source/KDTreeFeatureMaps_test.cpp
  • src/tests/class_tests/openms/source/MRMFeatureFilter_test.cpp
  • src/tests/class_tests/openms/source/MzTab_test.cpp
  • src/tests/class_tests/openms/source/OMSSACSVFile_test.cpp
  • src/tests/class_tests/openms/source/QTClusterFinder_test.cpp
  • src/tests/class_tests/openms/source/QcMLFile_test.cpp
  • src/tests/class_tests/openms/source/TIC_test.cpp
  • src/tests/class_tests/openms/source/TheoreticalSpectrumGenerator_test.cpp
🚧 Files skipped from review as they are similar to previous changes (28)
  • src/tests/class_tests/openms/source/TIC_test.cpp
  • src/openms/source/DATASTRUCTURES/CalibrationData.cpp
  • src/tests/class_tests/openms/source/ConsensusFeature_test.cpp
  • src/openms/source/FORMAT/Base64.cpp
  • src/openms/source/QC/TIC.cpp
  • src/tests/class_tests/openms/source/OMSSACSVFile_test.cpp
  • src/openms/source/CHEMISTRY/TheoreticalSpectrumGenerator.cpp
  • src/tests/class_tests/openms/source/TheoreticalSpectrumGenerator_test.cpp
  • src/openms/source/ANALYSIS/ID/IDScoreGetterSetter.cpp
  • src/tests/class_tests/openms/source/QTClusterFinder_test.cpp
  • src/tests/class_tests/openms/source/MzTab_test.cpp
  • src/tests/class_tests/openms/source/KDTreeFeatureMaps_test.cpp
  • src/openms/source/FORMAT/OMSSACSVFile.cpp
  • src/openms/source/FORMAT/MzTab.cpp
  • src/openms/source/FORMAT/ArrowIOHelpers.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMFeatureFilter.cpp
  • src/openms/include/OpenMS/ANALYSIS/QUANTITATION/KDTreeFeatureMaps.h
  • src/openms/source/ANALYSIS/QUANTITATION/KDTreeFeatureMaps.cpp
  • src/openms/source/KERNEL/ConsensusFeature.cpp
  • src/openms/source/FORMAT/QcMLFile.cpp
  • src/tests/class_tests/openms/source/CalibrationData_test.cpp
  • src/tests/class_tests/openms/source/FalseDiscoveryRate_test.cpp
  • src/openms/source/ANALYSIS/MAPMATCHING/QTClusterFinder.cpp
  • src/tests/class_tests/openms/data/QcMLFile_reload_A.qcML
  • src/tests/class_tests/openms/source/Base64_test.cpp
  • src/tests/class_tests/openms/source/QcMLFile_test.cpp
  • src/tests/class_tests/openms/source/MRMFeatureFilter_test.cpp
  • src/tests/class_tests/openms/source/FeatureMapArrowIO_test.cpp

@timosachsenberg
timosachsenberg merged commit 066f27a into develop Jul 24, 2026
39 checks passed
@timosachsenberg
timosachsenberg deleted the fix/9767-easy-boundary-fixes branch July 24, 2026 15:09
timosachsenberg added a commit that referenced this pull request Jul 25, 2026
… fix (#9791)

#9790 (14 boundary/serialization/state-consistency fixes from the #9767
audit) had no changelog entry. The existing Arrow-abort entry cited only
the tracking issue #9739; #9778 is the PR that actually implemented and
merged that fix, so it's now credited alongside it.


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

Co-authored-by: Claude <[email protected]>
timosachsenberg added a commit that referenced this pull request Sep 29, 2026
…hout features (#10310) (#10315)

A fraction in which no run has a feature gives the linker only empty maps.
That happens when no identification of the fraction's runs passes the
upstream FDR filter, as in the quantms BSA test with Sage, where Percolator
keeps no PSM in any run of fraction 1. Until #9790 this crashed
QTClusterFinder::run_() (massrange.front() on an empty vector, the segfault
reported in #10310; 3.5.0 has it too). Since then linking returns an empty
consensus map, but ProteomicsLFQ still asserted that it is not empty, so
Debug builds aborted on the same input. The fraction now contributes no
quantities and a warning names it; the other fractions are quantified as
before.

FeatureGroupingAlgorithmQT_test covers the call ProteomicsLFQ makes
(use_identifications=true) on empty maps; builds before #9790 segfault on
it. TOPP_ProteomicsLFQ_empty_fraction runs ProteomicsLFQ with a fraction
without identifications (the 2026-07-02 nightly segfaults on it, the Debug
build of develop aborted on the assertion) and compares the MSstats output
of the remaining fraction, which matches the 2026-09-27 Release nightly
byte for byte.


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

Co-authored-by: Claude <[email protected]>
timosachsenberg added a commit to timosachsenberg/OpenMS that referenced this pull request Oct 15, 2026
Conflicts resolved to develop's side: OpenMS#9790 (066f27a) fixed the short-
peptide underflow and the MRM %RSD on develop, and develop rewrote the
OpenNuXL references since.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012GBvJZN8neGpv9RoUshwFL
timosachsenberg added a commit to timosachsenberg/OpenMS that referenced this pull request Oct 15, 2026
TheoreticalSpectrumGenerator stopped the internal-fragment loop one start
position early (l + 3 < size): the internal fragment that ends next to
the C-terminal residue was never generated, and 4-mers got none. The
bound is l + 2 < size now.

- The short-peptide underflow and the MRM %RSD fix are on develop
  (OpenMS#9790); the pooled split-charge FDR fix is dropped: applyBasic(run_info,
  ids) has no caller outside pyOpenMS and that path has further problems.
- OpenNuXL annotates with internal fragments. In its 9 references only
  fragment_annotation lines change: the new fragments are added (e.g.
  VL, QL, DK-H3N1+), and at m/z 242.1496 QL replaces SSL-CO-H2O1+ (same
  mass). The other lines are kept; the test outputs match them within
  FuzzyDiff's tolerance.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012GBvJZN8neGpv9RoUshwFL
timosachsenberg added a commit that referenced this pull request Oct 15, 2026
…nt (#9600)

* Fix boundary/math bugs from issue #9597 (TSG internal fragments, FDR charge range, MRM RT %RSD)

Addresses three validated findings from #9597:

* TheoreticalSpectrumGenerator::addInternalFragmentPeaks_: the internal-fragment
  loop bound `l < size - 1 - 2` dropped the C-terminal-adjacent interior dipeptide
  (off-by-one) and, being unsigned, wrapped to ~1.8e19 for peptides of length 1-2
  (effectively infinite loop / OOM). Guard with `if (size < 4) return;` and use the
  underflow-safe bound `l + 2 < size`.

* FalseDiscoveryRate::applyBasic(run_info, ids): the pooled split_charge_variants
  path computed the upper charge bound with getChargeRange().first instead of
  .second, collapsing e.g. 2..4 to only charge 2.

* MRMFeatureFilter::calculateFilterValuesPercRSD: the component-group
  retention_time_u %RSD was computed from the retention_time_l fields (copy-paste);
  use the _u fields, mirroring the component-level block.

Adds regression tests for all three (fail before the fix, pass after). The TSG fix
emits the previously-missing internal fragments, so the nine OpenNuXL reference
outputs are updated accordingly (fragment_annotation strings only; no
identification/score/localization changes).

The fourth finding (TransformationDescription::getStatistics percentile index) was
validated as a non-bug: the index expression is floating-point and, for the default
percentile set, never produces an out-of-range value.

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

* Keep only the internal-fragment fix; update the OpenNuXL references

TheoreticalSpectrumGenerator stopped the internal-fragment loop one start
position early (l + 3 < size): the internal fragment that ends next to
the C-terminal residue was never generated, and 4-mers got none. The
bound is l + 2 < size now.

- The short-peptide underflow and the MRM %RSD fix are on develop
  (#9790); the pooled split-charge FDR fix is dropped: applyBasic(run_info,
  ids) has no caller outside pyOpenMS and that path has further problems.
- OpenNuXL annotates with internal fragments. In its 9 references only
  fragment_annotation lines change: the new fragments are added (e.g.
  VL, QL, DK-H3N1+), and at m/z 242.1496 QL replaces SSL-CO-H2O1+ (same
  mass). The other lines are kept; the test outputs match them within
  FuzzyDiff's tolerance.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012GBvJZN8neGpv9RoUshwFL

---------

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.

1 participant