Skip to content

PeptideIndexer mapping of empty sequences results in many error messages #2987

Closed

Description

@timosachsenberg

I get several millions erros of these kind (peptide ending on X) of error messages while mapping back an (accidentally) empty AASequence.
Error: start of peptide (37) is beyond end of protein 'CLLQSARVEPVQLMKMGVLTFGRREFRQIVDGVLRRX'!
<Error: start of peptide (44) is beyond end of protein 'SSTGLHPNRERGSIKDLTMDPLEDALESPSSNASSNAVAPITPX'!> occurred 39 times

Activity

  1. mwalzer commented on Nov 17, 2017

    @mwalzer
    Contributor

    So the AASequence is empty but still, the error reports a sequence?

  2. timosachsenberg commented on Nov 17, 2017

    @timosachsenberg
    ContributorAuthor

    I think this only happens if PeptideIndexer is used internally as class (not the tool). An only under some strange configurations like non-specific mapping

  3. added
    minor
    on Feb 7, 2018
  4. stale commented on Feb 7, 2020

    @stale

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

  5. timosachsenberg commented on Feb 7, 2020

    @timosachsenberg
    ContributorAuthor

    @cbielow do you know if this is fixed?

  6. stale commented on Mar 30, 2022

    @stale

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

  7. github-actions commented on Mar 15, 2026

    @github-actions
    Contributor

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

  8. jpfeuffer commented on Mar 15, 2026

    @jpfeuffer
    Contributor

    @coderabbitai can you check if this is fixed? If not create a plan to reduce logging in this algorithm/tool per default

  9. coderabbitai commented on Mar 15, 2026

    @coderabbitai
    Contributor

    Coding Plan

    Summary

    • Introduce an explicit mapping vector (needle_to_pep_idx) to decouple AC needle indices from peptide iteration order, allowing empty sequences to be safely skipped during trie construction
    • Modify FoundProteinFunctor::addHit() to use this mapping when recording hits, preserving correct annotation in the existing two-pointer sweep
    • Add defensive validation in ACTrie::addNeedle() to throw on empty needles, preventing silent corruption from any caller
    • Add focused tests for both the fix and the defensive guard
    Design Choices
    Design Choice 1: Handling empty sequences while maintaining index alignment

    Options Considered:

    1. Replace an empty sequence with a placeholder pattern that will never match (e.g., a very long string of rare characters)
    2. Skip empty sequences but introduce an explicit needle_index → original_pep_idx mapping vector
    3. Pre-filter the peptide list to remove empty sequences before the main loop

    Chosen Option: 2

    Rationale: An explicit mapping vector is the cleanest solution—it preserves the existing annotation logic, doesn't add artificial patterns to the trie, and clearly documents the index relationship.

    💡 User Tips

    Regenerate the plan with different choices with @coderabbitai <feedback>.

    Implementation Steps

    Phase 1: Handle Empty Sequences in PeptideIndexing

    This phase addresses the core bug by ensuring empty peptide sequences are not added to the Aho-Corasick trie while maintaining correct index mapping between trie needles and peptide hits.

    Task 1: Add Needle-to-Peptide Index Mapping

    Introduce an explicit mapping from AC needle indices to original peptide iteration indices, allowing empty sequences to be skipped without breaking the annotation phase.

    • Add std::vector<Size> needle_to_pep_idx before the trie-building loop in src/openms/source/ANALYSIS/ID/PeptideIndexing.cpp
    • Add a counter Size pep_idx = 0 to track the original iteration position
    • Modify the inner loop: before calling ac_trie.addNeedle(seq), check if seq.empty()
    • For non-empty sequences: push pep_idx onto needle_to_pep_idx, then call addNeedle(seq)
    • For empty sequences: skip the addNeedle call but still increment pep_idx
    • Add a deduplicated warning message for empty sequences (track count, emit summary once)
    Task 2: Update FoundProteinFunctor to Use the Mapping

    Modify the internal FoundProteinFunctor struct to resolve needle indices to original peptide indices when recording hits.

    • Add a const std::vector<Size>* needle_to_pep_idx_ptr member to FoundProteinFunctor in src/openms/source/ANALYSIS/ID/PeptideIndexing.cpp
    • Update addHit() to resolve idx_pep through the mapping: Size actual_pep_idx = (*needle_to_pep_idx_ptr)[idx_pep]
    • Store actual_pep_idx in PeptideProteinMatchInformation::peptide_index instead of the raw needle index
    • Initialize the pointer in the main func instance after trie building completes
    • Ensure each func_threads instance in the OpenMP parallel block receives the same pointer
    🤖 Prompt for AI agents
    Implement the core bug fix in
    `src/openms/source/ANALYSIS/ID/PeptideIndexing.cpp` to prevent empty peptide
    sequences from being added to the Aho-Corasick trie while keeping needle indices
    correctly aligned with peptide hit indices.
    
    **Task 1: Add Needle-to-Peptide Index Mapping**
    - Before the trie-building loop, declare `std::vector<Size> needle_to_pep_idx`
    and a counter `Size pep_idx = 0`
    - In the inner loop, before calling `ac_trie.addNeedle(seq)`, check if
    `seq.empty()`:
    - If non-empty: push `pep_idx` onto `needle_to_pep_idx`, then call
    `addNeedle(seq)`
      - If empty: skip `addNeedle` but still increment `pep_idx`
    - Track the count of empty sequences encountered and emit a single deduplicated
    warning summarizing the total
    
    **Task 2: Update `FoundProteinFunctor` to Use the Mapping**
    - Add a `const std::vector<Size>* needle_to_pep_idx_ptr` member to the
    `FoundProteinFunctor` struct
    - In `addHit()`, resolve the needle index to the original peptide index: `Size
    actual_pep_idx = (*needle_to_pep_idx_ptr)[idx_pep]`, and store `actual_pep_idx`
    in `PeptideProteinMatchInformation::peptide_index` instead of the raw needle
    index
    - After trie building completes, initialize `needle_to_pep_idx_ptr` on the main
    `func` instance
    - Ensure each `func_threads` instance in the OpenMP parallel block also receives
    the same pointer
    

    Phase 2: Add Defensive Validation in AhoCorasickAmbiguous

    This phase adds defensive checks to prevent future occurrences of this bug class by catching empty needles at the AC implementation level.

    Validate Non-Empty Needles in addNeedle()

    Add precondition enforcement that rejects empty pattern strings with a clear exception.

    • Modify addNeedle() in src/openms/source/ANALYSIS/ID/AhoCorasickAmbiguous.cpp to check for empty needle at method entry
    • Throw Exception::InvalidValue with a descriptive message explaining that empty needles would corrupt the trie structure
    • Update the Doxygen comment in src/openms/include/OpenMS/ANALYSIS/ID/AhoCorasickAmbiguous.h to document this precondition alongside the existing invalid-amino-acid exception
    🤖 Prompt for AI agents
    Add defensive input validation to the `addNeedle()` method to prevent empty
    strings from being silently accepted into the trie.
    
    - In `src/openms/source/ANALYSIS/ID/AhoCorasickAmbiguous.cpp`, at the entry of
    `addNeedle()`, add a check: if the needle is empty, throw
    `Exception::InvalidValue` with a descriptive message explaining that empty
    needles would corrupt the trie structure
    - In `src/openms/include/OpenMS/ANALYSIS/ID/AhoCorasickAmbiguous.h`, update the
    Doxygen comment for `addNeedle()` to document this new precondition alongside
    the existing invalid-amino-acid exception
    

    Phase 3: Add Test Coverage

    This phase ensures the fix is properly tested and guards against regression.

    Task 1: Test Empty Sequence Handling in PeptideIndexing

    Add test cases verifying correct behavior when empty sequences are present in the input.

    • Add a test in src/tests/class_tests/openms/source/PeptideIndexing_test.cpp with a mix of valid peptides and empty/all-stop-codon peptide sequences
    • Verify that valid peptides are still correctly mapped to their protein matches
    • Verify that empty sequences do not cause crashes or incorrect mappings for other peptides
    • Verify that the appropriate warning is emitted for empty sequences
    Task 2: Test Empty Needle Rejection in AhoCorasickAmbiguous

    Add test confirming that the defensive validation works correctly.

    • Add a test in src/tests/class_tests/openms/source/AhoCorasickAmbiguous_test.cpp that calls addNeedle("")
    • Use TEST_EXCEPTION to verify that Exception::InvalidValue is thrown
    🤖 Prompt for AI agents
    Add regression and defensive tests to cover the empty sequence fix and the new
    `addNeedle()` guard.
    
    **Task 1: PeptideIndexing empty sequence tests**
    (`src/tests/class_tests/openms/source/PeptideIndexing_test.cpp`)
    - Add a test with a mix of valid peptides and empty/all-stop-codon peptide
    sequences as input
    - Assert that valid peptides are still correctly mapped to their protein matches
    - Assert that empty sequences do not cause crashes or incorrect mappings for
    other peptides
    - Assert that the appropriate warning is emitted for empty sequences
    
    **Task 2: AhoCorasickAmbiguous empty needle rejection test**
    (`src/tests/class_tests/openms/source/AhoCorasickAmbiguous_test.cpp`)
    - Add a test that calls `addNeedle("")` on an AC trie instance
    - Use `TEST_EXCEPTION` to verify that `Exception::InvalidValue` is thrown
    
    Research

    PeptideIndexer produces millions of error messages ("start of peptide is beyond end of protein") when processing empty AASequences. The root cause is that empty peptide sequences are being added to the Aho-Corasick trie, which marks the root node as a hit and causes spurious matches at every position in every protein sequence.

    PeptideIndexer follows the standard OpenMS pattern: a thin TOPP tool (src/topp/PeptideIndexer.cpp) wraps a reusable algorithm class PeptideIndexing (src/openms/source/ANALYSIS/ID/PeptideIndexing.cpp). The algorithm uses the AhoCorasickAmbiguous class for multi-pattern string matching to find peptides within protein sequences. Peptide sequences are added to the trie during a setup phase, then proteins are searched in parallel. A critical invariant exists: the needle_index assigned by the AC trie must map 1:1 to the iteration order of peptide hits, since the annotation phase uses a synchronized counter to correlate search results back to the original PeptideHit objects.


    🚀 Next Steps

    🤖 All AI agent prompts combined
    Task: 1
    
    Implement the core bug fix in
    `src/openms/source/ANALYSIS/ID/PeptideIndexing.cpp` to prevent empty peptide
    sequences from being added to the Aho-Corasick trie while keeping needle indices
    correctly aligned with peptide hit indices.
    
    **Task 1: Add Needle-to-Peptide Index Mapping**
    - Before the trie-building loop, declare `std::vector<Size> needle_to_pep_idx`
    and a counter `Size pep_idx = 0`
    - In the inner loop, before calling `ac_trie.addNeedle(seq)`, check if
    `seq.empty()`:
    - If non-empty: push `pep_idx` onto `needle_to_pep_idx`, then call
    `addNeedle(seq)`
      - If empty: skip `addNeedle` but still increment `pep_idx`
    - Track the count of empty sequences encountered and emit a single deduplicated
    warning summarizing the total
    
    **Task 2: Update `FoundProteinFunctor` to Use the Mapping**
    - Add a `const std::vector<Size>* needle_to_pep_idx_ptr` member to the
    `FoundProteinFunctor` struct
    - In `addHit()`, resolve the needle index to the original peptide index: `Size
    actual_pep_idx = (*needle_to_pep_idx_ptr)[idx_pep]`, and store `actual_pep_idx`
    in `PeptideProteinMatchInformation::peptide_index` instead of the raw needle
    index
    - After trie building completes, initialize `needle_to_pep_idx_ptr` on the main
    `func` instance
    - Ensure each `func_threads` instance in the OpenMP parallel block also receives
    the same pointer
    ===============================================================================
    
    Task: 2
    
    Add defensive input validation to the `addNeedle()` method to prevent empty
    strings from being silently accepted into the trie.
    
    - In `src/openms/source/ANALYSIS/ID/AhoCorasickAmbiguous.cpp`, at the entry of
    `addNeedle()`, add a check: if the needle is empty, throw
    `Exception::InvalidValue` with a descriptive message explaining that empty
    needles would corrupt the trie structure
    - In `src/openms/include/OpenMS/ANALYSIS/ID/AhoCorasickAmbiguous.h`, update the
    Doxygen comment for `addNeedle()` to document this new precondition alongside
    the existing invalid-amino-acid exception
    ===============================================================================
    
    Task: 3
    
    Add regression and defensive tests to cover the empty sequence fix and the new
    `addNeedle()` guard.
    
    **Task 1: PeptideIndexing empty sequence tests**
    (`src/tests/class_tests/openms/source/PeptideIndexing_test.cpp`)
    - Add a test with a mix of valid peptides and empty/all-stop-codon peptide
    sequences as input
    - Assert that valid peptides are still correctly mapped to their protein matches
    - Assert that empty sequences do not cause crashes or incorrect mappings for
    other peptides
    - Assert that the appropriate warning is emitted for empty sequences
    
    **Task 2: AhoCorasickAmbiguous empty needle rejection test**
    (`src/tests/class_tests/openms/source/AhoCorasickAmbiguous_test.cpp`)
    - Add a test that calls `addNeedle("")` on an AC trie instance
    - Use `TEST_EXCEPTION` to verify that `Exception::InvalidValue` is thrown
    
    💡 Iterate on the plan with: @coderabbitai <feedback>
    Example Feedback
    - `@coderabbitai` You can skip phase 3. Add a simple unit test case for phase 2.
    - `@coderabbitai` For design choice 1 go ahead with option 3 and replan.
    

    💬 Have feedback or questions? Drop into our discord!

  10. github-actions commented on Sep 17, 2026

    @github-actions
    Contributor

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

  11. timosachsenberg commented on Sep 17, 2026

    @timosachsenberg
    ContributorAuthor

    @cbielow Re-checked this on current develop (eb020f9): still relevant — and the failure mode has gotten worse. It is no longer a flood of warnings; an empty peptide sequence now makes the Aho-Corasick search loop forever and exhaust memory.

    Root cause (unchanged, still unguarded)

    1. PeptideIndexing.cpp:413-430 adds every PeptideHit sequence as a needle — deliberately, since the annotation phase (~line 630) iterates pep_ids with a counter that must equal the AC needle index ("do not skip over peptides here"). Two ways to end up with an empty needle: an empty AASequence (AASequence::fromString("") returns empty without throwing, so even an idXML with sequence="" loads fine), or StringUtils::remove(seq, '*') on line 422 turning an all-stop-codon sequence into "".
    2. ACTrie::addNeedle() (AhoCorasickAmbiguous.cpp:55) has no empty check: for "" the character loop never runs, so line 72 marks the root node as a hit and registers the needle there.
    3. compressTrie() points the root's suffix link at itself (line 166), and addHits_() walks the suffix chain with while (collect()) i = trie_[i].suffix (line 324). At the root with has_hit == 1 that never terminates, appending a hit per iteration.

    Verified

    Compiled the real AhoCorasickAmbiguous.cpp standalone against minimal stubs, same query both times:

    • without the empty needle → hits: 1 → needle 0 len 8 at 10 (correct)
    • with one empty needle added → search never returns, std::bad_alloc within seconds under a 1 GB cap

    It trips on virtually any protein: as soon as the primary falls back to the root (the first residue that doesn't extend the current path), addHits_ starts spinning. AhoCorasickAmbiguous_test.cpp:102-122 covers '$' and '*' rejection but never addNeedle(""), which is why CI doesn't see it.

    The original message text also still exists, just relocated to EnzymaticDigestion::isValidProduct_() (EnzymaticDigestion.cpp:220-228), one OPENMS_LOG_WARN per occurrence — including a length == 0 branch. So the log-flood path is intact too; the process just dies before reaching it now.

    Suggested fix

    The plan posted by CodeRabbit above identifies the right root cause, but the needle_to_pep_idx mapping vector costs 8 bytes per peptide hit in a code path that deliberately packs matches into 4-byte fields for memory reasons. Minimal alternative: have ACTrie::addNeedle("") still increment needle_count_ but register nothing in the trie — caller indices stay aligned, no mapping vector, no changes to the annotation phase. Alternatively throw Exception::InvalidValue there (consistent with the existing '*'/'$' handling) and have PeptideIndexing catch it and name the offending hit. Either way PeptideIndexing should warn once with a count instead of per occurrence.

    Given it's an unbounded-memory hang reachable from a plain PeptideIndexer run on an idXML with an empty sequence, the wontfix/minor labels look stale. Happy to put up a PR with regression tests for both addNeedle("") and PeptideIndexing with empty/all-* hits.


    Generated by Claude Code

  12. cbielow commented on Sep 17, 2026

    @cbielow
    Contributor

    Minimal alternative: have ACTrie::addNeedle("") still increment needle_count_ but register nothing in the trie — caller indices stay aligned, no mapping vector, no changes to the annotation phase.

    That's the way to go.
    Ensures that pipelines keep running.
    Maybe warn with OPENMS_LOG_WARN << "ACTrie: Skipping an empty peptide that was used as input.\n" in addNeedle().

  13. added a commit that references this issue on Sep 17, 2026
    2ff8f31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

defectminor

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions