Skip to content

[FIX] pyOpenMS: set_peaks() metadata alignment, plus a writable ion mobility dimension (#9792 R-6.2) - #9808

Merged
timosachsenberg merged 4 commits into
developfrom
fix/9792-set-peaks-metadata-alignment
Jul 27, 2026
Merged

timosachsenberg merged 4 commits into
developfrom
fix/9792-set-peaks-metadata-alignment

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Closes item R-6.2 of #9792 — the last open piece of that issue's step 2. It was struck through in error when #9795 landed; #9795 fixed MSChromatogram/Mobilogram sorting and clear(), which is a different defect.

The defect

set_peaks() replaced the peak table without touching the parallel binary data arrays, so replacing the peaks of a container that carried a float, string or integer data array left it silently inconsistent:

spec.setFloatDataArrays([im_array])   # 100 entries, aligned with 100 peaks
spec.set_peaks((mz5, int5))           # 5 peaks -- array still has 100 entries

Nothing was reported at the call. The damage surfaced only later and elsewhere: as an Exception::Precondition from a subsequent sortByPosition()/select() (the check #9795 added), or as an mzML file written with a mis-sized binary data array.

The fix

All six overloads — MSSpectrum, MSChromatogram, Mobilogram, in both the two-array and the sequence spelling — take a metadata= policy:

value behaviour
"error" (default) refuse the call, leaving the container completely untouched
"clear" drop the arrays the new count stranded
"keep" the previous behaviour, opted into explicitly

The policy applies only when a non-empty data array's size differs from the new peak count. The predicate is MSChromatogram::checkDataArraySizes_()'s, empty-array exemption included, so this moves the core's own rejection to the call that causes it rather than imposing a stricter rule. Containers without data arrays are unaffected, and replacing peaks with an equally long set keeps its arrays under every policy — that is both the in-place edit idiom (recalibrate m/z, renormalise intensity) and the guarantee 7215fc7 added for bug #5876, which tests/unittests/test_IonMobilityData.py:135 depends on.

Why "error" and not "clear" as the default

Silently dropping annotations is the worse failure mode. An exception cannot regress a working program, because every case it fires on is already corrupt; a silent clear would hand back a spectrum missing the ion-mobility array the caller believes it still has. PYOPENMS_VIEW_FIRST_API_PROPOSAL.md already specified metadata="error" # default.

Ordering, which is where this is easy to get wrong

  • The check runs against the incoming count and before resize(), so a rejected call is a strict no-op. Checking self.size() instead would compare the arrays against the count they are still aligned with, and would accept the very case this exists to catch.
  • It runs after the existing mz/intensity length check, so mismatched inputs with metadata="clear" cannot drop the arrays and then fail.
  • The "clear" drop runs after the peaks are written. FloatDataArray.get_data_view() is zero-copy and getFloatDataArrays() hands out the container's own arrays, so spec.set_peaks(mz, spec.getFloatDataArrays()[0].get_data_view()[:n], metadata="clear") passes in a view of the very storage the policy releases — dropping first left the fill loop reading freed memory. Deferring also means a throwing resize() cannot leave the arrays already gone.

set_peaks(peaks, "clear") — the policy positionally alongside the sequence spelling — binds to the two-argument overload, which is registered first. The sequence overload's metadata is nb::kw_only() so its signature does not advertise a positional it rejects, and the two-argument overload diagnoses the mistake by name instead of failing inside the numpy conversion. bytes is diagnosed too, since the shared std::string caster accepts it.

Tests

267 regression tests in a new test_set_peaks_metadata_alignment.py, over all three containers × all three call spellings (two arrays, tuple, list — Mobilogram's sequence overload is a hand-written tuple/list branch rather than the generic one the other two use) × all three array families. 81 fail with the policy stubbed out, i.e. against the previous behaviour, while the ones guarding unchanged paths keep passing.

Full pyOpenMS suite green: 5651 passed, 0 failed.

The two test000.py blocks added by 7215fc7 as the #5876 regression guard now pass metadata="keep", which preserves their assertions verbatim while making the semantic change explicit at the call site.

Deliberately not addressed here

Reviewed with Codex, which caught the "clear" use-after-free and the unconditional-clear/docstring contradiction; both are fixed in the second commit.

Summary by CodeRabbit

  • New Features
    • Added per-peak ion mobility support for spectra, including set_drift_time_array() and set_peaks(..., ion_mobility=..., ion_mobility_unit=...).
    • Extended set_peaks() with a metadata= policy (error default, clear, keep) for spectra, chromatograms, and mobilograms.
  • Bug Fixes
    • Peak replacement now prevents inconsistent per-peak metadata; invalid inputs fail without changing the spectrum, while clear removes only stranded metadata.
  • Tests
    • Added regression coverage for metadata alignment/atomicity and ion mobility writing, including mzML round-trips and sortByPosition() behavior.

Second part: a writable ion mobility dimension

Added on request, because it is the same storage: the per-peak ion mobility array is a float data array, so it is governed by the policy above.

pyOpenMS could read ion mobility five ways — containsIMData(), getIMData(), get_drift_time_array(), get_drift_time_array_view(), rasterizeIMFrame() — and could not write it at all. The only route was the generic data-array API with the name spelled by hand:

fda = FloatDataArray()
fda.set_data(im)
fda.setName("Ion Mobility")     # this string is the entire contract
spec.setFloatDataArrays([fda])

Getting that string subtly wrong changes the unit rather than failing. IMDataConverter::getIMUnit() prefix-matches the legacy names and falls back to MILLISECOND when no CV accession is embedded, so labelling TIMS 1/K0 data "Ion Mobility" reports it as drift time in milliseconds.

What is new

spec.set_peaks(mz, intensity, ion_mobility=im, ion_mobility_unit=DriftTimeUnit.VSSC)
spec.set_drift_time_array(im, DriftTimeUnit.MILLISECOND)

Both name the array through IMDataConverter::setIMUnit() — from the PSI-MS CV, not a literal — so what is written is what getIMData() reads back and what survives an mzML round-trip ("mean ion mobility array" for MILLISECOND, "raw inverse reduced ion mobility array" for VSSC). The CV has no ion-mobility-array term for the other units, so CCS and FAIMS compensation voltage are rejected rather than given an invented name; that is the core's own documented rule, inherited rather than worked around.

  • An existing array is replaced in place, not appended — a second one would make getIMData() ambiguous.
  • ion_mobility_unit may be omitted when there is an existing array to inherit the unit from, which is the in-place mobility-edit case; with nothing to inherit from it raises rather than guessing.
  • The array is built and its unit resolved before anything is modified, so a wrong length or an unsupported unit leaves the spectrum untouched.

Where the two halves meet

An ion mobility array that set_peaks() is about to overwrite is exempt from the alignment check — you cannot strand an array you are replacing, and refusing would leave no way to change the peak count and the mobilities in one step:

spec.set_peaks(mz5, int5, ion_mobility=im5)   # old 100-entry IM array replaced, not rejected
spec.set_peaks(mz5, int5)                     # still rejected -- nothing is replacing it

The exemption is scoped to that one array, so a stale string or integer array in the same call is still reported. Both directions are tested.

Deliberately not changed

setDriftTime()/setDriftTimeUnit() are untouched. They describe a spectrum acquired at a single drift time, not a per-peak annotation, and a frame carrying an ion mobility array leaves them unset — matching what IMDataConverter::reshapeIMFrameToSingle() produces. (Worth knowing separately: get_drift_time_unit() gates on containsIMData(), an array property, but returns that scalar, so it reports NONE for a frame whose array says 1/K0. Pre-existing, not touched here.)

IMDataConverter itself remains unwrapped; only its naming helper is used, from C++.

32 tests in test_set_ion_mobility.py, including an mzML round-trip per supported unit. Full pyOpenMS suite: 5682 passed, 0 failed.

@timosachsenberg

Copy link
Copy Markdown
Contributor Author

If we want to tighten the contract here it needs to be done in the OpenMS library. It deliberately has data arrays that might have different sizes (e.g. for peak annotations, etc.)

@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

pyOpenMS set_peaks() now supports metadata policies across MSSpectrum, MSChromatogram, and Mobilogram. MSSpectrum also supports writing per-peak ion mobility through set_drift_time_array() and set_peaks().

Changes

Peak metadata and ion-mobility writing

Layer / File(s) Summary
Metadata policy contract
src/pyOpenMS/bindings/binding_utils.h
Adds "error", "clear", and "keep" policies with alignment validation, strict no-op rejection, and stranded-array cleanup.
MSSpectrum ion-mobility integration
src/pyOpenMS/bindings/bind_spectrum.cpp
Adds set_drift_time_array() and ion-mobility parameters to set_peaks(), including unit resolution, replacement, and atomic validation.
Chromatogram and mobilogram integration
src/pyOpenMS/bindings/bind_chromatogram.cpp, src/pyOpenMS/bindings/bind_kernel.cpp
Adds metadata-aware overloads that validate before resizing and clean stranded metadata after peak writes.
Regression validation and documentation
src/pyOpenMS/tests/unittests/*, CHANGELOG, src/pyOpenMS/tests/unittests/test000.py
Covers policy behavior, no-op failures, aliasing, ion-mobility persistence and sorting, and updated compatibility calls.

Sequence Diagram(s)

sequenceDiagram
  participant PythonCaller
  participant SetPeaksBinding
  participant MetadataHelpers
  participant IonMobilityData
  PythonCaller->>SetPeaksBinding: set_peaks(peaks, metadata=policy, ion_mobility=values)
  SetPeaksBinding->>IonMobilityData: validate values and unit
  SetPeaksBinding->>MetadataHelpers: check metadata alignment
  MetadataHelpers-->>SetPeaksBinding: accept or raise
  SetPeaksBinding->>SetPeaksBinding: write peaks
  SetPeaksBinding->>MetadataHelpers: drop stranded arrays
  SetPeaksBinding->>IonMobilityData: install or replace IM array
Loading

Possibly related issues

Poem

A rabbit hops through peaks in line,
With tidy tags and drift-time shine.
“Error,” “clear,” or “keep” they say,
While ion trails sort their way.
Tests bounce happily through the hay.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 73.47% 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 two main changes: metadata alignment handling and writable ion mobility support.
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 fix/9792-set-peaks-metadata-alignment

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

🤖 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/pyOpenMS/bindings/binding_utils.h`:
- Around line 294-318: Update dropStrandedPeakMetadata so it does not erase
elements directly from the vectors returned by getFloatDataArrays(),
getStringDataArrays(), or getIntegerDataArrays(). Materialize each mutable
data-array vector before filtering, remove stranded arrays by value, then
restore the resulting vector through the container so reference_internal-indexed
Python objects retain valid ownership.
🪄 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: d41e50e1-b5f7-4632-a77a-e5313b6e43f2

📥 Commits

Reviewing files that changed from the base of the PR and between cfc45ae and 73a1de2.

📒 Files selected for processing (7)
  • CHANGELOG
  • src/pyOpenMS/bindings/bind_chromatogram.cpp
  • src/pyOpenMS/bindings/bind_kernel.cpp
  • src/pyOpenMS/bindings/bind_spectrum.cpp
  • src/pyOpenMS/bindings/binding_utils.h
  • src/pyOpenMS/tests/unittests/test000.py
  • src/pyOpenMS/tests/unittests/test_set_peaks_metadata_alignment.py

Comment on lines +294 to +318
/// Drop the data arrays that a peak count of @p n stranded. Only PeakMetadataPolicy::Clear acts.
///
/// Call this *after* the peaks have been written, never before. The incoming intensity/position
/// arrays may alias the very storage this releases -- FloatDataArray.get_data_view() hands out a
/// zero-copy view into a data array, and getFloatDataArrays() exposes the container's own arrays
/// by reference -- so releasing it up front would leave the fill loop reading freed memory.
/// Deferring also means a throwing resize() cannot leave the arrays already dropped.
///
/// Arrays that still fit, and empty ones, are kept: they remain valid annotations, and the
/// docstring promises as much. Dropping rather than resizing to @p n is deliberate, since padding
/// would fabricate annotations that nothing marks as made up.
template <typename Container>
void dropStrandedPeakMetadata(Container& self, size_t n, PeakMetadataPolicy policy)
{
if (policy != PeakMetadataPolicy::Clear) return;

auto drop = [n](auto& arrays) {
arrays.erase(std::remove_if(arrays.begin(), arrays.end(),
[n](const auto& array) { return !peakMetadataArrayIsAligned(array, n); }),
arrays.end());
};
drop(self.getFloatDataArrays());
drop(self.getStringDataArrays());
drop(self.getIntegerDataArrays());
}

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check how std::vector<FloatDataArray>/StringDataArray/IntegerDataArray element access
# (__getitem__) is exposed to Python -- specifically whether indexing returns references
# tied to the individual element or the whole container, or a copy.
rg -n 'bind_vector' src/pyOpenMS/bindings -g '*.cpp' -A3 -B3
rg -n 'std::vector<OpenMS::DataArrays::(Float|String|Integer)DataArray>' src/pyOpenMS/bindings -g '*.cpp' -A5 -B5

Repository: OpenMS/OpenMS

Length of output: 7617


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== candidate bindings files =="
fd -a 'bind_(spectrum|chromatogram)\.cpp|binding_utils\.h' src/pyOpenMS/bindings src/pyOpenMS

echo
echo "== binding_utils relevant lifetime comments/helpers =="
sed -n '260,335p' src/pyOpenMS/bindings/binding_utils.h

echo
echo "== set_peaks definitions/usages in src/pyOpenMS/bindings =="
rg -n 'set_peaks|dropStrandedPeakMetadata|PeakMetadataPolicy::Clear' src/pyOpenMS/bindings -g '*.cpp' -g '*.h' -A8 -B8

echo
echo "== DataArray vector bindings outline/metric =="
rg -n 'bind_vector\(|__getitem__|operator\[\]|FloatDataArray|StringDataArray|IntegerDataArray' src/pyOpenMS/bindings -g '*.cpp' -A2 -B2

echo
echo "== nearby nanobind docs/dependency references =="
rg -n 'nanobind|nb::bind_vector|reference_internal|rv_policy::reference_internal' -g 'CMakeLists.txt' -g '*.cmake' -g '*.md' -g '*.cpp' src/pyOpenMS OpenMS CMake src -A2 -B2 | head -200

Repository: OpenMS/OpenMS

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== indexing of data-array vectors in spectrum/chromatogram bindings =="
rg -n 'getFloatDataArrays|getStringDataArrays|getIntegerDataArrays|__getitem__|bind_vector|make_iterator' src/pyOpenMS/bindings/bind_spectrum.cpp src/pyOpenMS/bindings/bind_chromatogram.cpp -A4 -B4

echo
echo "== nanobind policy/ownership dependency metadata =="
rg -n 'nanobind|nanobind-cmake|nanobind-cpp|nb::rv_policy::reference_internal|keep_alive' CMakeLists.txt src/pyOpenMS CMakeLists.txt src/pyOpenMS/CMakeLists.txt pyproject.toml setup.py -A2 -B2 2>/dev/null || true

echo
echo "== local tests mentioning getFloatDataArrays/set_peaks metadata =="
rg -n 'getFloatDataArrays|getStringDataArrays|getIntegerDataArrays|metadata=(\"|'\'')clear|set_peaks\(.*clear' tests src/pyOpenMS -g '*.py' -g '*.cpp' -A4 -B4

Repository: OpenMS/OpenMS

Length of output: 50370


Do not erase data arrays while reference_internal containers are indexed.

get...DataArrays() returns the vector by reference, but indexing the returned list returns references to individual FloatDataArray/StringDataArray/IntegerDataArray elements. If Python keeps one of those indexed objects, metadata='clear' can erase it via remove_if/erase() and leave the Python wrapper pointing into freed vector storage. Materialize the mutable vector up front, drop by value, then restore the container so indexed Python objects retain ownership.

🤖 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/pyOpenMS/bindings/binding_utils.h` around lines 294 - 318, Update
dropStrandedPeakMetadata so it does not erase elements directly from the vectors
returned by getFloatDataArrays(), getStringDataArrays(), or
getIntegerDataArrays(). Materialize each mutable data-array vector before
filtering, remove stranded arrays by value, then restore the resulting vector
through the container so reference_internal-indexed Python objects retain valid
ownership.

@timosachsenberg timosachsenberg changed the title [FIX] pyOpenMS: set_peaks() could silently leave aligned metadata misaligned (#9792 R-6.2) [FIX] pyOpenMS: set_peaks() metadata alignment, plus a writable ion mobility dimension (#9792 R-6.2) Jul 27, 2026

@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/pyOpenMS/bindings/bind_spectrum.cpp (1)

326-397: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicated metadata/ion-mobility lifecycle logic across the two set_peaks overloads.

The build-IM-array → checkPeakMetadataAlignment → resize → write-peaks → dropStrandedPeakMetadata → installIonMobilityArray sequence is repeated almost verbatim between the two-array overload (lines 326-365) and the sequence overload (lines 366-397). Since this sequence encodes a correctness-sensitive invariant (peak/metadata alignment, atomic no-op on failure), a future fix or ordering change applied to only one overload would silently reintroduce the bug this PR fixes in the other.

Consider extracting a shared private helper (e.g. applyPeaksWithMetadata(self, mz_arr, int_arr, policy, ion_mobility, ion_mobility_unit)) that both lambdas call after parsing their own input shape.

🤖 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/pyOpenMS/bindings/bind_spectrum.cpp` around lines 326 - 397, The peak and
metadata update lifecycle is duplicated across both set_peaks overloads, risking
inconsistent future fixes. Extract the shared logic from the two set_peaks
lambdas into a private helper such as applyPeaksWithMetadata, including
ion-mobility construction, alignment validation, resizing, peak writes, metadata
cleanup, and installation; have each overload call it after its own input
parsing and length validation.
🤖 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/pyOpenMS/bindings/bind_spectrum.cpp`:
- Around line 326-397: The peak and metadata update lifecycle is duplicated
across both set_peaks overloads, risking inconsistent future fixes. Extract the
shared logic from the two set_peaks lambdas into a private helper such as
applyPeaksWithMetadata, including ion-mobility construction, alignment
validation, resizing, peak writes, metadata cleanup, and installation; have each
overload call it after its own input parsing and length validation.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 64784c7d-bdc1-46d8-90c3-12a7ce08e2dc

📥 Commits

Reviewing files that changed from the base of the PR and between 73a1de2 and e478d15.

📒 Files selected for processing (4)
  • CHANGELOG
  • src/pyOpenMS/bindings/bind_spectrum.cpp
  • src/pyOpenMS/bindings/binding_utils.h
  • src/pyOpenMS/tests/unittests/test_set_ion_mobility.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/pyOpenMS/bindings/binding_utils.h

timosachsenberg added a commit that referenced this pull request Jul 27, 2026
Review follow-up (CodeRabbit on #9808): the build-array -> check-alignment ->
resize -> write-peaks -> drop-stranded sequence was repeated verbatim across all
six set_peaks() overloads. That sequence is not incidental duplication -- the
order of its steps is precisely the fix these commits exist for:

  - the alignment check runs against the incoming count and before resize(), so
    a rejected call is a strict no-op;
  - the stranded-array drop runs after the peaks are written, because the
    caller's arrays may alias the storage it releases.

Duplicated six ways, a future fix or reordering applied to one overload and not
the others would silently reinstate the bug in whichever spelling nobody edited.

writePeaksWithPolicy() in binding_utils.h now holds that sequence, parameterised
by the one container-specific part (writing m/z, RT or mobility into each peak).
All six overloads call it. The MSSpectrum pair additionally share
setSpectrumPeaks(), which adds the ion-mobility build/install either side of it;
they now differ only in how they get hold of the two input arrays, which is the
only thing that actually distinguishes them.

Behaviour is unchanged: the policy is still parsed before the sequence-shape
check so a bad policy is reported at the same point in both spellings, and the
full suite is identical at 5682 passed, 0 failed. Verified separately that every
call shape still resolves and errors as before.

Not done here: CodeRabbit's other finding, that dropStrandedPeakMetadata erases
from vectors handed to Python as reference_internal, so a previously retrieved
element reference is invalidated. The hazard is real -- elements of
getFloatDataArrays() do alias the container -- but its suggested remedy
(materialise, filter, assign back) does not fix it: vector copy-assignment
leaves slot 0 a live object holding different content, so a held reference
silently changes identity rather than dangling. It is also pre-existing and
shared with setFloatDataArrays() and clear(). A real fix needs the lease
machinery from #9792 steps 4-7.

Co-Authored-By: Claude Fable 5 <[email protected]>
@timosachsenberg

Copy link
Copy Markdown
Contributor Author

Acted on the duplication finding in fdeb3f5, independently of the contract question above.

The repeated sequence is not incidental: the order of its steps is the fix — the alignment check runs against the incoming count and before resize() so a rejected call is a strict no-op, and the stranded-array drop runs after the peaks are written because the caller's arrays may alias the storage it releases. Duplicated six ways, a later reordering applied to one overload and not the others would silently reinstate the bug in whichever spelling nobody edited.

writePeaksWithPolicy() in binding_utils.h now holds that sequence, parameterised by the one container-specific part (writing m/z, RT or mobility into each peak); all six overloads call it. The two MSSpectrum overloads additionally share setSpectrumPeaks(), which adds the ion-mobility build/install either side of it, so they now differ only in how they obtain the two input arrays. Behaviour is unchanged — suite identical at 5682 passed, 0 failed, and every call shape still resolves and errors as before.

On the other CodeRabbit finding (dropStrandedPeakMetadata erasing from vectors handed to Python as reference_internal): the hazard is real — I verified that elements of getFloatDataArrays() do alias the container, so mutating one is visible on the spectrum. But the suggested remedy does not fix it. Materialising, filtering and assigning back still goes through vector::operator=, which leaves slot 0 a live object holding different content, so a held reference silently changes identity instead of dangling — a different surprise, not a cure. The hazard is also pre-existing and shared with setFloatDataArrays() and clear(); metadata="clear" adds one more mutator to a class that already behaves this way rather than introducing a new one. A real fix needs the lease/generation machinery from steps 4–7 of #9792, which does not exist yet, so I have left it and noted it in the commit rather than applying a change that would look like a fix without being one.

timosachsenberg and others added 4 commits July 27, 2026 14:43
…aligned (#9792 R-6.2)

set_peaks() replaced the peak table without touching the parallel binary data
arrays, so replacing the peaks of a spectrum, chromatogram or mobilogram that
carried a float, string or integer data array left the container silently
inconsistent: setting 5 peaks on a spectrum whose 100-entry ion-mobility array
was aligned with its previous 100 peaks produced an object whose annotations no
longer described its peaks, with nothing reported at the call. The damage
surfaced only later and elsewhere -- as an Exception::Precondition thrown by a
subsequent sortByPosition()/select(), or as an mzML file written with a
mis-sized binary data array.

All six overloads (MSSpectrum, MSChromatogram, Mobilogram, in both the
two-array and the sequence spelling) now take a metadata= policy: 'error' (the
default) refuses the call, 'clear' drops all three array families, and 'keep' is
the previous behaviour, opted into explicitly.

The policy applies only when a non-empty data array's size differs from the new
peak count. The predicate is MSChromatogram::checkDataArraySizes_()'s,
empty-array exemption included, so this moves the core's own rejection to the
call that causes it rather than imposing a stricter rule: containers without
data arrays are unaffected, and replacing peaks with an equally long set still
keeps its arrays, which is both the in-place edit idiom and the guarantee
7215fc7 added for bug #5876.

'error' rather than 'clear' is the default because silently dropping
annotations is the worse failure mode: an exception cannot regress a working
program, since every case it fires on is already corrupt, whereas a silent
clear would hand back a spectrum missing the ion-mobility array the caller
believes it still has.

Ordering matters twice, and both orders are pinned by tests. The check runs
against the incoming count and before resize(), so a rejected call is a strict
no-op rather than leaving the peaks replaced -- checking self.size() instead
would compare the arrays against the count they are still aligned with, and
would accept the very case this exists to catch. And it runs after the existing
mz/intensity length check, so a call with mismatched inputs and metadata='clear'
cannot drop the arrays and then fail.

Passing the policy positionally alongside the sequence spelling,
set_peaks(peaks, 'clear'), binds to the two-argument overload because that one
is registered first; it is now reported as such instead of failing inside the
numpy conversion with a message that never mentions metadata. bytes is
diagnosed too, since the shared std::string caster accepts it and
set_peaks(mz, intensity, b'clear') is therefore a working spelling.

Two long-standing test000.py assertions built the mis-sized state by accident --
both reused an unrelated 3-entry array while setting 2 peaks -- while checking
only that set_peaks does not clear the arrays; they now use an equally long
array, which preserves the #5876 guard they were written for rather than
retiring it behind metadata='keep'.

Not addressed here, and still able to produce the same inconsistency: the
reverse direction, where setFloatDataArrays()/setIntegerDataArrays()/
setStringDataArrays() accept an array of any length, and the bare
resize()/reserve()/push_back() bindings.

189 regression tests were added, covering all three containers against all three
call spellings (two arrays, tuple, list -- Mobilogram's sequence overload is a
hand-written tuple/list branch rather than the generic one the other two use)
and all three array families; 57 of them fail with the alignment check stubbed
out, i.e. against the previous behaviour, while the ones guarding the unchanged
paths keep passing.

Co-Authored-By: Claude Fable 5 <[email protected]>
… still reading

Review follow-ups on the set_peaks() metadata policy.

1. Use-after-free under metadata='clear'. The policy was applied before the peaks
   were written, but the incoming intensity/position array may alias the very
   storage it releases: FloatDataArray.get_data_view() is zero-copy and
   getFloatDataArrays() hands out the container's own arrays, so

       view = spec.getFloatDataArrays()[0].get_data_view()[:8]
       spec.set_peaks(mz8, view, metadata="clear")

   dropped the array and then filled the peaks from released memory. The helper
   is now split: checkPeakMetadataAlignment() runs before resize() and only ever
   throws, and dropStrandedPeakMetadata() runs after the fill loop. Deferring the
   drop also means a throwing resize() can no longer leave the arrays already
   gone, so 'clear' cannot half-apply either. A regression test covers it and
   fails against the previous ordering.

2. 'clear' was unconditional, which contradicted its own docstring ("arrays that
   are already the right length are kept in every case") and the CHANGELOG. It
   now drops only the arrays the new peak count stranded; ones that still fit,
   and empty ones, are kept, so the same predicate governs all three policy
   values. Tests cover an aligned array surviving 'clear' and a mixed case where
   one family is dropped and another kept.

3. The sequence overload advertised a positional 'metadata' that it rejects,
   since set_peaks(peaks, "clear") binds to the two-argument overload registered
   before it. Its metadata argument is now nb::kw_only(), so the generated
   signature is honest; the runtime guard stays, because it is what produces the
   actionable message.

4. The two test000.py blocks from 7215fc7 (bug #5876) are restored verbatim
   and pass metadata='keep' instead of being re-fixtured to equal length. That
   preserves the historical assertions exactly rather than resting on a claim
   about the original author's intent, and makes the semantic change explicit at
   the call site.

Also from review: the 'rejected call is a no-op' and 'keep' tests now run against
all three call spellings rather than only the two-array one and compare array
values rather than just lengths; the empty-array test asserts the array stays
empty; and the CHANGELOG drops reserve() from the still-unguarded list, since it
does not change the peak count. Noted there instead: set_peaks() reads its inputs
after resize(), so a zero-copy view derived from the container's own peak storage
(e.g. get_peaks_struct()) is unsafe whenever the count changes -- pre-existing and
not addressed here.

267 regression tests, 81 of which fail with the policy stubbed out.

Co-Authored-By: Claude Fable 5 <[email protected]>
pyOpenMS could read the per-peak ion mobility array five ways -- containsIMData(),
getIMData(), get_drift_time_array(), get_drift_time_array_view() and
rasterizeIMFrame() -- but had no setter at all. The only way to attach ion
mobilities from Python was the generic data-array API with the array name spelled
by hand:

    fda = FloatDataArray()
    fda.set_data(im)
    fda.setName("Ion Mobility")
    spec.setFloatDataArrays([fda])

That string is the entire contract, and getting it subtly wrong changes the unit
rather than failing: IMDataConverter::getIMUnit() prefix-matches the legacy names
and falls back to MILLISECOND when no CV accession is embedded, so labelling TIMS
1/K0 data "Ion Mobility" reports it as drift time in milliseconds.

MSSpectrum gains set_drift_time_array(values, unit), and its two set_peaks()
overloads gain ion_mobility= / ion_mobility_unit= keywords so that peaks and their
mobilities can be replaced in one call. Both name the array through
IMDataConverter::setIMUnit(), i.e. from the PSI-MS controlled vocabulary, so what
is written is what getIMData() reads back and what survives an mzML round-trip.
The CV has no ion-mobility-array term for the remaining units, so CCS and FAIMS
compensation voltage are rejected rather than given an invented name; that is the
core's existing rule, inherited rather than worked around.

An existing array is replaced in place rather than appended, since a second one
would make getIMData() ambiguous, and the unit may be omitted when there is an
existing array to inherit it from -- the in-place mobility-edit case. The array is
built and its unit resolved before anything is modified, so a wrong length or an
unsupported unit leaves the spectrum untouched.

Where this meets the metadata policy from the previous commits: an ion mobility
array that set_peaks() is about to overwrite is exempt from the alignment check,
because a replaced array cannot be stranded and refusing would leave no way to
change the peak count and the mobilities in one step. The exemption is scoped to
that one array, so a stale string or integer array in the same call is still
reported, and a call that does not supply ion_mobility is unaffected.

This deliberately does not touch setDriftTime()/setDriftTimeUnit(), which describe
a spectrum acquired at a single drift time rather than a per-peak annotation; a
frame carrying an ion mobility array leaves those unset, matching what
IMDataConverter::reshapeIMFrameToSingle() produces.

32 tests, including an mzML round-trip per supported unit and the interaction with
the metadata policy in both directions. IMDataConverter itself remains unwrapped;
only its naming helper is used, from C++.

Co-Authored-By: Claude Fable 5 <[email protected]>
Review follow-up (CodeRabbit on #9808): the build-array -> check-alignment ->
resize -> write-peaks -> drop-stranded sequence was repeated verbatim across all
six set_peaks() overloads. That sequence is not incidental duplication -- the
order of its steps is precisely the fix these commits exist for:

  - the alignment check runs against the incoming count and before resize(), so
    a rejected call is a strict no-op;
  - the stranded-array drop runs after the peaks are written, because the
    caller's arrays may alias the storage it releases.

Duplicated six ways, a future fix or reordering applied to one overload and not
the others would silently reinstate the bug in whichever spelling nobody edited.

writePeaksWithPolicy() in binding_utils.h now holds that sequence, parameterised
by the one container-specific part (writing m/z, RT or mobility into each peak).
All six overloads call it. The MSSpectrum pair additionally share
setSpectrumPeaks(), which adds the ion-mobility build/install either side of it;
they now differ only in how they get hold of the two input arrays, which is the
only thing that actually distinguishes them.

Behaviour is unchanged: the policy is still parsed before the sequence-shape
check so a bad policy is reported at the same point in both spellings, and the
full suite is identical at 5682 passed, 0 failed. Verified separately that every
call shape still resolves and errors as before.

Not done here: CodeRabbit's other finding, that dropStrandedPeakMetadata erases
from vectors handed to Python as reference_internal, so a previously retrieved
element reference is invalidated. The hazard is real -- elements of
getFloatDataArrays() do alias the container -- but its suggested remedy
(materialise, filter, assign back) does not fix it: vector copy-assignment
leaves slot 0 a live object holding different content, so a held reference
silently changes identity rather than dangling. It is also pre-existing and
shared with setFloatDataArrays() and clear(). A real fix needs the lease
machinery from #9792 steps 4-7.

Co-Authored-By: Claude Fable 5 <[email protected]>
@timosachsenberg
timosachsenberg force-pushed the fix/9792-set-peaks-metadata-alignment branch from fdeb3f5 to ef03c6e Compare July 27, 2026 13:03

@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: 1

🤖 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 `@CHANGELOG`:
- Line 21: Update the CHANGELOG rationale for the metadata='error' default to
state that each prevented call would otherwise make the container corrupt,
rather than claiming the container is already corrupt when the exception fires.
Preserve the surrounding explanation that error is preferred over silently
clearing annotations.
🪄 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: 39eda610-95ab-49c4-b9a2-8100f1444b35

📥 Commits

Reviewing files that changed from the base of the PR and between fdeb3f5 and ef03c6e.

📒 Files selected for processing (8)
  • CHANGELOG
  • src/pyOpenMS/bindings/bind_chromatogram.cpp
  • src/pyOpenMS/bindings/bind_kernel.cpp
  • src/pyOpenMS/bindings/bind_spectrum.cpp
  • src/pyOpenMS/bindings/binding_utils.h
  • src/pyOpenMS/tests/unittests/test000.py
  • src/pyOpenMS/tests/unittests/test_set_ion_mobility.py
  • src/pyOpenMS/tests/unittests/test_set_peaks_metadata_alignment.py
🚧 Files skipped from review as they are similar to previous changes (7)
  • src/pyOpenMS/tests/unittests/test_set_peaks_metadata_alignment.py
  • src/pyOpenMS/tests/unittests/test000.py
  • src/pyOpenMS/tests/unittests/test_set_ion_mobility.py
  • src/pyOpenMS/bindings/binding_utils.h
  • src/pyOpenMS/bindings/bind_spectrum.cpp
  • src/pyOpenMS/bindings/bind_kernel.cpp
  • src/pyOpenMS/bindings/bind_chromatogram.cpp

Comment thread CHANGELOG

General:
- Feature: pyOpenMS can now write the per-peak ion mobility dimension. It could already read it five ways -- containsIMData(), getIMData(), get_drift_time_array(), get_drift_time_array_view() and rasterizeIMFrame() -- but had no setter at all, so the only way to attach ion mobilities was the generic data-array API with the array name spelled by hand: fda.setName("Ion Mobility"); spec.setFloatDataArrays([fda]). That string is the entire contract, and getting it subtly wrong changes the unit rather than failing: IMDataConverter::getIMUnit() prefix-matches the legacy names and falls back to MILLISECOND when no CV accession is embedded, so labelling TIMS 1/K0 data "Ion Mobility" reports it as drift time in milliseconds. MSSpectrum gains set_drift_time_array(values, unit), and its two set_peaks() overloads gain ion_mobility= / ion_mobility_unit= keywords so peaks and their mobilities can be replaced in one call. Both name the array through IMDataConverter::setIMUnit(), i.e. from the PSI-MS controlled vocabulary ('mean ion mobility array' for MILLISECOND, 'raw inverse reduced ion mobility array' for VSSC), so what is written is what getIMData() reads back and what survives an mzML round-trip; the CV has no ion-mobility-array term for the other units, so CCS and FAIMS compensation voltage are rejected rather than given an invented name, inheriting the core's existing rule instead of working around it. An existing ion mobility array is replaced in place rather than appended, since a second one would make getIMData() ambiguous, and the unit may be omitted when there is an existing array to inherit it from, which is the in-place mobility-edit case. The array is built and its unit resolved before anything is modified, so a wrong length or an unsupported unit leaves the spectrum untouched. Where this meets the metadata policy below: an ion mobility array that set_peaks() is about to overwrite is exempt from the alignment check, because a replaced array cannot be stranded and refusing would leave no way to change the peak count and the mobilities together; the exemption is scoped to that one array, so a stale string or integer array in the same call is still reported. Note this deliberately does not touch setDriftTime()/setDriftTimeUnit(), which describe a spectrum acquired at a single drift time rather than a per-peak annotation -- a frame carrying an ion mobility array leaves those unset, matching what IMDataConverter::reshapeIMFrameToSingle() produces. 32 tests were added, including an mzML round-trip per supported unit. IMDataConverter itself remains unwrapped; only the naming helper is used, from C++ (part of #9792)
- Fix: pyOpenMS set_peaks() replaced the peak table without touching the parallel binary data arrays, so replacing the peaks of a spectrum, chromatogram or mobilogram that carried a float, string or integer data array left the container silently inconsistent -- setting 5 peaks on a spectrum whose 100-entry ion-mobility array was aligned with its previous 100 peaks produced an object whose annotations no longer described its peaks, with nothing reported at the call. The damage surfaced only later and elsewhere: as an Exception::Precondition thrown by a subsequent sortByPosition()/select() (the check #9795 added for MSChromatogram/Mobilogram), or as an mzML file written with a mis-sized binary data array. All six set_peaks overloads (MSSpectrum, MSChromatogram, Mobilogram, in both the two-array and the sequence spelling) now take a metadata= policy: 'error' (the default) refuses the call, 'clear' drops the arrays the new count stranded, and 'keep' is the previous behaviour, opted into explicitly. The policy applies only when a non-empty data array's size differs from the new peak count -- the predicate is MSChromatogram::checkDataArraySizes_()'s, empty-array exemption included -- so this moves the core's own rejection to the call that causes it rather than imposing a stricter rule: containers without data arrays are unaffected, and replacing peaks with an equally long set still keeps its arrays under every policy, which is both the in-place edit idiom (recalibrate m/z, renormalise intensity) and the guarantee 7215fc74af added for bug #5876. 'clear' is likewise scoped to the stranded arrays: one that still fits is a valid annotation, not collateral damage. 'error' rather than 'clear' is the default because silently dropping annotations is the worse failure mode: an exception cannot regress a working program, since every case it fires on is already corrupt, whereas a silent clear would hand back a spectrum missing the ion-mobility array the caller believes it still has. Ordering matters twice, and both orders are pinned by tests: the check runs against the incoming count and before resize(), so a rejected call is a strict no-op rather than leaving the peaks replaced (checking self.size() instead would compare the arrays against the count they are still aligned with, and would accept the very case this exists to catch), and it runs after the existing mz/intensity length check, so a call with mismatched inputs and metadata='clear' cannot drop the arrays and then fail. The 'clear' drop itself runs after the peaks have been written rather than before: FloatDataArray.get_data_view() is zero-copy and getFloatDataArrays() hands out the container's own arrays, so spec.set_peaks(mz, spec.getFloatDataArrays()[0].get_data_view()[:n], metadata='clear') passes in a view of the very storage the policy releases, and dropping first left the fill loop reading freed memory. Deferring also means a throwing resize() cannot leave the arrays already gone. Passing the policy positionally alongside the sequence spelling, set_peaks(peaks, 'clear'), binds to the two-argument overload because that one is registered first; it is now reported as such instead of failing inside the numpy conversion with a message that never mentions metadata. Two long-standing test000.py assertions, added by 7215fc74af as the #5876 regression guard, set 2 peaks on a container holding a 3-entry array and assert the array survives; they now pass metadata='keep', which preserves those assertions verbatim while making the semantic change explicit at the call site. Not addressed here, and still able to produce the same inconsistency: the reverse direction, where setFloatDataArrays()/setIntegerDataArrays()/setStringDataArrays() accept an array of any length, and the bare resize()/push_back() bindings (reserve() does not change the peak count and is unaffected). Also pre-existing and untouched: set_peaks() reads its inputs after resize(), so passing a zero-copy view derived from the container's own peak storage, e.g. from get_peaks_struct(), is unsafe whenever the count changes. 267 regression tests were added, covering all three containers against all three call spellings (two arrays, tuple, list -- Mobilogram's sequence overload is a hand-written tuple/list branch rather than the generic one the other two use) and all three array families; 81 of them fail with the policy stubbed out, i.e. against the previous behaviour, while the ones guarding the unchanged paths (equal-length replacement, no data arrays, empty arrays, metadata='keep') keep passing (R-6.2, part of #9792)

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Correct the rationale for metadata='error'.

The statement that “every case it fires on is already corrupt” is inaccurate: the container may be consistent before the call; the rejected replacement is what would otherwise create the mismatch. Reword this as “every case it prevents would otherwise make the container corrupt.”

🤖 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 `@CHANGELOG` at line 21, Update the CHANGELOG rationale for the
metadata='error' default to state that each prevented call would otherwise make
the container corrupt, rather than claiming the container is already corrupt
when the exception fires. Preserve the surrounding explanation that error is
preferred over silently clearing annotations.

@timosachsenberg
timosachsenberg merged commit e9ba7c2 into develop Jul 27, 2026
39 checks passed
@timosachsenberg
timosachsenberg deleted the fix/9792-set-peaks-metadata-alignment branch July 27, 2026 16:28
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