Skip to content

Fix AASequence copy constructor and __str__ method in Python bindings - #9098

Merged
timosachsenberg merged 8 commits into
developfrom
claude/fix-aaseq-copy-constructor-Cl5P5
Apr 7, 2026
Merged

timosachsenberg merged 8 commits into
developfrom
claude/fix-aaseq-copy-constructor-Cl5P5

Conversation

@t0mdavid-m

@t0mdavid-m t0mdavid-m commented Apr 7, 2026 •

Copy link
Copy Markdown
Member

Description

This PR fixes two issues in the Python bindings for the AASequence class and others:

  1. 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)

  2. Changes the __str__ method for AASequence to return the peptide sequence string.

Checklist

  • Make sure that you are listed in the AUTHORS file
  • Add relevant changes and new features to the CHANGELOG file
  • I have commented my code, particularly in hard-to-understand areas
  • New and existing unit tests pass locally with my changes
  • Updated or added python bindings for changed or new classes (Tick if no updates were necessary.)

https://claude.ai/code/session_012BLDPfomuwEnL52nFfuLfG

Summary by CodeRabbit

  • Behavior Changes

    • AASequence string conversion: str(obj) now returns the peptide sequence (e.g., "PEPTM(Oxidation)IDE") instead of repr-style output.
  • Tests

    • Added comprehensive tests for copy construction, shallow copy, and deep copy across pyopenms classes.
    • Updated AASequence unit test expectations to reflect the new str() behavior.
  • Bug Fixes / Stability

    • Improved robustness of spectrum copy/assignment to avoid null-related errors.

claude added 3 commits April 7, 2026 11:44
…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
@coderabbitai

coderabbitai Bot commented Apr 7, 2026 •

Copy link
Copy Markdown
Contributor

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

Reordered numerous nanobind constructor registrations; changed AASequence.__str__ to return toString() as a Python str; added a reflection-driven pytest module that probes and parametrizes copy/deepcopy/copy-constructor behavior across exported pyopenms classes.

Changes

Cohort / File(s) Summary
Constructor binding reorders
src/pyOpenMS/bindings/bind_analysis.cpp, src/pyOpenMS/bindings/bind_format.cpp, src/pyOpenMS/bindings/bind_kernel.cpp, src/pyOpenMS/bindings/bind_metadata.cpp, src/pyOpenMS/bindings/bind_misc.cpp
Adjusted registration order of constructor overloads (copy vs parameterized) for multiple classes (e.g., FIAMSScheduler, CachedmzML, IndexedMzMLHandler, XICParquetFile, XIMParquetFile, ProteinHit, Software, CVTerm, PeptideEvidence, USI, DefaultParamHandler) without changing signatures or other bindings.
Chemistry bindings
src/pyOpenMS/bindings/bind_chemistry.cpp
Reordered constructor overload registrations for AASequence and Ribonucleotide; changed AASequence.__str__ to return self.toString() as Python str instead of delegating to __repr__.
Tests — expectations & new suite
src/pyOpenMS/tests/unittests/test000.py, src/pyOpenMS/tests/unittests/test_copy_constructors.py
Updated test000.py expectations for AASequence.__str__; added test_copy_constructors.py, a reflection-driven pytest module that probes public pyopenms classes in subprocesses to build a safe set and parametrizes tests for copy.copy, copy.deepcopy, and explicit copy-construction, excluding classes that crash the probe.
Internal copy safety fix
src/openms/source/KERNEL/BinnedSpectrum.cpp
Fixed copy construction and assignment to handle nullable bins_ safely by conditionally copying or setting nullptr to avoid dereferencing null pointers.

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
Loading

Suggested reviewers

  • jpfeuffer

Poem

🐰 I hopped through bindings, tidy and spry,
constructors shuffled, neat in my eye,
AASequence sings its peptide song,
copies probed the whole night long,
carrot-approved, quick and spry!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 35.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly addresses the main changes: fixing AASequence's copy constructor dispatch in Python bindings and updating its str method, which are core objectives of the PR.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/fix-aaseq-copy-constructor-Cl5P5

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 and usage tips.

@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 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

📥 Commits

Reviewing files that changed from the base of the PR and between ad56cc7 and 33a895e.

📒 Files selected for processing (8)
  • src/pyOpenMS/bindings/bind_analysis.cpp
  • src/pyOpenMS/bindings/bind_chemistry.cpp
  • src/pyOpenMS/bindings/bind_format.cpp
  • src/pyOpenMS/bindings/bind_kernel.cpp
  • src/pyOpenMS/bindings/bind_metadata.cpp
  • src/pyOpenMS/bindings/bind_misc.cpp
  • src/pyOpenMS/tests/unittests/test000.py
  • src/pyOpenMS/tests/unittests/test_copy_constructors.py

@OpenMS OpenMS deleted a comment from github-actions Bot Apr 7, 2026
claude added 2 commits April 7, 2026 12:50
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

@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.

♻️ Duplicate comments (2)
src/pyOpenMS/tests/unittests/test_copy_constructors.py (2)

25-33: ⚠️ Potential issue | 🟠 Major

Classes 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_classes to 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 | 🟠 Major

Skip 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 constructor nb::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 == obj

Apply the same pattern to test_deepcopy and test_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.executable is trusted, the code template is hardcoded, and class_names comes from dir(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

📥 Commits

Reviewing files that changed from the base of the PR and between 87f13ab and 5745f6a.

📒 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

@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 (1)
src/pyOpenMS/tests/unittests/test_copy_constructors.py (1)

72-78: Timeout handling discards partial progress.

When timeout expires, all class_names are marked as crashed, losing information about classes that were successfully tested before the timeout. Consider parsing any partial stdout before returning.

Note: The S603 static analysis warning about untrusted subprocess input is a false positive—class_names is derived from dir(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 stdout from the TimeoutExpired exception:

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5745f6a and 67d797f.

📒 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

@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.

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 has nullptr bins_.

Now that copy/assign allow bins_ == nullptr, this method can receive such objects. Lines 135, 141, and 142 unconditionally dereference bins_, 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

📥 Commits

Reviewing files that changed from the base of the PR and between 67d797f and 7d8adb3.

📒 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
@t0mdavid-m

t0mdavid-m commented Apr 7, 2026 •

Copy link
Copy Markdown
Member Author

Added tests for the copy constructor and found out that the copy constructor segfaults for BinnedSpectrum. Fixed now.

@timosachsenberg
timosachsenberg merged commit d470b61 into develop Apr 7, 2026
41 checks passed
@timosachsenberg
timosachsenberg deleted the claude/fix-aaseq-copy-constructor-Cl5P5 branch April 7, 2026 18:38
@timosachsenberg

Copy link
Copy Markdown
Contributor

Thanks

github-actions Bot pushed a commit that referenced this pull request Apr 8, 2026
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]>
github-actions Bot pushed a commit that referenced this pull request Apr 8, 2026
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]>
timosachsenberg pushed a commit that referenced this pull request Apr 8, 2026
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]>
timosachsenberg added a commit that referenced this pull request Apr 8, 2026
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]>
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.

3 participants