Repository navigation
[FIX] pyOpenMS: set_peaks() metadata alignment, plus a writable ion mobility dimension (#9792 R-6.2) - #9808
Conversation
|
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.) |
📝 WalkthroughWalkthroughpyOpenMS ChangesPeak metadata and ion-mobility writing
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
Possibly related issues
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (7)
CHANGELOGsrc/pyOpenMS/bindings/bind_chromatogram.cppsrc/pyOpenMS/bindings/bind_kernel.cppsrc/pyOpenMS/bindings/bind_spectrum.cppsrc/pyOpenMS/bindings/binding_utils.hsrc/pyOpenMS/tests/unittests/test000.pysrc/pyOpenMS/tests/unittests/test_set_peaks_metadata_alignment.py
| /// 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()); | ||
| } |
There was a problem hiding this comment.
🩺 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 -B5Repository: 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 -200Repository: 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 -B4Repository: 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.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/pyOpenMS/bindings/bind_spectrum.cpp (1)
326-397: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicated metadata/ion-mobility lifecycle logic across the two
set_peaksoverloads.The build-IM-array →
checkPeakMetadataAlignment→resize→ write-peaks →dropStrandedPeakMetadata→installIonMobilityArraysequence 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
📒 Files selected for processing (4)
CHANGELOGsrc/pyOpenMS/bindings/bind_spectrum.cppsrc/pyOpenMS/bindings/binding_utils.hsrc/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
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]>
|
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
On the other CodeRabbit finding ( |
…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]>
fdeb3f5 to
ef03c6e
Compare
There was a problem hiding this comment.
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
📒 Files selected for processing (8)
CHANGELOGsrc/pyOpenMS/bindings/bind_chromatogram.cppsrc/pyOpenMS/bindings/bind_kernel.cppsrc/pyOpenMS/bindings/bind_spectrum.cppsrc/pyOpenMS/bindings/binding_utils.hsrc/pyOpenMS/tests/unittests/test000.pysrc/pyOpenMS/tests/unittests/test_set_ion_mobility.pysrc/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
|
|
||
| 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) |
There was a problem hiding this comment.
🎯 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.
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/Mobilogramsorting andclear(), 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:Nothing was reported at the call. The damage surfaced only later and elsewhere: as an
Exception::Preconditionfrom a subsequentsortByPosition()/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 ametadata=policy:"error"(default)"clear""keep"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, whichtests/unittests/test_IonMobilityData.py:135depends on.Why
"error"and not"clear"as the defaultSilently 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.mdalready specifiedmetadata="error" # default.Ordering, which is where this is easy to get wrong
resize(), so a rejected call is a strict no-op. Checkingself.size()instead would compare the arrays against the count they are still aligned with, and would accept the very case this exists to catch.metadata="clear"cannot drop the arrays and then fail."clear"drop runs after the peaks are written.FloatDataArray.get_data_view()is zero-copy andgetFloatDataArrays()hands out the container's own arrays, sospec.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 throwingresize()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'smetadataisnb::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.bytesis diagnosed too, since the sharedstd::stringcaster 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.pyblocks added by 7215fc7 as the #5876 regression guard now passmetadata="keep", which preserves their assertions verbatim while making the semantic change explicit at the call site.Deliberately not addressed here
setFloatDataArrays()/setIntegerDataArrays()/setStringDataArrays()still accept an array of any length, so the same inconsistency is reachable from the other side.dropStrandedPeakMetadata()/checkPeakMetadataAlignment()are shaped to serve that next.resize()/push_back()bindings — the rest of R-6.1. (reserve()does not change the peak count and is unaffected.)set_peaks()reads its inputs afterresize(), so a zero-copy view derived from the container's own peak storage (e.g. fromget_peaks_struct()) is unsafe whenever the count changes.MSSpectrum::select()is still missing the validation [FIX] MSChromatogram/Mobilogram: keep binary data arrays in sync with the peaks on sort and clear #9795 gave the other two classes, including a Python-reachable out-of-bounds read — filed separately as MSSpectrum::select() is missing the validation #9795 added to MSChromatogram/Mobilogram (Python-reachable out-of-bounds read) #9807.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
set_drift_time_array()andset_peaks(..., ion_mobility=..., ion_mobility_unit=...).set_peaks()with ametadata=policy (errordefault,clear,keep) for spectra, chromatograms, and mobilograms.clearremoves only stranded metadata.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:Getting that string subtly wrong changes the unit rather than failing.
IMDataConverter::getIMUnit()prefix-matches the legacy names and falls back toMILLISECONDwhen no CV accession is embedded, so labelling TIMS 1/K0 data"Ion Mobility"reports it as drift time in milliseconds.What is new
Both name the array through
IMDataConverter::setIMUnit()— from the PSI-MS CV, not a literal — so what is written is whatgetIMData()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, soCCSand FAIMS compensation voltage are rejected rather than given an invented name; that is the core's own documented rule, inherited rather than worked around.getIMData()ambiguous.ion_mobility_unitmay 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.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: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 whatIMDataConverter::reshapeIMFrameToSingle()produces. (Worth knowing separately:get_drift_time_unit()gates oncontainsIMData(), an array property, but returns that scalar, so it reportsNONEfor a frame whose array says 1/K0. Pre-existing, not touched here.)IMDataConverteritself 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.