Repository navigation
[FIX] pyOpenMS: consumer callbacks were handed a reference into the parser's buffer (#9792 R-4.7) - #9804
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughChangesThe nanobind consumer bridge now gives Python callbacks owned spectrum and chromatogram arguments during execution, restores edits afterward, and adds collecting transform overloads. Regression tests cover lifetime, zero-copy views, mutation, errors, streaming, and MzXML behavior. Consumer callback ownership
Sequence Diagram(s)sequenceDiagram
participant Parser
participant ConsumerBridge
participant PythonConsumer
participant MSExperiment
Parser->>ConsumerBridge: deliver spectrum or chromatogram
ConsumerBridge->>PythonConsumer: pass owned callback argument
PythonConsumer-->>ConsumerBridge: return or raise callback result
ConsumerBridge->>Parser: restore modified value
Parser->>MSExperiment: append processed spectrum
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 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.
🧹 Nitpick comments (3)
src/pyOpenMS/bindings/type_casters/nanobind_ms_data_consumer.h (2)
30-30: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueMove
OwningCallbackArginto its own header.This introduces a second class in
nanobind_ms_data_consumer.h; keep the helper template in a dedicated header.As per coding guidelines, “keep one class per file.”
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/pyOpenMS/bindings/type_casters/nanobind_ms_data_consumer.h` at line 30, Move the OwningCallbackArg class template out of nanobind_ms_data_consumer.h into a dedicated header, then update all includes and references so the existing behavior remains unchanged and nanobind_ms_data_consumer.h contains only its primary class.Source: Coding guidelines
52-53: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse the required brace layout.
Place the
if/elseand accessor braces on their own aligned lines.As per coding guidelines, use “braces on their own aligned lines.”
Also applies to: 61-61
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/pyOpenMS/bindings/type_casters/nanobind_ms_data_consumer.h` around lines 52 - 53, Reformat the conditional assignment around Py_REFCNT in the relevant accessor so the if and else braces each appear on their own aligned lines, and apply the same brace layout to the accessor block referenced at line 61. Preserve the existing move-versus-copy behavior.Source: Coding guidelines
src/pyOpenMS/tests/unittests/test_consumer_callback_lifetime.py (1)
74-75: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCover chromatogram retention and the ImzML consumer entry point.
Add a retained-chromatogram churn assertion and an
ImzMLFile.load(..., consumer)regression. The bridge changes both paths, but this suite currently only validates retained spectra and MzXML streaming.Also applies to: 284-291
🤖 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_consumer_callback_lifetime.py` around lines 74 - 75, Extend the lifetime tests around consumeChromatogram and the existing retained-spectrum churn coverage to assert chromatograms remain valid through retention churn. Add a regression test for the ImzMLFile.load(..., consumer) entry point, matching the existing MzXML consumer-streaming test patterns and validating the consumer receives the expected data.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@src/pyOpenMS/bindings/type_casters/nanobind_ms_data_consumer.h`:
- Line 30: Move the OwningCallbackArg class template out of
nanobind_ms_data_consumer.h into a dedicated header, then update all includes
and references so the existing behavior remains unchanged and
nanobind_ms_data_consumer.h contains only its primary class.
- Around line 52-53: Reformat the conditional assignment around Py_REFCNT in the
relevant accessor so the if and else braces each appear on their own aligned
lines, and apply the same brace layout to the accessor block referenced at line
61. Preserve the existing move-versus-copy behavior.
In `@src/pyOpenMS/tests/unittests/test_consumer_callback_lifetime.py`:
- Around line 74-75: Extend the lifetime tests around consumeChromatogram and
the existing retained-spectrum churn coverage to assert chromatograms remain
valid through retention churn. Add a regression test for the ImzMLFile.load(...,
consumer) entry point, matching the existing MzXML consumer-streaming test
patterns and validating the consumer receives the expected data.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 15c8d7b4-8d3e-45c4-abe1-60b556d794ee
📒 Files selected for processing (3)
CHANGELOGsrc/pyOpenMS/bindings/type_casters/nanobind_ms_data_consumer.hsrc/pyOpenMS/tests/unittests/test_consumer_callback_lifetime.py
c6af0b3 to
a576ae8
Compare
…arser's buffer (#9792 R-4.7) NanobindMSDataConsumer bridges a Python object to the C++ IMSDataConsumer interface, so MzMLFile.transform(), MzXMLFile.transform() and ImzMLFile.load(filename, consumer) can call back into Python. It passed each spectrum and chromatogram with plain nb::rv_policy::reference, while MzMLHandler clears and refills spectrum_data_ as soon as the callback returns. A consumer that kept what it was given -- `kept.append(s)`, a natural way to collect a subset while streaming -- therefore held objects whose scalars and peak data came from whatever had reused the memory. The same applied to every child alias derived from them, including the zero-copy ndarray from get_peaks_struct(). Neither obvious fix works. Copying into the callback would silently discard the consumer's edits: IMSDataConsumer explicitly permits a consumer to modify the spectra and MzMLHandler passes the modified value onward. Invalidating the wrapper when the callback returns cannot reach the child views, does not unregister the pointer (nanobind unregisters only at deallocation, so a retained-and-invalidated wrapper can be handed back for a later spectrum out of the recycled buffer), and risks destructing an object the binding does not own, since a reference cast may reuse any compatible registered instance. The callback is now given an object that owns its value: it is moved out of the caller's storage for the duration of the call and moved back afterwards, so in-place modification still reaches downstream storage; if the consumer kept a reference the value is copied back once and Python is left holding a valid independent snapshot instead of a dangling alias. This removes the aliasing rather than guarding it, so there is no invalidation contract, no registry reuse hazard and no escape detection to get wrong. MSSpectrum and MSChromatogram both have defaulted noexcept moves -- now enforced by static_assert, since the exception safety rests on it -- so the ordinary path copies no peak data and the only throwing step is the copy construction on the retained path, which happens before anything is assigned. Putting the value back is an explicit, throwing step after a successful callback: if it fails, the parser must not carry on with moved-from storage and hand that downstream, so the error propagates. The destructor repeats it only as a best-effort fallback for the path where the callback's own exception is already unwinding, and the handoff is scoped inside the try so it is destroyed before the catch runs, while nb::python_error still owns and has cleared the Python error indicator. The uniqueness test is reliable only while the GIL is held; on a free-threaded build, where gil_scoped_acquire does not serialise threads, the copy path is taken unconditionally. The header also gained the MSSpectrum/MSChromatogram includes it had been getting incidentally from its callers -- IMSDataConsumer only forward-declares them. The map-collecting transform overloads (MzMLFile.h:136, MzXMLFile.h:99) are additionally wrapped as transform(filename, consumer, exp). They set alwaysAppendData, so each spectrum is appended after the consumer has seen it, which makes the write-through contract observable -- and therefore testable -- from Python for the first time. That matters here: a copy-based fix passes every other test in this file and is caught only by these. 18 regression tests; 8 fail against the previous caster, 4 by terminating the interpreter, and 2 more fail if the aliasing is instead "fixed" with a copy. Co-Authored-By: Claude Fable 5 <[email protected]>
a576ae8 to
de99794
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@CHANGELOG`:
- Line 20: The changelog entry’s regression-test count conflicts with the PR
objective count. Verify whether 18 tests or 14 tests were added, then update the
test-count statement in the changelog accordingly; if 18 is correct, briefly
identify the four additional tests and what they cover.
🪄 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: 09648114-336d-485e-869f-72e78da83ff1
📒 Files selected for processing (4)
CHANGELOGsrc/pyOpenMS/bindings/bind_misc.cppsrc/pyOpenMS/bindings/type_casters/nanobind_ms_data_consumer.hsrc/pyOpenMS/tests/unittests/test_consumer_callback_lifetime.py
🚧 Files skipped from review as they are similar to previous changes (2)
- src/pyOpenMS/tests/unittests/test_consumer_callback_lifetime.py
- src/pyOpenMS/bindings/type_casters/nanobind_ms_data_consumer.h
…llback hand-off (#9792) The entry claimed that on a free-threaded build a false "unique" result would leave Python an empty value. That cannot happen: isUniquelyReferenced_() returns false unconditionally under NB_FREE_THREADED, so the copy path is always taken there. The reference-count test is in fact protected from both sides. nanobind emits the Py_mod_gil / Py_MOD_GIL_NOT_USED slot only for modules built with NB_FREE_THREADED (nb_defs.h:154), so a module built without it makes CPython re-enable the GIL even on a free-threaded interpreter. The refcount branch therefore always runs under a real GIL. Documentation only, no functional change. Co-Authored-By: Claude Opus 5 <[email protected]>
…wasted copy-back, close test gaps (#9792 R-4.7) Follow-ups from review of the consumer-callback lifetime fix. Guard the move cast. nb::cast consults nanobind's instance registry for every policy except copy (nb_type_put: `if (rvp != rv_policy::copy) { ... return the registered object; }`), so a move cast returns an already-registered wrapper -- having moved nothing -- whenever the address is one Python already knows. The comment claiming "a bound instance we just created" was therefore not true in general. No caller can reach it today, since the parser's batch storage is never exposed to Python, but it would quietly turn OwningCallbackArg into a no-op and reinstate the aliasing it exists to remove. Compare the instance pointer against the caller's address and throw instead. Nothing has moved in that case, so the caller's value is still intact when it throws. Stop restoring the value on the streaming path. MzMLFile/MzXMLFile::transform( filename, consumer) parse into a function-local dummy map that is destroyed on the spot, and the handler appends to it only when AlwaysAppendData is set (MzMLHandler.cpp:181-190, MzXMLHandler.cpp:1251-1266), so nothing observable reads the value back. Restoring it deep-copied the peak data into storage nobody reads -- for the retaining consumer that motivates the whole fix. Retaining every spectrum while streaming now costs ~4% over dropping them (measured on 1.2M peaks) rather than one full copy per spectrum. The map-collecting overloads must still restore and do; the flag defaults to restoring, so a caller added later is correct before it is fast. imzML keeps the default: it reaches the consumer through ImzMLInterceptConsumer, and that indirection is not worth guessing about. Close three test gaps. Every write-through test used a non-retaining consumer (the move branch) and every retain test a non-editing consumer, so the copy branch combined with write-through -- the one that has to copy an edit rather than move it -- was never exercised. consumeChromatogram had lifetime coverage but no write-through coverage. ImzMLFile.load(filename, consumer), the third caller of the bridge and the only one that releases the GIL around the parse, had none at all. 23 tests (was 18), all passing; full suite 2506 passed, 0 failed. Co-Authored-By: Claude Opus 5 <[email protected]>
…callback-lifetime # Conflicts: # CHANGELOG
|
Still not 100% confident but tests look good. Let’s try … |
Implements R-4.7 of #9792 (part V.5 in the issue). Independent of #9803 — different file, no overlap — so the two can merge in either order.
The bug
NanobindMSDataConsumerbridges a Python object to the C++IMSDataConsumerinterface, soMzMLFile.transform,MzXMLFile.transformandImzMLFile.load(filename, consumer)can call back into Python. It passed each spectrum with plainrv_policy::reference, whileMzMLHandlerclears and refillsspectrum_data_as soon as the callback returns:Every child alias derived from the spectrum inherits the problem, including the zero-copy ndarray from
get_peaks_struct().Why neither obvious fix works
Copying into the callback would silently discard the consumer's edits.
IMSDataConsumerdocuments that a consumer "may modify the spectra", andMzMLHandler.cpp:186-190passes the modified value onward — that's whatMSDataTransformingConsumerexists for. It happens to be unobservable from Python today only because the streaming overload (MzMLFile.h:119) is wrapped and the one that writes results back (:136) is not. Wrapping:136later is plausible, and a copy would quietly break it then.Invalidating the wrapper when the callback returns — which is what I originally planned — is worse than it looks:
get_peaks_struct()ndarray still reads recycled memory;inst_destructdoes not unregister the pointer (nanobind unregisters only at deallocation,nb_type.cpp:276) and a later cast returns the registered object without checking its state (:1771), so a retained-and-invalidated wrapper can be handed back for a later spectrum out of the reused buffer;referencecast may reuse any compatible registered instance, so callinginst_destructwithout first checkinginst_state().second == falsecan destruct an object the binding does not own.The fix
Hand the callback an object that owns its value: move it out of the caller's storage for the duration of the call, then move it back — or copy it back if the consumer kept a reference, leaving Python a valid independent snapshot.
This removes the aliasing rather than guarding it, so there is no invalidation contract, no
ReferenceErrorsemantics to define, no registry-reuse hazard and no escape detection to get wrong.MSSpectrumandMSChromatogramboth have defaulted noexcept moves, so the ordinary path copies no peak data. The restore is RAII, so a raising callback cannot leave the parser holding a moved-from value.The uniqueness test is a reference count, so it is only sound while the GIL is held. That is guaranteed here from both sides:
isUniquelyReferenced_()takes the copy path unconditionally underNB_FREE_THREADED, and a module built without that macro does not emit nanobind'sPy_mod_gil, Py_MOD_GIL_NOT_USEDslot (nb_defs.h:154), so CPython re-enables the GIL even on a free-threaded interpreter. The refcount branch therefore always runs under a real GIL, and no false "unique" is reachable.Exception and failure handling
Putting the value back is an explicit, throwing step after a successful callback: if it fails, the parser must not carry on with moved-from storage and hand that downstream (
MzMLHandler.cpp:186), so the error propagates. The destructor repeats it only as a best-effort fallback for the path where the callback's own exception is already unwinding, and it copy-constructs before assigning so a throw there leaves the caller's storage untouched.The handoff is scoped inside the
try, so unwinding destroys it before thecatchruns — whilenb::python_errorstill owns and has cleared the Python error indicator (error.cpp:25). Getting that ordering wrong would have run the restore with a pending exception set.Also binds the map-collecting
transformoverloadsMzMLFile::transform(filename, consumer, PeakMap&)(MzMLFile.h:136) and the mzXML equivalent (MzXMLFile.h:99) are now wrapped astransform(filename, consumer, exp). They setalwaysAppendData(MzMLFile.cpp:204), so each spectrum is appended after the consumer has seen it — which makes IMSDataConsumer's write-through contract observable, and therefore testable, from Python for the first time.This is not padding. Without it the central claim of this PR — that edits still reach C++ — rests on code review alone. With it there is a direct test, and I verified it discriminates: swapping the caster to the naive
rv_policy::copyfix leaves all 16 other tests green and fails only these two. A copy-based fix would otherwise have looked entirely correct.Verification
18 regression tests. Against
develop's caster, 8 fail and 4 terminate the interpreter:test_retained_spectra_survive_the_transformtest_retained_spectrum_owns_its_peak_datatest_retained_zero_copy_view_stays_validtest_view_retained_without_the_spectrum_stays_validtest_retained_chromatograms_survive_the_transformtest_delivered_spectra_match_a_normal_loadtest_exception_in_callback_does_not_corrupt_later_usetest_mzxml_transform_uses_the_same_bridgeThe other 6 are positive controls that pass either way — in-callback mutability, exception propagation, plain streaming,
setExperimentalSettingsdelivery, a missing-method consumer, and a guard assertingget_peaks_struct()really is zero-copy so the view tests cannot pass for the wrong reason.test_view_retained_without_the_spectrum_stays_validdeliberately keeps only the ndarray and drops every reference to the spectrum, isolating the child keep-alive edge; the other view test also retains the spectrum, so on its own it would not prove the child case.Plus 2 that fail only under a copy-based fix:
test_consumer_edits_reach_the_collected_map[mzML]and[mzXML].Full pyOpenMS suite: 2501 passed, 0 failed.
Not fixed here
The caster flattens every
nb::python_errorintostd::runtime_error(:22,:32,:42,:52), so a Python exception raised inside a callback loses its type crossing the boundary. Real, but a separate behavioural change — left out to keep this diff to one concern. There is a test pinning the current behaviour so a change is deliberate.Also note the header now includes
MSSpectrum.handMSChromatogram.hexplicitly:IMSDataConsumeronly forward-declares them, and the previous code was getting them incidentally from its callers. Astatic_asserton the move guarantees surfaced that.Part of #9792. Follows #9794, #9795 and #9803.
Summary by CodeRabbit
MzMLFile.transform/MzXMLFile.transform(and relatedimzMLloading), preventing later overwritten peak/scalar data (including zero-copy views).transform(..., exp=...)overloads for consumer-based streaming that also populate an outputMSExperiment.