Skip to content

BugFix : Fixed Targetedfileconverter crash - #7924

Merged
cbielow merged 6 commits into
OpenMS:developfrom
subCode321:fixcrash
Apr 2, 2025
Merged

cbielow merged 6 commits into
OpenMS:developfrom
subCode321:fixcrash

Conversation

@subCode321

@subCode321 subCode321 commented Mar 19, 2025 •

Copy link
Copy Markdown
Contributor

User description

Description

fixes #7923

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

How can I get additional information on failed tests during CI

Click to expand If your PR is failing you can check out

Advanced commands (admins / reviewer only)

Click to expand
  • /reformat (experimental) applies the clang-format style changes as additional commit. Note: your branch must have a different name (e.g., yourrepo:feature/XYZ) than the receiving branch (e.g., OpenMS:develop). Otherwise, reformat fails to push.
  • setting the label "NoJenkins" will skip tests for this PR on jenkins (saves resources e.g., on edits that do not affect tests)
  • commenting with rebuild jenkins will retrigger Jenkins-based CI builds

⚠️ Note: Once you opened a PR try to minimize the number of pushes to it as every push will trigger CI (automated builds and test) and is rather heavy on our infrastructure (e.g., if several pushes per day are performed).


PR Type

Bug fix


Description

  • Fixed crash in TargetedFileConverter when input TSV has fewer than 8 columns.

  • Adjusted minimum header size requirement from 8 to 1 in TransitionTSVFile.


Changes walkthrough 📝

Relevant files
Bug fix
TransitionTSVFile.cpp
Adjusted minimum header size in TransitionTSVFile               

