Skip to content

Fix data array misalignment in sort/select operations - #9799

Closed
timosachsenberg wants to merge 5 commits into
developfrom
claude/openms-pr-9795-review-vaqdlr
Closed

timosachsenberg wants to merge 5 commits into
developfrom
claude/openms-pr-9795-review-vaqdlr

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Description

This PR fixes a critical bug where MSChromatogram and Mobilogram silently mis-associated per-peak metadata during sorting and selection operations. The data arrays (FloatDataArray, StringDataArray, IntegerDataArray) are parallel to the peaks and must be permuted together, but several code paths failed to do so.

Issues Fixed

  1. sortByPosition() / sortByIntensity(): When data arrays were present, peaks were permuted but the arrays were left in their original order, causing metadata to be associated with the wrong peaks.

  2. sortByIntensity() fast path bug: The condition guarding the fast path was incorrect (float_data_arrays_.empty() alone), causing string/integer arrays to be silently ignored even when present.

  3. sort(lambda) template: Was not implemented; now properly permutes all data arrays alongside peaks using a generic index-based approach.

  4. select(): Improved validation and handling of duplicate indices (which must duplicate values, not leave moved-from holes).

  5. clear(): Now properly clears data arrays alongside peaks, preventing inconsistent state where arrays survived after peaks were dropped.

Key Changes

  • MSChromatogram.cpp / Mobilogram.cpp: Refactored sortByPosition() and sortByIntensity() to use a unified sort(lambda) implementation that permutes all data arrays together with peaks.
  • Added sort(lambda) template: Validates data array sizes up front, then uses index-based stable sort to permute peaks and all arrays together.
  • Added checkDataArraySizes_() helper: Validates that non-empty data arrays match the peak count before any mutation.
  • Updated select(): Validates indices and array sizes before modifying state; handles duplicate indices correctly by copying (not moving) string data.
  • Updated clear(): Now clears data arrays alongside peaks to maintain consistency.
  • PeakPickerMobilogram.cpp: Updated to use select() instead of clear()+push_back() to preserve data arrays.
  • LayerStoreData.cpp: Updated to use select() for proper subsetting.

Testing

Comprehensive regression tests added to both Mobilogram_test.cpp and MSChromatogram_test.cpp:

  • Verify peaks and all data array types are permuted together
  • Test stable sort behavior with tied keys
  • Validate error handling for mis-sized arrays and out-of-range indices
  • Test duplicate indices in select() produce correct duplicates
  • Test sort(lambda) with custom predicates

All existing tests pass; new tests ensure the bug does not regress.

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 (Not needed; no API changes to bound classes)

https://claude.ai/code/session_01NBHPFbi3DC2mFxeRK6VXXU

Summary by CodeRabbit

  • Bug Fixes

    • Sorting and subsetting of chromatograms and mobilograms now keep all peak-related metadata/data arrays properly aligned (including stable ordering and correct permutation across all array families).
    • Chromatogram and mobilogram clearing now fully removes associated data arrays and prevents cached range inconsistencies.
    • Peak filtering and range-based selection now validate inputs and avoid corrupting peak associations.
    • Mis-sized data arrays or invalid selection indices are rejected with precondition errors while leaving objects unchanged.
  • New Features

    • Added stable, predicate-based sorting and index-based selection for mobilograms and chromatograms, including correct handling of duplicate selections.
  • Documentation / Tests

    • Updated behavior documentation for sorting, selection, and clearing; expanded regression tests for alignment, stability, and error handling.

timosachsenberg and others added 4 commits July 26, 2026 04:54
Both classes carry float/string/integer data arrays that are parallel to
the peaks, but neither kept them in sync when the peaks were permuted or
dropped.

MSChromatogram::sortByPosition() guarded its metadata-ignoring fast path
on float_data_arrays_.empty() alone, ignoring string and integer arrays.
MSChromatogram::sortByIntensity() guarded on an inverted condition:

    float_data_arrays_.empty() && !string_data_arrays_.empty() && !integer_data_arrays_.empty()

i.e. it took the fast path precisely when string and integer arrays were
present, and the slow path when no metadata existed at all.

The sortByPosition() case is reachable on the mzML load path: MzMLHandler
populates chromatogram integer/string binary data arrays and then calls
sortByPosition() when 'sort_chromatograms_by_rt' is set, so a chromatogram
with integer/string arrays but no float array had its peaks reordered while
the arrays stayed in file order -- and the mismatch was written back out on
store.

Mobilogram::sortByIntensity()/sortByPosition() were a bare stable_sort over
the peaks and never touched any array family. No in-tree caller sorts a
Mobilogram, but both sorts and all three array accessors are exposed via
pyOpenMS, whose docstring already promised the arrays would follow.

Both classes now permute peaks and all three array families together,
reusing the select()-based approach MSSpectrum already uses. MSChromatogram
already had select() -- the sorts simply never called it. Mobilogram gains
the select() and sort(Predicate) members it was missing; its class test
already contained a placeholder section for the latter, now a real test.

Also fixes clear(): Mobilogram::clear() and MSChromatogram::clear(false)
retained the data arrays while dropping the peaks, leaving the container
internally inconsistent. Both now clear the arrays and ranges, matching
MSSpectrum::clear(); for MSChromatogram the 'clear_meta_data' flag now
governs only ChromatogramSettings and the name. This also removes a latent
accumulation bug in PeakPickerMobilogram, which does clear() -> resize() ->
push_back and would have appended to stale entries on reuse of its output.

Behaviour changes: MSChromatogram sorting is now stable (std::sort ->
std::stable_sort), and a data array whose size does not match the peak
count now throws Exception::Precondition instead of silently corrupting
the association.

Verified by rebuilding with only the buggy logic restored: 18 assertions
fail in MSChromatogram_test and 19 in Mobilogram_test, all passing with
the fix.

Part of #9792

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01APConSDbHrNux6qmuP4oVh
…allers

Review follow-ups on the data-array sync fix.

Headers: the new sort(Predicate) template calls std::stable_sort but the
headers only included <numeric>, relying transitively on another header for
<algorithm>. Both now include it directly.

select() validated data array sizes only after it had already permuted the
peaks, so the advertised Exception::Precondition left the container
half-permuted. Both MSChromatogram::select() and Mobilogram::select() now
validate every index and every non-empty data array size up front, so a
rejected call leaves the container exactly as it was. Out-of-range indices
are rejected as well; MSChromatogram::select previously documented that
"indices are NOT checked for validity", which the rewritten sorts now rely
on. Also switched the string arrays from std::move to copy: duplicate
indices previously yielded an empty string for the second occurrence,
because the source entry had already been moved from.

Three callers rebuilt a container with clear() + push_back and so relied on
the data arrays surviving clear():

- PeakPickerMobilogram::filterPeakIntensities_ (both overloads) and the GUI
  helper filterChrom now use select() instead, which subsets the arrays
  alongside the peaks. Previously the arrays survived but with a stale size;
  after the clear() change they would have been dropped. select() is correct
  under either semantics.
- MSDataCachedConsumer's comment claimed string arrays were preserved by its
  destructive clear. That was already untrue for spectra -- MSSpectrum::clear
  has always cleared all three families -- so the stale comment is corrected
  rather than the behaviour.

Documented that select() does not recompute cached ranges: a permutation
preserves them, but selecting a subset can leave them too wide.

Also corrected an overstated claim in the CHANGELOG: a sort that
short-circuits because the peaks are already in order does not inspect the
data arrays, so a size mismatch is only rejected when the sort actually
permutes.

New tests: duplicate indices, out-of-range indices, container state after a
rejected call, and reverse intensity sort with float arrays present.

Part of #9792

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01APConSDbHrNux6qmuP4oVh
- sort(Predicate): validate data-array sizes up front via a new shared
  checkDataArraySizes_() helper, so a mis-sized array throws
  Exception::Precondition *before* the user predicate can index it out of
  bounds. select() now reuses the same helper and drops its now-redundant
  per-lane size checks. (MSChromatogram, Mobilogram)
- sort() docs: converted from /// to Doxygen /** */ with
  @brief/@tparam/@param/@exception.
- PeakPickerMobilogram::filterPeakIntensities_ (both overloads): reject
  empty/inverted/out-of-range [left,right] before building the keep list.
  An empty mobilogram made findHighestPeak_ return right_index == SIZE_MAX
  (size()-1 underflow), which underflowed the reserve and spun the fill
  loop.
- LayerStoreData::filterChrom: call updateRanges() after select() so a
  filtered chromatogram's cached RT/intensity bounds reflect only the
  retained peaks.
- Tests: tied-key stable-order fixtures for MSChromatogram and Mobilogram
  (assert full peak + string + integer array order for ascending and
  descending sorts, from a start order that defeats every sort
  short-circuit) plus a direct sort(lambda) malformed-array precondition
  test.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NBHPFbi3DC2mFxeRK6VXXU
@coderabbitai

coderabbitai Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d36f1108-5116-40d8-916a-e2905772bb95

📥 Commits

Reviewing files that changed from the base of the PR and between cd19790 and c0fa0f5.

