Skip to content

[FIX] pyOpenMS: consumer callbacks were handed a reference into the parser's buffer (#9792 R-4.7) - #9804

Merged
timosachsenberg merged 4 commits into
developfrom
fix/9792-consumer-callback-lifetime
Jul 26, 2026
Merged

timosachsenberg merged 4 commits into
developfrom
fix/9792-consumer-callback-lifetime

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

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

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 with plain rv_policy::reference, while MzMLHandler clears and refills spectrum_data_ as soon as the callback returns:

kept = []
class C:
    def consumeSpectrum(self, s): kept.append(s)   # collect a subset while streaming
    ...
MzMLFile().transform(path, C())
kept[0].getRT()      # -> -1.0, size 0: values from whatever reused the memory

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. IMSDataConsumer documents that a consumer "may modify the spectra", and MzMLHandler.cpp:186-190 passes the modified value onward — that's what MSDataTransformingConsumer exists 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 :136 later 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:

  • it cannot reach child views, so a retained get_peaks_struct() ndarray still reads recycled memory;
  • inst_destruct does 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;
  • a reference cast may reuse any compatible registered instance, so calling inst_destruct without first checking inst_state().second == false can 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 ReferenceError semantics to define, no registry-reuse hazard and no escape detection to get wrong. MSSpectrum and MSChromatogram both 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 under NB_FREE_THREADED, and a module built without that macro does not emit nanobind's Py_mod_gil, Py_MOD_GIL_NOT_USED slot (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 the catch runs — while nb::python_error still 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 transform overloads

MzMLFile::transform(filename, consumer, PeakMap&) (MzMLFile.h:136) and the mzXML equivalent (MzXMLFile.h:99) are now wrapped as transform(filename, consumer, exp). They set alwaysAppendData (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::copy fix 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 on develop
test_retained_spectra_survive_the_transform fail
test_retained_spectrum_owns_its_peak_data crash
test_retained_zero_copy_view_stays_valid crash
test_view_retained_without_the_spectrum_stays_valid crash
test_retained_chromatograms_survive_the_transform crash
test_delivered_spectra_match_a_normal_load fail
test_exception_in_callback_does_not_corrupt_later_use fail
test_mzxml_transform_uses_the_same_bridge fail

The other 6 are positive controls that pass either way — in-callback mutability, exception propagation, plain streaming, setExperimentalSettings delivery, a missing-method consumer, and a guard asserting get_peaks_struct() really is zero-copy so the view tests cannot pass for the wrong reason.

test_view_retained_without_the_spectrum_stays_valid deliberately 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_error into std::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.h and MSChromatogram.h explicitly: IMSDataConsumer only forward-declares them, and the previous code was getting them incidentally from its callers. A static_assert on the move guarantees surfaced that.

Part of #9792. Follows #9794, #9795 and #9803.

Summary by CodeRabbit

  • Bug Fixes
    • Fixed stale-reference/use-after-free issues for spectra/chromatograms delivered to Python consumer callbacks during MzMLFile.transform / MzXMLFile.transform (and related imzML loading), preventing later overwritten peak/scalar data (including zero-copy views).
    • After the callback returns, retained Python references become independent snapshots; edits made inside the callback still propagate to results.
  • New Features
    • Added transform(..., exp=...) overloads for consumer-based streaming that also populate an output MSExperiment.
  • Tests
    • Added regression tests covering callback lifetime, retained objects vs. views, GC/buffer churn safety, exception behavior, and fidelity against standard loading.

@coderabbitai

coderabbitai Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Changes

The 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

Layer / File(s) Summary
Owned callback handoff
src/pyOpenMS/bindings/type_casters/nanobind_ms_data_consumer.h, CHANGELOG
OwningCallbackArg transfers callback data into Python and restores it afterward for spectra and chromatograms; the changelog records the fix.
Collecting transform overloads
src/pyOpenMS/bindings/bind_misc.cpp
MzML and MzXML consumer transforms gain overloads that append processed spectra to an MSExperiment.
Callback lifetime regression coverage
src/pyOpenMS/tests/unittests/test_consumer_callback_lifetime.py
Tests validate retained data, peak buffers, zero-copy views, mutations, map independence, exceptions, discarded data, experimental settings, and MzXML transforms.

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
Loading

Poem

A bunny gave each peak a home,
So retained views no longer roam.
Move out, call, then restore bright—
Mutations travel back just right.
MzML and MzXML cheer,
While stale data disappears.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 24.49% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main fix: pyOpenMS consumer callbacks previously received parser-buffer references.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/9792-consumer-callback-lifetime

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (3)
src/pyOpenMS/bindings/type_casters/nanobind_ms_data_consumer.h (2)

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

Move OwningCallbackArg into 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 value

Use the required brace layout.

Place the if/else and 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 win

Cover 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

📥 Commits

Reviewing files that changed from the base of the PR and between f9c181c and f62176d.

📒 Files selected for processing (3)
  • CHANGELOG
  • src/pyOpenMS/bindings/type_casters/nanobind_ms_data_consumer.h
  • src/pyOpenMS/tests/unittests/test_consumer_callback_lifetime.py

@timosachsenberg
timosachsenberg force-pushed the fix/9792-consumer-callback-lifetime branch 2 times, most recently from c6af0b3 to a576ae8 Compare July 26, 2026 15:34
…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]>
@timosachsenberg
timosachsenberg force-pushed the fix/9792-consumer-callback-lifetime branch from a576ae8 to de99794 Compare July 26, 2026 15:48

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

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

Inline comments:
In `@CHANGELOG`:
- Line 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

📥 Commits

Reviewing files that changed from the base of the PR and between a576ae8 and de99794.

📒 Files selected for processing (4)
  • CHANGELOG
  • src/pyOpenMS/bindings/bind_misc.cpp
  • src/pyOpenMS/bindings/type_casters/nanobind_ms_data_consumer.h
  • src/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

Comment thread CHANGELOG Resolved
timosachsenberg and others added 3 commits July 26, 2026 19:13
…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]>
@timosachsenberg

Copy link
Copy Markdown
Contributor Author

Still not 100% confident but tests look good. Let’s try …

@timosachsenberg
timosachsenberg merged commit bef744a into develop Jul 26, 2026
39 checks passed
@timosachsenberg
timosachsenberg deleted the fix/9792-consumer-callback-lifetime branch July 26, 2026 20:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant