Skip to content

[FIX] DIAScore slow, unprecise dotproduct. Add ASAN support for Windows - #8123

Merged
jpfeuffer merged 12 commits into
OpenMS:developfrom
jpfeuffer:fix/diascore
Jul 19, 2025
Merged

jpfeuffer merged 12 commits into
OpenMS:developfrom
jpfeuffer:fix/diascore

Conversation

@jpfeuffer

@jpfeuffer jpfeuffer commented Jul 15, 2025 •

Copy link
Copy Markdown
Contributor

Description

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

Summary by CodeRabbit

  • New Features

    • Added an option to enable AddressSanitizer for improved memory error detection, with support for compatible compilers and platforms including MSVC 2019 and newer.
  • Bug Fixes

    • Improved AddressSanitizer integration for external dependencies, ensuring consistent activation and proper handling across different compilers and build types.
    • Added checks to prevent AddressSanitizer use on unsupported compiler versions, providing clear error messages.
  • Style

    • Made minor formatting and type consistency adjustments in analysis code for improved readability.
  • Refactor

    • Simplified and optimized utility functions and SIMD string processing for safer and more efficient execution.
    • Enhanced standard algorithm usage with const iterators for improved safety and clarity.
    • Replaced manual dot product computation with Eigen library calls for optimized performance.
  • Chores

    • Enhanced debugging output in scoring routines to aid diagnostics.
    • Disabled building of example targets for certain dependencies to streamline builds.
    • Improved compiler pragma handling for better portability across compilers.

@coderabbitai

coderabbitai Bot commented Jul 15, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

This update introduces and refines AddressSanitizer (ASAN) support across CMake configuration files, centralizing option declarations and enforcing stricter compiler and build-type checks, especially for MSVC. It also adds extensive debug output to a scoring function, applies minor code cleanups, adds compiler-specific no-sanitize attributes to string length functions, and updates SIMD-based string length logic for safer memory access. Additionally, it wraps Clang-specific pragma directives with conditional compilation for better portability.

Changes

File(s) Change Summary
CMakeLists.txt, cmake/add_library_macros.cmake Moved and consolidated the ADDRESS_SANITIZER option declaration and inclusion logic to the main CMakeLists, removing it from add_library_macros.
cmake/AddressSanitizer.cmake Centralized build-type and compiler checks for ASAN, added MSVC 2019+ support with proper flags, improved error handling and messaging, removed redundant warnings inside target function.
src/openms/extern/SQLiteCpp/CMakeLists.txt Synchronized ASAN option with global setting, added MSVC 2019+ support, improved error handling, removed unconditional -fuse-ld=gold linker flag, updated ASAN usage messages.
src/openms/extern/tool_description_lib/tdl-config.cmake Added ASAN support with MSVC version/build-type checks, added /fsanitize=address flag for supported MSVC Debug builds, disabled yaml-cpp examples during fetch.
src/openms/source/ANALYSIS/OPENSWATH/DIAHelper.cpp Minor formatting and type consistency fixes (e.g., indentation, literal types, reference style) without logic changes.
src/openms/source/ANALYSIS/OPENSWATH/DIAPrescoring.cpp Added extensive debug print statements throughout the scoring function; updated iterator usage to const iterators for safety and clarity; no logic changes.
src/openms/source/FORMAT/HANDLERS/XMLHandler.cpp, src/openms/include/OpenMS/FORMAT/HANDLERS/XMLHandler.h Added compiler-specific no-address-sanitizer attributes to the strLength function and method to suppress ASAN instrumentation, preventing false positives.
src/openms/source/FORMAT/HANDLERS/MzMLHandler.cpp Wrapped Clang-specific diagnostic pragma push/pop directives with #ifdef __clang__ guards to improve portability without changing logic.
src/openswathalgo/include/OpenMS/OPENSWATHALGO/ALGO/StatsHelpers.h Refactored dotProd to use Eigen's vectorized dot product via Eigen::Map; simplified manhattanDist by removing unused variables; no functional changes.
src/openswathalgo/source/OPENSWATHALGO/ALGO/StatsHelpers.cpp Added #include <Eigen/Core>; implemented dotProd using Eigen; added explicit template instantiations; changed normalize to use const iterators.
src/openswathalgo/CMakeLists.txt Added private link dependency on Eigen3::Eigen to OpenSwathAlgo for internal use without exposing it publicly.
src/tests/class_tests/openms/source/StatsHelpers_test.cpp Updated test calls to use const iterators (cbegin(), cend()) for read-only access in vector operations; no logic changes.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CMake
    participant AddressSanitizer.cmake
    participant Compiler

    User->>CMake: Configure with ADDRESS_SANITIZER=ON
    CMake->>AddressSanitizer.cmake: Include and check ASAN option
    AddressSanitizer.cmake->>CMake: Validate compiler/build type
    alt MSVC 2019+ and Debug
        CMake->>Compiler: Add /fsanitize=address flags
    else GCC/Clang and Debug
        CMake->>Compiler: Add -fsanitize=address flags
    else
        AddressSanitizer.cmake->>CMake: Emit fatal error
    end