📒 Files selected for processing (3)
  • src/openms/source/ANALYSIS/OPENSWATH/PeakPickerMobilogram.cpp
  • src/openms/source/FORMAT/DATAACCESS/MSDataCachedConsumer.cpp
  • src/openms/source/KERNEL/MSChromatogram.cpp
💤 Files with no reviewable changes (1)
  • src/openms/source/FORMAT/DATAACCESS/MSDataCachedConsumer.cpp
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/openms/source/ANALYSIS/OPENSWATH/PeakPickerMobilogram.cpp
  • src/openms/source/KERNEL/MSChromatogram.cpp

📝 Walkthrough

Walkthrough

The change keeps chromatogram and mobilogram peaks aligned with float, string, and integer data arrays during sorting and selection. It adds size validation, clears parallel arrays consistently, updates filtering callers, and adds regression coverage.

Changes

Peak data alignment

Layer / File(s) Summary
Public sorting and selection contracts
src/openms/include/OpenMS/KERNEL/MSChromatogram.h, src/openms/include/OpenMS/KERNEL/Mobilogram.h
Adds predicate-based sorting and selection APIs, documents stable parallel-array permutation, and defines size-validation and clearing behavior.
Aligned sorting and storage operations
src/openms/source/KERNEL/MSChromatogram.cpp, src/openms/source/KERNEL/Mobilogram.cpp
Sorting preserves peak-associated arrays, selection validates before mutation, duplicate string indices are copied safely, and clear() removes parallel arrays.
Downstream filtering integration
src/openms/source/ANALYSIS/OPENSWATH/PeakPickerMobilogram.cpp, src/openms_gui/source/VISUAL/VISITORS/LayerStoreData.cpp, src/openms/source/FORMAT/DATAACCESS/MSDataCachedConsumer.cpp
Filtering uses validated selection and updates chromatogram ranges; cached consumers rely on clear(false) for array cleanup.
Regression coverage and release notes
src/tests/class_tests/openms/source/MSChromatogram_test.cpp, src/tests/class_tests/openms/source/Mobilogram_test.cpp, CHANGELOG
Tests cover sorting, selection, validation, duplicate indices, stable ordering, and clearing; the changelog records the fixes.

Sequence Diagram(s)

sequenceDiagram
  participant PeakPickerMobilogram
  participant Mobilogram
  participant DataArrays
  PeakPickerMobilogram->>Mobilogram: build selection indices
  PeakPickerMobilogram->>Mobilogram: select(indices)
  Mobilogram->>DataArrays: subset aligned float/string/integer arrays
  Mobilogram-->>PeakPickerMobilogram: filtered mobilogram
Loading

Possibly related PRs

  • OpenMS/OpenMS#9795: Contains directly overlapping sorting, selection, clearing, validation, and PeakPickerMobilogram fixes.

Poem

A rabbit sorts peaks in a neat little line,
With strings and intensities kept in design.
No array gets lost, no values stray,
Selection brings duplicates safely their way.
Clear leaves the garden tidy and bright—
Stable data hops home by night.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 8.33% 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 clearly summarizes the main change: fixing data array misalignment during sort and select operations.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/openms-pr-9795-review-vaqdlr

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.

🧹 Nitpick comments (3)
src/openms/source/FORMAT/DATAACCESS/MSDataCachedConsumer.cpp (1)

50-57: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

The explicit setFloatDataArrays({}) / setIntegerDataArrays({}) calls are now redundant.

clear(false) drops all three parallel array families after this PR, so these two setters no longer do anything. Dropping them keeps a single source of truth for the invariant (the postconditions below still assert it).

Also applies to: 68-75

🤖 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/DATAACCESS/MSDataCachedConsumer.cpp` around lines 50
- 57, Update the clearData_ blocks in the affected consumer paths to rely solely
on s.clear(false), removing the redundant setFloatDataArrays({}) and
setIntegerDataArrays({}) calls while preserving the existing postcondition
assertions.
src/openms/source/KERNEL/MSChromatogram.cpp (1)

115-147: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

MSChromatogram::sortByIntensity() has no already-sorted short-circuit, which also makes the CHANGELOG claim inaccurate. sortByPosition() (Line 151) and Mobilogram::sortByIntensity() both return early when the peaks are already ordered; the chromatogram intensity sort always permutes, so it always runs checkDataArraySizes_() and throws on a mis-sized array even for already-sorted input.

  • src/openms/source/KERNEL/MSChromatogram.cpp#L115-L147: add an std::is_sorted early return (ascending and reverse comparators) before the fast path, mirroring Mobilogram::sortByIntensity().
  • CHANGELOG#L20: the sentence "a sort that short-circuits because the peaks are already in order does not inspect the arrays" only holds once the guard above is added — otherwise reword it to exclude MSChromatogram::sortByIntensity().
🤖 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/KERNEL/MSChromatogram.cpp` around lines 115 - 147, Add an
std::is_sorted early return at the start of MSChromatogram::sortByIntensity(bool
reverse), using comparators for both ascending and reverse intensity order,
before the fast-path/data-array handling. Update CHANGELOG line 20 to ensure its
statement about already-ordered sorts not inspecting arrays is accurate, either
by reflecting the new chromatogram guard or excluding
MSChromatogram::sortByIntensity() if appropriate.
src/openms/source/ANALYSIS/OPENSWATH/PeakPickerMobilogram.cpp (1)

265-285: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider logging when the bounds guard skips filtering.

Both overloads now silently leave the mobilogram unfiltered on empty/inverted/out-of-range bounds, so the caller gets the full mobilogram back with no indication that top-peak filtering did not happen. An OPENMS_LOG_DEBUG line here would make that diagnosable; std::iota would also replace the manual keep loop.

Also applies to: 287-307

🤖 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/OPENSWATH/PeakPickerMobilogram.cpp` around lines
265 - 285, Update both mobilogram filtering overloads to emit an
OPENMS_LOG_DEBUG message when the empty, inverted, or out-of-range bounds guard
returns without filtering, including enough context to diagnose the skipped
top-peak selection. Preserve the existing untouched-mobilogram behavior, and
replace the manual keep-index loop with std::iota where applicable.
🤖 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/ANALYSIS/OPENSWATH/PeakPickerMobilogram.cpp`:
- Around line 265-285: Update both mobilogram filtering overloads to emit an
OPENMS_LOG_DEBUG message when the empty, inverted, or out-of-range bounds guard
returns without filtering, including enough context to diagnose the skipped
top-peak selection. Preserve the existing untouched-mobilogram behavior, and
replace the manual keep-index loop with std::iota where applicable.

In `@src/openms/source/FORMAT/DATAACCESS/MSDataCachedConsumer.cpp`:
- Around line 50-57: Update the clearData_ blocks in the affected consumer paths
to rely solely on s.clear(false), removing the redundant setFloatDataArrays({})
and setIntegerDataArrays({}) calls while preserving the existing postcondition
assertions.

In `@src/openms/source/KERNEL/MSChromatogram.cpp`:
- Around line 115-147: Add an std::is_sorted early return at the start of
MSChromatogram::sortByIntensity(bool reverse), using comparators for both
ascending and reverse intensity order, before the fast-path/data-array handling.
Update CHANGELOG line 20 to ensure its statement about already-ordered sorts not
inspecting arrays is accurate, either by reflecting the new chromatogram guard
or excluding MSChromatogram::sortByIntensity() if appropriate.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 25ad9462-1af3-4065-b114-d45a0d6be3a5

📥 Commits

Reviewing files that changed from the base of the PR and between 70f5a18 and 4a15718.

📒 Files selected for processing (10)
  • CHANGELOG
  • src/openms/include/OpenMS/KERNEL/MSChromatogram.h
  • src/openms/include/OpenMS/KERNEL/Mobilogram.h
  • src/openms/source/ANALYSIS/OPENSWATH/PeakPickerMobilogram.cpp
  • src/openms/source/FORMAT/DATAACCESS/MSDataCachedConsumer.cpp
  • src/openms/source/KERNEL/MSChromatogram.cpp
  • src/openms/source/KERNEL/Mobilogram.cpp
  • src/openms_gui/source/VISUAL/VISITORS/LayerStoreData.cpp
  • src/tests/class_tests/openms/source/MSChromatogram_test.cpp
  • src/tests/class_tests/openms/source/Mobilogram_test.cpp

…ers, filter-skip logging

- MSChromatogram::sortByIntensity(): add the already-sorted std::is_sorted
  short-circuit that sortByPosition() and Mobilogram::sortByIntensity() already
  have. All four sort entry points now skip the permutation (and thus the
  data-array validation) when the peaks are already ordered, which also makes the
  CHANGELOG's "a short-circuiting sort does not inspect the arrays" statement
  accurate for this method.
- MSDataCachedConsumer: drop the now-redundant setFloatDataArrays({}) /
  setIntegerDataArrays({}) calls after clear(false), which already drops all
  parallel arrays -- clear() is the single source of truth. The postconditions
  still assert the invariant.
- PeakPickerMobilogram::filterPeakIntensities_ (both overloads): log at DEBUG when
  the bounds guard skips filtering (the caller otherwise gets the unfiltered
  mobilogram back with no indication), and build the keep list with std::iota.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NBHPFbi3DC2mFxeRK6VXXU
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