Skip to content

[FIX] MSChromatogram/Mobilogram: keep binary data arrays in sync with the peaks on sort and clear - #9795

Merged
timosachsenberg merged 5 commits into
developfrom
fix/chromatogram-mobilogram-dataarray-sync
Jul 26, 2026
Merged

timosachsenberg merged 5 commits into
developfrom
fix/chromatogram-mobilogram-dataarray-sync

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Fixes the correctness bugs recorded as Part V of #9792, in the core library rather than in the bindings.

The bugs

1. MSChromatogram::sortByPosition() — fast path guarded on float arrays alone

if (float_data_arrays_.empty())   // string_ and integer_ ignored
{
  std::sort(ContainerType::begin(), ContainerType::end(), PeakType::PositionLess());
}

A chromatogram with string or integer data arrays but no float array had its peaks reordered while the arrays stayed put.

This is reachable on the mzML load path. MzMLHandler populates chromatogram integer and string binary data arrays (MzMLHandler.cpp:603-683) and then calls sortByPosition() when sort_chromatograms_by_rt is set (:221-223). The mis-associated arrays are then written back out on store (:5712-5725), so the corruption round-trips to disk.

2. MSChromatogram::sortByIntensity() — inverted guard

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

The two ! are inverted. This takes the metadata-ignoring fast path precisely when string and integer arrays exist, and takes the slow path when no metadata exists at all (merely wasteful).

3. Mobilogram::sortByIntensity() / sortByPosition() — arrays never touched

Both were a bare stable_sort over the peaks; none of the three array families were permuted. No in-tree caller sorts a Mobilogram, so this is latent in C++ — but both sorts and all three array accessors are exposed via pyOpenMS, and the binding docstring already promised "Meta data arrays will be sorted accordingly".

4. Mobilogram::clear() and MSChromatogram::clear(false) — arrays survive the peaks

Both dropped the peaks while retaining the parallel data arrays, leaving the container internally inconsistent. MSSpectrum::clear() already clears them unconditionally, using its flag only for shrink_to_fit and descriptive settings; the two siblings disagreed with it and with each other.

This also removes a latent accumulation bug in PeakPickerMobilogram, which does clear() → resize() → push_back (:85, :122, :136-140) and would have appended to stale entries on any reuse of the output Mobilogram.

The fix

Reuse the approach MSSpectrum already uses rather than inventing one: a select(indices) that permutes peaks and all three array families with size validation, plus a sort(Predicate) helper that is iota + stable_sort + select.

  • MSChromatogram already had select() — the sorts simply never called it. Added the sort(Predicate) helper and rewrote both sorts as all-three-empty → stable_sort, else sort(cmp). This deletes ~80 lines of hand-rolled permutation, which is where both guard bugs lived.
  • Mobilogram had neither, so select() and sort(Predicate) were added. Its class test already contained a placeholder START_SECTION(template<class Predicate> void sort(const Predicate& lambda)) marked NOT_TESTABLE, which is now a real test.
  • Both clear() variants now clear the arrays and ranges, matching MSSpectrum::clear().

Behavior changes

  1. MSChromatogram sorting is now stable (std::sort → std::stable_sort), matching MSSpectrum. Deterministic tie order.
  2. A mis-sized data array now throws Exception::Precondition instead of silently corrupting the association — for a sort that actually permutes. A sort that short-circuits because the peaks are already in order does not inspect the arrays, so it still passes silently.
  3. MSChromatogram::clear(false) now clears data arrays and ranges; clear_meta_data governs only ChromatogramSettings and the name.
  4. Mobilogram::clear() now clears the data arrays.

Verification

I rebuilt with only the buggy logic restored (keeping the new members so the tests still compile) and ran the new tests against it:

buggy build fixed build
MSChromatogram_test 18 assertions fail pass
Mobilogram_test 19 assertions fail pass

The failure values show the defect directly — e.g. after sortByPosition() on peaks in RT order 3,1,2:

line 380: TEST_STRING_EQUAL(c.getStringDataArrays()[0][0],"rt1"): got "rt3", expected "rt1"
line 383: TEST_EQUAL(c.getIntegerDataArrays()[0][0],1):          got '3',   expected '1'

The peaks sorted; the metadata stayed in its original order.

New coverage: per-class sections asserting that sortByPosition, sortByIntensity and sortByIntensity(reverse=true) permute peaks and every array family, that array names survive, that a size mismatch throws, and that clear() empties the arrays; plus real tests for Mobilogram::select() and Mobilogram::sort(Predicate).

Review follow-ups

A review pass over this branch turned up several further issues, all fixed here:

  • MSChromatogram.h / Mobilogram.h used std::stable_sort in the new sort(Predicate) template but only included <numeric>, relying transitively on another header for <algorithm>. Both now include it directly.
  • select() validated array sizes after it had already permuted the peaks, so the advertised exception left the object half-permuted. Both classes now validate all indices and all array sizes up front, so a rejected call leaves the container untouched. Out-of-range indices are now rejected too, rather than being undefined behaviour (MSChromatogram::select previously documented "indices are NOT checked for validity").
  • select() moved out of std::string entries, so duplicate indices produced empty strings for the second occurrence. String arrays are now copied.
  • Three callers relied on clear() leaving the data arrays behind. PeakPickerMobilogram::filterPeakIntensities_ (both overloads) and the GUI's filterChrom rebuilt a container with clear() + push_back, which previously left the arrays present but mis-sized and would now drop them; both now use select(), which is correct in either case. MSDataCachedConsumer's comment claimed string arrays were preserved — that was already untrue for spectra (MSSpectrum::clear has always cleared all three families), so the comment is corrected rather than the behaviour.
  • select() does not recompute cached ranges. A permutation preserves them; a subset can leave them too wide. Now documented on both declarations.

Scope

Core-library fix only. The pyOpenMS ownership/lifetime design questions stay in #9792; the iterator use-after-free was fixed separately in #9794.

🤖 Generated with Claude Code

https://claude.ai/code/session_01APConSDbHrNux6qmuP4oVh

Summary by CodeRabbit

  • Bug Fixes
    • Fixed chromatogram and mobilogram sorting/subsetting to keep per-peak float/string/integer metadata aligned.
    • Made sorting stable (preserves relative order for ties).
    • Corrected clear() behavior so it consistently removes peaks and their associated parallel data (and metadata when requested).
    • Added safeguards so invalid peak/array sizes or selections fail with clear precondition errors instead of risking corruption.
  • New Features
    • Added stable, predicate-based sort and index-based select for both chromatograms and mobilograms.
  • Improvements
    • Updated peak intensity filtering and GUI RT-window filtering to use index-based subsetting while preserving alignment.
  • Tests
    • Expanded regression and edge-case coverage for sorting/selection/clearing behavior.

@coderabbitai

coderabbitai Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

MSChromatogram and Mobilogram sorting now stably reorder peaks with parallel data arrays. Clearing removes associated arrays, selection validates inputs before mutation, and filtering uses index-based selection. Tests cover synchronization, metadata preservation, duplicates, clearing, and precondition exceptions.

Changes

Peak and parallel-data consistency

Layer / File(s) Summary
Stable sorting with parallel arrays
src/openms/include/OpenMS/KERNEL/{MSChromatogram,Mobilogram}.h, src/openms/source/KERNEL/{MSChromatogram,Mobilogram}.cpp, src/tests/class_tests/openms/source/*_test.cpp
Index-based stable sorting reorders peaks and float, string, and integer arrays together, with fast paths when auxiliary arrays are empty.
Clearing and validated selection
src/openms/include/OpenMS/KERNEL/{MSChromatogram,Mobilogram}.h, src/openms/source/KERNEL/{MSChromatogram,Mobilogram}.cpp, src/tests/class_tests/openms/source/*_test.cpp
Clearing removes parallel arrays, while selection validates indices and array sizes before rebuilding selected peak and metadata entries.
Filtering integration and regression coverage
src/openms/source/ANALYSIS/OPENSWATH/PeakPickerMobilogram.cpp, src/openms_gui/source/VISUAL/VISITORS/LayerStoreData.cpp, src/openms/source/FORMAT/DATAACCESS/MSDataCachedConsumer.cpp, CHANGELOG
Filtering now uses index-based selection; range checks, comments, tests, and the changelog cover synchronization and precondition behavior.

Sequence Diagram(s)

sequenceDiagram
  participant PeakPickerMobilogram
  participant Mobilogram
  participant PeakDataArrays
  PeakPickerMobilogram->>Mobilogram: select(keep_indices)
  Mobilogram->>PeakDataArrays: validate sizes and select matching entries
  PeakDataArrays-->>Mobilogram: synchronized filtered arrays
  Mobilogram-->>PeakPickerMobilogram: filtered mobilogram
Loading

Possibly related issues

Possibly related PRs

  • OpenMS/OpenMS#9799 — Implements closely related sorting, selection, clearing, and PeakPickerMobilogram consistency changes.

Suggested reviewers: cbielow

Poem

I’m a rabbit with peaks in a line,
Each label stays paired and fine.
Select, sort, and clear with care,
No stray carrots hiding there.
Stable hops make data shine!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 9.09% 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 fix: keeping MSChromatogram and Mobilogram data arrays synchronized during sort and clear 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 unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/chromatogram-mobilogram-dataarray-sync

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

🧹 Nitpick comments (1)
src/openms/include/OpenMS/KERNEL/MSChromatogram.h (1)

221-233: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Both new inline sort() templates call std::stable_sort while only <numeric> was added. The shared root cause is that the sorting logic moved into the headers, but the <algorithm> include stayed in the .cpp files, leaving header consumers dependent on transitive includes.

  • src/openms/include/OpenMS/KERNEL/MSChromatogram.h#L221-L233: add #include <algorithm> alongside <numeric> at the top of the header.
  • src/openms/include/OpenMS/KERNEL/Mobilogram.h#L367-L379: add #include <algorithm> alongside <numeric> at the top of the header.
🤖 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/include/OpenMS/KERNEL/MSChromatogram.h` around lines 221 - 233,
Both inline sort templates use std::stable_sort without directly including its
declaration. Add the <algorithm> header alongside <numeric> in
src/openms/include/OpenMS/KERNEL/MSChromatogram.h (anchor, lines 221-233) and
src/openms/include/OpenMS/KERNEL/Mobilogram.h (sibling, lines 367-379); no
changes to the sort implementations are needed.
🤖 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/include/OpenMS/KERNEL/Mobilogram.h`:
- Around line 580-589: The pyOpenMS test suite lacks coverage for the Mobilogram
bindings’ generic sort() and select() methods. Add tests for both APIs that
construct mobilograms with associated data arrays, invoke sorting and
selecting/reordering, and assert the peaks and data-array values remain
correctly reordered and aligned; follow the existing Mobilogram.addon test
patterns.

In `@src/openms/source/KERNEL/Mobilogram.cpp`:
- Around line 483-484: Update the Mobilogram::select() path so cached ranges are
refreshed when the selected peak count differs from the original count; invoke
the existing updateRanges() mechanism after shrinking the mobilogram, while
preserving the current return behavior.
- Around line 404-437: In Mobilogram::select, validate every non-empty
float_data_arrays_ lane against data_.size() before moving or swapping any data,
so a mismatch leaves the mobilogram unchanged; then remove the now-redundant
checks from the permutation loop. Apply the same validation-before-mutation
ordering in MSChromatogram::select, preserving existing exception behavior and
selection logic.

In `@src/tests/class_tests/openms/source/MSChromatogram_test.cpp`:
- Around line 353-411: Expand the sortByPosition and sortByIntensity tests
around the existing make fixture with tied RT and intensity values, then assert
the complete resulting order of peaks plus corresponding string and integer data
arrays for ascending and reverse sorts. Ensure the fixtures also verify stable
ordering among equal keys, including all positions rather than only endpoints.

---

Nitpick comments:
In `@src/openms/include/OpenMS/KERNEL/MSChromatogram.h`:
- Around line 221-233: Both inline sort templates use std::stable_sort without
directly including its declaration. Add the <algorithm> header alongside
<numeric> in src/openms/include/OpenMS/KERNEL/MSChromatogram.h (anchor, lines
221-233) and src/openms/include/OpenMS/KERNEL/Mobilogram.h (sibling, lines
367-379); no changes to the sort implementations are needed.
🪄 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: 6ef63f4d-28cc-4f92-a96b-ca41ae8f46eb

📥 Commits

Reviewing files that changed from the base of the PR and between ea03681 and ab0c80d.

📒 Files selected for processing (7)
  • CHANGELOG
  • src/openms/include/OpenMS/KERNEL/MSChromatogram.h
  • src/openms/include/OpenMS/KERNEL/Mobilogram.h
  • src/openms/source/KERNEL/MSChromatogram.cpp
  • src/openms/source/KERNEL/Mobilogram.cpp
  • src/tests/class_tests/openms/source/MSChromatogram_test.cpp
  • src/tests/class_tests/openms/source/Mobilogram_test.cpp

Comment thread src/openms/source/KERNEL/Mobilogram.cpp Resolved
Comment thread src/openms/source/KERNEL/Mobilogram.cpp Resolved

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

359-369: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Apply the required C++ brace and indentation style.

  • src/openms/source/KERNEL/MSChromatogram.cpp#L359-L369: put the validation-lambda body braces on separate aligned lines.
  • src/openms/source/KERNEL/Mobilogram.cpp#L117-L160: format the newly added sort-lambda bodies with aligned standalone braces.
  • src/openms/source/KERNEL/Mobilogram.cpp#L420-L430: format the validation-lambda body with aligned standalone braces.
  • src/openms/source/ANALYSIS/OPENSWATH/PeakPickerMobilogram.cpp#L267-L289: use 2-space indentation and standalone braces for the new loops.

As per coding guidelines: “format C++ with 2-space indentation … and braces on their own aligned lines.”

🤖 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 359 - 369, Apply
the required C++ formatting: in src/openms/source/KERNEL/MSChromatogram.cpp
lines 359-369, place the validation lambda body braces on separate aligned
lines; in src/openms/source/KERNEL/Mobilogram.cpp lines 117-160, format the new
sort-lambda bodies with standalone aligned braces; in
src/openms/source/KERNEL/Mobilogram.cpp lines 420-430, format the validation
lambda similarly; and in
src/openms/source/ANALYSIS/OPENSWATH/PeakPickerMobilogram.cpp lines 267-289, use
2-space indentation and standalone aligned braces for the new loops.

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/KERNEL/MSChromatogram.cpp`:
- Around line 359-369: Apply the required C++ formatting: in
src/openms/source/KERNEL/MSChromatogram.cpp lines 359-369, place the validation
lambda body braces on separate aligned lines; in
src/openms/source/KERNEL/Mobilogram.cpp lines 117-160, format the new
sort-lambda bodies with standalone aligned braces; in
src/openms/source/KERNEL/Mobilogram.cpp lines 420-430, format the validation
lambda similarly; and in
src/openms/source/ANALYSIS/OPENSWATH/PeakPickerMobilogram.cpp lines 267-289, use
2-space indentation and standalone aligned braces for the new loops.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: cc91d97b-7b44-4221-b45c-989f75f020d5

📥 Commits

Reviewing files that changed from the base of the PR and between ab0c80d and f6202a5.

📒 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
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/openms/include/OpenMS/KERNEL/MSChromatogram.h
  • src/tests/class_tests/openms/source/MSChromatogram_test.cpp
  • src/openms/include/OpenMS/KERNEL/Mobilogram.h
  • src/tests/class_tests/openms/source/Mobilogram_test.cpp

@timosachsenberg
timosachsenberg force-pushed the fix/chromatogram-mobilogram-dataarray-sync branch from f6202a5 to d3a3c32 Compare July 25, 2026 23:02

@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

🧹 Nitpick comments (1)
src/openms/source/ANALYSIS/OPENSWATH/PeakPickerMobilogram.cpp (1)

271-273: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use the repository’s required brace placement.

Place the for braces on their own aligned lines.

As per coding guidelines, “braces on their own aligned lines; always use braces for blocks.”

Also applies to: 281-289

🤖 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
271 - 273, Update the loops around the visible for statement, including the
additionally referenced loop, to place opening and closing braces on their own
aligned lines while preserving the existing loop bodies and mandatory-braces
style.

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_gui/source/VISUAL/VISITORS/LayerStoreData.cpp`:
- Around line 92-93: Update the filtering logic around the LayerStoreData
operation that assigns out = in and calls out.select(keep) to invoke
out.updateRanges() afterward, ensuring cached RT/intensity bounds reflect only
retained peaks. Add a regression test assertion verifying the filtered
chromatogram ranges are recomputed correctly.

In `@src/openms/source/ANALYSIS/OPENSWATH/PeakPickerMobilogram.cpp`:
- Around line 269-274: Validate left_index and right_index for each target
mobilogram before the keep.reserve and loop in the mobilogram selection logic,
including the corresponding block around the second range. Reject or skip ranges
where right_index is SIZE_MAX, either bound is outside the mobilogram, or
right_index is less than left_index, preventing size underflow and
non-terminating iteration before calling mobilogram.select(keep).

---

Nitpick comments:
In `@src/openms/source/ANALYSIS/OPENSWATH/PeakPickerMobilogram.cpp`:
- Around line 271-273: Update the loops around the visible for statement,
including the additionally referenced loop, to place opening and closing braces
on their own aligned lines while preserving the existing loop bodies and
mandatory-braces style.
🪄 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: 760c8c3f-6a37-474f-899d-f1e7032890b7

📥 Commits

Reviewing files that changed from the base of the PR and between f6202a5 and d3a3c32.

📒 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
🚧 Files skipped from review as they are similar to previous changes (8)
  • src/openms/source/FORMAT/DATAACCESS/MSDataCachedConsumer.cpp
  • src/openms/include/OpenMS/KERNEL/MSChromatogram.h
  • src/tests/class_tests/openms/source/Mobilogram_test.cpp
  • src/openms/include/OpenMS/KERNEL/Mobilogram.h
  • CHANGELOG
  • src/tests/class_tests/openms/source/MSChromatogram_test.cpp
  • src/openms/source/KERNEL/Mobilogram.cpp
  • src/openms/source/KERNEL/MSChromatogram.cpp

timosachsenberg and others added 2 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
@timosachsenberg
timosachsenberg force-pushed the fix/chromatogram-mobilogram-dataarray-sync branch from d3a3c32 to 09e9693 Compare July 26, 2026 02:55

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/openms/include/OpenMS/KERNEL/MSChromatogram.h`:
- Around line 230-233: Update the sorting method around the indices/lambda
stable_sort to validate all parallel-array sizes before invoking the user
predicate. Extract select()’s existing size validation into a shared helper,
call it before std::stable_sort, and add a regression test covering malformed
arrays with a lambda sort that must raise Exception::Precondition.
- Around line 222-228: Update the public MSChromatogram::sort template
documentation from the current `///` block to a `/** */` Doxygen block with a
required `@brief`. Add `@tparam` documentation for Predicate and `@param`
documentation for lambda, including that it may raise `Exception::Precondition`,
while preserving the existing sorting and data-array behavior details.
🪄 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: a176bfc0-96b0-46fd-95cd-147c0a3027d2

📥 Commits

Reviewing files that changed from the base of the PR and between d3a3c32 and 09e9693.

📒 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
🚧 Files skipped from review as they are similar to previous changes (7)
  • src/openms/source/FORMAT/DATAACCESS/MSDataCachedConsumer.cpp
  • CHANGELOG
  • src/openms/source/ANALYSIS/OPENSWATH/PeakPickerMobilogram.cpp
  • src/openms/source/KERNEL/Mobilogram.cpp
  • src/openms/include/OpenMS/KERNEL/Mobilogram.h
  • src/tests/class_tests/openms/source/MSChromatogram_test.cpp
  • src/openms/source/KERNEL/MSChromatogram.cpp

claude added 2 commits July 26, 2026 07:29
- 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
…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
@timosachsenberg
timosachsenberg merged commit f9c181c into develop Jul 26, 2026
22 checks passed
@timosachsenberg
timosachsenberg deleted the fix/chromatogram-mobilogram-dataarray-sync branch July 26, 2026 09:14
timosachsenberg added a commit that referenced this pull request Jul 28, 2026
…rings (#9812)

* docs(pyOpenMS): fix stale/missing MSChromatogram and Mobilogram docstrings

MSChromatogram.findNearest() carried a copy-pasted sortByPosition()
docstring instead of describing its own binary-search-nearest-RT
behavior. MSChromatogram.clear()/sortByIntensity() and
Mobilogram.sortByPosition()/sortByIntensity() had no docstring at all,
and Mobilogram.clear() still said "Clear all peaks" even though #9795
made it also clear the parallel data arrays. Bring all of these in
line with the corresponding Doxygen comments in MSChromatogram.h /
Mobilogram.h.

* fix: apply CodeRabbit auto-fixes

Fixed 2 file(s) based on 4 unresolved review comments.

Co-authored-by: CodeRabbit <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: CodeRabbit <[email protected]>
timosachsenberg added a commit that referenced this pull request Aug 6, 2026
…feature (#9881)

The 3.6 section had grown to 217 KB (22x the 3.5 section), mostly because
recent entries were appended verbatim as PR-body-style root-cause writeups,
with newest entries prepended to "General:" regardless of topic.

Collapse incremental/superseded PR chains into one entry per feature:

  - QPX Parquet export: ~30 entries across #9692-#9878 (long-format
    conversion, run_file_name resolution, validation, transactional writes,
    streaming/parallel build) reduced to a 6-item block. The export is new in
    3.6, so the intermediate fixes never shipped to users.
  - ProteinQuantifier/PeptideAndProteinQuant: the per-assay grain change,
    fractions:aggregate, best_charge rename, the same undetected-peptide
    aggregation defect fixed at three levels, and the perf work bundled.
  - pyOpenMS nanobind lifetime/use-after-free work (#9792, #9794, #9795).
  - ProSE: 30 entries down to 17, grouped by search modes, calibration,
    FDR, Percolator and FragmentIndex.
  - Bruker TimsTOF, IMAGING, ThermoRawFile and the native Parquet formats
    each get one nested block instead of scattered entries.
  - ~20 near-identical per-tool ".idparquet/.featureparquet support" and
    "Thermo .raw input" entries folded into "TOPP tools > all:".

Remove exact duplicates (ProteinQuantifier -ratios removal, Annotation1DItem
DLLAPI, ConsensusMapArrowExport streaming, macOS pkg notarization, Qt removal
steps duplicated between General/Dependencies/Build System, IsoelectricPoint
and IMAGING multi-region duplicated between General and OpenMS Library).

File misplaced entries into the sections they belong to and add a GUI tools
section, matching the structure used by 3.5 and earlier releases.

Net: 217 KB -> 82 KB with all 440 distinct PR references preserved; the five
dropped refs are CI-internal test guards and a historical bug reference.


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

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.

2 participants