Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
53 commits
Select commit Hold shift + click to select a range
42fab99
[FEATURE] Simple, targeted, fast IsobaricWorkflow
jpfeuffer Jan 14, 2024
8f704fd
Merge remote-tracking branch 'origin/develop' into feature/isobaricWo…
timosachsenberg Jan 31, 2024
f4c7455
started moving some parts that can be used by LFQ and Isobaric Workfl…
timosachsenberg Jan 31, 2024
6eee06a
fix build
Feb 21, 2024
bb9f877
backporting include fix
Feb 21, 2024
821fff3
fix DLL export
Feb 21, 2024
3bed458
Merge branch 'develop' into feature/isobaricWorkflow
timosachsenberg Feb 21, 2024
fc427b1
Update MatrixUtils.h
timosachsenberg Feb 21, 2024
8c95b91
Merge branch 'develop' into feature/isobaricWorkflow
timosachsenberg Feb 21, 2024
330caa8
add Eigen to metaprosip deps
jpfeuffer Feb 21, 2024
404a8b4
print eigen version
timosachsenberg Feb 22, 2024
e073b20
Merge remote-tracking branch 'origin' into feature/isobaricWorkflow
timosachsenberg Feb 22, 2024
41ce7ed
Update src/openms/include/OpenMS/MATH/MISC/NonNegativeLeastSquaresSol…
timosachsenberg Feb 22, 2024
36aedc7
Merge branch 'develop' into feature/isobaricWorkflow
poshul Mar 5, 2024
2b6b90d
[FIX] remove references to removed type 'MutableEigenMatrixXdPtr'
hendrikweisser Mar 13, 2024
7d9c40f
Merge pull request #6 from hendrikweisser/feature/isobaricWorkflow
jpfeuffer Mar 15, 2024
09f02c4
[FIX] use MS2 spec for quant purity, return purity=1 for empty window…
jpfeuffer Mar 18, 2024
cb20452
Merge branch 'develop' into feature/isobaricWorkflow
jpfeuffer Oct 25, 2024
ec4ae91
fix after merge. start adding exp design
jpfeuffer Oct 28, 2024
aa7bad7
Merge branch 'develop' into feature/isobaricWorkflow
timosachsenberg Mar 21, 2025
c6ebf4b
fix compile
timosachsenberg Mar 21, 2025
af4fa16
expand doc
timosachsenberg Mar 21, 2025
fe1e028
fix header
timosachsenberg Mar 21, 2025
e7d6c1e
Apply suggestions from code review
timosachsenberg Mar 21, 2025
6ed3587
add topp doc
timosachsenberg Mar 21, 2025
adc42a0
minor fixes
timosachsenberg Mar 21, 2025
5b6d19b
rebuild doc
timosachsenberg Mar 21, 2025
27dd7cf
Add mathematical functions for binomial coefficient and log-sum-exp o…
timosachsenberg Mar 24, 2025
068b7c9
use new methods
timosachsenberg Mar 24, 2025
a84565c
Update supported labeling methods in documentation
timosachsenberg Apr 14, 2025
9538046
Merge branch 'develop' into feature/isobaricWorkflow
timosachsenberg Sep 16, 2025
934cf4c
update with new PeptideIdentificationList datastructure
timosachsenberg Sep 16, 2025
a73546e
Merge branch 'develop' into feature/isobaricWorkflow
timosachsenberg Sep 23, 2025
18d56ea
more fixes
timosachsenberg Sep 23, 2025
82b6c6a
math test
timosachsenberg Sep 23, 2025
43a0fe4
Fix tests
jpfeuffer Sep 23, 2025
b77d100
Update src/tests/class_tests/openms/source/MathFunctions_test.cpp
timosachsenberg Sep 24, 2025
a959434
fix test
timosachsenberg Sep 24, 2025
5492a1c
Exposing parameter in IsobaricWorkflow
MaLLLiYA May 26, 2025
7344ebc
Update src/topp/IsobaricWorkflow.cpp
timosachsenberg May 26, 2025
b5e2f04
Apply suggestions from code review
MaLLLiYA Jun 3, 2025
6cfff54
Add the missing parameters
MaLLLiYA Sep 23, 2025
cc41f46
typo
timosachsenberg Sep 24, 2025
3b548a4
address review comments
jpfeuffer Sep 24, 2025
2f7350d
review comments and param cleanup
jpfeuffer Oct 2, 2025
48e70cd
Merge branch 'develop' into feature/isobaricWorkflow
timosachsenberg Oct 10, 2025
9b92f09
apply fix from AI
timosachsenberg Oct 17, 2025
c6162d4
fix doxygen
timosachsenberg Oct 17, 2025
0d247f7
Update src/openms/include/OpenMS/ANALYSIS/QUANTITATION/IsobaricChanne…
timosachsenberg Oct 17, 2025
7551a78
Merge branch 'develop' into feature/isobaricWorkflow
timosachsenberg Oct 17, 2025
acfffe5
second fix
timosachsenberg Oct 17, 2025
e751b0d
Merge remote-tracking branch 'jpfeuffer/feature/isobaricWorkflow' int…
timosachsenberg Oct 17, 2025
c5458bf
Merge branch 'develop' into feature/isobaricWorkflow
timosachsenberg Oct 23, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/doxygen/public/TOPP.doxygen
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@
- @subpage TOPP_FeatureFinderMetaboIdent - Detects features in MS1 data corresponding to small molecule identifications.
- @subpage TOPP_FeatureFinderMultiplex - Identifies peptide multiplets (pairs, triplets etc., e.g. for SILAC or Dimethyl labeling) and determines their relative abundance.
- @subpage TOPP_IsobaricAnalyzer - Extracts and normalizes TMT and iTRAQ information from an MS experiment.
- @subpage TOPP_IsobaricWorkflow - Complete workflow for quantification with isobaric labeling (TMT, iTRAQ) combining several OpenMS tools.
- @subpage TOPP_MassTraceExtractor - Annotates mass traces in centroided LC-MS maps.
- @subpage TOPP_MetaboliteAdductDecharger - Decharges and merges different feature charge variants of the same small molecule.
- @subpage TOPP_MetaProSIP - Detect labeled peptides from protein-SIP experiments.
Expand Down
214 changes: 178 additions & 36 deletions src/openms/include/OpenMS/ANALYSIS/ID/IDMergerAlgorithm.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/METADATA/ExperimentalDesign.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>

