Repository navigation
Fix AASequence copy constructor and __str__ method in Python bindings - #9098
Conversation
…dings Move copy constructor registration before string constructors so nanobind dispatches AASequence(existing_seq) to the copy constructor instead of converting to string via __str__. Also fix __str__ to return the peptide string (toString()) instead of delegating to __repr__, which produced an unparseable format like "AASequence(sequence='MK', ...)". https://claude.ai/code/session_012BLDPfomuwEnL52nFfuLfG
…dings Move copy constructor registration before string-accepting constructors in 11 additional classes (ProteinHit, Software, CVTerm, PeptideEvidence, USI, Ribonucleotide, FIAMSScheduler, CachedmzML, IndexedMzMLHandler, XICParquetFile, XIMParquetFile, DefaultParamHandler). nanobind uses registration order for overload dispatch, so string constructors registered first could intercept copy-construction via implicit conversion. https://claude.ai/code/session_012BLDPfomuwEnL52nFfuLfG
Add test_copy_constructors.py with three parametrized tests that run across all public pyopenms classes: copy.copy(), copy.deepcopy(), and ClassName(obj) copy construction. This catches regressions where nanobind dispatches copy-construction to a string constructor due to registration order. Remove the now-redundant AASequence-specific copy constructor test from test000.py. https://claude.ai/code/session_012BLDPfomuwEnL52nFfuLfG
|
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:
📝 WalkthroughWalkthroughReordered numerous nanobind constructor registrations; changed Changes
Sequence Diagram(s)sequenceDiagram
participant PyTest as Test Runner
participant Probe as Subprocess Probe
participant PyOpenMS as pyopenms classes
participant OS as OS/Runtime
PyTest->>Probe: spawn subprocess (enumerate classes)
Probe->>PyOpenMS: import & instantiate classes (default-construct)
PyOpenMS-->>Probe: success / raises / segfault
Probe->>OS: report crash or stdout safe list
OS-->>Probe: exit status
Probe-->>PyTest: return safe set & crashed list
PyTest->>PyTest: parametrize copy/deepcopy/copy-constructor tests using safe set
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ 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.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/pyOpenMS/tests/unittests/test_copy_constructors.py`:
- Around line 48-92: Replace the current conditional skips in test_copy_copy,
test_deepcopy, and test_copy_constructor so that missing copy-related bindings
cause test failures instead of silent skips: remove the broad hasattr checks for
"__copy__" and "__deepcopy__" and the TypeError except that lead to pytest.skip,
and instead maintain a small explicit denylist (e.g., a module-level set) of
class names that are intentionally unsupported; for all other classes obtained
via ALL_CLASSES and constructed via _try_default_construct, assert presence of
the default constructor and copy constructor semantics (using cls(obj)), and
assert that copy.copy and copy.deepcopy produce the same type and equality when
_has_own_eq(cls) is true. Reference the test functions test_copy_copy,
test_deepcopy, test_copy_constructor and helpers ALL_CLASSES,
_try_default_construct, and _has_own_eq to locate and update the logic.
🪄 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
Run ID: da784901-165d-49a3-8e48-bb0a6e174ba2
📒 Files selected for processing (8)
src/pyOpenMS/bindings/bind_analysis.cppsrc/pyOpenMS/bindings/bind_chemistry.cppsrc/pyOpenMS/bindings/bind_format.cppsrc/pyOpenMS/bindings/bind_kernel.cppsrc/pyOpenMS/bindings/bind_metadata.cppsrc/pyOpenMS/bindings/bind_misc.cppsrc/pyOpenMS/tests/unittests/test000.pysrc/pyOpenMS/tests/unittests/test_copy_constructors.py
Filter the parametrized test to only classes that explicitly register __copy__ in their bindings (~276 classes), rather than testing all ~600 classes. Classes without __copy__ may have uninitialized pointers or missing copy constructors that cause C++ segfaults — which cannot be caught by Python exception handlers. Also only catch TypeError (no matching overload) in test_copy_constructor, not RuntimeError — a RuntimeError means the wrong constructor was called, which is the exact bug we want to detect. https://claude.ai/code/session_012BLDPfomuwEnL52nFfuLfG
Instead of letting a segfault kill the entire pytest process, probe each copyable class in a subprocess at collection time. Classes that crash the subprocess are excluded from parametrized tests but cause test_no_segfaults_during_copy to FAIL with a clear list of crashers. This ensures: - CI fails when classes segfault (not silently skipped) - All crashing classes are identified in a single run - Remaining copy tests still execute normally https://claude.ai/code/session_012BLDPfomuwEnL52nFfuLfG
There was a problem hiding this comment.
♻️ Duplicate comments (2)
src/pyOpenMS/tests/unittests/test_copy_constructors.py (2)
25-33:⚠️ Potential issue | 🟠 MajorClasses without
__copy__are silently excluded from the test suite.Line 32 filters to only classes that already have
__copy__, so if a binding loses its__copy__method entirely, the class disappears from the test suite rather than causing a test failure. This defeats the purpose of catching regressions where copy support is removed. Based on learnings, class bindings must include__copy__method.🔒 Suggested approach
Maintain an explicit denylist of class names that are intentionally unsupported (e.g., a module-level set like
_INTENTIONALLY_NO_COPY = {"KernelDensity", ...}), then change_get_copyable_classesto return all public non-enum classes, and in each test function, assert that either the class is in the denylist OR it has the required copy support. This way, removing copy support from a binding causes test failure rather than silent exclusion.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/pyOpenMS/tests/unittests/test_copy_constructors.py` around lines 25 - 33, The current helper _get_copyable_classes filters out classes that lack __copy__, causing regressions to be silently excluded; change the approach to return all public non-enum classes (i.e., remove the hasattr(..., "__copy__") filter in _get_copyable_classes) and introduce a module-level denylist (e.g., _INTENTIONALLY_NO_COPY = {"ClassA", "ClassB", ...}) of known exceptions; update the tests to iterate over all classes returned by _get_copyable_classes and assert for each class that either its name is in _INTENTIONALLY_NO_COPY or the class has a __copy__ method (use getattr(pyopenms, name) to inspect), so missing __copy__ on a previously supported binding will fail the test.
131-171:⚠️ Potential issue | 🟠 MajorSkip conditions allow missing copy support to pass silently.
The test functions skip in several scenarios:
- Lines 135-136, 148-149, 161-162: Skip if default construction fails (missing
nb::init<>())- Lines 166-167: Skip if copy constructor raises TypeError (missing
nb::init<const ClassName &>())These skips allow bindings to lose default constructors or copy constructors without causing test failures. Based on learnings, class bindings must include default constructor
nb::init<>()and copy constructornb::init<const ClassName &>().♻️ Recommended approach
Replace the skip logic with an explicit denylist pattern:
# Module-level denylist of classes intentionally without copy support _NO_COPY_SUPPORT = { # Add specific class names that legitimately can't be default-constructed or copied } `@pytest.mark.parametrize`("class_name", COPYABLE_CLASSES) def test_copy_copy(class_name): if class_name in _NO_COPY_SUPPORT: pytest.skip(f"{class_name} is in known denylist") cls = getattr(pyopenms, class_name) obj = _try_default_construct(cls) assert obj is not None, f"{class_name} must have default constructor" obj_copy = copy.copy(obj) assert type(obj_copy) is type(obj) if _has_own_eq(cls): assert obj_copy == objApply the same pattern to
test_deepcopyandtest_copy_constructor, removing the TypeError skip in the latter.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/pyOpenMS/tests/unittests/test_copy_constructors.py` around lines 131 - 171, Replace the permissive skips in test_copy_copy, test_deepcopy, and test_copy_constructor with an explicit module-level denylist (e.g. _NO_COPY_SUPPORT) and assert checks: first check if class_name is in _NO_COPY_SUPPORT and pytest.skip if so, then call cls = getattr(pyopenms, class_name) and obj = _try_default_construct(cls) and assert obj is not None with a failure message requiring nb::init<>(), and in test_copy_constructor remove the try/except TypeError branch and instead assert that cls(obj) succeeds (failing the test if copy ctor is missing) to force binding authors to add nb::init<const ClassName &>(). Ensure you reference the test functions test_copy_copy, test_deepcopy, test_copy_constructor and the denylist _NO_COPY_SUPPORT when making the changes.
🧹 Nitpick comments (1)
src/pyOpenMS/tests/unittests/test_copy_constructors.py (1)
68-70: Static analysis flags subprocess execution, but risk is low in test context.Ruff S603 flags the subprocess call as potentially executing untrusted input. In this case,
sys.executableis trusted, the code template is hardcoded, andclass_namescomes fromdir(pyopenms), so the risk is minimal. However, if pyopenms namespace pollution is a concern, consider adding an assertion that validates class_names before interpolation.🛡️ Optional defensive check
def _probe_safe_classes(class_names, timeout=120): """Probe which classes can be default-constructed and copied without segfaulting. Runs operations in a subprocess. If it crashes, identifies the crasher from the last successfully printed class name and recurses on remaining classes. Returns (safe_set, crashed_list). """ if not class_names: return set(), [] + # Validate class_names are simple identifiers (defense-in-depth) + assert all(isinstance(n, str) and n.isidentifier() for n in class_names) + code = _PROBE_CODE.format(class_names=class_names)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/pyOpenMS/tests/unittests/test_copy_constructors.py` around lines 68 - 70, The subprocess.run invocation (result = subprocess.run(...)) interpolates class_names into the Python code string; add a defensive validation step before building 'code' that asserts class_names contains only expected safe identifiers (e.g., non-empty strings matching a valid identifier/whitelist or coming from dir(pyopenms]) and raise/assert if any value is suspicious, then proceed to construct and run the subprocess; this keeps the existing test behavior while satisfying the static-analysis concern.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@src/pyOpenMS/tests/unittests/test_copy_constructors.py`:
- Around line 25-33: The current helper _get_copyable_classes filters out
classes that lack __copy__, causing regressions to be silently excluded; change
the approach to return all public non-enum classes (i.e., remove the
hasattr(..., "__copy__") filter in _get_copyable_classes) and introduce a
module-level denylist (e.g., _INTENTIONALLY_NO_COPY = {"ClassA", "ClassB", ...})
of known exceptions; update the tests to iterate over all classes returned by
_get_copyable_classes and assert for each class that either its name is in
_INTENTIONALLY_NO_COPY or the class has a __copy__ method (use getattr(pyopenms,
name) to inspect), so missing __copy__ on a previously supported binding will
fail the test.
- Around line 131-171: Replace the permissive skips in test_copy_copy,
test_deepcopy, and test_copy_constructor with an explicit module-level denylist
(e.g. _NO_COPY_SUPPORT) and assert checks: first check if class_name is in
_NO_COPY_SUPPORT and pytest.skip if so, then call cls = getattr(pyopenms,
class_name) and obj = _try_default_construct(cls) and assert obj is not None
with a failure message requiring nb::init<>(), and in test_copy_constructor
remove the try/except TypeError branch and instead assert that cls(obj) succeeds
(failing the test if copy ctor is missing) to force binding authors to add
nb::init<const ClassName &>(). Ensure you reference the test functions
test_copy_copy, test_deepcopy, test_copy_constructor and the denylist
_NO_COPY_SUPPORT when making the changes.
---
Nitpick comments:
In `@src/pyOpenMS/tests/unittests/test_copy_constructors.py`:
- Around line 68-70: The subprocess.run invocation (result =
subprocess.run(...)) interpolates class_names into the Python code string; add a
defensive validation step before building 'code' that asserts class_names
contains only expected safe identifiers (e.g., non-empty strings matching a
valid identifier/whitelist or coming from dir(pyopenms]) and raise/assert if any
value is suspicious, then proceed to construct and run the subprocess; this
keeps the existing test behavior while satisfying the static-analysis concern.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: f330780e-6bf7-4cfe-b5a8-75b1442d9229
📒 Files selected for processing (1)
src/pyOpenMS/tests/unittests/test_copy_constructors.py
66 classes inherit __copy__ from a base (DefaultParamHandler, ProgressLogger, etc.) via nanobind inheritance. The base's __copy__ returns a base-type copy (object slicing), causing test_copy_copy to fail with type mismatches like `type(copy) is DefaultParamHandler` instead of `AScore`. Fix: check `"__copy__" in cls.__dict__` instead of `hasattr(cls, "__copy__")` to only test classes that explicitly register their own __copy__ binding. Classes with inherited __copy__ need their own binding added before they can be tested. https://claude.ai/code/session_012BLDPfomuwEnL52nFfuLfG
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/pyOpenMS/tests/unittests/test_copy_constructors.py (1)
72-78: Timeout handling discards partial progress.When timeout expires, all
class_namesare marked as crashed, losing information about classes that were successfully tested before the timeout. Consider parsing any partialstdoutbefore returning.Note: The S603 static analysis warning about untrusted subprocess input is a false positive—
class_namesis derived fromdir(pyopenms), not user input.♻️ Suggested improvement to preserve partial results on timeout
try: result = subprocess.run( [sys.executable, "-c", code], capture_output=True, text=True, timeout=timeout ) except subprocess.TimeoutExpired: - return set(), list(class_names) + # Timeout: treat remaining unprocessed classes as crashed + return set(), list(class_names)A more thorough fix would capture
stdoutfrom theTimeoutExpiredexception:except subprocess.TimeoutExpired as e: # Parse any partial output before timeout partial_safe = set() partial_skipped = set() if e.stdout: for line in e.stdout.strip().splitlines(): if line.startswith("OK:"): partial_safe.add(line[3:]) elif line.startswith("SKIP:"): partial_skipped.add(line[5:]) reported = partial_safe | partial_skipped remaining = [n for n in class_names if n not in reported] return partial_safe, remaining🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/pyOpenMS/tests/unittests/test_copy_constructors.py` around lines 72 - 78, The current TimeoutExpired except block discards partial test output and marks all class_names as crashed; update the except subprocess.TimeoutExpired handler to capture the exception as e, inspect e.stdout (or result.stdout if available) for lines starting with "OK:" and "SKIP:" to build partial_safe and partial_skipped sets, compute remaining = [n for n in class_names if n not in (partial_safe | partial_skipped)], and return the parsed partial results (e.g., partial_safe and remaining) instead of returning an empty set and the full class_names list; reference subprocess.TimeoutExpired, class_names, and the subprocess.run call to locate the code to modify.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@src/pyOpenMS/tests/unittests/test_copy_constructors.py`:
- Around line 72-78: The current TimeoutExpired except block discards partial
test output and marks all class_names as crashed; update the except
subprocess.TimeoutExpired handler to capture the exception as e, inspect
e.stdout (or result.stdout if available) for lines starting with "OK:" and
"SKIP:" to build partial_safe and partial_skipped sets, compute remaining = [n
for n in class_names if n not in (partial_safe | partial_skipped)], and return
the parsed partial results (e.g., partial_safe and remaining) instead of
returning an empty set and the full class_names list; reference
subprocess.TimeoutExpired, class_names, and the subprocess.run call to locate
the code to modify.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 67d33abb-bc6b-4e5d-a398-7cd846d33528
📒 Files selected for processing (1)
src/pyOpenMS/tests/unittests/test_copy_constructors.py
The default constructor (added for nanobind bindings) leaves bins_ as nullptr. The copy constructor and assignment operator unconditionally dereference rhs.bins_, causing a segfault when copying a default-constructed BinnedSpectrum. Add null checks to both. https://claude.ai/code/session_012BLDPfomuwEnL52nFfuLfG
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/openms/source/KERNEL/BinnedSpectrum.cpp (1)
125-153:⚠️ Potential issue | 🟠 Major
operator==will crash if either operand hasnullptrbins_.Now that copy/assign allow
bins_ == nullptr, this method can receive such objects. Lines 135, 141, and 142 unconditionally dereferencebins_, which will segfault.Consider adding a nullptr check at the start:
Suggested fix
bool BinnedSpectrum::operator==(const BinnedSpectrum& rhs) const { + // Handle nullptr cases (e.g., default-constructed objects) + if (bins_ == nullptr || rhs.bins_ == nullptr) + { + return bins_ == rhs.bins_; // Both nullptr => equal + } + // first compare bin layout and precursors if (std::tie(unit_ppm_, bin_size_, bin_spread_, precursors_)Similar guards may be needed in
getBinIntensity(line 189) and the comparison classes shown in the relevant snippets (BinnedSpectralContrastAngle,BinnedSharedPeakCount,BinnedSumAgreeingIntensities,SpectraSTSimilarityScore).🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/source/KERNEL/BinnedSpectrum.cpp` around lines 125 - 153, The operator== currently dereferences bins_ and rhs.bins_ unconditionally and will crash if either is nullptr; add null checks at the start of BinnedSpectrum::operator== so that if both bins_ are nullptr it returns true, if only one is nullptr it returns false, and only then proceed to compare nonZeros() and construct SparseVectorIteratorType; apply the same defensive pattern to getBinIntensity and the comparator classes BinnedSpectralContrastAngle, BinnedSharedPeakCount, BinnedSumAgreeingIntensities, and SpectraSTSimilarityScore by guarding accesses to bins_ (and rhs.bins_) and avoiding dereferencing when null.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Outside diff comments:
In `@src/openms/source/KERNEL/BinnedSpectrum.cpp`:
- Around line 125-153: The operator== currently dereferences bins_ and rhs.bins_
unconditionally and will crash if either is nullptr; add null checks at the
start of BinnedSpectrum::operator== so that if both bins_ are nullptr it returns
true, if only one is nullptr it returns false, and only then proceed to compare
nonZeros() and construct SparseVectorIteratorType; apply the same defensive
pattern to getBinIntensity and the comparator classes
BinnedSpectralContrastAngle, BinnedSharedPeakCount,
BinnedSumAgreeingIntensities, and SpectraSTSimilarityScore by guarding accesses
to bins_ (and rhs.bins_) and avoiding dereferencing when null.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: daded2b7-3189-45ad-a8f1-48594baf73f0
📒 Files selected for processing (1)
src/openms/source/KERNEL/BinnedSpectrum.cpp
operator== dereferences bins_ (line 135: bins_->nonZeros()) without checking for nullptr, causing a segfault when comparing default-constructed BinnedSpectrum objects. Add null checks before accessing the sparse vector. https://claude.ai/code/session_012BLDPfomuwEnL52nFfuLfG
|
Added tests for the copy constructor and found out that the copy constructor segfaults for |
|
Thanks |
Add missing entries for changes since last sync: - PeptideDataBaseSearchFI: BREAKING default fragment:min_ion_index=2 (#9094) - PyOpenMS: Fix AASequence.__str__() and copy constructor dispatch (#9098) - Build: minimum Boost version bumped to 1.81 (#9095) Co-authored-by: Copilot <[email protected]>
Add missing entries for commits since last sync (2026-04-06): - Boost minimum version raised to 1.81 (#9095) - FragmentIndex default min_ion_index=2, skipping b1/b2/y1/y2 (#9094) - FragmentIndex faster build with bitmask/SoA/SIMD (#9088) - AASequence copy constructor fix in pyOpenMS bindings (#9098) Co-authored-by: Copilot <[email protected]>
Add missing entries for commits since last sync (2026-04-06): - Boost minimum version raised to 1.81 (#9095) - FragmentIndex default min_ion_index=2, skipping b1/b2/y1/y2 (#9094) - FragmentIndex faster build with bitmask/SoA/SIMD (#9088) - AASequence copy constructor fix in pyOpenMS bindings (#9098) Co-authored-by: GitHub Copilot <[email protected]> Co-authored-by: Copilot <[email protected]>
Add missing entries for changes since last sync: - PeptideDataBaseSearchFI: BREAKING default fragment:min_ion_index=2 (#9094) - PyOpenMS: Fix AASequence.__str__() and copy constructor dispatch (#9098) - Build: minimum Boost version bumped to 1.81 (#9095) Co-authored-by: GitHub Copilot <[email protected]> Co-authored-by: Copilot <[email protected]> Co-authored-by: Timo Sachsenberg <[email protected]>
Description
This PR fixes two issues in the Python bindings for the
AASequenceclass and others:In nanobind, constructor overloads are tried in the order they are registered. The copy constructor was registered after string constructors in 12 classes, so I moved it before them to ensure it gets matched first (this should be legacy behavior afaik)
Changes the
__str__method forAASequenceto return the peptide sequence string.Checklist
https://claude.ai/code/session_012BLDPfomuwEnL52nFfuLfG
Summary by CodeRabbit
Behavior Changes
Tests
Bug Fixes / Stability