Loading

Possibly related PRs

Suggested labels

Review effort 2/5, Performance

Suggested reviewers

  • timosachsenberg

Poem

🐇 A hop, a skip, a sanitizer’s cheer,
Memory bugs now disappear!
Flags set right for MSVC and friends,
Debugging journeys with safer ends.
In code’s green meadow, I leap with glee,
Safe and sound as safe can be! 🌿✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6b7e131 and d3131af.

📒 Files selected for processing (1)
  • src/openms/source/ANALYSIS/OPENSWATH/DIAPrescoring.cpp (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/openms/source/ANALYSIS/OPENSWATH/DIAPrescoring.cpp
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
  • GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
  • GitHub Check: build-and-test (macos-13, xcode, 14.2)
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @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.

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

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

164-307: Consider making debug output conditional.

The extensive debug output added throughout the scoring function will help with debugging as intended, but it may be too verbose for production use. Consider:

  1. Wrapping debug output in conditional compilation directives (#ifdef DEBUG or similar)
  2. Using a configurable logging level to control verbosity
  3. Adding a parameter to enable/disable debug output

The const iterator usage improvements (cbegin(), cend()) are excellent for code safety and consistency.

Example approach for conditional debug output:

+#ifdef OPENMS_DEBUG_SCORING
 std::cout << "intTheor: ";
 for (const auto& val : intTheor)
 {
   std::cout << val << " ";
 }
 std::cout << std::endl;
+#endif
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 60cd3f8 and 092ba54.

📒 Files selected for processing (10)
  • CMakeLists.txt (1 hunks)
  • cmake/AddressSanitizer.cmake (1 hunks)
  • cmake/add_library_macros.cmake (0 hunks)
  • src/openms/extern/SQLiteCpp/CMakeLists.txt (1 hunks)
  • src/openms/extern/tool_description_lib/tdl-config.cmake (2 hunks)
  • src/openms/source/ANALYSIS/OPENSWATH/DIAHelper.cpp (4 hunks)
  • src/openms/source/ANALYSIS/OPENSWATH/DIAPrescoring.cpp (4 hunks)
  • src/openms/source/FORMAT/HANDLERS/XMLHandler.cpp (1 hunks)
  • src/openswathalgo/include/OpenMS/OPENSWATHALGO/ALGO/StatsHelpers.h (1 hunks)
  • src/openswathalgo/source/OPENSWATHALGO/ALGO/StatsHelpers.cpp (1 hunks)
💤 Files with no reviewable changes (1)
  • cmake/add_library_macros.cmake
🧰 Additional context used
🧠 Learnings (1)
src/openms/source/ANALYSIS/OPENSWATH/DIAHelper.cpp (3)
Learnt from: jpfeuffer
PR: OpenMS/OpenMS#7970
File: src/pyOpenMS/addons/MSSpectrum.pyx:24-28
Timestamp: 2025-04-07T21:16:06.557Z
Learning: In OpenMS, the proper way to access ion mobility data in MSSpectrum is to use the `getIMData()` method, which returns a tuple with (position, unit). The position corresponds to the index in the FloatDataArrays where the ion mobility data is stored. Always use this method rather than assuming the first FloatDataArray contains ion mobility data.
Learnt from: jpfeuffer
PR: OpenMS/OpenMS#7970
File: src/pyOpenMS/addons/MSSpectrum.pyx:24-28
Timestamp: 2025-04-07T21:16:06.557Z
Learning: In OpenMS, the proper way to access ion mobility data in MSSpectrum is to use the `getIMData()` method, which returns a tuple with (position, unit). The position corresponds to the index in the FloatDataArrays where the ion mobility data is stored. Always use this method rather than assuming the first FloatDataArray contains ion mobility data.
Learnt from: jpfeuffer
PR: OpenMS/OpenMS#7970
File: src/pyOpenMS/addons/MSSpectrum.pyx:38-38
Timestamp: 2025-04-07T21:15:07.674Z
Learning: In mass spectrometry data, precursor charges can be negative, so signed integer types (like np.int16) should be used instead of unsigned integers (like np.uint16) when storing charge values.
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
  • GitHub Check: build-and-test (macos-13, xcode, 14.2)
🔇 Additional comments (16)
src/openswathalgo/include/OpenMS/OPENSWATHALGO/ALGO/StatsHelpers.h (1)

70-72: LGTM! Clean simplification of the loop logic.

The removal of unused loop variable i and intermediate variable x makes the code more concise while maintaining the same functionality. The direct iterator-based loop is clearer and more efficient.

src/openswathalgo/source/OPENSWATHALGO/ALGO/StatsHelpers.cpp (1)

28-28: LGTM! Improved const-correctness.

Using cbegin() and cend() instead of begin() and end() ensures that the const input vector is treated correctly and prevents accidental modification during the transform operation.

src/openms/source/ANALYSIS/OPENSWATH/DIAHelper.cpp (4)

219-219: LGTM! Fixed indentation consistency.

The indentation has been corrected to use tabs consistently with the rest of the codebase.


231-231: LGTM! Improved type consistency.

Changed from integer -1 to floating-point -1. for consistent double type usage, which aligns with the variable type being double.


436-436: LGTM! Updated reference syntax.

The reference syntax has been updated appropriately for the function signature.


474-474: LGTM! Corrected variable type.

Changed mul from 1. (double) to 1 (int) since this is used as a counter variable, making the type more appropriate for its usage.

src/openms/source/FORMAT/HANDLERS/XMLHandler.cpp (1)

434-472: LGTM! Improved SIMD safety to address ASAN issues.

The refactored strLength function now includes proper bounds checking before SIMD operations:

  • Explicitly checks for availability of 8 characters before SIMD loads
  • Prevents potential buffer overruns that AddressSanitizer would detect
  • Falls back to scalar processing when fewer than 8 characters remain
  • Maintains the same functionality while ensuring memory safety

This addresses the ASAN fixes mentioned in the PR objectives and makes the SIMD operations much safer.

src/openms/source/ANALYSIS/OPENSWATH/DIAPrescoring.cpp (2)

142-142: LGTM! Corrected variable type.

Changed chg from 1. (double) to 1 (int) since charge values should be integers, improving type consistency.


183-184: LGTM! Improved const-correctness throughout.

The consistent use of const iterators (cbegin(), cend()) in standard algorithms improves code safety and aligns with the const-correctness improvements made in the related helper functions.

Also applies to: 199-200, 214-214, 230-230, 234-235, 288-288, 298-298, 302-302

CMakeLists.txt (1)

278-283: LGTM! Well-structured centralization of AddressSanitizer configuration.

The addition of the ADDRESS_SANITIZER option and inclusion of the dedicated CMake script follows good practices for centralized build configuration management.

src/openms/extern/tool_description_lib/tdl-config.cmake (2)

12-23: LGTM! Proper ASAN integration with MSVC version validation.

The AddressSanitizer support correctly validates MSVC version requirements and applies appropriate compiler flags for Debug builds. The error handling for unsupported MSVC versions is appropriate.


42-42: LGTM! Good addition to prevent unnecessary example builds.

Setting YAML_CPP_BUILD_EXAMPLES=OFF prevents building unnecessary examples during dependency fetch, which is a good optimization.

src/openms/extern/SQLiteCpp/CMakeLists.txt (2)

239-243: LGTM! Proper integration with global ASAN configuration.

The override of SQLITECPP_USE_ASAN based on the global ADDRESS_SANITIZER setting ensures consistency with the centralized configuration approach.


245-262: LGTM! Well-structured ASAN support with proper MSVC handling.

The reorganization properly separates MSVC and non-MSVC logic, applies appropriate compiler flags, and maintains consistent version checking. The use of target_compile_options for MSVC is the correct approach.

cmake/AddressSanitizer.cmake (2)

40-52: LGTM! Excellent centralization of ASAN validation.

The global validation approach prevents duplicate checks across targets and provides clear error messages for unsupported configurations. The Debug-only restriction is appropriate for AddressSanitizer usage.


60-68: LGTM! Proper MSVC support added to the function.

The addition of MSVC-specific flags using target_compile_options and target_link_options with /fsanitize=address is correct and maintains consistency with the global validation checks.

Comment thread cmake/AddressSanitizer.cmake Resolved
Comment thread cmake/AddressSanitizer.cmake Resolved

@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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a80eb76 and 608407c.

📒 Files selected for processing (1)
  • src/openswathalgo/CMakeLists.txt (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
src/openswathalgo/CMakeLists.txt (1)
Learnt from: FreezB11
PR: OpenMS/OpenMS#7969
File: src/pyOpenMS/pxds/TMTThirtyTwoPlexQuantitationMethod.pxd:4-4
Timestamp: 2025-06-16T15:48:09.667Z
Learning: In OpenMS .pxd files, the established pattern for extern from statements is to include angle brackets inside the string literal, like `cdef extern from "<OpenMS/PATH/TO/FILE.h>" namespace "OpenMS":`. This is consistent across all existing quantitation method .pxd files and other .pxd files in the OpenMS codebase.
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (macos-13, xcode, 14.2)
  • GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (macos-14, xcode, 15.0.1)

Comment thread src/openswathalgo/CMakeLists.txt Resolved

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 608407c and fe530d0.

📒 Files selected for processing (4)
  • cmake/AddressSanitizer.cmake (1 hunks)
  • cmake/add_library_macros.cmake (1 hunks)
  • src/openswathalgo/include/OpenMS/OPENSWATHALGO/ALGO/StatsHelpers.h (3 hunks)
  • src/openswathalgo/source/OPENSWATHALGO/ALGO/StatsHelpers.cpp (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • cmake/add_library_macros.cmake
  • cmake/AddressSanitizer.cmake
  • src/openswathalgo/include/OpenMS/OPENSWATHALGO/ALGO/StatsHelpers.h
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/openswathalgo/source/OPENSWATHALGO/ALGO/StatsHelpers.cpp (1)
src/openswathalgo/include/OpenMS/OPENSWATHALGO/ALGO/StatsHelpers.h (1)
  • dotProd (47-47)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (macos-13, xcode, 14.2)
🔇 Additional comments (3)
src/openswathalgo/source/OPENSWATHALGO/ALGO/StatsHelpers.cpp (3)

15-15: LGTM: Eigen include addition is appropriate.

Adding Eigen/Core for the new dotProd function implementation is the correct approach for efficient linear algebra operations.


29-29: LGTM: Const-correctness improvement.

Using cbegin() and cend() instead of begin() and end() properly enforces const-correctness since the source container is only being read from, not modified.


92-99: LGTM: Explicit template instantiations are well-structured.

The explicit template instantiations for std::vector<double>, std::vector<float>, and std::vector<int> const iterators with OPENSWATHALGO_DLLAPI linkage are properly implemented to ensure these specific versions are compiled and exported.

Comment on lines +74 to +89
template <typename Texp, typename Ttheo>
double dotProd(Texp intExpBeg, Texp intExpEnd, Ttheo intTheo)
{
size_t size = std::distance(intExpBeg, intExpEnd);

// Get the value types
using ExpType = typename std::iterator_traits<Texp>::value_type;
using TheoType = typename std::iterator_traits<Ttheo>::value_type;

// Create appropriate Eigen maps based on the actual data types
Eigen::Map<const Eigen::Matrix<ExpType, Eigen::Dynamic, 1>> vec1(&(*intExpBeg), size);
Eigen::Map<const Eigen::Matrix<TheoType, Eigen::Dynamic, 1>> vec2(&(*intTheo), size);

// Compute dot product and cast result to double
return static_cast<double>(vec1.dot(vec2));
}

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

Add size validation for safer memory access.

The function assumes both iterator ranges have the same size but doesn't validate this. This could lead to buffer overruns if the theoretical intensities range is shorter than the experimental range.

 template <typename Texp, typename Ttheo>
 double dotProd(Texp intExpBeg, Texp intExpEnd, Ttheo intTheo)
 {
   size_t size = std::distance(intExpBeg, intExpEnd);
+  
+  // Validate input ranges
+  if (size == 0) {
+    return 0.0;
+  }
   
   // Get the value types
   using ExpType = typename std::iterator_traits<Texp>::value_type;
   using TheoType = typename std::iterator_traits<Ttheo>::value_type;
   
   // Create appropriate Eigen maps based on the actual data types
   Eigen::Map<const Eigen::Matrix<ExpType, Eigen::Dynamic, 1>> vec1(&(*intExpBeg), size);
   Eigen::Map<const Eigen::Matrix<TheoType, Eigen::Dynamic, 1>> vec2(&(*intTheo), size);
   
   // Compute dot product and cast result to double
   return static_cast<double>(vec1.dot(vec2));
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
template <typename Texp, typename Ttheo>
double dotProd(Texp intExpBeg, Texp intExpEnd, Ttheo intTheo)
{
size_t size = std::distance(intExpBeg, intExpEnd);
// Get the value types
using ExpType = typename std::iterator_traits<Texp>::value_type;
using TheoType = typename std::iterator_traits<Ttheo>::value_type;
// Create appropriate Eigen maps based on the actual data types
Eigen::Map<const Eigen::Matrix<ExpType, Eigen::Dynamic, 1>> vec1(&(*intExpBeg), size);
Eigen::Map<const Eigen::Matrix<TheoType, Eigen::Dynamic, 1>> vec2(&(*intTheo), size);
// Compute dot product and cast result to double
return static_cast<double>(vec1.dot(vec2));
}
template <typename Texp, typename Ttheo>
double dotProd(Texp intExpBeg, Texp intExpEnd, Ttheo intTheo)
{
size_t size = std::distance(intExpBeg, intExpEnd);
// Validate input ranges
if (size == 0) {
return 0.0;
}
// Get the value types
using ExpType = typename std::iterator_traits<Texp>::value_type;
using TheoType = typename std::iterator_traits<Ttheo>::value_type;
// Create appropriate Eigen maps based on the actual data types
Eigen::Map<const Eigen::Matrix<ExpType, Eigen::Dynamic, 1>> vec1(&(*intExpBeg), size);
Eigen::Map<const Eigen::Matrix<TheoType, Eigen::Dynamic, 1>> vec2(&(*intTheo), size);
// Compute dot product and cast result to double
return static_cast<double>(vec1.dot(vec2));
}
🤖 Prompt for AI Agents
In src/openswathalgo/source/OPENSWATHALGO/ALGO/StatsHelpers.cpp between lines 74
and 89, the dotProd function assumes the experimental and theoretical iterator
ranges have the same size but does not validate this, risking buffer overruns.
Add a check to ensure the size of the theoretical range matches the experimental
range before proceeding. If the sizes differ, handle the error appropriately,
such as throwing an exception or returning an error value, to prevent unsafe
memory access.

Comment on lines +84 to +85
Eigen::Map<const Eigen::Matrix<ExpType, Eigen::Dynamic, 1>> vec1(&(*intExpBeg), size);
Eigen::Map<const Eigen::Matrix<TheoType, Eigen::Dynamic, 1>> vec2(&(*intTheo), size);

@coderabbitai coderabbitai Bot Jul 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.

💡 Verification agent

🧩 Analysis chain

Verify iterator contiguity assumption.

The function uses &(*intExpBeg) to obtain pointers for Eigen::Map, which assumes the iterators point to contiguous memory. This is safe for std::vector iterators but may not be for other container types.


🏁 Script executed:

#!/bin/bash
# Description: Check if dotProd is only called with std::vector iterators
# Expected: Only std::vector iterators should be used with this function

echo "Searching for dotProd function calls:"
rg -A 3 -B 1 "dotProd\s*\(" --type cpp

echo -e "\nSearching for explicit template instantiations:"
rg "template.*dotProd" --type cpp

Length of output: 4511


Require contiguous iterators for Eigen::Map in dotProd

The implementation of dotProd in StatsHelpers.cpp uses

Eigen::Map<const Eigen::Matrix<ExpType, Eigen::Dynamic, 1>> vec1(&(*intExpBeg), size);

which assumes that intExpBeg/intTheo point into contiguous memory. Although we only explicitly instantiate and ever call dotProd with std::vector<>::const_iterator, the unconstrained template could be misused with non‐contiguous containers (e.g. std::deque) and silently break.

To prevent this, constrain the template parameters to contiguous iterators (C++20) or add a static_assert on the iterator category. For example:

— include/OpenMS/OPENSWATHALGO/ALGO/StatsHelpers.h

+#include <iterator>

-template <typename Texp, typename Ttheo>
-double dotProd(Texp intExpBeg, Texp intExpEnd, Ttheo intTheo);
+template <
+  std::contiguous_iterator Texp,
+  std::contiguous_iterator Ttheo
+>
+double dotProd(Texp intExpBeg, Texp intExpEnd, Ttheo intTheo);

Or, if you’re not yet on C++20, inside the function body add:

static_assert(
  std::is_same_v<typename std::iterator_traits<Texp>::iterator_category,
                 std::random_access_iterator_tag>,
  "dotProd requires contiguous (e.g. std::vector) iterators");

This will produce a clear compile‐time error if someone attempts to call dotProd with a non‐contiguous iterator.

🤖 Prompt for AI Agents
In src/openswathalgo/source/OPENSWATHALGO/ALGO/StatsHelpers.cpp around lines
84-85, the dotProd function uses Eigen::Map with iterators assuming contiguous
memory, which can cause silent errors if non-contiguous iterators are used. To
fix this, add a static_assert inside the dotProd function to ensure the iterator
category is std::random_access_iterator_tag, enforcing that only contiguous
iterators like those from std::vector are accepted and producing a clear
compile-time error otherwise.

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.

True. Who would want to do this on non-contiguous iterators?! Although possible, we should stop supporting 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.

@jpfeuffer Exactly! There's no practical benefit to supporting non-contiguous iterators for dot product operations, and it just creates a potential footgun. Let me help you implement the static_assert fix to make this requirement explicit.

Task: Add static_assert to enforce contiguous iterators in dotProd

  • Add static_assert inside the dotProd function to ensure only contiguous iterators are accepted
  • This will produce a clear compile-time error if someone tries to use non-contiguous iterators

⏳ Preparing changes...

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.

I don't care. Can be continuous only

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

Choose a reason for hiding this comment

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

A summary of the changes CodeRabbit can apply:

  • Modify StatsHelpers.cpp by adding an #include <iterator> directive and inserting static_assert checks in the dotProd function to enforce that its template parameters use random access iterators, ensuring safer and more efficient iterator usage.

  • Modify StatsHelpers.cpp by adding #include <iterator> if missing and inserting static assertions in the dotProd function to ensure both iterator template parameters are contiguous random-access iterators, enforcing safer usage.

  • ✅ Create PR with these edits
  • 📌 Create commit in current branch
  • 📋 Get copyable edits

@timosachsenberg

Copy link
Copy Markdown
Contributor

if we are sure it has no issues: could we keep the simd code for release mode and the non-simd code for debug with asan?

@jpfeuffer

Copy link
Copy Markdown
Contributor Author

Maybe. But not in this PR. It doesn't even work what I am doing on Windows. Just keeping it there in the hope that Microsoft fixes it at some point.

@jpfeuffer

Copy link
Copy Markdown
Contributor Author

I have no idea how to correctly write doxygen for this.

@jpfeuffer jpfeuffer changed the title try fix diascore with safer code and debug output. also fix ASAN [FIX] DIAScore slow, unprecise dotproduct. Add ASAN support for Windows Jul 17, 2025
OpenSwath::normalize(intExp, intExpEuclidNorm, intExp);
OpenSwath::normalize(intTheor, intTheorEuclidNorm, intTheor);

std::cout << "Norms: intExpEuclidNorm: " << intExpEuclidNorm

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.

TODO remove all debug stmts

@timosachsenberg

Copy link
Copy Markdown
Contributor

Fixed doxygen.

@jpfeuffer

Copy link
Copy Markdown
Contributor Author

Nice. I will remove the debug code tomorrow then I think we can merge.

Comment on lines +245 to +260
if (MSVC)
if (MSVC_VERSION GREATER_EQUAL 1920) # MSVC 2019 or later
message (STATUS "SQLiteCpp Using Address Sanitizer")
# add AddressSanitizer for compiler and linker
target_compile_options(SQLiteCpp
PUBLIC
/fsanitize=address
)
else()
message(FATAL_ERROR "AddressSanitizer is not supported for MSVC versions < 2019.")
endif()
else()
if ((CMAKE_CXX_COMPILER_VERSION GREATER_EQUAL 6) OR ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang"))
message (STATUS "SQLiteCpp Using Address Sanitizer")
set_target_properties(SQLiteCpp PROPERTIES COMPILE_FLAGS "-fsanitize=address -fno-omit-frame-pointer")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fsanitize=address")

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.

this will be lost when we update SQLiteCpp.
Push it upstream?

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.

Yes I can/will. Let's merge with it meanwhile?

Comment on lines +12 to +23
if (ADDRESS_SANITIZER)
if (MSVC AND MSVC_VERSION LESS 1920)
message(FATAL_ERROR "AddressSanitizer is not supported for MSVC versions < 2019.")
else()
# For Windows, every static lib that uses STL needs to be compiled with ASAN ON
# otherwise the linker will complain about mismatch in annotated vs unannotated STL
# types. https://learn.microsoft.com/en-us/cpp/sanitizers/error-container-overflow?view=msvc-170
if ("${CMAKE_BUILD_TYPE}" STREQUAL "Debug")
add_compile_options("/fsanitize=address")
endif()
endif()
endif()

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.

same problem.
Can we add this code after including tdl? i.e. make it part of OpenMS?

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.

Yes can do too

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.

Yeah so this is a tricky one. Not sure how I get access to the options in fetch content there. Basically what I am doing here is to set the options for all targets generated in that subfolder.

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.

If I do it one directory up, it will affect more of our dependencies.
Maybe something like
Add options
Include
Remove options
works from outside.

Comment on lines -49 to -50
std::transform(intExpBeg, intExpEnd, intTheo, res.begin(), std::multiplies<double>());
double sum = std::accumulate(res.begin(), res.end(), 0.);

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.

So, was one of those two the culprit?

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.

Yes or their combination. It doesn't look like there was UB anywhere but maybe too much rounding going on with all the intermediate doubles this creates.

using TheoType = typename std::iterator_traits<Ttheo>::value_type;

// Create appropriate Eigen maps based on the actual data types
Eigen::Map<const Eigen::Matrix<ExpType, Eigen::Dynamic, 1>> vec1(&(*intExpBeg), size);

@timosachsenberg timosachsenberg Jul 18, 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.

/**
 * @brief Computes the dot product of two vectors using Eigen::Map for high performance.
 *
 * This function works on any C++ container that satisfies the ContiguousFloatVector concept,
 * such as std::vector<float>, std::vector<double>, or std::array<float, N>.
 *
 * @tparam Vec1 The type of the first vector container.
 * @tparam Vec2 The type of the second vector container.
 * @param v1 The first vector.
 * @param v2 The second vector.
 * @return The dot product of v1 and v2.
 */
template <ContiguousFloatVector Vec1, ContiguousFloatVector Vec2>
auto dot_product(const Vec1& v1, const Vec2& v2) -> std::ranges::range_value_t<Vec1>
{
    // Precondition: The vectors must be the same size.
    assert(v1.size() == v2.size() && "Vectors must have the same size for dot product.");

    // Ensure both vectors have the same underlying floating-point type.
    static_assert(
        std::is_same_v<std::ranges::range_value_t<Vec1>, std::ranges::range_value_t<Vec2>>,
        "Vector value types must be identical."
    );

    using Scalar = std::ranges::range_value_t<Vec1>;
    
    // Create Eigen::Map objects to view the container data as Eigen vectors.
    // This is a zero-copy operation.
    // The `Unaligned` flag is crucial for safety, as standard containers
    // like std::vector don't guarantee alignment for Eigen's SIMD operations.
    Eigen::Map<const Eigen::VectorX<Scalar>, Eigen::Unaligned> map1(v1.data(), v1.size());
    Eigen::Map<const Eigen::VectorX<Scalar>, Eigen::Unaligned> map2(v2.data(), v2.size());

    // Perform the dot product using Eigen's optimized implementation.
    return map1.dot(map2);
}

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.

AI claims the unaligned flag is crucial

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.

#include <concepts>
#include <ranges>
#include <type_traits>

// Concept to check if a type is a contiguous range of a floating-point type.
template <typename T>
concept ContiguousFloatVector =
    std::ranges::contiguous_range<T> &&
    std::is_floating_point_v<std::ranges::range_value_t<T>>;

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.

Yes let's do unaligned. Didn't know there was this option.

@jpfeuffer jpfeuffer Jul 18, 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.

Unaligned is already the default. Which makes sense.

@jpfeuffer

Copy link
Copy Markdown
Contributor Author

Let's see if this solves other problems in the other PR too.

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