src/openms/source/ANALYSIS/OPENSWATH/TransitionTSVFile.cpp

  • Reduced the minimum header size from 8 to 1.
  • Ensured compatibility with TSV files having fewer columns.
  • +1/-1     

    Need help?
  • Type /help how to ... in the comments thread for any questions about Qodo Merge usage.
  • Check out the documentation for more information.
  • Summary by CodeRabbit

    • New Features
      • Enhanced file header processing now supports input files with minimal header content, allowing for a broader range of formats and a more flexible user experience.
      • Improved error handling provides specific feedback when required header columns are missing.

    @coderabbitai

    coderabbitai Bot commented Mar 19, 2025 •

    Copy link
    Copy Markdown
    Contributor

    Walkthrough

    The pull request adjusts the header validation in the TransitionTSVFile class by lowering the required minimum header field count from 8 to 4. This change occurs in the getTSVHeader_ method, allowing headers with at least four fields to be considered valid. The update enhances error handling for cases where files with fewer than four columns could lead to processing errors.

    Changes

    File Change Summary
    src/openms/.../ANALYSIS/OPENSWATH/TransitionTSVFile.cpp Updated min_header_size in getTSVHeader_ from 8 to 4, replaced possibleDelimiters with std::array, and improved delimiter handling.

    Sequence Diagram(s)

    sequenceDiagram
        participant Client
        participant TransitionTSVFile
        Client->>TransitionTSVFile: Call getTSVHeader_(TSV input)
        TransitionTSVFile->>TransitionTSVFile: Parse header fields
        alt Header field count >= 4
            TransitionTSVFile->>Client: Return parsed header
        else
            TransitionTSVFile->>Client: Trigger error handling
        end
    
    Loading

    Assessment against linked issues

    Objective Addressed Explanation
    Allow TSV headers with fewer than 8 columns to prevent TargetedFileConverter crashes [#7923] ✅

    Poem

    Hoppy headers now set so low,
    With just four fields, the checks still go!
    I'm a rabbit of code, bouncing with glee,
    Parsing TSVs more freely, you'll see.
    Cheers to changes that keep crashes at bay! 🐇

    ✨ Finishing Touches
    • 📝 Generate Docstrings

    🪧 Tips

    Chat

    There are 3 ways to chat with CodeRabbit:

    • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
      • I pushed a fix in commit <commit_id>, please review it.
      • Generate unit testing code for this file.
      • Open a follow-up GitHub issue for this discussion.
    • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
      • @coderabbitai generate unit testing code for this file.
      • @coderabbitai modularize this function.
    • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
      • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
      • @coderabbitai read src/utils.ts and generate unit testing code.
      • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
      • @coderabbitai help me debug CodeRabbit configuration file.

    Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

    CodeRabbit Commands (Invoked using PR comments)

    • @coderabbitai pause to pause the reviews on a PR.
    • @coderabbitai resume to resume the paused reviews.
    • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
    • @coderabbitai full review to do a full review from scratch and review all the files again.
    • @coderabbitai summary to regenerate the summary of the PR.
    • @coderabbitai generate docstrings to generate docstrings for this PR.
    • @coderabbitai resolve resolve all the CodeRabbit review comments.
    • @coderabbitai plan to trigger planning for file edits and PR creation.
    • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
    • @coderabbitai help to get help.

    Other keywords and placeholders

    • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
    • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
    • Add @coderabbitai anywhere in the PR title to generate the title automatically.

    CodeRabbit Configuration File (.coderabbit.yaml)

    • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
    • Please see the configuration documentation for more information.
    • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

    Documentation and Community

    • Visit our Documentation for detailed information on how to use CodeRabbit.
    • Join our Discord Community to get help, request features, and share feedback.
    • Follow us on X/Twitter for updates and announcements.

    @qodo-code-review

    Copy link
    Copy Markdown
    Contributor

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    🎫 Ticket compliance analysis ✅

    7923 - PR Code Verified

    Compliant requirements:

    • Fix TargetedFileConverter crash when there are less than 8 columns in the input TSV

    Requires further human verification:

    • Address the inconsistency between documentation and actual code behavior regarding required columns - need to verify if documentation needs to be updated to match the new code behavior

    ⏱️ Estimated effort to review: 1 🔵⚪⚪⚪⚪
    🧪 No relevant tests
    🔒 No security concerns identified
    ⚡ Recommended focus areas for review

    Validation Missing

    The fix reduces the minimum header size requirement from 8 to 1, but there's no validation to ensure that required columns are still present. This might prevent crashes but could lead to unexpected behavior if essential columns are missing.

    Size min_header_size = 1;

    @qodo-code-review

    Copy link
    Copy Markdown
    Contributor

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Impact
    Possible issue
    Increase minimum header size

    Setting min_header_size to 1 is too permissive and may lead to incorrect parsing
    of malformed files. Consider using a more reasonable minimum size that reflects
    the essential columns needed for a valid TSV file in this context.

    src/openms/source/ANALYSIS/OPENSWATH/TransitionTSVFile.cpp [150]

    -Size min_header_size = 1;
    +Size min_header_size = 3; // Minimum columns required for a valid transition file
    • Apply this suggestion
    Suggestion importance[1-10]: 5

    __

    Why: The suggestion raises a valid concern about setting min_header_size too low, which could lead to accepting malformed files. However, without knowing the specific requirements of the TSV format in this context, it's unclear if 3 is the correct minimum value, and the PR explicitly aims to ensure compatibility with TSV files having fewer columns.

    Low
    • More

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

    you found the correct place.
    But the fix needs more thought

    std::vector<std::string> header;
    int nr_delimiters = 3;
    Size min_header_size = 8;
    Size min_header_size = 1;

    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.

    not ideal IMHO.
    If you have a header which contains commata in a column name, then comma will be preferred.
    If the min_header_size is large, this is somewhat robust, but using 1, this cries for errors,
    Think of a more robust strategy, also look at the header, what is minimally expected. Its more than 1 column!

    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.

    Right, I'm looking into this

    @subCode321 subCode321 Mar 22, 2025 •

    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.

    @cbielow So I read the documentation and these are columns that are required (at minimum). So I can:

    • Set the min_header_size to 4
    • Reverse the possible delimiters order from const char possibleDelimiters[3] = {',', ';', '\t'}; to const char possibleDelimiters[3] = {'\t', ';', ','}; so that tabs get preference and even if headers have , inside their name the headers will get parsed on the basis of tabs.
    • And since these header names are *required .... I can also put in a check that after parsing these 4 should be found individually

    Do you think the approach looks good? Then I can make the relevant change

    Header Name Type Description
    PrecursorMz* float This describes the precursor ion m/z
    ProductMz* float; synonyms: FragmentMz This specifies the product ion m/z
    LibraryIntensity* float; synonyms: RelativeFragmentIntensity This specifies the relative intensity of the fragment ion
    NormalizedRetentionTime* float; synonyms: RetentionTime, Tr_recalibrated, iRT, RetentionTimeCalculatorScore This specifies the expected retention time (normalized retention time)

    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.

    yes, good strat!
    Go for it.

    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.

    if you want, also replace const char possibleDelimiters[3] with const std::array<char, 3> possible_delimiters;, which would enable easier iteration and avoid repeating '3' etc.

    @subCode321

    Copy link
    Copy Markdown
    Contributor Author
    image image

    Conversion is working!

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

    🧹 Nitpick comments (1)
    src/openms/source/ANALYSIS/OPENSWATH/TransitionTSVFile.cpp (1)

    171-190: Header validation is comprehensive but might be too strict

    The new validation ensures required headers are present, which is good. However, the current implementation marks valid_headers as false if ANY header doesn't match the predefined list. This could reject files with valid custom columns that aren't in the standard list.

    Looking at the code in lines 282-317, the system already handles column synonyms (e.g., "ProductMz" or "FragmentMz"). Consider only validating the presence of the four required columns mentioned in the error message rather than all columns.

    -bool valid_headers = true;
    -for (Size i = 0; i < header.size(); i++)
    -{
    -  header_dict[header[i]] = i;
    -  bool valid_header = false;
    -  for (auto header_name : header_names_) {
    -    if (header_name == header[i]) {
    -      valid_header = true;
    -    }
    -  }
    -
    -  if (!valid_header) {
    -    valid_headers = false;
    -  }
    -}
    -
    -if (!valid_headers) {
    +// Add columns to header dictionary
    +for (Size i = 0; i < header.size(); i++)
    +{
    +  header_dict[header[i]] = i;
    +}
    +
    +// Check if required columns are present
    +bool has_precursor_mz = header_dict.find("PrecursorMz") != header_dict.end();
    +bool has_product_mz = header_dict.find("ProductMz") != header_dict.end() || 
    +                     header_dict.find("FragmentMz") != header_dict.end();
    +bool has_library_intensity = header_dict.find("LibraryIntensity") != header_dict.end() || 
    +                           header_dict.find("RelativeIntensity") != header_dict.end() || 
    +                           header_dict.find("RelativeFragmentIntensity") != header_dict.end();
    +bool has_retention_time = header_dict.find("RetentionTimeCalculatorScore") != header_dict.end() || 
    +                         header_dict.find("iRT") != header_dict.end() || 
    +                         header_dict.find("NormalizedRetentionTime") != header_dict.end() || 
    +                         header_dict.find("RetentionTime") != header_dict.end() || 
    +                         header_dict.find("Tr_recalibrated") != header_dict.end() || 
    +                         header_dict.find("SpectraSTRetentionTime") != header_dict.end();
    +
    +if (!has_precursor_mz || !has_product_mz || !has_library_intensity || !has_retention_time) {
      throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
        "The provided TSV/CSV file is missing one or more required header columns. Please ensure it includes: PrecursorMz, ProductMz (or FragmentMz), LibraryIntensity (or RelativeFragmentIntensity), and NormalizedRetentionTime (or its synonyms).");
    }
    📜 Review details

    Configuration used: CodeRabbit UI
    Review profile: CHILL
    Plan: Pro

    📥 Commits

    Reviewing files that changed from the base of the PR and between 5264837 and f1fdcdd.

    📒 Files selected for processing (1)
    • src/openms/source/ANALYSIS/OPENSWATH/TransitionTSVFile.cpp (2 hunks)
    🔇 Additional comments (2)
    src/openms/source/ANALYSIS/OPENSWATH/TransitionTSVFile.cpp (2)

    149-150: Good improvements to header parsing configuration!

    The changes to reduce min_header_size from 8 to 4 columns and switch to std::array with tab-first delimiter preference address the crash in TargetedFileConverter, following the agreed approach in previous discussions. This improvement makes the code more resilient when handling files with fewer columns.


    152-157: Improved code readability with modern C++ constructs

    The range-based for loop replacing the index-based iteration is more readable and less error-prone.

    @subCode321

    Copy link
    Copy Markdown
    Contributor Author

    @cbielow, kindly check if the PR is good to go

    @subCode321
    subCode321 requested a review from cbielow March 31, 2025 17:57
    Comment on lines +171 to +191
    bool valid_headers = true;
    for (Size i = 0; i < header.size(); i++)
    {
    header_dict[header[i]] = i;
    bool valid_header = false;
    for (auto header_name : header_names_) {
    if (header_name == header[i]) {
    valid_header = true;
    }
    }

    if (!valid_header) {
    valid_headers = false;
    }
    }

    if (!valid_headers) {
    throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
    "The provided TSV/CSV file is missing one or more required header columns. Please ensure it includes: PrecursorMz, ProductMz (or FragmentMz), LibraryIntensity (or RelativeFragmentIntensity), and NormalizedRetentionTime (or its synonyms).");
    }

    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.

    looking at the code, this is not needed after all, since this is checked here

    if (!extractName<double>(mytransition.product, "ProductMz", tmp_line, header_dict) &&

    for the four required headers.

    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've dropped this additional check

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

    good to go,
    Please remove the second part of the new code which deals with headers (its duplicating functionality already present)

    Comment on lines -149 to +156
    int nr_delimiters = 3;
    Size min_header_size = 8;
    const char possibleDelimiters[3] = {',', ';', '\t'};
    Size min_header_size = 4;
    const std::array<char, 3> possible_delimiters = {'\t', ';', ','};

    for (int i = 0; i < nr_delimiters; i++)
    for (auto possible_delimiter : possible_delimiters)
    {
    header.clear();
    std::stringstream lineStream(line);
    delimiter = possibleDelimiters[i];
    delimiter = possible_delimiter;

    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.

    yes, good!

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

    🧹 Nitpick comments (1)
    src/openms/source/ANALYSIS/OPENSWATH/TransitionTSVFile.cpp (1)

    175-175: Why is this line change necessary?

    This empty line change appears to be unrelated to the PR's objective. If it was added unintentionally, consider removing it to maintain a cleaner diff.

    📜 Review details

    Configuration used: CodeRabbit UI
    Review profile: CHILL
    Plan: Pro

    📥 Commits

    Reviewing files that changed from the base of the PR and between f1fdcdd and b2b99bb.

    📒 Files selected for processing (1)
    • src/openms/source/ANALYSIS/OPENSWATH/TransitionTSVFile.cpp (2 hunks)
    🔇 Additional comments (2)
    src/openms/source/ANALYSIS/OPENSWATH/TransitionTSVFile.cpp (2)

    149-151: Improved header parsing robustness

    The code now requires a minimum of 4 header fields (matching the documented requirements) instead of 8, and uses a properly ordered array of delimiters that prioritizes tabs. This will fix the TargetedFileConverter crash when processing TSV files with fewer than 8 columns, while still ensuring the minimum required fields are present.


    152-157: Good C++ modernization

    The switch to range-based for loop with std::array improves code readability and follows modern C++ best practices, as suggested in the review comments.

    @subCode321

    Copy link
    Copy Markdown
    Contributor Author

    good to go, Please remove the second part of the new code which deals with headers (its duplicating functionality already present)

    I've removed, thanks for the review

    @cbielow
    cbielow enabled auto-merge April 2, 2025 14:29
    @subCode321

    Copy link
    Copy Markdown
    Contributor Author

    @cbielow can you re-run the checks for this PR, they got stopped after the merge of branch develop into my branch

    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

    Projects

    None yet

    Development

    Successfully merging this pull request may close these issues.

    TargetedFileConverter crash

    2 participants