#include <map>
#include <unordered_set>

namespace OpenMS
Expand All @@ -24,26 +26,77 @@ namespace OpenMS
//TODO add another subclass that does score-aware merging? (i.e. only keep best per peptide[sequence])

/**
* @brief Creates a new Protein ID run into which other runs can be inserted.
* Creates union of protein hits but concatenates PSMs. Checks
* search engine consistency of all inserted runs. It differs from the IDMerger tool,
* in that it is an algorithm class and it allows inserting multiple peptide hits per
* peptide sequence (not only the first occurrence).
* @brief Algorithm for merging multiple protein and peptide identification runs.
*
* @todo allow filtering for peptide sequence to supersede the IDMerger tool.
* This class creates a new Protein ID run into which other runs can be inserted.
* It performs the following operations:
* - Creates a union of protein hits from all inserted runs
* - Concatenates Peptide-Spectrum Matches (PSMs) from all runs
* - Checks search engine consistency across all inserted runs
* - Maintains references between peptide IDs and their corresponding protein IDs
*
* The algorithm differs from the IDMerger tool in two key aspects:
* 1. It is implemented as an algorithm class rather than a tool
* 2. It allows inserting multiple peptide hits per peptide sequence (not only the first occurrence)
*
* The class handles the complexity of merging identification data from different sources
* while ensuring consistency and maintaining proper references between proteins and peptides.
* It can be used in workflows where identification results from multiple files or runs
* need to be combined into a single comprehensive result set.
*
* The algorithm can optionally annotate the origin of each identification to maintain
* traceability of the merged results back to their source files.
*
* @see IDMerger
*
* @todo Allow filtering for peptide sequence to supersede the IDMerger tool.
* Make it keep the best PSMs though.
*/
class OPENMS_DLLAPI IDMergerAlgorithm:
public DefaultParamHandler,
public ProgressLogger
{
public:
explicit IDMergerAlgorithm (const String& runIdentifier = "merged");
/**
* @brief Constructor for the IDMergerAlgorithm.
*
* Initializes a new merger with the specified run identifier.
*
* @param runIdentifier Base identifier for the merged run (default: "merged")
* @param addTimeStampToID Whether to append a timestamp to the run identifier for uniqueness (default: true)
*/
explicit IDMergerAlgorithm (const String& runIdentifier = "merged", bool addTimeStampToID = true);
Comment thread
timosachsenberg marked this conversation as resolved.
Resolved

/// Insert (=move and clear) a run with its peptide IDs into the internal merged data structures,
/// based on the initial mapping from fileorigins to new run
void insertRuns(std::vector<ProteinIdentification>&& prots,
/**
* @brief Insert runs using move semantics.
*
* Inserts (moves and clears) protein and peptide identifications into the internal
* merged data structures. This version uses move semantics for better performance
* when the source data is no longer needed.
* Note:
* - Only inserts PeptideIdentifications from existing runs in @p prots (noop if prots is empty)
* - Duplicates file origins if multiple (compatible) protein runs from the same spectrumfile
* are merged
*
* @param prots Vector of protein identifications to be merged
* @param peps Vector of peptide identifications to be merged
*/
void insertRuns(std::vector<ProteinIdentification>&& prots,
PeptideIdentificationList&& peps);

Comment on lines +70 to +86

@coderabbitai coderabbitai Bot Sep 16, 2025 •

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.

⚠️ Potential issue

Guard against empty input for move-variant insertRuns.

Implementation reads search params from prots[0]; if prots is empty and this is the first insert, this will read out of bounds.

Proposed fix in the .cpp (move overload):

 void IDMergerAlgorithm::insertRuns(
       std::vector<ProteinIdentification>&& prots,
       PeptideIdentificationList&& peps
       )
 {
+  if (prots.empty()) return; // or throw; align with copy-variant behavior

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/openms/include/OpenMS/ANALYSIS/ID/IDMergerAlgorithm.h around lines 68-80:
the move-variant insertRuns can read prots[0] without checking for empty input;
in the .cpp implementation add a guard at the top so if both incoming vectors
are empty do nothing (return early), and if this is the first insert (internal
merged proteins/peptides are empty) only read prots[0] or peps[0] after
confirming prots/peps are non-empty; avoid out-of-bounds access and preserve
existing behavior for non-empty inputs by conditionally setting search
parameters/initial state only when source containers contain elements.

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.

how to handle?

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.

🧩 Analysis chain

@timosachsenberg The potential out-of-bounds issue identified by CodeRabbit is legitimate and should be addressed. Looking at the current implementation, there are a few ways to handle this:

Recommended Approach

Add input validation at the beginning of both insertRuns variants to ensure consistent behavior:

void IDMergerAlgorithm::insertRuns(
    std::vector<ProteinIdentification>&& prots,
    PeptideIdentificationList&& peps)
{
    // Validate inputs - both should be non-empty for meaningful merging
    if (prots.empty() || peps.empty()) {
        OPENMS_LOG_WARN << "Skipping insertion of empty protein or peptide identification vectors" << std::endl;
        return;
    }
    
    // Rest of existing implementation...
}

Alternative Approaches

  1. Throw exception for invalid input (stricter):
if (prots.empty() || peps.empty()) {
    throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
                                     "Cannot insert empty identification vectors");
}
  1. Allow empty peptides but require proteins (if that makes biological sense):
if (prots.empty()) {
    OPENMS_LOG_WARN << "Skipping insertion due to empty protein identifications" << std::endl;
    return;
}

Why This Matters

The current implementation accesses prots[0] to read search parameters without bounds checking, which will cause undefined behavior (likely a crash) if prots is empty. The commented-out validation code suggests this was previously considered but removed.

I recommend the first approach (log warning and return early) as it's the most user-friendly while preventing crashes. This should be applied to both the move and copy variants for consistency.

What's your preference for handling this edge case?


🏁 Script executed:

#!/bin/bash
# Let's look at the actual implementation of the insertRuns methods in the .cpp file
cat src/openms/source/ANALYSIS/ID/IDMergerAlgorithm.cpp

Length of output: 14775


@timosachsenberg Looking at the implementation, I can see the exact issue and the solution is straightforward.

The Problem

The move variant of insertRuns (line 47) lacks the input validation that the copy variant already has.

Move variant (vulnerable):

void IDMergerAlgorithm::insertRuns(
    std::vector<ProteinIdentification>&& prots,
    PeptideIdentificationList&& peps)
{
    // No bounds checking here!
    if (!filled_)
    {
        // ... 
        copySearchParams_(prots[0], prot_result_); // ← CRASH if prots is empty

Copy variant (protected):

void IDMergerAlgorithm::insertRuns(
    const std::vector<ProteinIdentification>& prots,
    const PeptideIdentificationList& peps)
{
    // Copy logic...
    if (prots.empty() || peps.empty()) return; //error? ← Already has protection!

The Fix

Add the same guard to the move variant. Insert this line right after the opening brace of the move variant:

void IDMergerAlgorithm::insertRuns(
    std::vector<ProteinIdentification>&& prots,
    PeptideIdentificationList&& peps)
{
    if (prots.empty() || peps.empty()) return; // Match copy variant behavior
    
    // Rest of existing implementation...

This ensures both variants behave consistently and prevents the out-of-bounds access when prots[0] is accessed in copySearchParams_.

Location

The fix should go at line 50 in src/openms/source/ANALYSIS/ID/IDMergerAlgorithm.cpp, right after the opening brace of the move variant insertRuns method.

This is a simple consistency fix that aligns both method variants to handle empty inputs the same way.

/**
Comment thread
jpfeuffer marked this conversation as resolved.
Resolved
* @brief Insert runs using copy semantics.
*
* Inserts (copies) protein and peptide identifications into the internal
* merged data structures. This version preserves the source data.
* Note:
* - Only inserts PeptideIdentifications from existing runs in @p prots (noop if prots is empty)
* - Duplicates file origins if multiple (compatible) protein runs from the same spectrumfile
* are merged
*
* @param prots Vector of protein identifications to be merged
* @param peps Vector of peptide identifications to be merged
*/
void insertRuns(const std::vector<ProteinIdentification>& prots,
const PeptideIdentificationList& peps);

Expand All @@ -54,83 +107,172 @@ namespace OpenMS
// Current solution would be to clear the ProteinIdentification if you do not need the proteins and add all the
// necessary information about origin(s) to this ProteinIdentification.

/// Return the merged results and reset/clear all internal data
/**
* @brief Return the merged results and reset internal state.
*
* Retrieves the merged protein and peptide identifications and clears all internal
* data structures, preparing the algorithm instance for potential reuse.
*
* This method should be called after all desired runs have been inserted to obtain
* the final merged result.
*
* @param prots [out] The merged protein identification containing the union of all protein hits
* @param peps [out] The merged peptide identifications containing all PSMs from the inserted runs
*
* @note After calling this method, the internal state is reset, and the algorithm
* can be reused for a new merging operation.
*/
void returnResultsAndClear(ProteinIdentification& prots,
PeptideIdentificationList& peps);
Comment thread
jpfeuffer marked this conversation as resolved.
Resolved

private:

/// Returns the new identifier. The initial identifier plus a timestamp.
String getNewIdentifier_() const;
/**
* @brief Generate a new identifier for the merged run.
*
* Creates a new identifier by combining the base identifier with a timestamp
* if requested.
*
* @param addTimeStampToID Whether to append a timestamp to the identifier
* @return The generated identifier string
*/
String getNewIdentifier_(bool addTimeStampToID) const;

/// Copies over search parameters
/**
* @brief Copy search parameters between protein identifications.
*
* Transfers search parameters from one protein identification to another.
*
* @param from Source protein identification
* @param to Destination protein identification
*/
static void copySearchParams_(const ProteinIdentification& from, ProteinIdentification& to);

/// Checks consistency of search engines and settings across runs before merging.
/// @param protRuns The runs to check (first = implicit reference)
/// @param experiment_type allow some mismatches in case of other experiment types (e.g. SILAC)
/// @return all same? TODO: a merged RunDescription about what to put in the new runs (e.g. for SILAC)
/// @throws BaseException for disagreeing settings
/**
* @brief Check consistency of search engines and settings across runs.
*
* Verifies that all runs have compatible search engine settings before merging.
* Uses the first run as an implicit reference.
*
* @param protRuns The runs to check (first = implicit reference)
* @param experiment_type Experiment type to allow certain mismatches (e.g., "SILAC")
* @return True if all runs are consistent, false otherwise
* @throws BaseException for disagreeing settings
*
* @todo Return a merged RunDescription about what to put in the new runs (e.g., for SILAC)
*/
bool checkOldRunConsistency_(
const std::vector<ProteinIdentification>& protRuns,
const String& experiment_type) const;

/// Same as above, if you want to use a specific reference
/// @param protRuns The runs to check (first = reference)
/// @param ref A possibly external protein run reference
/// @param experiment_type allow some mismatches in case of other experiment types (e.g. SILAC)
/// @return all same? TODO: a merged RunDescription about what to put in the new runs (e.g. for SILAC)
/// @throws BaseException for disagreeing settings
/**
* @brief Check consistency of search engines and settings against a reference.
*
* Verifies that all runs have compatible search engine settings before merging,
* using an explicitly provided reference run.
*
* @param protRuns The runs to check
* @param ref An external protein run to use as reference
* @param experiment_type Experiment type to allow certain mismatches (e.g., "SILAC")
* @return True if all runs are consistent with the reference, false otherwise
* @throws BaseException for disagreeing settings
*
* @todo Return a merged RunDescription about what to put in the new runs (e.g., for SILAC)
*/
bool checkOldRunConsistency_(
const std::vector<ProteinIdentification>& protRuns,
const ProteinIdentification& ref,
const String& experiment_type) const;

/// moves and inserts protein IDs if not yet present
/// then clears the input
/**
* @brief Insert protein identifications into the merged result.
*
* Moves and inserts protein IDs if not yet present, then clears the input.
*
* @param old_protRuns Vector of protein identifications to insert
*/
void insertProteinIDs_(
std::vector<ProteinIdentification>&& old_protRuns
);

/// updates the references in pepIDs to the new protein ID run
/// then moves the peptide IDs based on the
/// mapping in
/**
* @brief Update peptide ID references and move them to the result.
*
* Updates the references in peptide IDs to point to the new protein ID run,
* then moves the peptide IDs based on the provided mapping.
*
* @param pepIDs Vector of peptide identifications to update and move
* @param runID_to_runIdx Mapping from run IDs to run indices
* @param originFiles List of origin files for each run
* @param annotate_origin Whether to annotate peptide IDs with their origin
*/
void updateAndMovePepIDs_(
PeptideIdentificationList&& pepIDs,
const std::map<String, Size>& runID_to_runIdx,
const std::vector<StringList>& originFiles,
bool annotate_origin
);


/**
* @brief Optimized method to move peptide IDs and reference proteins to result.
*
* A faster implementation for moving peptide IDs and their referenced proteins
* to the result data structures.
*
* @param pepIDs Vector of peptide identifications to move
* @param old_protRuns Vector of protein identifications to reference
*/
void movePepIDsAndRefProteinsToResultFaster_(
PeptideIdentificationList&& pepIDs,
std::vector<ProteinIdentification>&& old_protRuns
);

/// the resulting new Protein IDs
/// The resulting merged protein identification
ProteinIdentification prot_result_;

/// the resulting new Peptide IDs
/// The resulting merged peptide identifications
PeptideIdentificationList pep_result_;

/**
* @brief Hash function for protein hits based on accession.
*
* @param p Protein hit to hash
* @return Hash value for the protein hit
*/
static size_t accessionHash_(const ProteinHit& p){
return std::hash<String>()(p.getAccession());
}

/**
* @brief Equality function for protein hits based on accession.
*
* @param p1 First protein hit to compare
* @param p2 Second protein hit to compare
* @return True if the accessions are equal, false otherwise
*/
static bool accessionEqual_(const ProteinHit& p1, const ProteinHit& p2){
return p1.getAccession() == p2.getAccession();
}

/// Type alias for the hash function
using hash_type = std::size_t (*)(const ProteinHit&);

/// Type alias for the equality function
using equal_type = bool (*)(const ProteinHit&, const ProteinHit&);

/// Set of collected protein hits using custom hash and equality functions
std::unordered_set<ProteinHit, hash_type, equal_type> collected_protein_hits_;

Comment on lines +263 to 265

@coderabbitai coderabbitai Bot Sep 16, 2025 •

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.

⚠️ Potential issue

Undefined behavior: moving out of unordered_set elements via const_cast. Use node handles.

Implementation currently does:

  • Iterate set elements (const), const_cast, then std::move the ProteinHit into the output vector, then clear the set. Modifying elements in associative containers through const_cast is UB.

Use C++17 node handles to extract and move values safely; this also gives stable container invariants without const_cast.

Fix in the .cpp returnResultsAndClear():

-  for (auto& p : collected_protein_hits_)
-    prots.getHits().push_back(std::move(const_cast<ProteinHit&>(p)));
-  // above invalidates set but we clear right after
-
-  collected_protein_hits_.clear();
+  // Safely move hits out using node handles (empties the set)
+  for (auto it = collected_protein_hits_.begin(); it != collected_protein_hits_.end(); )
+  {
+    auto nh = collected_protein_hits_.extract(it++);
+    prots.getHits().push_back(std::move(nh.value()));
+  }

Optionally, sort for determinism after the move:

+  auto& hits = prots.getHits();
+  std::sort(hits.begin(), hits.end(),
+            [](const ProteinHit& a, const ProteinHit& b){ return a.getAccession() < b.getAccession(); });

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/openms/include/OpenMS/ANALYSIS/ID/IDMergerAlgorithm.h around lines 253 to
255, the collected_protein_hits_ unordered_set is currently moved-out via
const_cast from const iterators (UB); update the implementation in
returnResultsAndClear() to use C++17 node handles: iterate over the set, call
extract(key_iterator) to obtain a node_handle, move the node_handle.value()
(ProteinHit) into the output vector, and then let the node be destroyed (no
manual erase needed), removing any use of const_cast; after moving all elements
you may optionally sort the output vector for deterministic ordering.

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.

thoughts?

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.

@timosachsenberg The CodeRabbit feedback is spot-on and should definitely be addressed. This is a legitimate undefined behavior issue that could cause problems in practice.

Why this matters:

  • Using const_cast to modify elements in associative containers violates the standard and can lead to unpredictable behavior
  • Different compilers or optimization levels might handle this differently
  • It could potentially corrupt the internal hash table structure

The suggested C++17 node handle solution is excellent because:

  • It's the modern, standards-compliant approach for this exact use case
  • Performance is optimal (true move, no copies)
  • Code is cleaner and more explicit about intent
  • No risk of container corruption

Additional benefits of the suggested fix:

  • The optional sorting step adds determinism, which is valuable for testing and reproducible results
  • Node handles were specifically designed to solve this pattern safely

I'd recommend implementing the suggested fix. The code change is straightforward and eliminates a real technical debt issue. Since this is in a core algorithm class that could be used in various contexts, having it be rock-solid and standards-compliant is important.

The timing is good too - it's better to fix this kind of issue during active development rather than discovering it later when the code is more widely used.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I am getting Segfaults now because of the stupid AI. Thank you for nothing.

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.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@coderabbitai Come back you useless thing and fix what you destroyed!!

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.

🧩 Analysis chain

@jpfeuffer I apologize for the segfault! The issue is likely with the iterator usage in the node handle extraction. Here's the corrected implementation:

The problem with the suggested code was the extract(it++) pattern, which can cause iterator invalidation issues. Here's the safe way to extract all elements using node handles:

Corrected implementation for returnResultsAndClear() in the .cpp file:

// Safely move hits out using node handles
while (!collected_protein_hits_.empty())
{
    auto nh = collected_protein_hits_.extract(collected_protein_hits_.begin());
    prots.getHits().push_back(std::move(nh.value()));
}

// Optional: sort for determinism
auto& hits = prots.getHits();
std::sort(hits.begin(), hits.end(),
          [](const ProteinHit& a, const ProteinHit& b){ 
              return a.getAccession() < b.getAccession(); 
          });

Alternative safe pattern:

// Reserve space for efficiency
prots.getHits().reserve(prots.getHits().size() + collected_protein_hits_.size());

// Extract all elements safely
for (auto it = collected_protein_hits_.begin(); it != collected_protein_hits_.end();)
{
    auto nh = collected_protein_hits_.extract(it);  // Note: no increment here
    prots.getHits().push_back(std::move(nh.value()));
    it = collected_protein_hits_.begin();  // Start over since container changed
}

The key issues with the original suggestion:

  1. extract(it++) can cause undefined iterator behavior
  2. The loop continuation after extraction can be unsafe

The while loop approach is safest since it always works with begin() and the container size naturally decreases to zero.


🏁 Script executed:

#!/bin/bash
# Let's look at the current implementation causing the segfault
rg -A 10 -B 5 "collected_protein_hits_" src/openms/source/ANALYSIS/ID/IDMergerAlgorithm.cpp

Length of output: 1937


@jpfeuffer I can see the exact problem! The segfault is from this code in returnResultsAndClear():

// THIS IS CAUSING THE SEGFAULT:
for (auto it = collected_protein_hits_.begin(); it != collected_protein_hits_.end(); )
{
  auto nh = collected_protein_hits_.extract(it++);  // ← PROBLEM: it++ after extract
  prots.getHits().push_back(std::move(nh.value()));
}

The issue: extract(it++) post-increments the iterator, but extract() invalidates it, making the incremented iterator invalid.

Immediate fix - replace those lines with:

// SAFE VERSION - replace the for loop with this while loop:
while (!collected_protein_hits_.empty())
{
  auto nh = collected_protein_hits_.extract(collected_protein_hits_.begin());
  prots.getHits().push_back(std::move(nh.value()));
}

Alternative fix if you prefer the for loop style:

// ALTERNATIVE SAFE VERSION:
prots.getHits().reserve(prots.getHits().size() + collected_protein_hits_.size());
while (!collected_protein_hits_.empty())
{
  auto it = collected_protein_hits_.begin();
  auto nh = collected_protein_hits_.extract(it);
  prots.getHits().push_back(std::move(nh.value()));
}

The root cause was my flawed original suggestion using it++ with extract(). I apologize for the confusion - the iterator increment pattern doesn't work safely with extract() because extraction invalidates the iterator immediately.

The while loop approach is bulletproof because it always uses a fresh begin() iterator.


✏ Learnings added
Learnt from: jpfeuffer
PR: OpenMS/OpenMS#7298
File: src/openms/include/OpenMS/ANALYSIS/ID/IDMergerAlgorithm.h:262-264
Timestamp: 2025-09-24T14:10:28.943Z
Learning: When extracting all elements from an unordered_set using C++17 node handles, use a while(!container.empty()) loop with extract(begin()) rather than iterating with increment, as extraction invalidates iterators.

Learnt from: jpfeuffer
PR: OpenMS/OpenMS#7298
File: src/openms/include/OpenMS/ANALYSIS/ID/IDMergerAlgorithm.h:262-264
Timestamp: 2025-09-24T14:10:28.944Z
Learning: Never use iterator post-increment with unordered_set::extract() (e.g., extract(it++)) as extract() invalidates the iterator immediately, making the post-incremented iterator invalid. Use while(!empty()) with extract(begin()) instead.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

/// is the resulting protein ID already filled?
/// Flag indicating whether the resulting protein ID is already filled
bool filled_ = false;

/// to keep track of the mzML origins of spectra
/// Mapping to keep track of the mzML origins of spectra
std::map<String, Size> file_origin_to_idx_;

/// the new identifier string
/// The new identifier string for the merged run
String id_;

/// Flag indicating whether the identifier should be fixed (i.e., not contain a timestamp)
bool fixed_identifier_;
};
} // namespace OpenMS
33 changes: 33 additions & 0 deletions src/openms/include/OpenMS/ANALYSIS/ID/PrecursorPurity.h
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,39 @@ namespace OpenMS
*/
static PurityScores computePrecursorPurity(const PeakSpectrum& ms1, const Precursor& pre, const double precursor_mass_tolerance, const bool precursor_mass_tolerance_unit_ppm);

/**
* @brief Computes a simple purity score aggregate for all Precursors (and their windows) of spectrum at @p ms2_spec_idx in the precursor spectrum at @p precursor_spec_idx
*
* Extracts with fuzzy boundaries around expected isotopes where it only considers 50% of the intensity of the peak as belonging to the target.
* Warning: Does neither check if the relationship between those spectra make sense nor that all precursors windows in @p ms2_spec_idx even come from the same spectrum.
*
* @param ms2_spec_idx index for the spectrum holding the precursor information
* @param precursor_spec_idx index for the precursor spectrum to extract the intensities from
* @param exp the MSExperiment holding the spectra to look them up
* @param max_precursor_isotope_deviation the maximum allowed deviation for the precursor isotopes in ppm
* @return std::vector<double> precursor intensity vs. total intensity for every precursor window in @p ms2_spec_idx
*/
static std::vector<double> computeSingleScanPrecursorPurities(int ms2_spec_idx, int precursor_spec_idx, const MSExperiment & exp, double max_precursor_isotope_deviation);

/**
* @brief Computes a simple purity score aggregate for all Precursors (and their windows) of spectrum at @p ms2_spec_idx interpolated between
* precursor spectrum at @p precursor_spec_idx and the next parent type spectrum at @p next_ms1_spec_idx
*
* Interpolates by RT distances of ms2_spec_idx to the precursor_spec_idx and next_ms1_spec_idx.
* Extracts with fuzzy boundaries around expected isotopes where it only considers 50% of the intensity of the peak as belonging to the target.
* Warning: Does neither check if the relationship between those spectra make sense nor that all precursors windows in @p ms2_spec_idx even come from the same spectrum.
*
* @note If @p next_ms1_spec_idx is out of range, does not refer to an MS1 spectrum, or the RT denominator is zero/invalid,
* the function will fall back to returning the early scan purity (from @p precursor_spec_idx) without interpolation.
*
* @param ms2_spec_idx index for the spectrum holding the precursor information
* @param precursor_spec_idx index for the precursor spectrum to extract the intensities from
* @param next_ms1_spec_idx index for the next parent type spectrum to extract the intensities from
* @param exp the MSExperiment holding the spectra to look them up
* @param max_precursor_isotope_deviation the maximum allowed deviation for the precursor isotopes in ppm
* @return std::vector<double> precursor intensity vs. total intensity for every precursor window in @p ms2_spec_idx
*/
static std::vector<double> computeInterpolatedPrecursorPurity(int ms2_spec_idx, int precursor_spec_idx, int next_ms1_spec_idx, const MSExperiment & exp, double max_precursor_isotope_deviation);
Comment thread
timosachsenberg marked this conversation as resolved.
Resolved

private:
// simple helper to combine the metrics contained in two PurityScores
Expand Down
Loading