Repository navigation
[FIX] pyOpenMS: keep containers alive while their iterators exist (use-after-free in all 13 __iter__ bindings) - #9794
Conversation
96e4d77 to
858574f
Compare
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (11)
🚧 Files skipped from review as they are similar to previous changes (9)
📝 WalkthroughWalkthroughpyOpenMS iterator bindings now apply ChangesIterator lifetime management
Possibly related issues
Suggested reviewers: 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/tests/unittests/test_iterator_lifetime.py`:
- Line 31: Wrap the overlength list comprehension assigned to junk across
multiple lines, preserving its existing bytearray values, size sequence, and
repetition count while conforming to PEP 8 line-length conventions.
🪄 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: 9bc50963-41f1-4c44-854f-920fe997f7cd
📒 Files selected for processing (11)
CHANGELOGsrc/pyOpenMS/README_WRAPPING_NEW_CLASSES.mdsrc/pyOpenMS/bindings/bind_analysis.cppsrc/pyOpenMS/bindings/bind_chemistry.cppsrc/pyOpenMS/bindings/bind_chromatogram.cppsrc/pyOpenMS/bindings/bind_datastructures.cppsrc/pyOpenMS/bindings/bind_experiment.cppsrc/pyOpenMS/bindings/bind_kernel.cppsrc/pyOpenMS/bindings/bind_metadata.cppsrc/pyOpenMS/bindings/bind_spectrum.cppsrc/pyOpenMS/tests/unittests/test_iterator_lifetime.py
| """Force collection and aggressively reuse freed heap blocks.""" | ||
| gc.collect() | ||
| # Allocations of assorted sizes, then dropped, to reuse a freed buffer. | ||
| junk = [bytearray(b"\xa5" * n) for n in (16, 64, 256, 1024, 4096) for _ in range(200)] |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Wrap the overlength comprehension.
Line 31 exceeds PEP 8 line-length conventions.
Proposed fix
- junk = [bytearray(b"\xa5" * n) for n in (16, 64, 256, 1024, 4096) for _ in range(200)]
+ junk = [
+ bytearray(b"\xa5" * n)
+ for n in (16, 64, 256, 1024, 4096)
+ for _ in range(200)
+ ]As per coding guidelines, **/*.py must use PEP 8 conventions.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| junk = [bytearray(b"\xa5" * n) for n in (16, 64, 256, 1024, 4096) for _ in range(200)] | |
| junk = [ | |
| bytearray(b"\xa5" * n) | |
| for n in (16, 64, 256, 1024, 4096) | |
| for _ in range(200) | |
| ] |
🤖 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/tests/unittests/test_iterator_lifetime.py` at line 31, Wrap the
overlength list comprehension assigned to junk across multiple lines, preserving
its existing bytearray values, size sequence, and repetition count while
conforming to PEP 8 line-length conventions.
Sources: Coding guidelines, Learnings
a3a62c5 to
cb1e6d3
Compare
nanobind's make_iterator stores the raw C++ begin/end iterators in the
object it returns and takes no reference to the container. The
rv_policy::reference_internal template argument governs only the elements
that are yielded, so it does not keep the container alive.
Every pyOpenMS __iter__ binding relied on that policy alone, so an
iterator could outlive the container it walks:
it = iter(build_spectrum()) # temporary is freed here
list(it) # reads freed memory
All 13 __iter__ bindings now carry nb::keep_alive<0, 1>(), which is what
nanobind's own bind_vector attaches to the __iter__ it generates:
MSSpectrum, MSChromatogram, MSExperiment, Mobilogram, FeatureMap,
ConsensusMap, Param, PeptideIdentificationList, AASequence,
IsotopeDistribution, NASequence, PeakGroup, DeconvolvedSpectrum.
The container-protocol template in README_WRAPPING_NEW_CLASSES.md omitted
the same annotation and is the likely origin of the pattern; it is fixed
and now documents why the annotation is mandatory.
Adds test_iterator_lifetime.py: 13 containers x 3 scenarios (iterator over
a temporary, iterator surviving del of the container, partially consumed
iterator whose container is dropped mid-iteration). Verified against a
build with the fix reverted: all 13 containers fail, 6 with a hard
segfault (FeatureMap, ConsensusMap, Param, PeptideIdentificationList,
AASequence, NASequence) and 7 by yielding values read back from reused
heap memory.
Part of #9792
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01APConSDbHrNux6qmuP4oVh
Two review findings on the regression test: 1. The baseline in two of the three tests was computed by iterating a temporary, which is exactly the use-after-free being tested. On a build without the keep-alive that read freed memory, so the test could in principle compare garbage against garbage. The baseline is now read from a named container that is provably alive during the comprehension. 2. The existing tests provoke undefined behaviour and rely on it manifesting (it reliably does -- 6 of 13 containers segfault without the fix -- but that is not guaranteed). Added a test that checks the annotation directly instead: nb::keep_alive<0, 1>() increments the container's refcount for as long as the iterator lives, so a missing annotation now fails deterministically with no UB involved. Verified against the built module: iter() takes the refcount 2 -> 3 and dropping the iterator returns it to 2. 52 tests (13 containers x 4 scenarios), all passing. Part of #9792 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01APConSDbHrNux6qmuP4oVh
cb1e6d3 to
86c2f52
Compare
|
Looks correct now |
…#9792 V.4) (#9803) * [FIX] pyOpenMS: borrowed references that could outlive their referent (#9792 V.4) Same defect class as the __iter__ use-after-free fixed in #9794, in three shapes. Wrong keep-alive target. PeakIndex::getFeature/getPeak/getSpectrum return a reference into the *map argument* (PeakIndex.h all `return map[...]`), but were annotated rv_policy::reference_internal, which keeps argument 1 -- the PeakIndex -- alive instead. They now use rv_policy::reference with keep_alive<0, 2>(). Retained raw pointers. Twelve setters/constructors handed OpenMS a pointer to a Python-owned object that C++ stores verbatim and keeps using. keep_alive cannot repair these: every receiver is copyable, and a C++ copy duplicates the stored pointer without carrying the Python-side lifetime edge, so the copy is left pointing at released storage as soon as the original wrapper is collected -- and copies also escape through getPrefix()/getSubsequence()/__copy__. They are made safe instead by guaranteeing the pointee has process lifetime: - validation against the owning database, raising ValueError otherwise, for NASequence::set/setFivePrimeMod/setThreePrimeMod/setSequence, AASequence::setModification(size_t, Residue*), EnzymaticDigestion::setEnzyme, RNaseDigestion::setEnzyme and ResidueDB::getModifiedResidue; - interning for AASequence::set{,N-terminal,C-terminal}Modification and Residue::setModification, which now route through the existing by-reference overloads so a copy is registered in ModificationsDB and the database-owned pointer is stored. The interned group matters most: the indexed AASequence setter funnels into ResidueDB, which caches the modified Residue for the life of the process, so a Python-owned modification affected later, independently constructed sequences long after any possible keep-alive nurse was released. These raw-pointer overloads were registered ahead of their safe by-reference siblings; since nanobind resolves overloads in registration order and both match an instance in the strict pass, positional and `modification=` calls always took the unsafe path while only the `mod=` spelling reached the safe one. Both spellings are preserved. The IsobaricQuantifier/IsobaricNormalizer/IsobaricChannelExtractor constructors (9 registrations) store the IsobaricQuantitationMethod by reference and gained keep_alive<1, 2>(), with the pointer-duplicating copy paths removed from the first two. KDTreeFeatureMaps, KDTreeFeatureNode and MapAlignmentAlgorithmKD are removed rather than repaired. addMaps received the maps through nanobind's *copying* STL list caster while C++ stored pointers into that call-local copy, so accessors read released storage even with the caller's map still referenced -- silently wrong from ~100 features, process termination from ~5000 -- and it was the class's only entry point. MapAlignmentAlgorithmKD's entire public API requires a KDTreeFeatureMaps and was unreachable; KDTreeFeatureNode had no constructible path. FeatureGroupingAlgorithmKD, which builds the tree internally over storage it owns, is the supported entry point and is unaffected. Found while editing the same lines: NASequence::set and AASequence::setModification(Size, const Residue*) index their vectors without a range check, unlike the sibling overloads which throw IndexOverflow, so an out-of-range index was an out-of-bounds write; NASequence::get reads unchecked while __getitem__ beside it already guarded. All three now raise IndexError. 61 regression tests added; 24 of them fail without the fix, 2 by terminating the interpreter. The wrapping guide gains a section on retained pointers, including the note that an audit must grep `nb::init<` as well as `.def(...)` -- which is how the isobaric constructors were missed on the first pass. Co-Authored-By: Claude Fable 5 <[email protected]> * Address review: unbound kd_tree property and unchecked PeakIndex indices Two follow-ups from the CodeRabbit review of the previous commit. FeatureMapping_FeatureMappingInfo.kd_tree stayed bound as a def_rw after the KDTreeFeatureMaps bindings were removed. Its member is of exactly that type, so reading the attribute raised "Unable to convert function return value to a Python type!". A grep for the type name missed it because the binding names the member pointer, not the type. The property is dropped. PeakIndex::getFeature/getPeak/getSpectrum range-check only through OPENMS_PRECONDITION, which expands to nothing in a release build (Macros.h:91), so an out-of-range PeakIndex read past the end of the container -- verified to terminate the interpreter. The three bindings now raise IndexError, matching the guards added elsewhere in this branch. Co-Authored-By: Claude Fable 5 <[email protected]> * Stop wrapping PeakIndex PeakIndex was orphaned surface. Its only producer anywhere in OpenMS is AreaIterator::getPeakIndex() (AreaIterator.h:260), and AreaIterator, areaBegin and areaEnd are not wrapped -- MSExperiment has no area* method in Python at all -- so no binding could ever hand one out. No other binding returned or accepted one either, and nothing in the tests, addons or docs referenced it. That left the three accessors as pure indirection over indexing the caller already had: idx.getFeature(fm) is fm[idx.peak], idx.getPeak(exp) is exp[idx.spectrum][idx.peak]. The one thing they added over plain indexing was a range check written with OPENMS_PRECONDITION, which expands to nothing in a release build, so an out-of-range index read past the end of the container instead. Unlike the KDTree removals this one was not broken -- the keep-alive target and the bounds checks were corrected earlier in this branch -- it simply had no way to be reached. If area iteration is wrapped later, PeakIndex should come back with it, with the keep-alive edge on the map argument rather than on the index; the wrapping guide keeps that lesson as a worked example. Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]>
…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]>
…gs (#9792) The earlier commits converted the six containers I had enumerated by hand and stopped there. Fourteen element accessors were left aliasing, which is the same enumeration failure #9792 keeps catching -- Part I of the issue names five of them explicitly as confirmed-at-runtime aliasing element accessors and records that 16 of 21 __getitem__ bindings returned references. Converted to owned values: DeconvolvedSpectrum, AASequence, IsotopeDistribution, MassTraces, AcquisitionInfo, PeptideIdentificationList, plus the PeakGroup and Param iterators. After this there are no aliasing __getitem__ or __iter__ bindings left in the tree, verified directly. AASequence is the one with a sharper motivation than consistency. It stores std::vector<const Residue*> pointing into ResidueDB (AASequence.h:622), so seq[i] returned a reference to a process-lifetime database entry -- and since nanobind erases constness, Python got a mutable handle on it. Editing a residue obtained that way changed it for every sequence in the process, including ones constructed afterwards. That is the same corruption shape as V.4 (#9803), reached through a different entry point, and copying removes the route rather than guarding it. A regression test covers it. Two of the fourteen were dead code rather than live aliases: PeakGroup (bind_analysis.cpp) and DataFilters (bind_processing.cpp) each registered a by-value __getitem__ *ahead* of a reference_internal one with the same signature. nanobind resolves overloads in registration order, so the by-value one always won and the second was unreachable -- as #9792 I.1 describes. Those registrations are removed rather than converted; observable behaviour is unchanged. No class now registers __getitem__ twice. keep_alive<0,1> is retained at all 13 make_iterator sites; it guards the iterator object, not the elements, and dropping it would reopen #9794. MassTraces gains no write path from this: the class binds getters only, so it is a read-only algorithm result and a copy is the correct return. The other converted containers all have __setitem__ or push_back. Alias surface: 356 rv_policy::reference_internal sites at the start of this branch, 213 now. What remains is member sub-object accessors, keyed lookups and self-returns -- categories that need their own decision, since a member's address cannot be invalidated independently of its parent and the keep-alive edge is a complete guarantee for it now that every container element is an owned Python object. Six regression tests added. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
) * [pyOpenMS] Element access returns owned values, not aliases (#9792) Indexing and iterating a container now yield an owned copy on every element container, instead of a live alias into the container's storage. Writes go back through __setitem__. This restores the semantics of the Cython bindings up to release 3.5, where the autowrap wrapper representation (a shared_ptr-owned C++ instance per wrapper) structurally forced a copy on every wrapped-type return. The nanobind port made these paths reference_internal aliases, which is the root of the use-after-free and wrong-element-write failures catalogued in #9792 -- and it was a side effect of the port rather than a decision. Converted (indexing and iteration, both directions now agree): MSSpectrum -> Peak1D (__iter__ was aliasing; __getitem__ already copied) MSChromatogram -> ChromatogramPeak Mobilogram -> MobilityPeak1D MSExperiment -> MSSpectrum / MSChromatogram, incl. getSpectrum, getChromatogram, getSpectra, getChromatograms FeatureMap -> Feature ConsensusMap -> ConsensusFeature getSpectra()/getChromatograms() are included because they were declared by value in the 3.5 pxd (libcpp_vector[MSSpectrum] getSpectra()), i.e. they copied there too; test_AcquisitionInfo.py still uses the copy-and-write-back idiom that only makes sense under copy semantics, and it keeps passing. keep_alive<0,1> is retained at all 13 make_iterator sites. It guards the iterator object, which still holds raw C++ iterators, and is a separate concern from the element policy -- removing it would reopen #9794. Verified by compiling a standalone nanobind module reproducing the exact pattern, with the old reference_internal bindings kept as negative controls: copies do not leak edits, aliases do; a held spectrum survives 5000 addSpectrum calls intact, while the aliased control degrades to rt=2.6e-315 and a len() that overflows; the iterator still outlives its container. Also updates the container-protocol template in README_WRAPPING_NEW_CLASSES.md, which taught the aliasing pattern and is how it spread, and the three peak-access class docstrings. Not in scope, and still aliasing: reference-returned vectors of sub-objects (getHits, getFloatDataArrays, getPrecursors, ...) and AcquisitionInfo. These were also copies in 3.5, so they are the natural next step, but there are ~105 such sites and they are a separate change. The boundary is pinned by tests so it stays deliberate. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS] Drop inert reference_internal policies; stop materialising whole data-array vectors to read one element Two preparatory changes, both independently useful and neither altering behaviour. They clear the way for converting the object-element vector getters (getHits, getFloatDataArrays, getPrecursors, ...) to value semantics, which is the remaining half of the #9792 element-access work. 1. Inert rv_policy::reference_internal removed from 29 bindings. These return a reference to a scalar/string, or to a vector of them (vector<double>&, vector<std::string>&, float&, int&, std::string&). nanobind's value casters ignore rv_policy: Python receives immutable floats, ints and strings, so no alias exists and the policy never did anything. It was actively misleading -- a reader of FloatDataArray.__getitem__ returning `float&` with reference_internal reasonably concludes fda[0] aliases -- and it inflated every audit count and every VI.11 grep in #9792 by ~10%. Verified the diff touches nothing but the policy token: 29 changed line pairs, each differing from its original only by removal of that token. Worth recording, because it makes the remaining count meaningful: `const` in the binding signature does NOT make a getter read-only from Python. nanobind erases C++ constness, so a `const std::vector<T>&` with reference_internal still hands out mutable aliasing wrappers. Confirmed by compiling a minimal module: mutating through a const-returned getter changed the owner's value. The real object-aliasing surface is therefore 77 sites, not the 38 non-const ones. 2. Five call sites no longer fetch every data array to read one. `spec.getFloatDataArrays()[im_idx]` materialises a Python wrapper for every float data array of the spectrum, then uses one. All five sites sit inside per-spectrum loops on the dataframe export paths (get_df, get_massql_df, get_ion_df, the Arrow builders), so this ran once per spectrum over whole files. They now call get_drift_time_array(), which already existed and does the same resolution in C++, copying only the ion mobility array. This is also what makes converting getFloatDataArrays() to a copy safe later: as written, those loops would have deep-copied every array of every spectrum. Behaviour is preserved exactly at each site: get_drift_time_array() returns None on precisely the containsIMData() condition, so it replaces the guard in three sites, the try/except RuntimeError plus bounds check in get_ion_df, and in get_massql_df the raise-on-missing is kept explicitly. It already returns float32, so the dtype conversions were redundant. The remaining getFloatDataArrays() uses are `for fda in ...` loops that genuinely need every array; those are left alone. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS] Core data classes: vector getters return owned values (#9792) Extends the element-access policy to the reference-returning vector getters on the classes users touch most: MSSpectrum, MSChromatogram, MSExperiment, FeatureMap, ConsensusMap, Feature, ConsensusFeature, PeptideIdentification, ProteinIdentification, PeptideHit, SpectrumSettings, ExperimentalSettings, AnnotatedMSRun, BinnedSpectrum. 32 getters, among them getFloatDataArrays / getIntegerDataArrays / getStringDataArrays, getHits, getPrecursors, getProducts, getProteinIdentifications, getPeakAnnotations, getPeptideEvidences, getDataProcessing, getConvexHulls, getSubordinates. These were declared by value in the 3.5 pxd (libcpp_vector[PeptideHit] getHits()), so they copied under the Cython bindings; the nanobind port made them reference_internal, and nanobind's list caster propagates the policy per element, so each call handed out N wrappers aliasing the container. Writes go through the existing setters, which is the idiom the 3.5-era tests already use. Worth recording: `const` on the C++ return bought nothing. nanobind erases constness, so `const std::vector<T>&` with reference_internal still produced mutable aliasing wrappers -- confirmed by compiling a minimal module and mutating through a const-returned getter. So the aliasing surface here was the full set, not just the non-const half. Two things this exposed that are worth flagging for review: - Six of the getters (the three data-array pairs on MSSpectrum and MSChromatogram) are multi-line, carrying rv_policy on the closing line rather than the .def line. Changing the return type without also removing the policy would have left `reference_internal` on a by-value return -- i.e. element wrappers aliasing into a temporary vector destroyed at the end of the call, which is worse than what was there before. Verified zero value-returning getters carry the policy now. - getDataProcessing returns vector<shared_ptr<DataProcessing>>. Copying the vector copies the shared_ptrs, so the pointees stay shared. That is the intended semantics for shared_ptr and is unchanged by this commit; it does mean a "copy" here is not an isolated deep copy. Nine docstrings that advertised "a const reference to ..." were corrected; they would otherwise have described the opposite of the behaviour. Five regression tests added for the copy semantics and the write-back route. The two tests that pinned getHits() as aliasing are updated -- they recorded the pre-existing boundary, which this commit moves. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS] Remaining vector getters return owned values (#9792) Completes the conversion started in the previous commit, covering the long tail: TargetedExperiment (11 getters), Instrument, InstrumentSettings, Residue, ResidueModification, CVMappings, IncludeExcludeTarget, TraMLProduct, ReactionMonitoringTransition, MRMTransitionGroup (both template instantiations), Sample, IsotopeDistribution, ChromatogramSettings, MetaInfoDescription, PEFFFile, MultiplexDeltaMasses(Generator) and the eight isobaric quantitation methods. 50 getters converted. With this, no vector getter returning wrapped OpenMS objects hands out aliases, and none carries rv_policy::reference_internal. Verified both directly. The `*Muteable` accessors on MRMTransitionGroup are included rather than exempted. An earlier reading treated them as deliberate mutation handles whose purpose a copy would defeat; that was wrong -- the class binds addTransition and addFeature, so the write path is unaffected. Likewise IsotopeDistribution::getContainer (the class binds set() and insert()) and TraMLProduct's list getters (addConfiguration / addInterpretation). The five accessors that genuinely have no write path -- getChannelInformation on the isobaric methods, BinnedSpectrum::getPrecursors, PEFFFile::getHeaders and the two MultiplexDeltaMasses getters -- belong to read-only config or result objects whose classes bind getters only, so a copy is the correct return there rather than a limitation. Two getters in this set were reclassified as inert rather than converted, since their element types go through value casters and never aliased: Param::getValidStrings (std::basic_string<char> is std::string) and ConvexHull2D::getHullPoints (DPosition<2> has a custom caster and is not bound as a class; a vector of them becomes a numpy array). They only lose the misleading policy. Six more docstrings advertising "a reference to ..." corrected. Alias surface across the bindings: 356 rv_policy::reference_internal sites at the start of this branch, 227 now. The remainder are single-object member accessors (getInstrumentSettings, getSample, getOptions and similar), which are a separate category and untouched here. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS] Convert the remaining aliasing __getitem__/__iter__ bindings (#9792) The earlier commits converted the six containers I had enumerated by hand and stopped there. Fourteen element accessors were left aliasing, which is the same enumeration failure #9792 keeps catching -- Part I of the issue names five of them explicitly as confirmed-at-runtime aliasing element accessors and records that 16 of 21 __getitem__ bindings returned references. Converted to owned values: DeconvolvedSpectrum, AASequence, IsotopeDistribution, MassTraces, AcquisitionInfo, PeptideIdentificationList, plus the PeakGroup and Param iterators. After this there are no aliasing __getitem__ or __iter__ bindings left in the tree, verified directly. AASequence is the one with a sharper motivation than consistency. It stores std::vector<const Residue*> pointing into ResidueDB (AASequence.h:622), so seq[i] returned a reference to a process-lifetime database entry -- and since nanobind erases constness, Python got a mutable handle on it. Editing a residue obtained that way changed it for every sequence in the process, including ones constructed afterwards. That is the same corruption shape as V.4 (#9803), reached through a different entry point, and copying removes the route rather than guarding it. A regression test covers it. Two of the fourteen were dead code rather than live aliases: PeakGroup (bind_analysis.cpp) and DataFilters (bind_processing.cpp) each registered a by-value __getitem__ *ahead* of a reference_internal one with the same signature. nanobind resolves overloads in registration order, so the by-value one always won and the second was unreachable -- as #9792 I.1 describes. Those registrations are removed rather than converted; observable behaviour is unchanged. No class now registers __getitem__ twice. keep_alive<0,1> is retained at all 13 make_iterator sites; it guards the iterator object, not the elements, and dropping it would reopen #9794. MassTraces gains no write path from this: the class binds getters only, so it is a read-only algorithm result and a copy is the correct return. The other converted containers all have __setitem__ or push_back. Alias surface: 356 rv_policy::reference_internal sites at the start of this branch, 213 now. What remains is member sub-object accessors, keyed lookups and self-returns -- categories that need their own decision, since a member's address cannot be invalidated independently of its parent and the keep-alive edge is a complete guarantee for it now that every container element is an owned Python object. Six regression tests added. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [FIX][pyOpenMS] set_drift_time_array: don't free a buffer a live view points into installIonMobilityArray replaced an existing ion mobility array with self.getFloatDataArrays()[self.getIMData().first] = std::move(fda); DataArrays::FloatDataArray derives from std::vector<float>, so that move-assignment deallocates the destination's float storage. Meanwhile get_drift_time_array_view() (bind_spectrum.cpp) hands numpy a raw arr.data() pointer with only the owning Python object as a keep-alive -- never the buffer -- and FloatDataArray.get_data_view() does the same. Reading such a view after the replacement was a use-after-free with the nanobind ownership graph fully intact and nothing to notice the free: v = s.get_drift_time_array_view() s.set_drift_time_array(new_values) v[0] # reads freed memory Also reachable through set_peaks(..., ion_mobility=...) on the default metadata="error" policy, because the alignment check deliberately exempts the array that call is about to replace. Fix: when the replacement has the same length -- which is the normal case, since both entry points require one entry per peak -- copy the values into the existing storage and assign the MetaInfoDescription base separately. The buffer address is unchanged, so live views stay valid and simply observe the new values, which is how a zero-copy view behaves for any other in-place write. The metadata is still replaced wholesale, as the move-assignment did, so the unit carried by the array name is updated exactly as before. Only a length change still replaces the storage, where no view could survive regardless. Verified the premise by compiling the two paths against a struct with FloatDataArray's shape (a metadata base plus std::vector<float>): move-assign reports the buffer replaced and the old one freed, the in-place path reports it unchanged with the view observing the new values and the metadata transferred. This is independent of the element-access work on this branch and predates it; it was found while auditing the ownership proposal. Note the sibling route is already safe as a side effect of the earlier commits: getFloatDataArrays() now returns copies, so a view taken through it points into a Python-owned array rather than the spectrum's storage. get_drift_time_array_view() was the remaining route and is what this fixes. Three regression tests added. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS] Element access under other names: at/front/back/getResidue/getElement Review of the branch found six element accessors that the earlier sweeps missed because they are not spelled __getitem__ or __iter__. All returned references into the receiver and are converted to owned values, matching the accessors beside them: AASequence.getResidue(i) -> Residue ims::IMSAlphabet.getElement(i) -> IMSElement PeptideIdentificationList.at(i) -> PeptideIdentification PeptideIdentificationList.front() -> PeptideIdentification PeptideIdentificationList.back() -> PeptideIdentification MSImagingExperiment.getSpectrum(x, y) -> MSSpectrum AASequence.getResidue is the one that mattered. The previous commit converted AASequence.__getitem__ because it aliased a process-lifetime ResidueDB entry that nanobind exposes as mutable, so editing it corrupted the residue for every sequence in the process. getResidue(i) is the same call by another name and left that route fully open, which made the previous commit message overclaim. It is closed now. Two of these were found only after widening the search twice: first from __getitem__/__iter__ to any accessor taking an integer index, then to .def() forms where the method name sits on a different line from the .def( token. MSImagingExperiment.getSpectrum(x, y) is indexed by a 2D pixel coordinate and was missed by both earlier patterns. Two latent crashes fixed on lines already being rewritten, called out rather than folded in silently: PeptideIdentificationList.front() and .back() had no emptiness guard, so calling either on an empty list was undefined behaviour; AASequence.getResidue had no bounds check in the binding, and the core's OPENMS_PRECONDITION compiles to nothing in release builds. Both now raise IndexError. at() needs no guard -- std::vector::at already throws, and nanobind maps std::out_of_range to IndexError. MSImagingExperiment.getMSExperiment() and getGeometry() were found by the same sweep and deliberately left alone: they return the contained object itself, not an element of it, so they belong to the member-accessor category that is still open. After this there are no aliasing element accessors of any spelling left in the tree. Alias surface: 356 at the start of this branch, 207 now. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS][docs] Document copy/reference semantics; pin chaining with tests The branch changed where copies happen but never tested chained access, which is where the rules actually interact. Eight tests now pin the boundary, and OWNERSHIP.md states it for users. What the tests establish, verified against a compiled model of the same binding shapes before being written against pyOpenMS: spec.getInstrumentSettings().setZoomScan(True) lands (no container access) exp[0].getInstrumentSettings().setZoomScan(True) LOST (exp[0] is a copy) spec.getPrecursors()[0].setMZ(999.0) LOST (collection getter copies) for s in exp: s.setRT(...) LOST s = exp[0]; s.setRT(...); exp[0] = s lands, nested edits included Reads are safe everywhere, including through a temporary produced mid-chain: nanobind keeps the parent alive for as long as the object taken from it, so exp[0].getInstrumentSettings().getZoomScan() is well-defined even though exp[0] is a temporary. Only writes are affected. The rule that follows is that a write lands exactly when the chain from a variable you hold to the target crosses no container access and no collection getter. Recorded honestly in the document rather than glossed: this is two rules, not one, and which applies is not visible at the call site -- getPrecursors() copies while getInstrumentSettings() does not, and the names do not say so. The ~166 single sub-object getters are the last group returning references. Converting them would collapse the document to its first sentence at the cost of making algo.getParameters().setValue(...) a silent no-op. That decision is open; the write-back form is correct under either outcome, so the document recommends it unconditionally. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS][docs] Correct the cost stated for converting the sub-object getters OWNERSHIP.md justified leaving ~166 single sub-object getters as references by saying conversion would make algo.getParameters().setValue(...) a silent no-op, "a common idiom". Both halves are wrong and the document should not carry them. It is not common: no Python in this repository chains a write through getParameters(), and exactly two lines chain one through any single sub-object getter at all (chrom.getPrecursor().setMZ(...) and getProduct(), both in test_dataframe_columns.py). More to the point, it does not work. DefaultParamHandler::setParameters() applies defaults, validates against them, and ends with updateMembers_(), the hook algorithms override to copy parameter values into their own members (DefaultParamHandler.cpp:44-70). Mutating the Param in place reaches none of that, so the algorithm never picks the change up. setParameters() was always required; the in-place form only looked like it worked. Also states plainly why the two rules exist -- the split was made for memory safety (a collection getter yields one alias per element; a single sub-object cannot be invalidated independently of its parent) and that criterion is invisible to callers, who only experience whether a write sticks. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS] Single sub-object getters return owned values; one rule for all getters Converts the last group of getters that handed out references into their parent: 132 single sub-object accessors (getInstrumentSettings, getAcquisitionInfo, getSourceFile, getParameters, getSample, getOptions, spectrumRanges, getGeometry, and so on). The policy is now uniform and statable in one sentence: every getter returns an owned copy, and a change reaches its parent only through the matching setter. Before this commit the split was between collection getters (copied) and single sub-object getters (aliased) -- a real distinction, but one made for memory safety, which is invisible to callers. What a caller experiences is whether a write sticks, and on that axis the split was arbitrary: getPrecursors() and getInstrumentSettings() look identical at a call site and behaved oppositely. What the change costs, checked rather than assumed: - Exactly two lines of Python in this repository chain a write through such a getter (chrom.getPrecursor().setMZ(...) and getProduct(), in test_dataframe_columns.py). Nothing else in the tree relies on it. - The idiom usually cited as the reason not to do this, algo.getParameters().setValue(...), already did not work and is used nowhere here. DefaultParamHandler::setParameters() applies defaults, validates and calls updateMembers_() (DefaultParamHandler.cpp:44-70), which is where an algorithm copies parameter values into its own members. Editing the Param in place reaches none of that. - Reads get more expensive where the sub-object is large: consumer.getData() and imaging getMSExperiment() now copy a whole experiment. Five such accessors return an algorithm's result and have no setter, which is correct -- they are outputs, and copying an output is what a caller wants. The doc tells users to fetch once rather than call in a loop. Deliberately left aliasing, and both are self-evident at the call site rather than something to memorise: - 33 fluent builders and compound-assignment operators returning *this (ParquetFilter.eq(...).andNext()); a copy would break chaining outright. - 31 accessors returning a pointer to a process-lifetime database entry (ResidueDB, ModificationsDB). These are Category S in #9792's taxonomy, where aliasing is correct. They do carry the same global-mutation hazard that AASequence[i] had, and closing that needs null handling, so it is separate work rather than part of this sweep. - 11 keyed lookups still to be triaged: some are element access, some are database lookups, and they need reading one at a time. Alias surface: 356 rv_policy::reference_internal sites at the start of this branch, 75 now, all three remaining groups accounted for above. OWNERSHIP.md is rewritten around the single rule and gains a migration section. Two chaining tests that asserted the old split are inverted -- they recorded the boundary this commit removes -- and a test pins that fluent builders still chain. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS] Convert binding_utils.h getters; document attribute access Two gaps found by scanning surfaces the earlier sweeps never looked at. 1. binding_utils.h was never touched. Every conversion script globbed bind_*.cpp, so the shared helper templates kept their aliasing getters -- and def_DefaultParamHandler is applied to 11 classes, so getParameters() and getDefaults() still returned references into the handler on all of them. That made OWNERSHIP.md's "every getter returns a copy" false as written. Five sites converted: getParameters, getDefaults and getCVTerms were real aliases; getLoadedFileType (an enum) and getSubsections (vector<string>) went through value casters and only lost a misleading policy. Two docstrings corrected. There are now no rv_policy::reference_internal sites outside bind_*.cpp; arrow_zerocopy.cpp, peak_layout.h, main_module.cpp and every type caster were checked and have none. 2. def_rw/def_ro attributes alias, and nothing said so. Verified by compiling a minimal module: a def_rw member of class type hands out a reference and writes land, while string and scalar-vector members go through value casters and cannot alias. Of 1078 such bindings, 31 expose a member whose type is a bound class -- all on plain data-holder structs (SiriusTargetDecoySpectra, RangeSet, PreprocessedPairSpectra, AQS_featureConcentration and similar); none on the main containers. These are left aliasing deliberately. They are attributes, not getters, and Python attributes are expected to be live -- `pair.target.setRT(5)` landing is what a reader assumes, and def_rw already supplies the native write path via `pair.target = ...`. Converting them would put the silent-no-op trap behind syntax that looks nothing like a function call, which is worse than the inconsistency it removes. So the policy is two lines rather than one, but they follow ordinary Python intuition instead of an internal distinction: a method hands you a copy and needs a write-back; an attribute is the object itself. OWNERSHIP.md now says so, and a test pins the behaviour. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS][test] Fix three test bugs found by running against a real build These tests were written without a build to run them against. Building pyOpenMS locally surfaced three failures, all in the tests rather than in the bindings; each underlying semantic was verified directly before the test was touched, so the expectations were corrected to what the API actually does rather than relaxed to make them pass. - Residue exposes getName(), not getFullName(). The latter came from a grep whose context window ran into a neighbouring class. Affected the two AASequence/ResidueDB tests. - A default-constructed IsotopeDistribution already holds one element, so the first insert() lands at index 1, not 0. The test asserted against index 0 and compared it to the value it had inserted. It now captures the original value at index 1 and asserts it is unchanged, which does not depend on that detail. Verified behaviour on the built module before editing: IsotopeDistribution d[1].mz 100.0 -> mutate returned peak -> 100.0 copy AASequence residue 'Proline' -> setName('CORRUPTED') same sequence -> 'Proline' copy NEW sequence -> 'Proline' DB clean The last line is the claim the AASequence conversion was made for: a sequence constructed after the mutation still reads clean, so the process-wide ResidueDB was not edited. Before the conversion that route corrupted the residue for every sequence in the process. All 68 ownership, chaining and ion-mobility tests now pass against a real build of this branch. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS] Fix write-back regressions found by the full test suite Element access now yields owned copies, so four call sites that mutated through a getter were silently no-ops: - PeptideIdentificationList.update_scores_from_df(): the edited PeptideIdentification was never written back to the list. - test_imaging: getGeometry().addRegion() never reached the experiment. - test_ImzMLFile: getSpectrum(0).setRT()/setMSLevel() never reached the experiment before storing. - test_dataframe_columns: getPrecursor()/getProduct().setMZ() on a chromatogram fixture. Each is rewritten to the documented form -- read, edit, put back. Full unit suite: 5488 passed, 0 failed. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS][docs] CHANGELOG entry for the restored copy semantics (#9792) Records the BREAKING getter-ownership change and the set_drift_time_array buffer fix in the 3.6.0 PyOpenMS section. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS] Address review findings on the ownership change (#9792) Functional: - DTA2DFile and ConsensusXMLFile lost every route to configure their PeakFileOptions: both C++ classes expose only `PeakFileOptions& getOptions()` and no setter, so once the getter returned a copy the options could not be set at all. Both now bind setOptions(), matching the other nine file classes. - TargetedExperiment.getPeptideByRef()/getCompoundByRef() still carried reference_internal and handed out mutable aliases into the stored vectors -- the exact hazard this branch removes elsewhere, and inconsistent with getProteinByRef(). All three now return copies; setProteins()/setPeptides()/setCompounds() are the write-back path. - MassTraces had a copy-returning __getitem__ and no __setitem__; the container protocol is symmetric again. Documentation accuracy: - OWNERSHIP.md: document the shared_ptr carve-out. getDataProcessing() copies the list, but its entries are shared by design, so an in-place edit of an entry is visible through the owner. Deep-copying would break that sharing; the write-back rule stays the safe habit. - Stale "Returns a reference" wording on spectrumRanges, chromatogramRanges, Gradient.getEluents and Gradient.getTimepoints. - getCVTerms carried getAccession's description, in both the def_CVTermList template and the CVTermList class binding. - FLASHDeconvAlgorithm and SpectralDeconvolution had a whole run of docstrings shifted by one method (getAveragine documented run(), getDecoyAveragine documented getAveragine, and so on). Realigned against the C++ headers. - README_WRAPPING_NEW_CLASSES.md: nb::handle() is not a valid scope for make_iterator's lazily created type; use nb::type<T>(). Fixed the two remaining OWNERSHIP_PROPOSAL.md references. Tests: file-options round trips for six classes, ByRef copy semantics for all three TargetedExperiment entry types, the MassTraces protocol, and the shared_ptr carve-out pinned so doc and behaviour cannot drift. Full unit suite: 5663 passed, 0 failed. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS] Close the remaining aliasing getters found in review (#9792) A third binding shape -- `&Class::method` pointer-to-member instead of a lambda -- was never reached by the earlier conversion sweeps, which all matched on `[](Class& self)`. Seventeen getters in that shape still carried reference_internal. All return `const T&`, so dropping the policy lets nanobind's default resolve the lvalue reference to a copy: - OSWData/OSWProtein/OSWPeptidePrecursor/OSWPeakGroup/OSWTransition (getProteins, getPeptidePrecursors, getFeatures, getTransition, ...) - IDRipper::RipFileIdentifier and RipFileContent - IonImage.getMzRange, MSImagingGeometry.getRegions/getRegion - MassExplainer.getCompomerById (policy sat on a continuation line) Also aliasing, now returning owned values: - AASequence.getNTerminalModification/getCTerminalModification and Residue.getModification returned a `const ResidueModification*` into the process-wide ModificationsDB with reference_internal -- a mutable alias (nanobind erases const, and ResidueModification binds ~30 setters), so editing one corrupted that modification for every sequence in the process. Now std::optional<ResidueModification>, which also keeps the None-when-unmodified result. Their docstrings had claimed "a copy". - NASequence.getSequence handed out mutable aliases into RibonucleotideDB. - Param.getEntry aliased into a user-owned Param; ParamNode's two finders returned raw pointers, which the default policy resolves to `reference`, so a by-value return was needed rather than only dropping the token. MRMTransitionGroup was left with no write-back path at all: getFeaturesMuteable/getTransitionsMuteable/getChromatograms/ getPrecursorChromatograms now copy, but the class binds no whole-collection setter and add* appends rather than replaces, so an in-place edit was an unrecoverable no-op. (5764d80 justified the conversion with "the class binds addTransition and addFeature" -- append is not replace, so that was wrong.) Adds setFeatures/setTransitions/setChromatograms/setPrecursorChromatograms to both instantiations. No non-ndarray, non-fluent-builder reference_internal remains, so OWNERSHIP.md's claim now holds. Its exception list is corrected: database lookups are an exception only for the DB singletons' own accessors, since an entry reached through your own object is now a copy. The migration section no longer says "from 3.6.0" -- aliasing was introduced and removed inside the same unreleased cycle. Also: getSpectrumAccessOpenMSPtr stops at the first cached_data marker instead of copying every spectrum in the run, and a chaining test's `in (True, False)` assert (true for any bool) is now `is False`. Full unit suite: 5669 passed, 0 failed. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS] Verification pass on the review fixes (#9792) Two things the review's own findings did not name, found while checking its claims against the code: - ParquetFilterBuilder.filter() still aliased. It is the chain terminator -- it hands out the builder's accumulated ParquetFilter, not the builder itself -- so reference_internal made the returned filter keep changing as the builder was extended further. Now returns a copy. This was the last getter outside the two documented exception classes. - test_terminal_modification_is_interned_not_aliased asserted `stored is not mod`, which proved interning only while the getter aliased. Now that it copies, that assertion passes either way and the test could no longer detect raw-pointer storage. Restored its power by reading the modification back through the sequence after dropping the Python object. Re-audited with a statement-aware scan rather than a per-line one. The 48 remaining reference_internal policies are 8 zero-copy ndarray views and 40 in-place operators / fluent builders that return the object they were called on (`return self += rhs`, `self.andNext()`, ...). All 13 make_iterator sites carry keep_alive<0,1>. Full unit suite: 5669 passed, 0 failed. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS] Don't wrap ParquetFilterBuilder; ParquetFilter is the API ParquetFilterBuilder is a C++-side ergonomics class: its own doxygen says it "wraps a ParquetFilter instance and forwards all condition-building operations". ParquetFilter already exposes the identical fluent API (eq/ne/lt/le/gt/ge/in/andNext/orNext/empty, each returning itself) and is the type the Parquet readers actually take, so in Python the builder was duplicate surface whose only extra was a filter() call to unwrap it. Its sole reference anywhere in the Python tree was inside _parquet_query.py, which nothing imports -- the live query builder is _ChromatogramQuery in pyopenms/addons/xicparquetfile.py, which keeps its own filter list and never touched the C++ builder. That module is repointed at ParquetFilter, a drop-in since it only ever called the shared fluent methods and never filter(). This also removes the last getter outside the documented exception classes: ParquetFilterBuilder.filter() was the chain terminator handing out the builder's accumulated filter. Full unit suite: 5662 passed, 0 failed. The count drops by 7 from the previous run because test_copy_constructors and test_docstrings parameterize 3 and 4 cases per bound class over dynamically enumerated class lists; no hand-written test was lost. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS] Fix stale key maps in the MRMTransitionGroup setters (#9792) The setters added in 5607ebe assigned straight through getXMuteable(), which replaces the vector but leaves MRMTransitionGroup's three key -> index maps untouched. Reproduced from Python: after a reordering setChromatograms, getChromatogram("a") returned the chromatogram named "b"; after a shrinking one, getChromatogram("b") indexed past the end of a one-element vector (the OPENMS_PRECONDITION guarding it is compiled out in release builds). Replacement now goes through the keyed add* API, keyed by native ID -- the same rebuild MRMTransitionGroup::subset() performs internally -- so the maps stay consistent for reorderings, growth and shrinkage alike, and the in-place write-back case is unaffected. Also from review: - NASequence.getSequence() skipped null entries, which would silently shift every later position; it now raises instead. - FLASHDeconvAlgorithm.getAveragine/getDecoyAveragine documented calculateAveragine(), which that class does not bind (SpectralDeconvolution does, so its wording stands). They now name run(). - OWNERSHIP.md said the remaining reference_internal policies were all numpy views. They are not: the in-place operators and fluent builders use it too. Both cases are now named so a future audit expects them. - test_residue_modification_is_a_copy only checked that a modification exists; it now mutates the returned copy and asserts ModificationsDB is untouched. - Reindented getSpectrumAccessOpenMSPtr to 4-space steps; it was the only 6-space block in an otherwise 4-space file. Removed pyopenms/_parquet_query.py: nothing imports it, the live query builder is _ChromatogramQuery in addons/xicparquetfile.py, and its ChromatogramQuery.to_dict() called a _get_data_dict_from_parquet_filter() that exists nowhere in the repository. Full unit suite: 5662 passed, 0 failed. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS] Realign the PEFFFile and InternalCalibration docstrings (#9792) The last outstanding review item, and the shift ran further than the review noted: every PEFFFile docstring from readStart through writeEnd described the *previous* method, so readStart documented store(), getHeaders documented readNext(), atEnd documented getHeaders(), both writeStart overloads documented atEnd(), writeNext documented writeStart(), and writeEnd documented writeNext(). All seven realigned against PEFFFile.h. InternalCalibration.getCalibrationPoints() carried fillCalibrants()'s entire parameter block (pep_ids, tol_ppm, "Number of calibration masses found") although it takes no arguments and returns CalibrationData. Same defect family as the FLASHDeconvAlgorithm and SpectralDeconvolution docstrings fixed in 5607ebe. Full unit suite: 5662 passed, 0 failed. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS] MRM setters preserve caller-supplied lookup keys (#9792) The rebuild added in a440f7b re-added every element keyed by getNativeID(), but addTransition/addChromatogram/addPrecursorChromatogram take a key that is independent of the native ID. Reproduced: a chromatogram added under "custom_key" with native ID "native_id" lost that key on a plain no-edit write-back -- hasChromatogram("custom_key") went False and the entry was silently re-keyed to "native_id". MRMTransitionGroup exposes no way to enumerate or rebuild its key -> index maps, so a faithful rebuild is impossible from the binding layer. What is possible, and is exactly what these setters exist for, is positional replacement: element i keeps its key, every key keeps pointing at a valid index. So the setters now assign in place and refuse a size change with a message pointing at the add*() methods, which are the supported way to grow a keyed collection. This also drops the earlier out-of-bounds hazard by construction rather than by rebuilding. setFeatures is unaffected -- features carry no key map. Full unit suite: 5663 passed, 0 failed. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS] Close the NASequence aliasing gap and three smaller review findings (#9792) A fresh review pass over the full diff found seven issues; all verified against the code before fixing. NASequence was the one subsystem the conversion missed end to end: - __getitem__, __iter__, get(), getFivePrimeMod() and getThreePrimeMod() still returned live mutable aliases into the process-wide RibonucleotideDB (rv_policy::reference; nanobind erases const), so na[0].setName(...) corrupted that ribonucleotide for every sequence in the process -- the same class of bug closed for AASequence/ResidueDB. All five now return owned copies (optional for the terminal mods); __iter__ materialises the copies and iterates those, so it is self-contained rather than keep-alive-guarded, and the keep-alive refcount test now recognises that design (the two outlives-tests still pin its safety directly). - The documented round trip was impossible: getSequence() returns owned copies, but the setters gated on POINTER IDENTITY with a DB entry, so setSequence(getSequence()) always raised. requireDBRibonucleotide_ is now resolveDBRibonucleotide_: identity is irrelevant, the code is looked up and the database's own entry is stored (so nothing can dangle); a code not in the DB is still rejected. MSExperiment/MSImagingExperiment: - getSpectrum(id)/getChromatogram(id) wrapped an unchecked C++ spectra_[id]; the copy conversion made the out-of-bounds read unconditional. Both now raise IndexError like __getitem__. - The imaging per-pixel getter copied with no way back; setSpectrum(x, y, spectrum) is the write-back, assigning through the mutable C++ getter so pixel validation is shared. SimpleOpenMSSpectraFactory: - The cached_data probe now runs C++-side (_contains_cached_data_marker), so building a SpectrumAccess no longer copies every spectrum of the run just to read DataProcessing metadata. - Exercising the factory revealed it has been broken on develop all along: _python_extras.py never imported SpectrumAccessOpenMS or SpectrumAccessOpenMSCached, so BOTH branches raised NameError and nothing ever called it. The import is fixed for the uncached branch; the cached branch raises a clear NotImplementedError because SpectrumAccessOpenMSCached is not wrapped in the nanobind port at all (pre-existing port gap, out of scope here). Documentation: - FileHandler.getFeatOptions docstring said "Mutable access" for a copy-returning getter. - CHANGELOG and the chaining-test docstring said two exceptions where OWNERSHIP.md documents three; all three files now agree. Tests: NASequence non-aliasing + round trip, bounds checks, per-pixel write-back, and the first test that actually calls the factory. Full unit suite: 5668 passed, 0 failed. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS] Opt-in aliasing access under the explicit _view naming scheme (#9792) Copies stay the default on every plain getter; when copying is too expensive and the caller accepts the hazards, the _view family is the named, deliberate way in (matching get_peaks_view()/get_data_view(), which already use the suffix for zero-copy numpy views): - singular + _view -> one live element get_spectrum_view(i), get_chromatogram_view(i), get_feature_view(i) - plural + _view -> list of live elements get_spectra_view(), get_chromatograms_view(), get_features_view() - iter_<singular>_views() -> iterator of live elements iter_spectrum_views(), iter_chromatogram_views(), iter_feature_views() Contract (stated once in OWNERSHIP.md): edits through a view land immediately, every view keeps its parent alive, and a view is valid only until the underlying list is resized or reordered -- the documented #9792 hazard the name opts into. Only the single-element views are bound in C++ (bounds-checked, reference_internal so each wrapper carries the parent keep-alive and has stable identity via nanobind's instance map). The plural and iterator forms are Python addons that call the bound element view per element, so every yielded view inherits the keep-alive from the binding -- no manual lifetime plumbing. README_WRAPPING_NEW_CLASSES.md records that recipe for future wrappers; CHANGELOG records the scheme. Verified empirically before pinning: edit-lands, stable identity, parent-outlives-del, bounds errors, all three forms per class, and that the unsuffixed getters still copy. 10 tests in test_view_accessors.py. Full unit suite: 5676 passed, 0 failed. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS] Extend the _view family and iterate views in DataFrame exports (#9792) Extend the opt-in aliasing accessors to the remaining containers where element copies dominate runtime, and convert pyOpenMS's own Python helpers to iterate views instead of copies. New C++ element views (rv_policy::reference_internal, bounds-checked), each with plural get_*_views() and iter_*_views() addon counterparts: - ConsensusMap.get_consensus_feature_view(i) - PeptideIdentificationList.get_peptide_identification_view(i) - MSSpectrum/MSChromatogram.get_{float,integer,string}_data_array_view(i) (chains with .get_data_view() for a fully zero-copy numpy path) - MRMTransitionGroupCP / LightMRMTransitionGroupCP .get_feature_view(i) and .get_chromatogram_view(i) Private _*_count helpers back the plural/iter addons so they no longer copy whole collections just to learn their length. Addon hot loops now iterate views internally (get_df/get_ion_df/ to_df exports, meta-value sweeps, update_scores_from_df — which now edits through a view instead of copy + write-back). Iterating spectra of a peak-heavy experiment this way measures ~100x faster than the copying default. Docs: OWNERSHIP.md lists the classes with view support and the zero-copy chain; CHANGELOG notes the availability and speedup. Tests: five new cases in test_view_accessors.py covering the new views, including a data-array edit landing in the owning spectrum. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * Add missing ctest DEPENDS for two FuzzyDiff output tests TOPP_FeatureFinderMetabo_4_out and TOPP_FeatureFinderMultiplex_7_out2 were the only two of 767 FuzzyDiff comparison tests without a DEPENDS on the tool run that produces their input, so a parallel ctest could schedule them before (or concurrently with) their producers and fail on a missing/partial temp file. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS] Drop the get_ prefix from aliasing accessors (#9792) The get_ prefix now unambiguously means "returns an owned copy", so accessors that alias never carry it. The name split is the ownership contract: get_* -> owned copy (the default rule) *_view / *_views / *_struct -> zero-copy alias of the parent Renames (nothing here has shipped -- the nanobind port is first released in 3.6.0): - element views: get_spectrum_view -> spectrum_view, and likewise feature_view, chromatogram_view, consensus_feature_view, peptide_identification_view, {float,integer,string}_data_array_view - list forms: get_spectra_view -> spectrum_views etc.; the plural noun gave way to <singular>_views to mirror iter_<singular>_views and to avoid double plurals like features_views - numpy views: get_data_view -> data_view, get_matrix_view -> matrix_view, get_{mz,intensity,time,drift_time}_array_view -> same minus get_ - struct views: get_peaks_struct -> peaks_struct, get_pixels_struct -> pixels_struct The deprecated _mv aliases now delegate to the new names (old alias names unchanged). Docs (OWNERSHIP.md, README, performance.rst, CHANGELOG) state the prefix rule; tests renamed alongside. Full suite: 5681 passed, 80 skipped, 11 xfailed, 7 xpassed. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS][docs] Teach the view family in the user guide (#9792) The user-guide examples never mentioned zero-copy access. Introduce the _view naming scheme where the tutorials cover the patterns it serves: - ms_data.rst: after the copy-based intensity-sum example, explain that iteration/indexing/getSpectrum return owned copies, show the same sum through iter_spectrum_views(), and state the aliasing contract in a caution block (resize/sort invalidates views; get_* copies, *_view/*_views/*_struct alias). plot_spectra_2D now iterates views; the peak-access note mentions peaks_struct(), and the data-array section shows the float_data_array_view(0).data_view() chain. - first_steps.rst: note in the iteration section that iteration hands out copies, pointing at iter_spectrum_views() and the MS data chapter. All new/changed example code executed against the built module (zero-copy sum matches the copy-based sum at 700.0; the data-array view chain writes through to the spectrum). Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS][docs] Explain ownership semantics for beginners in Getting Started (#9792) Add a "Copies, Not References" section to first_steps.rst, placed right after the reader first indexes and iterates an experiment: the one rule (everything you take out of a container is your own copy), the surprise it prevents (editing the copy does not edit the experiment, shown with real tiny.mzML output), the read-it/edit-it/put-it-back pattern, why the alternative is dangerous, and the naming contract (get_* copies; _view/_views/_struct alias) with a pointer to the MS data chapter. Folds in the earlier short copies-note, which sat between a sentence and its code block and interrupted the flow. Both snippets executed against the built module (353.43 unchanged after the copy edit; 999.9 after write-back). Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS][docs] Drop the layman analogies from the ownership section (#9792) State the rule technically: containers use value semantics for element access, returned objects own their data. Replaces the photocopy/binder analogy, and tightens the rationale to name the actual failure modes (use-after-free on reallocation, re-binding on sort). Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS] Address review findings: None clears NASequence terminal mods (#9792) NASequence.setFivePrimeMod/setThreePrimeMod now accept None to clear the modification: the C++ setters store the pointer without dereferencing and nullptr is the documented "no modification" state, but the binding rejected None before the lambda ran, leaving no way to clear a terminal mod from Python. Non-None values still resolve against RibonucleotideDB; the blanket None-rejection test drops these two entries (with a comment on why the AASequence setters stay: their pointer overload dereferences, and clearing goes through setNTerminalModification("")) and gains a set-then-clear round-trip test. Smaller findings from the same review: - performance.rst: each benchmark is now a complete, runnable timeit command (shared setup hoisted into a shell variable) - README_WRAPPING_NEW_CLASSES.md: plural view form corrected to <singular>_views() per the established naming scheme - OWNERSHIP.md: the reference_internal audit note now lists all three aliasing categories (numpy views, the _view element family, in-place operators/builders) - test_chaining_semantics.py: "two documented exceptions" heading no longer contradicts the three cases OWNERSHIP.md documents - test_zerocopy_conventions.py: deprecation-message assertions reject the removed get_-prefixed names instead of matching them as substrings - test_set_ion_mobility.py: the length-change test now exercises set_drift_time_array's own storage-replacement branch (shrink peaks with metadata="keep", then replace the stale array) as its docstring claims Full suite: 5681 passed, 0 failures. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS][docs] Document the OpenSwath shared_ptr types under the sharing exception (#9792) The shared-ownership exception claimed getDataProcessing() was the only shared-alias surface. The OpenSwath interchange types are the same category: OSSpectrum/OSChromatogram array accessors and the ISpectrumAccess getSpectrumById()/getChromatogramById() return shared_ptrs because sharing arrays between pipeline stages without copying is that data model's purpose. Name them so the "and nothing else" claim is actually true. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS][docs] Drop the migration section from OWNERSHIP.md (#9792) Aliasing was introduced and removed inside the same unreleased 3.6.0 development cycle, so there is no released version to migrate from and the section only addressed hypothetical code written against a dev build. A one-sentence note in "Why it works this way" keeps that fact; the CHANGELOG pointer no longer mentions migration patterns. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS][docs] Ownership coverage for the FAQ and contributor guides (#9792) Audit of the doc surfaces found three gaps, all fixed: - faq.rst: the first entry now answers the top newcomer question ("I modified a spectrum from my experiment, but the change is gone") with the read-edit-put-back pattern, the _view escape hatch, and the get_*-copies rule (snippets executed against the built module) - README.md: the zero-copy convention table gains the element-view family row and states the get_ prefix rule up front, pointing at OWNERSHIP.md - CLAUDE.md: the class-wrapping instructions open with the ownership rule so new bindings don't reintroduce reference_internal getters Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS][tests] Pin the ndarray contract of the numpy copy accessors (#9792) The view family's array-ness was already asserted (isinstance + dtype in test_zerocopy_conventions.py, with writeback tests proving aliasing), but most tests exercise the *copy* accessors through np.allclose()/len(), which accept plain Python lists just as well. A binding regression that fell back to the std::vector caster would therefore pass unnoticed while silently changing dtype, memory cost and vectorized semantics. New test_copy_accessors_return_numpy_arrays covers every accessor documented "as numpy array": get_peaks() on MSSpectrum, MSChromatogram and Mobilogram (both halves), get_mz_array()/get_intensity_array(), Float/IntegerDataArray.get_data(), MatrixDouble.get_matrix(), and MSExperiment.get2DPeakData()/get2DPeakDataLong() — isinstance(np.ndarray) plus the exact dtype for each. The OpenSwath get_*_array() copies return lists by documented contract (their ndarray path is *_array_view()), recorded in the docstring. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS][docs] Tighten view-invalidation and empty-behavior wording Two review findings on the docs: - faq.rst said views survive until the container is "resized or sorted"; OWNERSHIP.md's contract is resized or *reordered*, with sorting as one example. The FAQ now matches the contract. - README.md's element-view table row claimed "IndexError on out-of-range" for all three access forms; only the indexed form can raise. The plural forms now document their empty-result behavior (empty list / exhausted iterator). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS] Return caster-handled element access by value The review noted the three DataArray __getitem__ bindings still returned float&, int& and std::string&. That was safe — nanobind's casters copy arithmetic and string values into new immutable Python objects at the call boundary, so no alias can reach Python — but the signatures looked exactly like the aliasing pattern this PR removes. Return them by value so the signature states the copy rule; for the string this trades one extra copy per element access (bulk access is get_data()). A sweep over all binding files for the same pattern found three more const std::string& returns on FeatureFinderMetaboIdentCompound (getName/getFormula/getAdduct), now also by value. Vector-reference returns stay const& deliberately: the list caster copies every element anyway, and by-value would copy the vector twice. The CLAUDE.md wrapping guide now records the rule (scalars/strings by value, vector const& acceptable, aliasing only arises for bound classes). Full pyOpenMS suite: 5682 passed, 0 failed. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS] Reject modified Ribonucleotide copies instead of silently resolving resolveDBRibonucleotide_ resolves the passed object by code and stores RibonucleotideDB's own entry. If the caller had edited their copy (setAvgMass, setName, ... are all bound), those edits were silently discarded: seq.set(0, edited) succeeded and stored the pristine database entry. The pre-#9947 guard rejected such objects loudly. The resolver now compares the resolved database entry against the passed object with Ribonucleotide::operator== (all fields) and raises ValueError on mismatch, pointing at registering the modification in RibonucleotideDB. Unmodified round trips (seq.set(0, seq[0]), setSequence(getSequence()), terminal mods) are unchanged. Covers set(), setSequence(), setFivePrimeMod() and setThreePrimeMod(), which all funnel through the resolver. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS] Index-based iterators: mutation during iteration is defined The __iter__ bindings used nb::make_iterator, which stores raw C++ begin()/end() iterators. Mutating a container while a Python iteration was in flight (for s in exp: exp.addSpectrum(...)) invalidated those iterators and dereferenced freed memory on the next step -- the same push_back-reallocation class this PR closes for held elements (#9792), surviving in the iterator object itself. All twelve element-container iterators (MSExperiment, FeatureMap, ConsensusMap, MSSpectrum, MSChromatogram, Mobilogram, PeptideIdentificationList, AASequence, IsotopeDistribution, DeconvolvedSpectrum, PeakGroup, Param) are now safe: - index_value_iterator.h: an iterator holding a strong reference to the parent plus an index; every step bounds-checks against the container's *current* size and returns an owned copy. Mutation during iteration is therefore defined exactly like Python's list iteration -- appended elements are visited, shrinking ends the loop early -- and can never touch freed memory. The owner reference replaces nb::keep_alive. - Param has no index access (its ParamIterator walks the entry tree), so its __iter__ snapshots owned entry copies up front instead. test_iterator_mutation_safety.py pins the new semantics (growth with reallocation, shrink-stops-early, snapshot, copies stay intact); test_iterator_lifetime.py's retention test now checks the owner reference and skips Param alongside NASequence (a snapshot has nothing to retain -- its outlives tests still run). OWNERSHIP.md documents the list-like contract. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS] Iterate views in the DataFrame/Arrow/MassQL export paths OWNERSHIP.md and the CHANGELOG state that pyOpenMS's own DataFrame exports iterate views internally so the copy rule costs nothing there, and get_ion_df plus the FeatureMap/ConsensusMap/PeptideIdentificationList addons were converted accordingly -- but the largest paths still iterated copies: to_df()/to_arrow() (_build_spectra_arrow, both formats), get_massql_df() (both MS levels), _dataframes.py (both formats), and MRMTransitionGroupCP.to_chromatogram_df()/to_feature_df(). Each copied every spectrum or chromatogram (peaks and data arrays included) just to read it -- ~120x slower than view iteration on the PR's benchmark data. All eight loops now use the view accessors (iter_spectrum_views(), chromatogram_views(), feature_views()). The loop bodies only read and extract values, so aliasing is safe; output is unchanged (pinned by the existing DataFrame/MassQL tests). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH * [pyOpenMS] Generate the plural/iterator view families from one template The 15 <singular>_views() / iter_<singular>_views() pairs (MSExperiment spectra+chromatograms, FeatureMap, ConsensusMap, PeptideIdentificationList, the three data-array families on MSSpectrum and MSChromatogram, and both MRMTransitionGroup instantiations) were hand-written near-identical copies across seven addon files — 30 functions whose docstring wording had already started to drift. addons/__init__.py gains register_element_views(class_name, singular, count_method, plural): it fabricates both functions with proper __name__/__doc__ and registers them through the existing addon machinery. Each family is now one declarative line next to the file's other addons; behavior, names, and IndexError/aliasing semantics are unchanged (pinned by test_view_accessors.py and the export paths, which run through the generated iterators). The C++ side's <singular>_view(i) + count blocks stay hand-written on purpose: their accessor expressions, bounds checks and docstring tails differ per container, and a functor-parameterized template would hide the reference_internal + bounds check each site needs to show. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH --------- Co-authored-by: Claude <[email protected]>
* [pyOpenMS] Element access returns owned values, not aliases (#9792)
Indexing and iterating a container now yield an owned copy on every element
container, instead of a live alias into the container's storage. Writes go
back through __setitem__.
This restores the semantics of the Cython bindings up to release 3.5, where
the autowrap wrapper representation (a shared_ptr-owned C++ instance per
wrapper) structurally forced a copy on every wrapped-type return. The nanobind
port made these paths reference_internal aliases, which is the root of the
use-after-free and wrong-element-write failures catalogued in #9792 -- and it
was a side effect of the port rather than a decision.
Converted (indexing and iteration, both directions now agree):
MSSpectrum -> Peak1D (__iter__ was aliasing; __getitem__ already copied)
MSChromatogram -> ChromatogramPeak
Mobilogram -> MobilityPeak1D
MSExperiment -> MSSpectrum / MSChromatogram, incl. getSpectrum,
getChromatogram, getSpectra, getChromatograms
FeatureMap -> Feature
ConsensusMap -> ConsensusFeature
getSpectra()/getChromatograms() are included because they were declared by
value in the 3.5 pxd (libcpp_vector[MSSpectrum] getSpectra()), i.e. they
copied there too; test_AcquisitionInfo.py still uses the copy-and-write-back
idiom that only makes sense under copy semantics, and it keeps passing.
keep_alive<0,1> is retained at all 13 make_iterator sites. It guards the
iterator object, which still holds raw C++ iterators, and is a separate
concern from the element policy -- removing it would reopen #9794.
Verified by compiling a standalone nanobind module reproducing the exact
pattern, with the old reference_internal bindings kept as negative controls:
copies do not leak edits, aliases do; a held spectrum survives 5000
addSpectrum calls intact, while the aliased control degrades to
rt=2.6e-315 and a len() that overflows; the iterator still outlives its
container.
Also updates the container-protocol template in
README_WRAPPING_NEW_CLASSES.md, which taught the aliasing pattern and is how
it spread, and the three peak-access class docstrings.
Not in scope, and still aliasing: reference-returned vectors of sub-objects
(getHits, getFloatDataArrays, getPrecursors, ...) and AcquisitionInfo. These
were also copies in 3.5, so they are the natural next step, but there are
~105 such sites and they are a separate change. The boundary is pinned by
tests so it stays deliberate.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] Drop inert reference_internal policies; stop materialising whole
data-array vectors to read one element
Two preparatory changes, both independently useful and neither altering
behaviour. They clear the way for converting the object-element vector getters
(getHits, getFloatDataArrays, getPrecursors, ...) to value semantics, which is
the remaining half of the #9792 element-access work.
1. Inert rv_policy::reference_internal removed from 29 bindings.
These return a reference to a scalar/string, or to a vector of them
(vector<double>&, vector<std::string>&, float&, int&, std::string&).
nanobind's value casters ignore rv_policy: Python receives immutable floats,
ints and strings, so no alias exists and the policy never did anything. It
was actively misleading -- a reader of FloatDataArray.__getitem__ returning
`float&` with reference_internal reasonably concludes fda[0] aliases -- and
it inflated every audit count and every VI.11 grep in #9792 by ~10%.
Verified the diff touches nothing but the policy token: 29 changed line
pairs, each differing from its original only by removal of that token.
Worth recording, because it makes the remaining count meaningful: `const` in
the binding signature does NOT make a getter read-only from Python. nanobind
erases C++ constness, so a `const std::vector<T>&` with reference_internal
still hands out mutable aliasing wrappers. Confirmed by compiling a minimal
module: mutating through a const-returned getter changed the owner's value.
The real object-aliasing surface is therefore 77 sites, not the 38 non-const
ones.
2. Five call sites no longer fetch every data array to read one.
`spec.getFloatDataArrays()[im_idx]` materialises a Python wrapper for every
float data array of the spectrum, then uses one. All five sites sit inside
per-spectrum loops on the dataframe export paths (get_df, get_massql_df,
get_ion_df, the Arrow builders), so this ran once per spectrum over whole
files. They now call get_drift_time_array(), which already existed and does
the same resolution in C++, copying only the ion mobility array.
This is also what makes converting getFloatDataArrays() to a copy safe
later: as written, those loops would have deep-copied every array of every
spectrum.
Behaviour is preserved exactly at each site: get_drift_time_array() returns
None on precisely the containsIMData() condition, so it replaces the guard
in three sites, the try/except RuntimeError plus bounds check in get_ion_df,
and in get_massql_df the raise-on-missing is kept explicitly. It already
returns float32, so the dtype conversions were redundant.
The remaining getFloatDataArrays() uses are `for fda in ...` loops that
genuinely need every array; those are left alone.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] Core data classes: vector getters return owned values (#9792)
Extends the element-access policy to the reference-returning vector getters on
the classes users touch most: MSSpectrum, MSChromatogram, MSExperiment,
FeatureMap, ConsensusMap, Feature, ConsensusFeature, PeptideIdentification,
ProteinIdentification, PeptideHit, SpectrumSettings, ExperimentalSettings,
AnnotatedMSRun, BinnedSpectrum. 32 getters, among them getFloatDataArrays /
getIntegerDataArrays / getStringDataArrays, getHits, getPrecursors,
getProducts, getProteinIdentifications, getPeakAnnotations,
getPeptideEvidences, getDataProcessing, getConvexHulls, getSubordinates.
These were declared by value in the 3.5 pxd (libcpp_vector[PeptideHit]
getHits()), so they copied under the Cython bindings; the nanobind port made
them reference_internal, and nanobind's list caster propagates the policy per
element, so each call handed out N wrappers aliasing the container. Writes go
through the existing setters, which is the idiom the 3.5-era tests already use.
Worth recording: `const` on the C++ return bought nothing. nanobind erases
constness, so `const std::vector<T>&` with reference_internal still produced
mutable aliasing wrappers -- confirmed by compiling a minimal module and
mutating through a const-returned getter. So the aliasing surface here was the
full set, not just the non-const half.
Two things this exposed that are worth flagging for review:
- Six of the getters (the three data-array pairs on MSSpectrum and
MSChromatogram) are multi-line, carrying rv_policy on the closing line rather
than the .def line. Changing the return type without also removing the policy
would have left `reference_internal` on a by-value return -- i.e. element
wrappers aliasing into a temporary vector destroyed at the end of the call,
which is worse than what was there before. Verified zero value-returning
getters carry the policy now.
- getDataProcessing returns vector<shared_ptr<DataProcessing>>. Copying the
vector copies the shared_ptrs, so the pointees stay shared. That is the
intended semantics for shared_ptr and is unchanged by this commit; it does
mean a "copy" here is not an isolated deep copy.
Nine docstrings that advertised "a const reference to ..." were corrected; they
would otherwise have described the opposite of the behaviour.
Five regression tests added for the copy semantics and the write-back route.
The two tests that pinned getHits() as aliasing are updated -- they recorded
the pre-existing boundary, which this commit moves.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] Remaining vector getters return owned values (#9792)
Completes the conversion started in the previous commit, covering the long tail:
TargetedExperiment (11 getters), Instrument, InstrumentSettings, Residue,
ResidueModification, CVMappings, IncludeExcludeTarget, TraMLProduct,
ReactionMonitoringTransition, MRMTransitionGroup (both template
instantiations), Sample, IsotopeDistribution, ChromatogramSettings,
MetaInfoDescription, PEFFFile, MultiplexDeltaMasses(Generator) and the eight
isobaric quantitation methods. 50 getters converted.
With this, no vector getter returning wrapped OpenMS objects hands out aliases,
and none carries rv_policy::reference_internal. Verified both directly.
The `*Muteable` accessors on MRMTransitionGroup are included rather than
exempted. An earlier reading treated them as deliberate mutation handles whose
purpose a copy would defeat; that was wrong -- the class binds addTransition
and addFeature, so the write path is unaffected. Likewise
IsotopeDistribution::getContainer (the class binds set() and insert()) and
TraMLProduct's list getters (addConfiguration / addInterpretation). The five
accessors that genuinely have no write path -- getChannelInformation on the
isobaric methods, BinnedSpectrum::getPrecursors, PEFFFile::getHeaders and the
two MultiplexDeltaMasses getters -- belong to read-only config or result
objects whose classes bind getters only, so a copy is the correct return there
rather than a limitation.
Two getters in this set were reclassified as inert rather than converted, since
their element types go through value casters and never aliased:
Param::getValidStrings (std::basic_string<char> is std::string) and
ConvexHull2D::getHullPoints (DPosition<2> has a custom caster and is not bound
as a class; a vector of them becomes a numpy array). They only lose the
misleading policy.
Six more docstrings advertising "a reference to ..." corrected.
Alias surface across the bindings: 356 rv_policy::reference_internal sites at
the start of this branch, 227 now. The remainder are single-object member
accessors (getInstrumentSettings, getSample, getOptions and similar), which are
a separate category and untouched here.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] Convert the remaining aliasing __getitem__/__iter__ bindings (#9792)
The earlier commits converted the six containers I had enumerated by hand and
stopped there. Fourteen element accessors were left aliasing, which is the same
enumeration failure #9792 keeps catching -- Part I of the issue names five of
them explicitly as confirmed-at-runtime aliasing element accessors and records
that 16 of 21 __getitem__ bindings returned references.
Converted to owned values: DeconvolvedSpectrum, AASequence, IsotopeDistribution,
MassTraces, AcquisitionInfo, PeptideIdentificationList, plus the PeakGroup and
Param iterators. After this there are no aliasing __getitem__ or __iter__
bindings left in the tree, verified directly.
AASequence is the one with a sharper motivation than consistency. It stores
std::vector<const Residue*> pointing into ResidueDB (AASequence.h:622), so
seq[i] returned a reference to a process-lifetime database entry -- and since
nanobind erases constness, Python got a mutable handle on it. Editing a residue
obtained that way changed it for every sequence in the process, including ones
constructed afterwards. That is the same corruption shape as V.4 (#9803),
reached through a different entry point, and copying removes the route rather
than guarding it. A regression test covers it.
Two of the fourteen were dead code rather than live aliases: PeakGroup
(bind_analysis.cpp) and DataFilters (bind_processing.cpp) each registered a
by-value __getitem__ *ahead* of a reference_internal one with the same
signature. nanobind resolves overloads in registration order, so the by-value
one always won and the second was unreachable -- as #9792 I.1 describes. Those
registrations are removed rather than converted; observable behaviour is
unchanged. No class now registers __getitem__ twice.
keep_alive<0,1> is retained at all 13 make_iterator sites; it guards the
iterator object, not the elements, and dropping it would reopen #9794.
MassTraces gains no write path from this: the class binds getters only, so it
is a read-only algorithm result and a copy is the correct return. The other
converted containers all have __setitem__ or push_back.
Alias surface: 356 rv_policy::reference_internal sites at the start of this
branch, 213 now. What remains is member sub-object accessors, keyed lookups and
self-returns -- categories that need their own decision, since a member's
address cannot be invalidated independently of its parent and the keep-alive
edge is a complete guarantee for it now that every container element is an
owned Python object.
Six regression tests added.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [FIX][pyOpenMS] set_drift_time_array: don't free a buffer a live view points into
installIonMobilityArray replaced an existing ion mobility array with
self.getFloatDataArrays()[self.getIMData().first] = std::move(fda);
DataArrays::FloatDataArray derives from std::vector<float>, so that
move-assignment deallocates the destination's float storage. Meanwhile
get_drift_time_array_view() (bind_spectrum.cpp) hands numpy a raw arr.data()
pointer with only the owning Python object as a keep-alive -- never the buffer
-- and FloatDataArray.get_data_view() does the same. Reading such a view after
the replacement was a use-after-free with the nanobind ownership graph fully
intact and nothing to notice the free:
v = s.get_drift_time_array_view()
s.set_drift_time_array(new_values)
v[0] # reads freed memory
Also reachable through set_peaks(..., ion_mobility=...) on the default
metadata="error" policy, because the alignment check deliberately exempts the
array that call is about to replace.
Fix: when the replacement has the same length -- which is the normal case, since
both entry points require one entry per peak -- copy the values into the
existing storage and assign the MetaInfoDescription base separately. The buffer
address is unchanged, so live views stay valid and simply observe the new
values, which is how a zero-copy view behaves for any other in-place write. The
metadata is still replaced wholesale, as the move-assignment did, so the unit
carried by the array name is updated exactly as before. Only a length change
still replaces the storage, where no view could survive regardless.
Verified the premise by compiling the two paths against a struct with
FloatDataArray's shape (a metadata base plus std::vector<float>): move-assign
reports the buffer replaced and the old one freed, the in-place path reports it
unchanged with the view observing the new values and the metadata transferred.
This is independent of the element-access work on this branch and predates it;
it was found while auditing the ownership proposal. Note the sibling route is
already safe as a side effect of the earlier commits: getFloatDataArrays() now
returns copies, so a view taken through it points into a Python-owned array
rather than the spectrum's storage. get_drift_time_array_view() was the
remaining route and is what this fixes.
Three regression tests added.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] Element access under other names: at/front/back/getResidue/getElement
Review of the branch found six element accessors that the earlier sweeps missed
because they are not spelled __getitem__ or __iter__. All returned references
into the receiver and are converted to owned values, matching the accessors
beside them:
AASequence.getResidue(i) -> Residue
ims::IMSAlphabet.getElement(i) -> IMSElement
PeptideIdentificationList.at(i) -> PeptideIdentification
PeptideIdentificationList.front() -> PeptideIdentification
PeptideIdentificationList.back() -> PeptideIdentification
MSImagingExperiment.getSpectrum(x, y) -> MSSpectrum
AASequence.getResidue is the one that mattered. The previous commit converted
AASequence.__getitem__ because it aliased a process-lifetime ResidueDB entry
that nanobind exposes as mutable, so editing it corrupted the residue for every
sequence in the process. getResidue(i) is the same call by another name and left
that route fully open, which made the previous commit message overclaim. It is
closed now.
Two of these were found only after widening the search twice: first from
__getitem__/__iter__ to any accessor taking an integer index, then to .def()
forms where the method name sits on a different line from the .def( token.
MSImagingExperiment.getSpectrum(x, y) is indexed by a 2D pixel coordinate and
was missed by both earlier patterns.
Two latent crashes fixed on lines already being rewritten, called out rather
than folded in silently: PeptideIdentificationList.front() and .back() had no
emptiness guard, so calling either on an empty list was undefined behaviour;
AASequence.getResidue had no bounds check in the binding, and the core's
OPENMS_PRECONDITION compiles to nothing in release builds. Both now raise
IndexError. at() needs no guard -- std::vector::at already throws, and nanobind
maps std::out_of_range to IndexError.
MSImagingExperiment.getMSExperiment() and getGeometry() were found by the same
sweep and deliberately left alone: they return the contained object itself, not
an element of it, so they belong to the member-accessor category that is still
open.
After this there are no aliasing element accessors of any spelling left in the
tree. Alias surface: 356 at the start of this branch, 207 now.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS][docs] Document copy/reference semantics; pin chaining with tests
The branch changed where copies happen but never tested chained access, which
is where the rules actually interact. Eight tests now pin the boundary, and
OWNERSHIP.md states it for users.
What the tests establish, verified against a compiled model of the same binding
shapes before being written against pyOpenMS:
spec.getInstrumentSettings().setZoomScan(True) lands (no container access)
exp[0].getInstrumentSettings().setZoomScan(True) LOST (exp[0] is a copy)
spec.getPrecursors()[0].setMZ(999.0) LOST (collection getter copies)
for s in exp: s.setRT(...) LOST
s = exp[0]; s.setRT(...); exp[0] = s lands, nested edits included
Reads are safe everywhere, including through a temporary produced mid-chain:
nanobind keeps the parent alive for as long as the object taken from it, so
exp[0].getInstrumentSettings().getZoomScan() is well-defined even though exp[0]
is a temporary. Only writes are affected.
The rule that follows is that a write lands exactly when the chain from a
variable you hold to the target crosses no container access and no collection
getter.
Recorded honestly in the document rather than glossed: this is two rules, not
one, and which applies is not visible at the call site -- getPrecursors()
copies while getInstrumentSettings() does not, and the names do not say so. The
~166 single sub-object getters are the last group returning references.
Converting them would collapse the document to its first sentence at the cost
of making algo.getParameters().setValue(...) a silent no-op. That decision is
open; the write-back form is correct under either outcome, so the document
recommends it unconditionally.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS][docs] Correct the cost stated for converting the sub-object getters
OWNERSHIP.md justified leaving ~166 single sub-object getters as references by
saying conversion would make algo.getParameters().setValue(...) a silent no-op,
"a common idiom". Both halves are wrong and the document should not carry them.
It is not common: no Python in this repository chains a write through
getParameters(), and exactly two lines chain one through any single sub-object
getter at all (chrom.getPrecursor().setMZ(...) and getProduct(), both in
test_dataframe_columns.py).
More to the point, it does not work. DefaultParamHandler::setParameters()
applies defaults, validates against them, and ends with updateMembers_(), the
hook algorithms override to copy parameter values into their own members
(DefaultParamHandler.cpp:44-70). Mutating the Param in place reaches none of
that, so the algorithm never picks the change up. setParameters() was always
required; the in-place form only looked like it worked.
Also states plainly why the two rules exist -- the split was made for memory
safety (a collection getter yields one alias per element; a single sub-object
cannot be invalidated independently of its parent) and that criterion is
invisible to callers, who only experience whether a write sticks.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] Single sub-object getters return owned values; one rule for all getters
Converts the last group of getters that handed out references into their
parent: 132 single sub-object accessors (getInstrumentSettings,
getAcquisitionInfo, getSourceFile, getParameters, getSample, getOptions,
spectrumRanges, getGeometry, and so on).
The policy is now uniform and statable in one sentence: every getter returns an
owned copy, and a change reaches its parent only through the matching setter.
Before this commit the split was between collection getters (copied) and single
sub-object getters (aliased) -- a real distinction, but one made for memory
safety, which is invisible to callers. What a caller experiences is whether a
write sticks, and on that axis the split was arbitrary: getPrecursors() and
getInstrumentSettings() look identical at a call site and behaved oppositely.
What the change costs, checked rather than assumed:
- Exactly two lines of Python in this repository chain a write through such a
getter (chrom.getPrecursor().setMZ(...) and getProduct(), in
test_dataframe_columns.py). Nothing else in the tree relies on it.
- The idiom usually cited as the reason not to do this,
algo.getParameters().setValue(...), already did not work and is used nowhere
here. DefaultParamHandler::setParameters() applies defaults, validates and
calls updateMembers_() (DefaultParamHandler.cpp:44-70), which is where an
algorithm copies parameter values into its own members. Editing the Param in
place reaches none of that.
- Reads get more expensive where the sub-object is large: consumer.getData()
and imaging getMSExperiment() now copy a whole experiment. Five such
accessors return an algorithm's result and have no setter, which is correct --
they are outputs, and copying an output is what a caller wants. The doc tells
users to fetch once rather than call in a loop.
Deliberately left aliasing, and both are self-evident at the call site rather
than something to memorise:
- 33 fluent builders and compound-assignment operators returning *this
(ParquetFilter.eq(...).andNext()); a copy would break chaining outright.
- 31 accessors returning a pointer to a process-lifetime database entry
(ResidueDB, ModificationsDB). These are Category S in #9792's taxonomy, where
aliasing is correct. They do carry the same global-mutation hazard that
AASequence[i] had, and closing that needs null handling, so it is separate
work rather than part of this sweep.
- 11 keyed lookups still to be triaged: some are element access, some are
database lookups, and they need reading one at a time.
Alias surface: 356 rv_policy::reference_internal sites at the start of this
branch, 75 now, all three remaining groups accounted for above.
OWNERSHIP.md is rewritten around the single rule and gains a migration section.
Two chaining tests that asserted the old split are inverted -- they recorded the
boundary this commit removes -- and a test pins that fluent builders still chain.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] Convert binding_utils.h getters; document attribute access
Two gaps found by scanning surfaces the earlier sweeps never looked at.
1. binding_utils.h was never touched. Every conversion script globbed
bind_*.cpp, so the shared helper templates kept their aliasing getters --
and def_DefaultParamHandler is applied to 11 classes, so getParameters()
and getDefaults() still returned references into the handler on all of
them. That made OWNERSHIP.md's "every getter returns a copy" false as
written. Five sites converted: getParameters, getDefaults and getCVTerms
were real aliases; getLoadedFileType (an enum) and getSubsections
(vector<string>) went through value casters and only lost a misleading
policy. Two docstrings corrected.
There are now no rv_policy::reference_internal sites outside bind_*.cpp;
arrow_zerocopy.cpp, peak_layout.h, main_module.cpp and every type caster
were checked and have none.
2. def_rw/def_ro attributes alias, and nothing said so. Verified by compiling
a minimal module: a def_rw member of class type hands out a reference and
writes land, while string and scalar-vector members go through value
casters and cannot alias. Of 1078 such bindings, 31 expose a member whose
type is a bound class -- all on plain data-holder structs
(SiriusTargetDecoySpectra, RangeSet, PreprocessedPairSpectra,
AQS_featureConcentration and similar); none on the main containers.
These are left aliasing deliberately. They are attributes, not getters, and
Python attributes are expected to be live -- `pair.target.setRT(5)` landing
is what a reader assumes, and def_rw already supplies the native write path
via `pair.target = ...`. Converting them would put the silent-no-op trap
behind syntax that looks nothing like a function call, which is worse than
the inconsistency it removes.
So the policy is two lines rather than one, but they follow ordinary Python
intuition instead of an internal distinction: a method hands you a copy and
needs a write-back; an attribute is the object itself. OWNERSHIP.md now says
so, and a test pins the behaviour.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS][test] Fix three test bugs found by running against a real build
These tests were written without a build to run them against. Building
pyOpenMS locally surfaced three failures, all in the tests rather than in the
bindings; each underlying semantic was verified directly before the test was
touched, so the expectations were corrected to what the API actually does
rather than relaxed to make them pass.
- Residue exposes getName(), not getFullName(). The latter came from a grep
whose context window ran into a neighbouring class. Affected the two
AASequence/ResidueDB tests.
- A default-constructed IsotopeDistribution already holds one element, so the
first insert() lands at index 1, not 0. The test asserted against index 0 and
compared it to the value it had inserted. It now captures the original value
at index 1 and asserts it is unchanged, which does not depend on that detail.
Verified behaviour on the built module before editing:
IsotopeDistribution d[1].mz 100.0 -> mutate returned peak -> 100.0 copy
AASequence residue 'Proline' -> setName('CORRUPTED')
same sequence -> 'Proline' copy
NEW sequence -> 'Proline' DB clean
The last line is the claim the AASequence conversion was made for: a sequence
constructed after the mutation still reads clean, so the process-wide ResidueDB
was not edited. Before the conversion that route corrupted the residue for every
sequence in the process.
All 68 ownership, chaining and ion-mobility tests now pass against a real build
of this branch.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] Fix write-back regressions found by the full test suite
Element access now yields owned copies, so four call sites that mutated
through a getter were silently no-ops:
- PeptideIdentificationList.update_scores_from_df(): the edited
PeptideIdentification was never written back to the list.
- test_imaging: getGeometry().addRegion() never reached the experiment.
- test_ImzMLFile: getSpectrum(0).setRT()/setMSLevel() never reached the
experiment before storing.
- test_dataframe_columns: getPrecursor()/getProduct().setMZ() on a
chromatogram fixture.
Each is rewritten to the documented form -- read, edit, put back.
Full unit suite: 5488 passed, 0 failed.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS][docs] CHANGELOG entry for the restored copy semantics (#9792)
Records the BREAKING getter-ownership change and the set_drift_time_array
buffer fix in the 3.6.0 PyOpenMS section.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] Address review findings on the ownership change (#9792)
Functional:
- DTA2DFile and ConsensusXMLFile lost every route to configure their
PeakFileOptions: both C++ classes expose only `PeakFileOptions&
getOptions()` and no setter, so once the getter returned a copy the
options could not be set at all. Both now bind setOptions(), matching
the other nine file classes.
- TargetedExperiment.getPeptideByRef()/getCompoundByRef() still carried
reference_internal and handed out mutable aliases into the stored
vectors -- the exact hazard this branch removes elsewhere, and
inconsistent with getProteinByRef(). All three now return copies;
setProteins()/setPeptides()/setCompounds() are the write-back path.
- MassTraces had a copy-returning __getitem__ and no __setitem__; the
container protocol is symmetric again.
Documentation accuracy:
- OWNERSHIP.md: document the shared_ptr carve-out. getDataProcessing()
copies the list, but its entries are shared by design, so an in-place
edit of an entry is visible through the owner. Deep-copying would break
that sharing; the write-back rule stays the safe habit.
- Stale "Returns a reference" wording on spectrumRanges,
chromatogramRanges, Gradient.getEluents and Gradient.getTimepoints.
- getCVTerms carried getAccession's description, in both the
def_CVTermList template and the CVTermList class binding.
- FLASHDeconvAlgorithm and SpectralDeconvolution had a whole run of
docstrings shifted by one method (getAveragine documented run(),
getDecoyAveragine documented getAveragine, and so on). Realigned
against the C++ headers.
- README_WRAPPING_NEW_CLASSES.md: nb::handle() is not a valid scope for
make_iterator's lazily created type; use nb::type<T>(). Fixed the two
remaining OWNERSHIP_PROPOSAL.md references.
Tests: file-options round trips for six classes, ByRef copy semantics for
all three TargetedExperiment entry types, the MassTraces protocol, and the
shared_ptr carve-out pinned so doc and behaviour cannot drift.
Full unit suite: 5663 passed, 0 failed.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] Close the remaining aliasing getters found in review (#9792)
A third binding shape -- `&Class::method` pointer-to-member instead of a
lambda -- was never reached by the earlier conversion sweeps, which all
matched on `[](Class& self)`. Seventeen getters in that shape still carried
reference_internal. All return `const T&`, so dropping the policy lets
nanobind's default resolve the lvalue reference to a copy:
- OSWData/OSWProtein/OSWPeptidePrecursor/OSWPeakGroup/OSWTransition
(getProteins, getPeptidePrecursors, getFeatures, getTransition, ...)
- IDRipper::RipFileIdentifier and RipFileContent
- IonImage.getMzRange, MSImagingGeometry.getRegions/getRegion
- MassExplainer.getCompomerById (policy sat on a continuation line)
Also aliasing, now returning owned values:
- AASequence.getNTerminalModification/getCTerminalModification and
Residue.getModification returned a `const ResidueModification*` into the
process-wide ModificationsDB with reference_internal -- a mutable alias
(nanobind erases const, and ResidueModification binds ~30 setters), so
editing one corrupted that modification for every sequence in the
process. Now std::optional<ResidueModification>, which also keeps the
None-when-unmodified result. Their docstrings had claimed "a copy".
- NASequence.getSequence handed out mutable aliases into RibonucleotideDB.
- Param.getEntry aliased into a user-owned Param; ParamNode's two finders
returned raw pointers, which the default policy resolves to `reference`,
so a by-value return was needed rather than only dropping the token.
MRMTransitionGroup was left with no write-back path at all:
getFeaturesMuteable/getTransitionsMuteable/getChromatograms/
getPrecursorChromatograms now copy, but the class binds no whole-collection
setter and add* appends rather than replaces, so an in-place edit was an
unrecoverable no-op. (5764d80 justified the conversion with "the class binds
addTransition and addFeature" -- append is not replace, so that was wrong.)
Adds setFeatures/setTransitions/setChromatograms/setPrecursorChromatograms
to both instantiations.
No non-ndarray, non-fluent-builder reference_internal remains, so
OWNERSHIP.md's claim now holds. Its exception list is corrected: database
lookups are an exception only for the DB singletons' own accessors, since
an entry reached through your own object is now a copy. The migration
section no longer says "from 3.6.0" -- aliasing was introduced and removed
inside the same unreleased cycle.
Also: getSpectrumAccessOpenMSPtr stops at the first cached_data marker
instead of copying every spectrum in the run, and a chaining test's
`in (True, False)` assert (true for any bool) is now `is False`.
Full unit suite: 5669 passed, 0 failed.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] Verification pass on the review fixes (#9792)
Two things the review's own findings did not name, found while checking
its claims against the code:
- ParquetFilterBuilder.filter() still aliased. It is the chain terminator
-- it hands out the builder's accumulated ParquetFilter, not the builder
itself -- so reference_internal made the returned filter keep changing as
the builder was extended further. Now returns a copy. This was the last
getter outside the two documented exception classes.
- test_terminal_modification_is_interned_not_aliased asserted
`stored is not mod`, which proved interning only while the getter
aliased. Now that it copies, that assertion passes either way and the
test could no longer detect raw-pointer storage. Restored its power by
reading the modification back through the sequence after dropping the
Python object.
Re-audited with a statement-aware scan rather than a per-line one. The 48
remaining reference_internal policies are 8 zero-copy ndarray views and 40
in-place operators / fluent builders that return the object they were
called on (`return self += rhs`, `self.andNext()`, ...). All 13
make_iterator sites carry keep_alive<0,1>.
Full unit suite: 5669 passed, 0 failed.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] Don't wrap ParquetFilterBuilder; ParquetFilter is the API
ParquetFilterBuilder is a C++-side ergonomics class: its own doxygen says
it "wraps a ParquetFilter instance and forwards all condition-building
operations". ParquetFilter already exposes the identical fluent API
(eq/ne/lt/le/gt/ge/in/andNext/orNext/empty, each returning itself) and is
the type the Parquet readers actually take, so in Python the builder was
duplicate surface whose only extra was a filter() call to unwrap it.
Its sole reference anywhere in the Python tree was inside _parquet_query.py,
which nothing imports -- the live query builder is _ChromatogramQuery in
pyopenms/addons/xicparquetfile.py, which keeps its own filter list and never
touched the C++ builder. That module is repointed at ParquetFilter, a
drop-in since it only ever called the shared fluent methods and never
filter().
This also removes the last getter outside the documented exception classes:
ParquetFilterBuilder.filter() was the chain terminator handing out the
builder's accumulated filter.
Full unit suite: 5662 passed, 0 failed. The count drops by 7 from the
previous run because test_copy_constructors and test_docstrings
parameterize 3 and 4 cases per bound class over dynamically enumerated
class lists; no hand-written test was lost.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] Fix stale key maps in the MRMTransitionGroup setters (#9792)
The setters added in 5607ebe assigned straight through getXMuteable(),
which replaces the vector but leaves MRMTransitionGroup's three key -> index
maps untouched. Reproduced from Python: after a reordering setChromatograms,
getChromatogram("a") returned the chromatogram named "b"; after a shrinking
one, getChromatogram("b") indexed past the end of a one-element vector (the
OPENMS_PRECONDITION guarding it is compiled out in release builds).
Replacement now goes through the keyed add* API, keyed by native ID -- the
same rebuild MRMTransitionGroup::subset() performs internally -- so the maps
stay consistent for reorderings, growth and shrinkage alike, and the
in-place write-back case is unaffected.
Also from review:
- NASequence.getSequence() skipped null entries, which would silently shift
every later position; it now raises instead.
- FLASHDeconvAlgorithm.getAveragine/getDecoyAveragine documented
calculateAveragine(), which that class does not bind (SpectralDeconvolution
does, so its wording stands). They now name run().
- OWNERSHIP.md said the remaining reference_internal policies were all numpy
views. They are not: the in-place operators and fluent builders use it too.
Both cases are now named so a future audit expects them.
- test_residue_modification_is_a_copy only checked that a modification
exists; it now mutates the returned copy and asserts ModificationsDB is
untouched.
- Reindented getSpectrumAccessOpenMSPtr to 4-space steps; it was the only
6-space block in an otherwise 4-space file.
Removed pyopenms/_parquet_query.py: nothing imports it, the live query
builder is _ChromatogramQuery in addons/xicparquetfile.py, and its
ChromatogramQuery.to_dict() called a _get_data_dict_from_parquet_filter()
that exists nowhere in the repository.
Full unit suite: 5662 passed, 0 failed.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] Realign the PEFFFile and InternalCalibration docstrings (#9792)
The last outstanding review item, and the shift ran further than the review
noted: every PEFFFile docstring from readStart through writeEnd described
the *previous* method, so readStart documented store(), getHeaders
documented readNext(), atEnd documented getHeaders(), both writeStart
overloads documented atEnd(), writeNext documented writeStart(), and
writeEnd documented writeNext(). All seven realigned against PEFFFile.h.
InternalCalibration.getCalibrationPoints() carried fillCalibrants()'s
entire parameter block (pep_ids, tol_ppm, "Number of calibration masses
found") although it takes no arguments and returns CalibrationData.
Same defect family as the FLASHDeconvAlgorithm and SpectralDeconvolution
docstrings fixed in 5607ebe.
Full unit suite: 5662 passed, 0 failed.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] MRM setters preserve caller-supplied lookup keys (#9792)
The rebuild added in a440f7b re-added every element keyed by getNativeID(),
but addTransition/addChromatogram/addPrecursorChromatogram take a key that
is independent of the native ID. Reproduced: a chromatogram added under
"custom_key" with native ID "native_id" lost that key on a plain no-edit
write-back -- hasChromatogram("custom_key") went False and the entry was
silently re-keyed to "native_id".
MRMTransitionGroup exposes no way to enumerate or rebuild its key -> index
maps, so a faithful rebuild is impossible from the binding layer. What is
possible, and is exactly what these setters exist for, is positional
replacement: element i keeps its key, every key keeps pointing at a valid
index. So the setters now assign in place and refuse a size change with a
message pointing at the add*() methods, which are the supported way to grow
a keyed collection. This also drops the earlier out-of-bounds hazard by
construction rather than by rebuilding.
setFeatures is unaffected -- features carry no key map.
Full unit suite: 5663 passed, 0 failed.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] Close the NASequence aliasing gap and three smaller review findings (#9792)
A fresh review pass over the full diff found seven issues; all verified
against the code before fixing.
NASequence was the one subsystem the conversion missed end to end:
- __getitem__, __iter__, get(), getFivePrimeMod() and getThreePrimeMod()
still returned live mutable aliases into the process-wide
RibonucleotideDB (rv_policy::reference; nanobind erases const), so
na[0].setName(...) corrupted that ribonucleotide for every sequence in
the process -- the same class of bug closed for AASequence/ResidueDB.
All five now return owned copies (optional for the terminal mods);
__iter__ materialises the copies and iterates those, so it is
self-contained rather than keep-alive-guarded, and the keep-alive
refcount test now recognises that design (the two outlives-tests still
pin its safety directly).
- The documented round trip was impossible: getSequence() returns owned
copies, but the setters gated on POINTER IDENTITY with a DB entry, so
setSequence(getSequence()) always raised. requireDBRibonucleotide_ is
now resolveDBRibonucleotide_: identity is irrelevant, the code is
looked up and the database's own entry is stored (so nothing can
dangle); a code not in the DB is still rejected.
MSExperiment/MSImagingExperiment:
- getSpectrum(id)/getChromatogram(id) wrapped an unchecked C++
spectra_[id]; the copy conversion made the out-of-bounds read
unconditional. Both now raise IndexError like __getitem__.
- The imaging per-pixel getter copied with no way back; setSpectrum(x, y,
spectrum) is the write-back, assigning through the mutable C++ getter
so pixel validation is shared.
SimpleOpenMSSpectraFactory:
- The cached_data probe now runs C++-side (_contains_cached_data_marker),
so building a SpectrumAccess no longer copies every spectrum of the run
just to read DataProcessing metadata.
- Exercising the factory revealed it has been broken on develop all
along: _python_extras.py never imported SpectrumAccessOpenMS or
SpectrumAccessOpenMSCached, so BOTH branches raised NameError and
nothing ever called it. The import is fixed for the uncached branch;
the cached branch raises a clear NotImplementedError because
SpectrumAccessOpenMSCached is not wrapped in the nanobind port at all
(pre-existing port gap, out of scope here).
Documentation:
- FileHandler.getFeatOptions docstring said "Mutable access" for a
copy-returning getter.
- CHANGELOG and the chaining-test docstring said two exceptions where
OWNERSHIP.md documents three; all three files now agree.
Tests: NASequence non-aliasing + round trip, bounds checks, per-pixel
write-back, and the first test that actually calls the factory.
Full unit suite: 5668 passed, 0 failed.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] Opt-in aliasing access under the explicit _view naming scheme (#9792)
Copies stay the default on every plain getter; when copying is too
expensive and the caller accepts the hazards, the _view family is the
named, deliberate way in (matching get_peaks_view()/get_data_view(),
which already use the suffix for zero-copy numpy views):
- singular + _view -> one live element
get_spectrum_view(i), get_chromatogram_view(i), get_feature_view(i)
- plural + _view -> list of live elements
get_spectra_view(), get_chromatograms_view(), get_features_view()
- iter_<singular>_views() -> iterator of live elements
iter_spectrum_views(), iter_chromatogram_views(), iter_feature_views()
Contract (stated once in OWNERSHIP.md): edits through a view land
immediately, every view keeps its parent alive, and a view is valid only
until the underlying list is resized or reordered -- the documented #9792
hazard the name opts into.
Only the single-element views are bound in C++ (bounds-checked,
reference_internal so each wrapper carries the parent keep-alive and has
stable identity via nanobind's instance map). The plural and iterator
forms are Python addons that call the bound element view per element, so
every yielded view inherits the keep-alive from the binding -- no manual
lifetime plumbing. README_WRAPPING_NEW_CLASSES.md records that recipe for
future wrappers; CHANGELOG records the scheme.
Verified empirically before pinning: edit-lands, stable identity,
parent-outlives-del, bounds errors, all three forms per class, and that
the unsuffixed getters still copy. 10 tests in test_view_accessors.py.
Full unit suite: 5676 passed, 0 failed.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] Extend the _view family and iterate views in DataFrame exports (#9792)
Extend the opt-in aliasing accessors to the remaining containers where
element copies dominate runtime, and convert pyOpenMS's own Python
helpers to iterate views instead of copies.
New C++ element views (rv_policy::reference_internal, bounds-checked),
each with plural get_*_views() and iter_*_views() addon counterparts:
- ConsensusMap.get_consensus_feature_view(i)
- PeptideIdentificationList.get_peptide_identification_view(i)
- MSSpectrum/MSChromatogram.get_{float,integer,string}_data_array_view(i)
(chains with .get_data_view() for a fully zero-copy numpy path)
- MRMTransitionGroupCP / LightMRMTransitionGroupCP
.get_feature_view(i) and .get_chromatogram_view(i)
Private _*_count helpers back the plural/iter addons so they no longer
copy whole collections just to learn their length.
Addon hot loops now iterate views internally (get_df/get_ion_df/
to_df exports, meta-value sweeps, update_scores_from_df — which now
edits through a view instead of copy + write-back). Iterating spectra
of a peak-heavy experiment this way measures ~100x faster than the
copying default.
Docs: OWNERSHIP.md lists the classes with view support and the
zero-copy chain; CHANGELOG notes the availability and speedup.
Tests: five new cases in test_view_accessors.py covering the new
views, including a data-array edit landing in the owning spectrum.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* Add missing ctest DEPENDS for two FuzzyDiff output tests
TOPP_FeatureFinderMetabo_4_out and TOPP_FeatureFinderMultiplex_7_out2
were the only two of 767 FuzzyDiff comparison tests without a DEPENDS
on the tool run that produces their input, so a parallel ctest could
schedule them before (or concurrently with) their producers and fail
on a missing/partial temp file.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] Drop the get_ prefix from aliasing accessors (#9792)
The get_ prefix now unambiguously means "returns an owned copy", so
accessors that alias never carry it. The name split is the ownership
contract:
get_* -> owned copy (the default rule)
*_view / *_views / *_struct -> zero-copy alias of the parent
Renames (nothing here has shipped -- the nanobind port is first
released in 3.6.0):
- element views: get_spectrum_view -> spectrum_view, and likewise
feature_view, chromatogram_view, consensus_feature_view,
peptide_identification_view, {float,integer,string}_data_array_view
- list forms: get_spectra_view -> spectrum_views etc.; the plural noun
gave way to <singular>_views to mirror iter_<singular>_views and to
avoid double plurals like features_views
- numpy views: get_data_view -> data_view, get_matrix_view ->
matrix_view, get_{mz,intensity,time,drift_time}_array_view -> same
minus get_
- struct views: get_peaks_struct -> peaks_struct, get_pixels_struct ->
pixels_struct
The deprecated _mv aliases now delegate to the new names (old alias
names unchanged). Docs (OWNERSHIP.md, README, performance.rst,
CHANGELOG) state the prefix rule; tests renamed alongside.
Full suite: 5681 passed, 80 skipped, 11 xfailed, 7 xpassed.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS][docs] Teach the view family in the user guide (#9792)
The user-guide examples never mentioned zero-copy access. Introduce the
_view naming scheme where the tutorials cover the patterns it serves:
- ms_data.rst: after the copy-based intensity-sum example, explain that
iteration/indexing/getSpectrum return owned copies, show the same sum
through iter_spectrum_views(), and state the aliasing contract in a
caution block (resize/sort invalidates views; get_* copies,
*_view/*_views/*_struct alias). plot_spectra_2D now iterates views;
the peak-access note mentions peaks_struct(), and the data-array
section shows the float_data_array_view(0).data_view() chain.
- first_steps.rst: note in the iteration section that iteration hands
out copies, pointing at iter_spectrum_views() and the MS data chapter.
All new/changed example code executed against the built module
(zero-copy sum matches the copy-based sum at 700.0; the data-array
view chain writes through to the spectrum).
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS][docs] Explain ownership semantics for beginners in Getting Started (#9792)
Add a "Copies, Not References" section to first_steps.rst, placed right
after the reader first indexes and iterates an experiment: the one rule
(everything you take out of a container is your own copy), the surprise
it prevents (editing the copy does not edit the experiment, shown with
real tiny.mzML output), the read-it/edit-it/put-it-back pattern, why the
alternative is dangerous, and the naming contract (get_* copies;
_view/_views/_struct alias) with a pointer to the MS data chapter.
Folds in the earlier short copies-note, which sat between a sentence and
its code block and interrupted the flow. Both snippets executed against
the built module (353.43 unchanged after the copy edit; 999.9 after
write-back).
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS][docs] Drop the layman analogies from the ownership section (#9792)
State the rule technically: containers use value semantics for element
access, returned objects own their data. Replaces the photocopy/binder
analogy, and tightens the rationale to name the actual failure modes
(use-after-free on reallocation, re-binding on sort).
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] Wrap SpectrumAccessOpenMSCached (on-disk cached spectrum access)
Bind the disk-backed OpenSWATH spectrum accessor: constructed from the
metadata mzML path, it serves metadata from memory and decodes peak data
on demand from the ".cached" side-car written by CachedmzML.store(). The
binding mirrors SpectrumAccessOpenMS (no nanobind base declared -- the
earlier xfail's claim that ISpectrumAccess+CachedmzML inheritance blocks
wrapping was wrong; the sibling accessors are bound the same way). The
docstring carries the class's thread-safety caveat.
SimpleOpenMSSpectraFactory.getSpectrumAccessOpenMSPtr() now returns it
for experiments carrying the cached_data marker, replacing the
NotImplementedError stopgap and matching the C++ factory exactly.
Tests: the missing-class xfail becomes a real existence test, and a new
factory test does the full round trip -- CachedmzML.store, reload the
metadata, factory dispatch, decode peaks from the side-car, RT lookup.
Full suite: 5687 passed, 0 failures.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] Address review findings: None clears NASequence terminal mods (#9792)
NASequence.setFivePrimeMod/setThreePrimeMod now accept None to clear the
modification: the C++ setters store the pointer without dereferencing and
nullptr is the documented "no modification" state, but the binding rejected
None before the lambda ran, leaving no way to clear a terminal mod from
Python. Non-None values still resolve against RibonucleotideDB; the blanket
None-rejection test drops these two entries (with a comment on why the
AASequence setters stay: their pointer overload dereferences, and clearing
goes through setNTerminalModification("")) and gains a set-then-clear
round-trip test.
Smaller findings from the same review:
- performance.rst: each benchmark is now a complete, runnable timeit
command (shared setup hoisted into a shell variable)
- README_WRAPPING_NEW_CLASSES.md: plural view form corrected to
<singular>_views() per the established naming scheme
- OWNERSHIP.md: the reference_internal audit note now lists all three
aliasing categories (numpy views, the _view element family, in-place
operators/builders)
- test_chaining_semantics.py: "two documented exceptions" heading no
longer contradicts the three cases OWNERSHIP.md documents
- test_zerocopy_conventions.py: deprecation-message assertions reject the
removed get_-prefixed names instead of matching them as substrings
- test_set_ion_mobility.py: the length-change test now exercises
set_drift_time_array's own storage-replacement branch (shrink peaks
with metadata="keep", then replace the stale array) as its docstring
claims
Full suite: 5681 passed, 0 failures.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] Wrapping-review follow-ups for SpectrumAccessOpenMSCached
Add the explicit copy-constructor binding (repo convention alongside
__copy__/__deepcopy__), and rewrite the stale "cannot bind" comment
further down the file: it claimed the ISpectrumAccess/CachedmzML bases
prevent binding this class, which the binding above disproves. Only
SpectrumAccessQuadMZTransforming remains unbound.
Also merges the current #9947 branch (review fixes from the same
CodeRabbit round that live in that PR's files).
Full suite: 5687 passed, 0 failures.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS][docs] Document the OpenSwath shared_ptr types under the sharing exception (#9792)
The shared-ownership exception claimed getDataProcessing() was the only
shared-alias surface. The OpenSwath interchange types are the same
category: OSSpectrum/OSChromatogram array accessors and the
ISpectrumAccess getSpectrumById()/getChromatogramById() return
shared_ptrs because sharing arrays between pipeline stages without
copying is that data model's purpose. Name them so the "and nothing
else" claim is actually true.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS][docs] Drop the migration section from OWNERSHIP.md (#9792)
Aliasing was introduced and removed inside the same unreleased 3.6.0
development cycle, so there is no released version to migrate from and
the section only addressed hypothetical code written against a dev
build. A one-sentence note in "Why it works this way" keeps that fact;
the CHANGELOG pointer no longer mentions migration patterns.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS][docs] Ownership coverage for the FAQ and contributor guides (#9792)
Audit of the doc surfaces found three gaps, all fixed:
- faq.rst: the first entry now answers the top newcomer question ("I
modified a spectrum from my experiment, but the change is gone") with
the read-edit-put-back pattern, the _view escape hatch, and the
get_*-copies rule (snippets executed against the built module)
- README.md: the zero-copy convention table gains the element-view
family row and states the get_ prefix rule up front, pointing at
OWNERSHIP.md
- CLAUDE.md: the class-wrapping instructions open with the ownership
rule so new bindings don't reintroduce reference_internal getters
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS][tests] Pin the ndarray contract of the numpy copy accessors (#9792)
The view family's array-ness was already asserted (isinstance + dtype in
test_zerocopy_conventions.py, with writeback tests proving aliasing), but
most tests exercise the *copy* accessors through np.allclose()/len(),
which accept plain Python lists just as well. A binding regression that
fell back to the std::vector caster would therefore pass unnoticed while
silently changing dtype, memory cost and vectorized semantics.
New test_copy_accessors_return_numpy_arrays covers every accessor
documented "as numpy array": get_peaks() on MSSpectrum, MSChromatogram
and Mobilogram (both halves), get_mz_array()/get_intensity_array(),
Float/IntegerDataArray.get_data(), MatrixDouble.get_matrix(), and
MSExperiment.get2DPeakData()/get2DPeakDataLong() — isinstance(np.ndarray)
plus the exact dtype for each. The OpenSwath get_*_array() copies return
lists by documented contract (their ndarray path is *_array_view()),
recorded in the docstring.
Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS][docs] Tighten view-invalidation and empty-behavior wording
Two review findings on the docs:
- faq.rst said views survive until the container is "resized or
sorted"; OWNERSHIP.md's contract is resized or *reordered*, with
sorting as one example. The FAQ now matches the contract.
- README.md's element-view table row claimed "IndexError on
out-of-range" for all three access forms; only the indexed form can
raise. The plural forms now document their empty-result behavior
(empty list / exhausted iterator).
Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] Return caster-handled element access by value
The review noted the three DataArray __getitem__ bindings still
returned float&, int& and std::string&. That was safe — nanobind's
casters copy arithmetic and string values into new immutable Python
objects at the call boundary, so no alias can reach Python — but the
signatures looked exactly like the aliasing pattern this PR removes.
Return them by value so the signature states the copy rule; for the
string this trades one extra copy per element access (bulk access is
get_data()).
A sweep over all binding files for the same pattern found three more
const std::string& returns on FeatureFinderMetaboIdentCompound
(getName/getFormula/getAdduct), now also by value. Vector-reference
returns stay const& deliberately: the list caster copies every element
anyway, and by-value would copy the vector twice. The CLAUDE.md
wrapping guide now records the rule (scalars/strings by value, vector
const& acceptable, aliasing only arises for bound classes).
Full pyOpenMS suite: 5682 passed, 0 failed.
Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] Reject modified Ribonucleotide copies instead of silently resolving
resolveDBRibonucleotide_ resolves the passed object by code and stores
RibonucleotideDB's own entry. If the caller had edited their copy
(setAvgMass, setName, ... are all bound), those edits were silently
discarded: seq.set(0, edited) succeeded and stored the pristine database
entry. The pre-#9947 guard rejected such objects loudly.
The resolver now compares the resolved database entry against the passed
object with Ribonucleotide::operator== (all fields) and raises ValueError
on mismatch, pointing at registering the modification in RibonucleotideDB.
Unmodified round trips (seq.set(0, seq[0]), setSequence(getSequence()),
terminal mods) are unchanged. Covers set(), setSequence(),
setFivePrimeMod() and setThreePrimeMod(), which all funnel through the
resolver.
Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] Index-based iterators: mutation during iteration is defined
The __iter__ bindings used nb::make_iterator, which stores raw C++
begin()/end() iterators. Mutating a container while a Python iteration
was in flight (for s in exp: exp.addSpectrum(...)) invalidated those
iterators and dereferenced freed memory on the next step -- the same
push_back-reallocation class this PR closes for held elements (#9792),
surviving in the iterator object itself.
All twelve element-container iterators (MSExperiment, FeatureMap,
ConsensusMap, MSSpectrum, MSChromatogram, Mobilogram,
PeptideIdentificationList, AASequence, IsotopeDistribution,
DeconvolvedSpectrum, PeakGroup, Param) are now safe:
- index_value_iterator.h: an iterator holding a strong reference to the
parent plus an index; every step bounds-checks against the container's
*current* size and returns an owned copy. Mutation during iteration is
therefore defined exactly like Python's list iteration -- appended
elements are visited, shrinking ends the loop early -- and can never
touch freed memory. The owner reference replaces nb::keep_alive.
- Param has no index access (its ParamIterator walks the entry tree), so
its __iter__ snapshots owned entry copies up front instead.
test_iterator_mutation_safety.py pins the new semantics (growth with
reallocation, shrink-stops-early, snapshot, copies stay intact);
test_iterator_lifetime.py's retention test now checks the owner
reference and skips Param alongside NASequence (a snapshot has nothing
to retain -- its outlives tests still run). OWNERSHIP.md documents the
list-like contract.
Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] Iterate views in the DataFrame/Arrow/MassQL export paths
OWNERSHIP.md and the CHANGELOG state that pyOpenMS's own DataFrame
exports iterate views internally so the copy rule costs nothing there,
and get_ion_df plus the FeatureMap/ConsensusMap/PeptideIdentificationList
addons were converted accordingly -- but the largest paths still
iterated copies: to_df()/to_arrow() (_build_spectra_arrow, both
formats), get_massql_df() (both MS levels), _dataframes.py (both
formats), and MRMTransitionGroupCP.to_chromatogram_df()/to_feature_df().
Each copied every spectrum or chromatogram (peaks and data arrays
included) just to read it -- ~120x slower than view iteration on the
PR's benchmark data.
All eight loops now use the view accessors (iter_spectrum_views(),
chromatogram_views(), feature_views()). The loop bodies only read and
extract values, so aliasing is safe; output is unchanged (pinned by the
existing DataFrame/MassQL tests).
Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
* [pyOpenMS] Generate the plural/iterator view families from one template
The 15 <singular>_…
) Indexing and iterating a container now yield an owned copy on every element container, instead of a live alias into the container's storage. Writes go back through __setitem__. This restores the semantics of the Cython bindings up to release 3.5, where the autowrap wrapper representation (a shared_ptr-owned C++ instance per wrapper) structurally forced a copy on every wrapped-type return. The nanobind port made these paths reference_internal aliases, which is the root of the use-after-free and wrong-element-write failures catalogued in OpenMS#9792 -- and it was a side effect of the port rather than a decision. Converted (indexing and iteration, both directions now agree): MSSpectrum -> Peak1D (__iter__ was aliasing; __getitem__ already copied) MSChromatogram -> ChromatogramPeak Mobilogram -> MobilityPeak1D MSExperiment -> MSSpectrum / MSChromatogram, incl. getSpectrum, getChromatogram, getSpectra, getChromatograms FeatureMap -> Feature ConsensusMap -> ConsensusFeature getSpectra()/getChromatograms() are included because they were declared by value in the 3.5 pxd (libcpp_vector[MSSpectrum] getSpectra()), i.e. they copied there too; test_AcquisitionInfo.py still uses the copy-and-write-back idiom that only makes sense under copy semantics, and it keeps passing. keep_alive<0,1> is retained at all 13 make_iterator sites. It guards the iterator object, which still holds raw C++ iterators, and is a separate concern from the element policy -- removing it would reopen OpenMS#9794. Verified by compiling a standalone nanobind module reproducing the exact pattern, with the old reference_internal bindings kept as negative controls: copies do not leak edits, aliases do; a held spectrum survives 5000 addSpectrum calls intact, while the aliased control degrades to rt=2.6e-315 and a len() that overflows; the iterator still outlives its container. Also updates the container-protocol template in README_WRAPPING_NEW_CLASSES.md, which taught the aliasing pattern and is how it spread, and the three peak-access class docstrings. Not in scope, and still aliasing: reference-returned vectors of sub-objects (getHits, getFloatDataArrays, getPrecursors, ...) and AcquisitionInfo. These were also copies in 3.5, so they are the natural next step, but there are ~105 such sites and they are a separate change. The boundary is pinned by tests so it stays deliberate. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Eq2zMe2q3VniiSoXNmxxrH
Fixes the confirmed use-after-free reported as Part IV of #9792.
The bug
nanobind's
make_iteratorstores the raw C++begin/enditerators in the object it returns and takes no reference to the container. Therv_policy::reference_internaltemplate argument governs only the elements that are yielded — it does not keep the container alive.Every pyOpenMS
__iter__binding relied on that policy alone:So an iterator can outlive the container it walks:
The same happens whenever the last reference is dropped before the iterator is consumed — a temporary, a
del, or a rebound name.nanobind's own
bind_vectorgets this right, which is the clearest statement of the intended contract (stl/bind_vector.h:75-79):The fix
nb::keep_alive<0, 1>()added to all 13__iter__bindings:MSSpectrum,MSChromatogram,MSExperiment,Mobilogram,FeatureMap,ConsensusMap,Param,PeptideIdentificationList,AASequence,IsotopeDistribution,NASequence,PeakGroup,DeconvolvedSpectrum.src/pyOpenMS/README_WRAPPING_NEW_CLASSES.mdis also fixed. Its "Container Protocols" template showed exactly the broken pattern and is the likely origin — leaving it would reintroduce the bug on the next class anyone wraps. It now carries the annotation plus a comment explaining thatreference_internalgoverns the elements, not the iterator.Verification
src/pyOpenMS/tests/unittests/test_iterator_lifetime.py— 13 containers x 3 scenarios (iterator over a temporary; iterator survivingdelof the container; partially-consumed iterator whose container is dropped mid-iteration). 39 tests.I built the bindings with the fix reverted and ran them. Every one of the 13 containers detects the bug, 6 with a hard segfault:
The non-segfaulting cases fail by yielding values read back from reused heap memory rather than the original contents.
Full pyOpenMS suite after the fix: 5283 passed, 79 skipped, 11 xfailed, 7 xpassed, 1 failed.
The single failure is
test_docstrings.py::TestAllClassDocstrings::test_method_docstrings_valid_rst[FeatureFinderAlgorithmMetaboIdent], which is pre-existing and unrelated. Its root cause:src/pyOpenMS/pyopenms/addons/featurefinderalgorithmmetaboident.pyuses Sphinx:meth:roles, which the bare-docutils validator in that test does not register. Both that addon andbind_featurefinder.cppare untouched by this PR (bind_featurefinder.cppcontains no:meth:at all). Worth fixing, but separately.Scope
This PR is only the memory-safety fix. The broader ownership/lifetime design questions — writable NumPy views that bypass the binding boundary, sort-invalidation, the
MSChromatogram/Mobilogramcorrectness bugs, and the binding rulebook — stay in #9792.🤖 Generated with Claude Code
https://claude.ai/code/session_01APConSDbHrNux6qmuP4oVh
Summary by CodeRabbit
__iter__iterators correctly keep their owning container alive, preventing invalid reads, use-after-free, and potential hard crashes when iterating over temporary, deleted, or partially-consumed containers.__iter__to require safe iterator lifetime handling for nanobind-bound container protocols.