Skip to content

[FIX] OpenSWATH: canonicalize and preserve library IDs across outputs - #9888

Merged
timosachsenberg merged 14 commits into
OpenMS:developfrom
singjc:fix/openswath-canonical-library-ids
Aug 10, 2026
Merged

timosachsenberg merged 14 commits into
OpenMS:developfrom
singjc:fix/openswath-canonical-library-ids

Conversation

@singjc

@singjc singjc commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Description

This PR introduces a canonical identifier boundary for OpenSWATH transition
libraries.

LightTargetedExperiment now uses canonical numeric precursor and transition
identifiers operationally, independent of the source library format:

  • source formats (TraML/TSV) are deterministically canonicalized at ingestion
  • persistent formats (PQP/OSWPQ) preserve and validate their stored numeric IDs
  • original/source identifiers remain provenance rather than operational foreign keys

Motivation

OpenSWATH currently gives LightTargetedExperiment different identifier
semantics depending on the library format.

For example, equivalent libraries loaded from TSV/TraML, PQP, and OSWPQ could
use different precursor/transition IDs. This caused identifiers written to
XIC/XIPM/XIM, OSW/PQP, and OSWPQ artifacts to refer to different entities
despite representing the same library records.

In particular, numeric source IDs could silently collide with independently
assigned persistent IDs, making numeric joins between output formats unsafe.

Changes

Canonical source-library IDs

Adds OpenSwathLibraryIDNormalizer, which normalizes source-format
LightTargetedExperiments at the ingestion boundary.

For TraML/TSV:

  • precursor source IDs are sorted lexicographically and assigned canonical
    numeric IDs
  • transition IDs are assigned deterministically from transition order
  • transition peptide_ref values are rewritten to canonical precursor IDs
  • transitionless compounds reserve their canonical ID but are omitted from the
    operational experiment
  • retained precursor IDs are therefore allowed to be sparse

The complete source compound set is used when assigning precursor IDs before
the operational subset is constructed. This mirrors the existing PQP
conversion convention and ensures direct source loading and source -> PQP
round-trips use the same IDs.

A fresh LightTargetedExperiment is constructed rather than mutating compound
IDs in place, avoiding stale compound_reference_map_ entries.

Persistent library formats

PQP and OSWPQ are treated as already-canonical persistent formats and are
validated rather than renumbered.

The OSWPQ reader now uses:

  • precursor_id as LightCompound.id
  • transition_id as LightTransition.transition_name
  • precursor_id as LightTransition.peptide_ref

instead of restoring traml_id into operational identifiers.

Tests and reference outputs

Tests were added/updated for:

  • canonical source-ID normalization
  • sparse precursor IDs caused by transitionless source compounds
  • PQP ID semantics
  • OSWPQ numeric-ID semantics
  • OSWPQ round-trip behavior

OpenSwathWorkflow reference outputs were updated to reflect the intentional
canonical-ID change.

The OSWPQ decoy-generator round-trip reference was also updated. All 22 rows
were independently checked: non-ID text fields are identical and numeric
fields are equivalent within 1e-12; only the operational precursor/transition
identifiers change.

Validation

  • OpenSwathWorkflow-focused scope: 85/85 tests pass
  • broader OpenSWATH scope: 203/203 tests pass

For the transitionless-compound edge case in OpenSwathWorkflow test 15,
direct TraML ingestion and:

TraML → TargetedFileConverter → PQP → OpenSwathWorkflow

produce byte-identical featureXML and chromatogram mzML output.

Breaking behavior

Operational precursor and transition IDs exposed in outputs may change for
TraML/TSV inputs.

Source/descriptive IDs should no longer be assumed to be operational foreign
keys. Persistent numeric canonical IDs are used instead.

Follow-up

This PR intentionally does not complete the writer-side identifier refactor.

A follow-up will:

  • make the PQP writer preserve incoming canonical IDs instead of renumbering
  • make the OSWPQ writer preserve incoming canonical IDs instead of allocating
    its current independent/1-based ID space
  • remove the OpenSwathWorkflow post-load TraML→PQP remapping path
  • remove downstream fallback/ID-allocation logic from XIC/XIPM/XIM and
    OSW/OSWPQ writers
  • unify run-ID canonicalization
  • add cross-format identity/fingerprint checks

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 consistent numeric identifiers for OpenSWATH precursors and transitions across supported library formats.
    • Preserved source identifiers and provenance during PQP and Parquet conversions.
    • Added decoy-prefix handling and canonical target matching.
  • Bug Fixes

    • Added validation for invalid, duplicate, missing, or inconsistent identifiers and references.
    • Improved identifier preservation and reference handling during library conversion and loading.
    • Updated workflow outputs to reflect stable canonical identifiers.
  • Documentation

    • Clarified identifier behavior and compatibility for PQP, OSWPQ, and Parquet libraries.

@coderabbitai

coderabbitai Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The change adds canonical OpenSWATH precursor and transition identifiers. It normalizes and validates IDs, preserves source provenance, supports decoy resolution, and propagates mappings through PQP, Parquet, workflow, filtering, and regression-test paths.

Changes

Canonical OpenSWATH identifiers

Layer / File(s) Summary
Identifier contract and normalization
src/openms/include/OpenMS/ANALYSIS/OPENSWATH/*, src/openms/source/ANALYSIS/OPENSWATH/OpenSwathLibraryIDNormalizer.cpp, src/openms/include/OpenMS/APPLICATIONS/OpenSwathBase.h, src/openms/source/APPLICATIONS/OpenSwathBase.cpp
Adds canonical numeric IDs, source mappings, decoy handling, validation, and source-aware transition-list loading.
PQP and Parquet persistence
src/openms/source/ANALYSIS/OPENSWATH/TransitionPQPFile.cpp, src/openms/source/ANALYSIS/OPENSWATH/TransitionParquetFile.cpp, src/openms/source/ANALYSIS/OPENSWATH/OpenSwathOSWParquetWriter.cpp
Preserves canonical IDs, restores source IDs through mappings, validates ID domains, and rejects invalid or incompatible identifiers.
Workflow integration
src/topp/OpenSwathWorkflow.cpp, src/topp/TargetedFileConverter.cpp, src/topp/TransitionListEvidenceFilter.cpp
Propagates source mappings through loading, decoy materialization, decoy matching, filtering, and output writing.
Validation and regression coverage
src/tests/class_tests/openms/source/*, src/tests/topp/CMakeLists.txt, src/tests/class_tests/openms/executables.cmake
Tests normalization, sparse IDs, invalid references, decoy recovery, PQP compatibility, Parquet round trips, and workflow output identity.
Workflow fixtures
src/tests/topp/OpenSwathWorkflow_*_output.*
Regenerates chromatogram and feature outputs with numeric precursor, transition, and peptide-reference identifiers.

Sequence Diagram(s)

sequenceDiagram
  participant OpenSwathBase
  participant LibraryReader
  participant OpenSwathLibraryIDNormalizer
  participant TransitionPQPFile
  participant TransitionParquetFile
  participant OpenSwathOSWParquetWriter
  OpenSwathBase->>LibraryReader: load transition library
  LibraryReader-->>OpenSwathBase: LightTargetedExperiment
  OpenSwathBase->>OpenSwathLibraryIDNormalizer: normalize or validate IDs
  OpenSwathLibraryIDNormalizer-->>OpenSwathBase: canonical experiment and source mapping
  OpenSwathBase->>TransitionPQPFile: write canonical IDs and provenance
  OpenSwathBase->>TransitionParquetFile: write canonical IDs and provenance
  TransitionParquetFile->>OpenSwathOSWParquetWriter: persist validated ID domains
Loading

Suggested reviewers: cbielow, timosachsenberg

Poem

A rabbit sorts each ID in line,
Canonical numbers neatly shine.
Decoys find their matching track,
Source mappings guide them back.
PQP and Parquet keep the sign.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 3.23% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: canonicalizing and preserving OpenSWATH library IDs across outputs.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/openms/source/ANALYSIS/OPENSWATH/TransitionParquetFile.cpp (1)

271-300: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Reject duplicate precursor_id rows before canonical validation.

precursor_map.emplace(...) keeps the first row for a duplicate key and silently drops later metadata. The compound.id assignment then exposes only one value to validateCanonicalIDs, so the duplicate cannot be detected. A transition can use incorrect precursor metadata.

Check the insertion result and throw Exception::InvalidValue when precursor_id already exists. Add a regression test with two precursor rows that use the same ID.

Based on src/openms/source/ANALYSIS/OPENSWATH/OpenSwathLibraryIDNormalizer.cpp, duplicate precursor IDs must reach OpenSwathLibraryIDNormalizer::validateCanonicalIDs.

Proposed validation
-      precursor_map.emplace(precursor_id, std::move(info));
+      const auto insertion = precursor_map.emplace(precursor_id, std::move(info));
+      if (!insertion.second)
+      {
+        throw Exception::InvalidValue(
+          __FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
+          "Duplicate precursor_id '" + StringUtils::toStr(precursor_id) + "'", "");
+      }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/source/ANALYSIS/OPENSWATH/TransitionParquetFile.cpp` around lines
271 - 300, Update the precursor insertion logic using the
`precursor_map.emplace` result: detect an existing `precursor_id` and throw
`Exception::InvalidValue` instead of silently retaining the first row. Add a
regression test covering two precursor rows with the same ID, ensuring
duplicates are rejected before
`OpenSwathLibraryIDNormalizer::validateCanonicalIDs`.
🧹 Nitpick comments (5)
src/tests/class_tests/openms/source/OpenSwathLibraryIDNormalizer_test.cpp (1)

169-209: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Test duplicate canonical precursor IDs directly.

validateCanonicalIDs rejects duplicate precursor IDs, but this section only tests duplicate transition IDs. A regression in precursor uniqueness validation would pass.

Proposed test
   OpenSwathLibraryIDNormalizer::validateCanonicalIDs(valid);

+  OpenSwath::LightTargetedExperiment duplicate_precursor = valid;
+  duplicate_precursor.compounds[1].id = "0";
+  TEST_EXCEPTION(Exception::InvalidValue,
+                 OpenSwathLibraryIDNormalizer::validateCanonicalIDs(duplicate_precursor))
+
   OpenSwath::LightTargetedExperiment leading_zero = valid;

As per coding guidelines, “Write unit tests for new functionality and ensure existing tests pass before suggesting changes.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/tests/class_tests/openms/source/OpenSwathLibraryIDNormalizer_test.cpp`
around lines 169 - 209, Extend the validateCanonicalIDs test section with a case
that duplicates an existing compound precursor ID in valid.compounds and asserts
OpenSwathLibraryIDNormalizer::validateCanonicalIDs throws
Exception::InvalidValue. Keep the existing duplicate_transition case unchanged
so precursor and transition uniqueness are tested separately.

Source: Coding guidelines

src/openms/source/ANALYSIS/OPENSWATH/OpenSwathLibraryIDNormalizer.cpp (3)

26-29: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Exception location always reports this helper, not the failing call site.

throwInvalidID_ passes __FILE__, __LINE__, and OPENMS_PRETTY_FUNCTION expanded inside the helper. Every thrown InvalidValue therefore reports line 28 and the helper signature. That hides which validation failed. Forward the caller location instead.

♻️ Proposed change
-    [[noreturn]] void throwInvalidID_(const std::string& message, const std::string& value)
+    [[noreturn]] void throwInvalidID_(const char* file, int line, const char* function,
+                                      const std::string& message, const std::string& value)
     {
-      throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, message, value);
+      throw Exception::InvalidValue(file, line, function, message, value);
     }

Then call it as throwInvalidID_(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, ...), or wrap that in a small macro.

As per coding guidelines: "throw with file, line, and OPENMS_PRETTY_FUNCTION".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/source/ANALYSIS/OPENSWATH/OpenSwathLibraryIDNormalizer.cpp` around
lines 26 - 29, Update throwInvalidID_ to accept caller-provided file, line, and
function context, and use those values when constructing
Exception::InvalidValue. Update every call site to forward __FILE__, __LINE__,
and OPENMS_PRETTY_FUNCTION before the existing message and value arguments,
preserving the current validation behavior.

Source: Coding guidelines


94-139: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Log the number of compounds dropped during normalization.

Lines 121-139 silently discard every compound that no transition references. A user who supplies a library with transitionless compounds gets a smaller experiment and no message. Emit a debug or info message with the dropped count so the behavior is traceable.

♻️ Proposed change
     validateCanonicalIDs(normalized);
+    const Size dropped = exp.compounds.size() - normalized.compounds.size();
+    if (dropped > 0)
+    {
+      OPENMS_LOG_DEBUG << "OpenSwathLibraryIDNormalizer: omitted " << dropped
+                       << " compound(s) without transitions from the operational library.\n";
+    }
     exp = std::move(normalized);

Add #include <OpenMS/CONCEPT/LogStream.h>.

As per coding guidelines: "Use OpenMS logging macros and OpenMS::LogStream".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/source/ANALYSIS/OPENSWATH/OpenSwathLibraryIDNormalizer.cpp` around
lines 94 - 139, Track how many source compounds are skipped in the normalization
loop of OpenSwathLibraryIDNormalizer, then emit an OpenMS debug or info message
via LogStream reporting that dropped count after normalization. Add the OpenMS
LogStream header and preserve the existing filtering behavior and compound ID
canonicalization.

Source: Coding guidelines


61-72: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Bind IDs by const reference to avoid per-row string copies.

Lines 63, 101, 123, and 144 copy each ID into a new std::string. These loops run once per compound and once per transition. Large libraries contain millions of transitions, so the copies add avoidable allocations. Bind const references instead.

♻️ Proposed change
     for (const auto& compound : exp.compounds)
     {
-      const std::string source_id = compound.id;
+      const std::string& source_id = compound.id;
       if (source_id.empty())
     for (const auto& transition : exp.transitions)
     {
-      const std::string source_ref = transition.peptide_ref;
+      const std::string& source_ref = transition.peptide_ref;
       if (source_ref.empty())
     for (const auto& source_compound : exp.compounds)
     {
-      const std::string source_id = source_compound.id;
+      const std::string& source_id = source_compound.id;
       if (!referenced_compound_ids.contains(source_id))
       auto& transition = normalized.transitions[i];
-      const std::string source_ref = transition.peptide_ref;
+      const std::string& source_ref = transition.peptide_ref;
       const auto precursor_it = precursor_id_map.find(source_ref);

The same pattern appears at lines 168, 181, and 188 in validateCanonicalIDs.

Also applies to: 121-155

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/source/ANALYSIS/OPENSWATH/OpenSwathLibraryIDNormalizer.cpp` around
lines 61 - 72, Replace per-row ID value copies with const-reference bindings
throughout the affected loops in OpenSwathLibraryIDNormalizer, including the
compound/transition handling and validateCanonicalIDs. Update source_id and the
corresponding ID locals at the referenced locations to bind directly to the
existing string values while preserving all validation and normalization
behavior.
src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathLibraryIDNormalizer.h (1)

37-69: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add @param tags for the exp parameters.

Both methods document @p exp in prose but declare no parameter tag. The project Doxygen rule requires parameter tags with a direction. Use @param[in,out] exp for normalizeSourceIDs and @param[in] exp for validateCanonicalIDs.

📝 Proposed doc addition
       `@throws` Exception::InvalidValue If a compound ID is empty/duplicated or a transition
               references an unknown/empty compound ID.
+
+      `@param`[in,out] exp Experiment whose precursor/transition identifiers are canonicalized in place.
     */
     static void normalizeSourceIDs(OpenSwath::LightTargetedExperiment& exp);
       `@throws` Exception::InvalidValue If any canonical-ID invariant is violated.
+
+      `@param`[in] exp Experiment to validate.
     */
     static void validateCanonicalIDs(const OpenSwath::LightTargetedExperiment& exp);

As per coding guidelines: "Doxygen comments must use /** */ with @ tags; @brief is required, parameter tags must use [in], [out], or [in,out]".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathLibraryIDNormalizer.h`
around lines 37 - 69, Add Doxygen parameter tags to the comments for
normalizeSourceIDs and validateCanonicalIDs: document exp as `@param`[in,out] for
normalizeSourceIDs and `@param`[in] for validateCanonicalIDs, preserving the
existing descriptions.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/tests/class_tests/openms/source/TransitionParquetFile_test.cpp`:
- Around line 294-305: The TransitionParquetFile tests do not fully verify
canonical persistent precursor IDs after serialization and round-trip loading.
In src/tests/class_tests/openms/source/TransitionParquetFile_test.cpp lines
294-305, assert that compound_refs.size() equals expected_precursor_ids.size()
after the existing membership checks; in lines 345-361, validate roundtrip_exp
with OpenSwathLibraryIDNormalizer::validateCanonicalIDs after the round trip.

---

Outside diff comments:
In `@src/openms/source/ANALYSIS/OPENSWATH/TransitionParquetFile.cpp`:
- Around line 271-300: Update the precursor insertion logic using the
`precursor_map.emplace` result: detect an existing `precursor_id` and throw
`Exception::InvalidValue` instead of silently retaining the first row. Add a
regression test covering two precursor rows with the same ID, ensuring
duplicates are rejected before
`OpenSwathLibraryIDNormalizer::validateCanonicalIDs`.

---

Nitpick comments:
In `@src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathLibraryIDNormalizer.h`:
- Around line 37-69: Add Doxygen parameter tags to the comments for
normalizeSourceIDs and validateCanonicalIDs: document exp as `@param`[in,out] for
normalizeSourceIDs and `@param`[in] for validateCanonicalIDs, preserving the
existing descriptions.

In `@src/openms/source/ANALYSIS/OPENSWATH/OpenSwathLibraryIDNormalizer.cpp`:
- Around line 26-29: Update throwInvalidID_ to accept caller-provided file,
line, and function context, and use those values when constructing
Exception::InvalidValue. Update every call site to forward __FILE__, __LINE__,
and OPENMS_PRETTY_FUNCTION before the existing message and value arguments,
preserving the current validation behavior.
- Around line 94-139: Track how many source compounds are skipped in the
normalization loop of OpenSwathLibraryIDNormalizer, then emit an OpenMS debug or
info message via LogStream reporting that dropped count after normalization. Add
the OpenMS LogStream header and preserve the existing filtering behavior and
compound ID canonicalization.
- Around line 61-72: Replace per-row ID value copies with const-reference
bindings throughout the affected loops in OpenSwathLibraryIDNormalizer,
including the compound/transition handling and validateCanonicalIDs. Update
source_id and the corresponding ID locals at the referenced locations to bind
directly to the existing string values while preserving all validation and
normalization behavior.

In `@src/tests/class_tests/openms/source/OpenSwathLibraryIDNormalizer_test.cpp`:
- Around line 169-209: Extend the validateCanonicalIDs test section with a case
that duplicates an existing compound precursor ID in valid.compounds and asserts
OpenSwathLibraryIDNormalizer::validateCanonicalIDs throws
Exception::InvalidValue. Keep the existing duplicate_transition case unchanged
so precursor and transition uniqueness are tested separately.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a45bb2f1-aeb4-4e30-bbc5-18be4fdc4876

📥 Commits

Reviewing files that changed from the base of the PR and between 1640a43 and 1adf5bd.

⛔ Files ignored due to path filters (2)
  • src/tests/topp/OpenSwathDecoyGenerator_parquet_output.tsv is excluded by !**/*.tsv
  • src/tests/topp/OpenSwathWorkflow_1_output.xic.tsv is excluded by !**/*.tsv
📒 Files selected for processing (37)
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathLibraryIDNormalizer.h
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/TransitionPQPFile.h
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/TransitionParquetFile.h
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/sources.cmake
  • src/openms/include/OpenMS/APPLICATIONS/OpenSwathBase.h
  • src/openms/source/ANALYSIS/OPENSWATH/OpenSwathLibraryIDNormalizer.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/TransitionParquetFile.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/sources.cmake
  • src/openms/source/APPLICATIONS/OpenSwathBase.cpp
  • src/tests/class_tests/openms/executables.cmake
  • src/tests/class_tests/openms/source/OpenSwathLibraryIDNormalizer_test.cpp
  • src/tests/class_tests/openms/source/TransitionPQPFile_test.cpp
  • src/tests/class_tests/openms/source/TransitionParquetFile_test.cpp
  • src/tests/topp/OpenSwathWorkflow_15_output.chrom.mzML
  • src/tests/topp/OpenSwathWorkflow_15_output.featureXML
  • src/tests/topp/OpenSwathWorkflow_16_output.chrom.mzML
  • src/tests/topp/OpenSwathWorkflow_16_output.featureXML
  • src/tests/topp/OpenSwathWorkflow_17_output.chrom.mzML
  • src/tests/topp/OpenSwathWorkflow_17_output.featureXML
  • src/tests/topp/OpenSwathWorkflow_18_output.featureXML
  • src/tests/topp/OpenSwathWorkflow_19_output.featureXML
  • src/tests/topp/OpenSwathWorkflow_1_output.chrom.mzML
  • src/tests/topp/OpenSwathWorkflow_1_output.featureXML
  • src/tests/topp/OpenSwathWorkflow_20_output.featureXML
  • src/tests/topp/OpenSwathWorkflow_21_output.featureXML
  • src/tests/topp/OpenSwathWorkflow_22_output.chrom.mzML
  • src/tests/topp/OpenSwathWorkflow_22_output.featureXML
  • src/tests/topp/OpenSwathWorkflow_23_output.chrom.mzML
  • src/tests/topp/OpenSwathWorkflow_23_output.featureXML
  • src/tests/topp/OpenSwathWorkflow_24_output.featureXML
  • src/tests/topp/OpenSwathWorkflow_25_output.featureXML
  • src/tests/topp/OpenSwathWorkflow_27_expected.featureXML
  • src/tests/topp/OpenSwathWorkflow_2_output.chrom.mzML
  • src/tests/topp/OpenSwathWorkflow_2_output.featureXML
  • src/tests/topp/OpenSwathWorkflow_3_output.chrom.mzML
  • src/tests/topp/OpenSwathWorkflow_3_output.featureXML
  • src/tests/topp/OpenSwathWorkflow_threads_output.featureXML

Copy link
Copy Markdown
Contributor

Hi @singjc — thanks for working on this. I reviewed the current head, 294e4a4074. Could you please double-check the following interactions? I may be missing intended sequencing, but the first three look unsafe if the writer/remapping follow-up lands separately from this ingestion change.

  1. The legacy TSV → OSW remapping path can collapse numeric source IDs.

    OpenSwathBase.cpp now canonicalizes TSV/TraML IDs immediately after loading, but src/topp/OpenSwathWorkflow.cpp:1216-1244 still treats the resulting IDs as source TraML IDs and maps them through getPQPIDToTraMLIDMap().

    For example, source precursor IDs "1" and "2" canonicalize to "0" and "1". The later map is keyed by the original IDs, so its "1" -> "0" entry remaps the already-canonical second precursor from "1" to "0", collapsing both precursors. Numeric source transition names can collapse the same way. Because validation runs before this remap, this is silent.

    Could the stale remap be removed (or the generated PQP reloaded) in this PR, with a TSV → OSW regression using numeric source IDs?

  2. The OSWPQ writers still create a different ID domain from XIC output.

    The normalizer assigns zero-based precursor/transition IDs (OpenSwathLibraryIDNormalizer.cpp:89-92,141-154), and MSChromatogramParquetConsumer preserves numeric zero. In contrast, both TransitionParquetFile.cpp:399-440,570-580 and OpenSwathOSWParquetWriter.cpp:412-465 start at 1 and reject/remap <= 0.

    OpenSwathWorkflow permits simultaneous .xic and .oswpq output. With precursors A and B, XIC records them as IDs 0 and 1, while the OSWPQ library records them as 1 and 2. ID 1 therefore denotes B in XIC but A in OSWPQ; transitions have the same shift. That appears to reintroduce the unsafe cross-output joins this PR is intended to remove.

    Could writer-side ID preservation be made atomic with canonicalization, and covered by a cross-output identity test?

  3. Canonicalization removes source-ID decoy semantics before downstream filtering.

    OpenSwathLibraryIDNormalizer.cpp:153-154 overwrites DECOY_* precursor references and transition names. The workflow and both transition-list evidence filters still explicitly use these prefixes for decoy detection/pairing, including the default keep_matching behavior.

    If a source format omits an explicit decoy field and relies on the prefix, the normalized entry can become a target. Even when the decoy flag is explicit, matching a target/decoy pair by source ID is no longer possible unless a source→canonical map is retained and supplied. Could decoy status/pairing be materialized before IDs are overwritten (or the provenance map be preserved), with prefixed-decoy filtering regressions?

  4. Duplicate OSWPQ precursor IDs are silently collapsed at the reader boundary.

    TransitionParquetFile.cpp:262-275 inserts precursor rows into an unordered_map<int64_t, PrecursorInfo> but ignores the result of emplace. A second row with the same precursor_id is discarded, and all transitions then bind to the first row's metadata. The later canonical validation only sees the collapsed experiment.

    Direct callers such as OpenSwathAssayGenerator, OpenSwathDecoyGenerator, and TargetedFileConverter use this reader without going through TOPPOpenSwathBase, so reader-boundary validation would also protect those paths. Could duplicate IDs be rejected here by checking emplace().second, followed by full canonical validation before returning?

The current Build and Test and pyOpenMS wheel workflows are green, but I could not find regressions covering numeric-ID TSV → OSW conversion, simultaneous XIC/OSWPQ identity, or prefixed decoys through canonicalization.

@singjc

singjc commented Aug 9, 2026

Copy link
Copy Markdown
Contributor Author
  • Removed the post-load TSV->PQP ID remapping and added a regression for numeric source IDs.
  • PQP/OSWPQ now preserve canonical precursor/transition IDs instead of creating a separate 1-based ID domain.
  • Kept source-ID provenance for prefix-based decoy detection and keep_matching, with a regression for prefix-only decoys.
  • OSWPQ now rejects duplicate precursor_id values and validates canonical IDs on read.

I also kept the existing public overloads for compatibility.

@singjc singjc changed the title [FIX] OpenSWATH: canonicalize library IDs at ingestion [FIX] OpenSWATH: canonicalize and preserve library IDs across outputs Aug 9, 2026

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/openms/include/OpenMS/APPLICATIONS/OpenSwathBase.h (1)

205-233: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Attach the detailed Doxygen block to the overload that has source_ids.

The block at lines 205-221 documents @param[out] source_ids, but it closes before line 222 and therefore applies to the three-argument overload at lines 223-226. That overload has no source_ids parameter, so Doxygen reports an undocumented/unknown parameter, and the canonical four-argument overload keeps only a one-line comment.

Move the block to the four-argument declaration and give the compatibility overload a short brief.

📝 Proposed documentation fix
-     * `@param`[in] tr_type Input file type
-     * `@param`[in] tr_file Input file name
-     * `@param`[in] tsv_reader_param Parameters on how to interpret spectral data
-     * `@param`[out] source_ids Optional source-precursor provenance mapping. For TraML/TSV
-     *             this is captured during canonicalization; for PQP/OSWPQ it is reconstructed
-     *             from persistent TRAML_ID metadata when available.
-     *
-     */
-    /// Compatibility overload retaining the existing three-argument API.
-    OpenSwath::LightTargetedExperiment loadTransitionList(
-      const FileTypes::Type& tr_type,
-      const std::string& tr_file,
-      const Param& tsv_reader_param);
-
-    /// Canonical-loading path that additionally returns source-ID provenance.
-    OpenSwath::LightTargetedExperiment loadTransitionList(
-      const FileTypes::Type& tr_type,
-      const std::string& tr_file,
-      const Param& tsv_reader_param,
-      OpenSwathLibraryIDNormalizer::SourceIDMapping* source_ids);
+     * `@param`[in] tr_type Input file type
+     * `@param`[in] tr_file Input file name
+     * `@param`[in] tsv_reader_param Parameters on how to interpret spectral data
+     */
+    /// Compatibility overload retaining the existing three-argument API.
+    OpenSwath::LightTargetedExperiment loadTransitionList(
+      const FileTypes::Type& tr_type,
+      const std::string& tr_file,
+      const Param& tsv_reader_param);
+
+    /**
+     * `@brief` Canonical-loading path that additionally returns source-ID provenance.
+     *
+     * `@param`[in] tr_type Input file type
+     * `@param`[in] tr_file Input file name
+     * `@param`[in] tsv_reader_param Parameters on how to interpret spectral data
+     * `@param`[out] source_ids Optional source-precursor provenance mapping. For TraML/TSV
+     *             this is captured during canonicalization; for PQP/OSWPQ it is reconstructed
+     *             from persistent TRAML_ID metadata when available.
+     */
+    OpenSwath::LightTargetedExperiment loadTransitionList(
+      const FileTypes::Type& tr_type,
+      const std::string& tr_file,
+      const Param& tsv_reader_param,
+      OpenSwathLibraryIDNormalizer::SourceIDMapping* source_ids);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/include/OpenMS/APPLICATIONS/OpenSwathBase.h` around lines 205 -
233, Move the detailed Doxygen block describing canonicalization and source-ID
provenance so it directly documents the four-argument loadTransitionList
overload with OpenSwathLibraryIDNormalizer::SourceIDMapping* source_ids. Replace
the current detailed block above the three-argument compatibility overload with
a brief compatibility `@brief`, leaving the declarations and behavior unchanged.

Source: Coding guidelines

src/openms/include/OpenMS/ANALYSIS/OPENSWATH/TransitionParquetFile.h (1)

120-142: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Doxygen blocks bind to the compatibility overload, not to the overload that declares source_ids. Each of these three APIs adds a compatibility overload ahead of the new overload that owns source_ids, while the existing /** */ block stays in place. Doxygen attaches a block to the declaration that follows it, so every block now documents a parameter its target overload does not have.

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/TransitionParquetFile.h#L120-L142: move the reader block onto the three-argument convertParquetToTargetedExperiment, and leave a /// brief on the two-argument overload.
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/TransitionParquetFile.h#L153-L170: move the writer block onto the three-argument convertLightTargetedExperimentToParquet, and leave a /// brief on the two-argument overload.
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathOSWParquetWriter.h#L69-L91: move the block onto the seven-argument write, and additionally add @throws Exception::InvalidValue for the new validateCanonicalIDs(assay_library) precondition that both overloads now enforce.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/include/OpenMS/ANALYSIS/OPENSWATH/TransitionParquetFile.h` around
lines 120 - 142, Correct Doxygen attachment for all three overload pairs: in
src/openms/include/OpenMS/ANALYSIS/OPENSWATH/TransitionParquetFile.h:120-142,
move the reader documentation block to the three-argument
convertParquetToTargetedExperiment and leave only a /// brief on the
two-argument overload; in
src/openms/include/OpenMS/ANALYSIS/OPENSWATH/TransitionParquetFile.h:153-170, do
the same for convertLightTargetedExperimentToParquet, attaching the block to its
three-argument overload; in
src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathOSWParquetWriter.h:69-91,
attach the block to the seven-argument write overload and document that both
overloads can throw Exception::InvalidValue when
validateCanonicalIDs(assay_library) fails.

Source: Coding guidelines

🧹 Nitpick comments (12)
src/topp/OpenSwathWorkflow.cpp (1)

607-616: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Duplicated mapsToSelectedTarget_ helper in two TOPP tools. Both files define the same static wrapper around OpenSwathLibraryIDNormalizer::canonicalTargetForDecoyPrecursor; the shared root cause is that the wrapper was added per tool instead of to the normalizer.

  • src/topp/OpenSwathWorkflow.cpp#L607-L616: remove the local wrapper and call OpenSwathLibraryIDNormalizer::canonicalTargetForDecoyPrecursor directly at line 682, or use a shared helper.
  • src/topp/TransitionListEvidenceFilter.cpp#L386-L395: remove the identical local wrapper and use the same shared helper at line 435.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/topp/OpenSwathWorkflow.cpp` around lines 607 - 616, The duplicated
mapsToSelectedTarget_ wrappers should be removed from
src/topp/OpenSwathWorkflow.cpp lines 607-616 and
src/topp/TransitionListEvidenceFilter.cpp lines 386-395. Update the call sites
in OpenSwathWorkflow.cpp around line 682 and TransitionListEvidenceFilter.cpp
around line 435 to invoke
OpenSwathLibraryIDNormalizer::canonicalTargetForDecoyPrecursor directly, or
replace both with one shared helper.
src/tests/topp/CMakeLists.txt (1)

2245-2315: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

The paired comparison cannot detect a collapse that affects both output paths.

TOPP_OpenSwathWorkflow_numeric_ids_osw_identity compares two produced files. It proves that the featureXML path and the OSW path agree. If a future change collapsed numeric source IDs in loadTransitionList itself, both paths would collapse in the same way and the test would still pass.

Consider adding one committed reference for OpenSwathWorkflow_numeric_ids_featurexml.tmp.xic.tsv so the absolute identifier values are pinned as well.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/tests/topp/CMakeLists.txt` around lines 2245 - 2315, The regression test
only compares featureXML and OSW outputs, so shared incorrect numeric-ID
canonicalization could go undetected. Add a committed golden reference for
OpenSwathWorkflow_numeric_ids_featurexml.tmp.xic.tsv and a corresponding
diff-based CMake test, anchored to
TOPP_OpenSwathWorkflow_numeric_ids_featurexml_xic_text, to assert the absolute
identifier values while retaining the existing cross-path comparison.
src/topp/TargetedFileConverter.cpp (1)

160-208: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider filtering empty source IDs from precursor_canonical_to_source as well.

Lines 172-188 keep every canonical -> source precursor entry, including entries whose TRAML_ID is empty. Lines 191-202 erase the empty entries from the transition map. The two maps therefore follow different rules.

An empty source value cannot match a decoy prefix and is written back as an absent traml_id, so behavior is correct today. Making both maps drop empty values keeps the provenance contract uniform for later consumers.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/topp/TargetedFileConverter.cpp` around lines 160 - 208, Filter empty
source IDs from precursor_canonical_to_source in the persistent PQP handling
alongside transition_canonical_to_source. Remove entries with empty values
before building precursor_source_to_canonical, while preserving
duplicate-mapping validation for remaining entries so both provenance maps
follow the same contract.
src/tests/class_tests/openms/source/OpenSwathLibraryIDNormalizer_test.cpp (2)

182-182: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Rename the section to reflect what it tests.

The section name is a normalizeSourceIDs signature, but the body also tests materializeDecoyPrefix and canonicalTargetForDecoyPrecursor. Use an [EXTRA] section name that names the behaviour, as the other files in this PR do.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/tests/class_tests/openms/source/OpenSwathLibraryIDNormalizer_test.cpp` at
line 182, Rename the START_SECTION label for the test covering
normalizeSourceIDs, materializeDecoyPrefix, and canonicalTargetForDecoyPrecursor
to an [EXTRA] behavior-focused name describing preservation of source-prefix
decoy semantics, rather than presenting it as only a normalizeSourceIDs
signature test.

232-247: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for the empty-mapping compatibility fallback.

The tests exercise only the provenance-backed path of canonicalTargetForDecoyPrecursor. The fallback branch, which fires when both precursor maps are empty and returns a stripped source ID, has no coverage. That branch carries the mixed return-domain risk. Add a case with a default-constructed SourceIDMapping.

💚 Proposed test addition
   TEST_EQUAL(OpenSwathLibraryIDNormalizer::canonicalTargetForDecoyPrecursor(
                canonical_target, source_ids, "DECOY_").has_value(),
              false)
+
+  // Compatibility path: no provenance available, so source IDs are accepted directly.
+  const OpenSwathLibraryIDNormalizer::SourceIDMapping empty_ids;
+  const auto fallback_target = OpenSwathLibraryIDNormalizer::canonicalTargetForDecoyPrecursor(
+    "DECOY_PEPTIDE", empty_ids, "DECOY_");
+  TEST_EQUAL(fallback_target.has_value(), true)
+  TEST_EQUAL(*fallback_target, "PEPTIDE")
+
+  // An empty prefix never pairs, regardless of provenance.
+  TEST_EQUAL(OpenSwathLibraryIDNormalizer::canonicalTargetForDecoyPrecursor(
+               canonical_decoy, source_ids, "").has_value(),
+             false)
 }

As per path instructions "Write unit tests for new functionality and ensure existing tests pass before suggesting changes".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/tests/class_tests/openms/source/OpenSwathLibraryIDNormalizer_test.cpp`
around lines 232 - 247, Extend the existing canonicalTargetForDecoyPrecursor
tests with a default-constructed SourceIDMapping whose precursor maps are empty,
and verify the compatibility fallback returns the expected stripped source ID
for a decoy precursor. Keep the existing provenance-backed assertions unchanged
and cover the fallback’s source-ID return domain.

Source: Path instructions

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

509-510: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use a lookup instead of operator[] for consistency.

compound_decoy[compound.id] default-inserts false for every compound without a decoy transition, growing the map during a read-only pass. The result is correct, but Lines 532-540 in this same function explicitly avoid operator[] on precursor_mz for exactly this reason. Align the two.

♻️ Proposed change
-      const bool is_decoy = compound_decoy[compound.id];
+      const auto decoy_it = compound_decoy.find(compound.id);
+      const bool is_decoy = decoy_it != compound_decoy.end() && decoy_it->second;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/source/ANALYSIS/OPENSWATH/TransitionParquetFile.cpp` around lines
509 - 510, Update the compound_decoy access in the surrounding
transition-processing function to use a non-mutating lookup instead of
operator[], matching the existing precursor_mz handling at lines 532-540.
Preserve false for compounds without a decoy entry while avoiding insertion into
compound_decoy during the read-only pass.

384-392: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider matching the precursor path's duplicate diagnostics.

The precursor loop at Lines 290-317 rejects duplicate IDs and ambiguous provenance with table-specific messages. This transition loop ignores the emplace result. Duplicate transition_id values are still caught, but only later by validateCanonicalIDs at Line 415, with the generic message "Canonical transition IDs must be unique" and no mention of the OSWPQ transition table. Adding a check here would make corrupt-input diagnostics symmetric.

If you rely on validateCanonicalIDs on purpose, add a short comment stating that.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/source/ANALYSIS/OPENSWATH/TransitionParquetFile.cpp` around lines
384 - 392, Update the transition loop around transition_name and source_ids to
inspect the result of inserting into transition_canonical_to_source, matching
the precursor loop’s duplicate and ambiguous-provenance diagnostics with
transition-table-specific messages. Preserve the existing mapping for unique
IDs, and ensure duplicate transition IDs or conflicting source IDs are rejected
at this point; alternatively, document explicitly why validateCanonicalIDs
remains the intended check.
src/openms/source/ANALYSIS/OPENSWATH/OpenSwathLibraryIDNormalizer.cpp (2)

31-34: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider exposing the conventional decoy-prefix check instead of duplicating it.

The same prefix list (DECOY/Decoy/decoy) also exists in hasDecoyPrefix_ in src/topp/OpenSwathWorkflow.cpp and src/topp/TransitionListEvidenceFilter.cpp. Three copies can diverge when the list changes. Consider promoting this helper to a public static on OpenSwathLibraryIDNormalizer and calling it from both TOPP helpers.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/source/ANALYSIS/OPENSWATH/OpenSwathLibraryIDNormalizer.cpp` around
lines 31 - 34, Promote hasConventionalDecoyPrefix_ into a public static method
on OpenSwathLibraryIDNormalizer, preserving its DECOY/Decoy/decoy matching
behavior. Update hasDecoyPrefix_ in OpenSwathWorkflow.cpp and
TransitionListEvidenceFilter.cpp to call this shared method instead of
duplicating the prefix list.

166-177: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Avoid the per-transition string copies in the hot loop.

source_transition_id and canonical_transition_id are copied into emplace and then the same values are assigned again. For libraries with millions of transitions this adds avoidable allocations. Move the source ID into the map and move the canonical ID into transition_name.

♻️ Proposed change
-      const std::string source_transition_id = transition.transition_name;
+      std::string source_transition_id = transition.transition_name;
       if (!transition.getDecoy() &&
           (hasConventionalDecoyPrefix_(source_ref) || hasConventionalDecoyPrefix_(source_transition_id)))
       {
         transition.setDecoy(true);
       }
 
-      const std::string canonical_transition_id = StringUtils::toStr(static_cast<int64_t>(i));
-      source_ids.transition_canonical_to_source.emplace(canonical_transition_id, source_transition_id);
+      std::string canonical_transition_id = StringUtils::toStr(static_cast<int64_t>(i));
+      source_ids.transition_canonical_to_source.emplace(canonical_transition_id, std::move(source_transition_id));
       transition.peptide_ref = precursor_it->second;
-      transition.transition_name = canonical_transition_id;
+      transition.transition_name = std::move(canonical_transition_id);
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/source/ANALYSIS/OPENSWATH/OpenSwathLibraryIDNormalizer.cpp` around
lines 166 - 177, Update the transition-processing loop around
source_transition_id and canonical_transition_id to move these strings into
source_ids.transition_canonical_to_source and transition.transition_name,
respectively, instead of copying them during emplace and assignment. Preserve
the existing mapping and canonical naming behavior.
src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathLibraryIDNormalizer.h (1)

104-118: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add @param[in] tags to match the sibling declaration.

materializeDecoyPrefix above documents each parameter with a direction tag. This block describes the parameters only in prose. Add explicit tags for decoy_ref, source_ids, and decoy_prefix.

As per coding guidelines "parameter tags must use [in], [out], or [in,out]".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathLibraryIDNormalizer.h`
around lines 104 - 118, Update the canonicalTargetForDecoyPrecursor
documentation to add `@param`[in] tags for decoy_ref, source_ids, and
decoy_prefix, while preserving the existing descriptions and return
documentation.

Source: Coding guidelines

src/openms/source/ANALYSIS/OPENSWATH/TransitionPQPFile.cpp (1)

1134-1156: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Restrict tableName to a known set before interpolating it into SQL.

tableName is concatenated into the query at Line 1143. SQLite cannot bind an identifier as a parameter, so the only safe option is a whitelist. Every current caller passes the literal "PRECURSOR" or "TRANSITION", so this is not exploitable today, but the method is public and the class was already hardened against SQL injection in the library string fields (GH #9730 / #9734). getPQPIDToTraMLIDMap at Line 1115 has the same shape; fixing both keeps the boundary consistent.

Also finalize stmt on the exception path. If Sql::extractValue throws, the statement at Line 1140 leaks until the connection closes.

🔒️ Proposed hardening
   std::unordered_map<std::string, std::string> TransitionPQPFile::getPQPCurrentIDToTraMLIDMap(
     const char* filename,
     const std::string& tableName)
   {
+    if (tableName != "PRECURSOR" && tableName != "TRANSITION")
+    {
+      throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
+                                       "Unsupported PQP table name: " + tableName);
+    }
     SqliteConnector conn(filename);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/source/ANALYSIS/OPENSWATH/TransitionPQPFile.cpp` around lines 1134
- 1156, Update getPQPCurrentIDToTraMLIDMap and getPQPIDToTraMLIDMap to validate
tableName against the allowed PRECURSOR and TRANSITION identifiers before
constructing SQL, rejecting any other value. Ensure both methods finalize their
prepared statements on all paths, including exceptions thrown by
Sql::extractValue, while preserving the existing result mapping behavior.
src/tests/class_tests/openms/source/TransitionPQPFile_test.cpp (1)

267-311: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the decoy outcome that the DECOY_ fixture names imply.

Lines 268-270 use DECOY_source_B and DECOY_source_tr_B, but no assertion checks a decoy flag. The section verifies IDs and provenance only, so the prefixed names imply coverage that is absent.

Canonicalization strips the source prefix from the operational IDs. Prefix-based decoy resolution therefore depends on OpenSwathLibraryIDNormalizer::materializeDecoyPrefix plus the provenance map. Call it on the round-tripped experiment with "DECOY_" and assert that the transition mapped to precursor "7" is a decoy while the one mapped to "0" is not.

Do you want me to write this assertion block?

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/tests/class_tests/openms/source/TransitionPQPFile_test.cpp` around lines
267 - 311, The round-trip test lacks assertions for decoy status despite using
DECOY_ source fixtures. After validateCanonicalIDs(roundtrip), call
OpenSwathLibraryIDNormalizer::materializeDecoyPrefix on roundtrip with "DECOY_"
and assert that the transition whose peptide_ref is "7" is marked decoy, while
the transition mapped to "0" is not.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@CHANGELOG`:
- Line 471: Expand the CHANGELOG entry for “Canonicalize and preserve library
IDs across outputs (`#9888`)” to explicitly state that operational chromatogram,
precursor, and transition IDs for TraML/TSV inputs may change across releases,
following the neighboring entries’ user-visible change notation.

In `@src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathLibraryIDNormalizer.h`:
- Line 84: Update the Doxygen block for
OpenSwathLibraryIDNormalizer::normalizeSourceIDs to add an `@return` description
for SourceIDMapping, stating that the provenance maps cover all source
compounds, including compounds dropped from the operational experiment.

In `@src/openms/include/OpenMS/ANALYSIS/OPENSWATH/TransitionPQPFile.h`:
- Around line 269-290: Split the Doxygen documentation so each
convertLightTargetedExperimentToPQP overload has its own /** */ block: document
the two-argument compatibility overload without source_ids, and document the
three-argument canonical overload with the source_ids parameter and canonical-ID
contract. Apply the same correction to convertParquetToTargetedExperiment and
convertLightTargetedExperimentToParquet, ensuring each block has `@brief` and
correctly tagged [in] parameters.
- Around line 319-331: Validate tableName at the start of both
getPQPIDToTraMLIDMap() and getPQPCurrentIDToTraMLIDMap(), accepting only
PRECURSOR or TRANSITION and rejecting other values before constructing or
preparing the SQL statement. Document this rejection in each accessor’s `@throws`
or `@exception` documentation.

In `@src/openms/source/ANALYSIS/OPENSWATH/OpenSwathOSWParquetWriter.cpp`:
- Around line 382-412: The existing ID reads in the precursor and transition
validation loops incorrectly pass allow_null=false, causing null values to throw
before the intended validation. Update the getInt64 calls for PRECURSOR_ID and
TRANSITION_ID in the existing_precursor_ids and existing_transition_refs checks
to allow nulls and retain the -1 fallback, then explicitly reject null IDs at
this location with the appropriate null-ID error before duplicate or
canonical-ID validation.

In `@src/openms/source/ANALYSIS/OPENSWATH/TransitionParquetFile.cpp`:
- Around line 418-438: Add a non-throwing
OpenSwathLibraryIDNormalizer::hasCanonicalIDs predicate that checks the same
invariant as validateCanonicalIDs, then update both
TransitionParquetFile::convertLightTargetedExperimentToParquet and
TransitionPQPFile::convertLightTargetedExperimentToPQP to branch on it. Preserve
canonical experiments unchanged, normalize only non-canonical source-style
experiments, and allow malformed canonical inputs to be rejected rather than
silently renumbered; remove the exception-based fallback.

In `@src/openms/source/ANALYSIS/OPENSWATH/TransitionPQPFile.cpp`:
- Around line 1189-1205: Restrict the try/catch in the LightTargetedExperiment
conversion flow to OpenSwathLibraryIDNormalizer::validateCanonicalIDs only;
perform convertLightTargetedExperimentToPQP exactly once after validation
succeeds so write-time Exception::InvalidValue errors propagate unchanged. Apply
the same structure to
TransitionParquetFile::convertLightTargetedExperimentToParquet, preserving
fallback normalization only when validation itself fails.

In `@src/openms/source/APPLICATIONS/OpenSwathBase.cpp`:
- Around line 496-529: Filter empty source IDs from
precursor_canonical_to_source before retaining the map, matching the existing
cleanup of transition_canonical_to_source. Update the precursor-map construction
around getPQPCurrentIDToTraMLIDMap and preserve only entries with non-empty
source IDs, while still building precursor_source_to_canonical and detecting
conflicting non-empty mappings.

In `@src/tests/class_tests/openms/source/OpenSwathOSWParquetWriter_test.cpp`:
- Around line 14-21: Add the direct header include that declares
OpenSwathLibraryIDNormalizer to OpenSwathOSWParquetWriter_test.cpp, alongside
the existing OpenMS includes, so validateCanonicalIDs resolves without relying
on transitive includes.

In `@src/tests/class_tests/openms/source/TransitionParquetFile_test.cpp`:
- Around line 319-342: Update the duplicate fixture setup around
duplicate_precursors_table and transitions_table so every transition in the
duplicate archive references precursor ID 1. Preserve the original
transitions_table for other tests, and create or adjust a duplicate-specific
transition table before writing transitions.parquet, ensuring the duplicate
precursor ID is the only invalid condition exercised.

In `@src/topp/OpenSwathWorkflow.cpp`:
- Around line 1156-1179: Replace the unchecked raw-stream copy in the PQP branch
of the OSW conversion flow with std::filesystem::copy_file, preserving overwrite
behavior and allowing copy failures to throw immediately. Alternatively,
validate both input and output streams and throw Exception::FileNotWritable on
open or write failure before OpenSwathOSWWriter is invoked.

---

Outside diff comments:
In `@src/openms/include/OpenMS/ANALYSIS/OPENSWATH/TransitionParquetFile.h`:
- Around line 120-142: Correct Doxygen attachment for all three overload pairs:
in src/openms/include/OpenMS/ANALYSIS/OPENSWATH/TransitionParquetFile.h:120-142,
move the reader documentation block to the three-argument
convertParquetToTargetedExperiment and leave only a /// brief on the
two-argument overload; in
src/openms/include/OpenMS/ANALYSIS/OPENSWATH/TransitionParquetFile.h:153-170, do
the same for convertLightTargetedExperimentToParquet, attaching the block to its
three-argument overload; in
src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathOSWParquetWriter.h:69-91,
attach the block to the seven-argument write overload and document that both
overloads can throw Exception::InvalidValue when
validateCanonicalIDs(assay_library) fails.

In `@src/openms/include/OpenMS/APPLICATIONS/OpenSwathBase.h`:
- Around line 205-233: Move the detailed Doxygen block describing
canonicalization and source-ID provenance so it directly documents the
four-argument loadTransitionList overload with
OpenSwathLibraryIDNormalizer::SourceIDMapping* source_ids. Replace the current
detailed block above the three-argument compatibility overload with a brief
compatibility `@brief`, leaving the declarations and behavior unchanged.

---

Nitpick comments:
In `@src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathLibraryIDNormalizer.h`:
- Around line 104-118: Update the canonicalTargetForDecoyPrecursor documentation
to add `@param`[in] tags for decoy_ref, source_ids, and decoy_prefix, while
preserving the existing descriptions and return documentation.

In `@src/openms/source/ANALYSIS/OPENSWATH/OpenSwathLibraryIDNormalizer.cpp`:
- Around line 31-34: Promote hasConventionalDecoyPrefix_ into a public static
method on OpenSwathLibraryIDNormalizer, preserving its DECOY/Decoy/decoy
matching behavior. Update hasDecoyPrefix_ in OpenSwathWorkflow.cpp and
TransitionListEvidenceFilter.cpp to call this shared method instead of
duplicating the prefix list.
- Around line 166-177: Update the transition-processing loop around
source_transition_id and canonical_transition_id to move these strings into
source_ids.transition_canonical_to_source and transition.transition_name,
respectively, instead of copying them during emplace and assignment. Preserve
the existing mapping and canonical naming behavior.

In `@src/openms/source/ANALYSIS/OPENSWATH/TransitionParquetFile.cpp`:
- Around line 509-510: Update the compound_decoy access in the surrounding
transition-processing function to use a non-mutating lookup instead of
operator[], matching the existing precursor_mz handling at lines 532-540.
Preserve false for compounds without a decoy entry while avoiding insertion into
compound_decoy during the read-only pass.
- Around line 384-392: Update the transition loop around transition_name and
source_ids to inspect the result of inserting into
transition_canonical_to_source, matching the precursor loop’s duplicate and
ambiguous-provenance diagnostics with transition-table-specific messages.
Preserve the existing mapping for unique IDs, and ensure duplicate transition
IDs or conflicting source IDs are rejected at this point; alternatively,
document explicitly why validateCanonicalIDs remains the intended check.

In `@src/openms/source/ANALYSIS/OPENSWATH/TransitionPQPFile.cpp`:
- Around line 1134-1156: Update getPQPCurrentIDToTraMLIDMap and
getPQPIDToTraMLIDMap to validate tableName against the allowed PRECURSOR and
TRANSITION identifiers before constructing SQL, rejecting any other value.
Ensure both methods finalize their prepared statements on all paths, including
exceptions thrown by Sql::extractValue, while preserving the existing result
mapping behavior.

In `@src/tests/class_tests/openms/source/OpenSwathLibraryIDNormalizer_test.cpp`:
- Line 182: Rename the START_SECTION label for the test covering
normalizeSourceIDs, materializeDecoyPrefix, and canonicalTargetForDecoyPrecursor
to an [EXTRA] behavior-focused name describing preservation of source-prefix
decoy semantics, rather than presenting it as only a normalizeSourceIDs
signature test.
- Around line 232-247: Extend the existing canonicalTargetForDecoyPrecursor
tests with a default-constructed SourceIDMapping whose precursor maps are empty,
and verify the compatibility fallback returns the expected stripped source ID
for a decoy precursor. Keep the existing provenance-backed assertions unchanged
and cover the fallback’s source-ID return domain.

In `@src/tests/class_tests/openms/source/TransitionPQPFile_test.cpp`:
- Around line 267-311: The round-trip test lacks assertions for decoy status
despite using DECOY_ source fixtures. After validateCanonicalIDs(roundtrip),
call OpenSwathLibraryIDNormalizer::materializeDecoyPrefix on roundtrip with
"DECOY_" and assert that the transition whose peptide_ref is "7" is marked
decoy, while the transition mapped to "0" is not.

In `@src/tests/topp/CMakeLists.txt`:
- Around line 2245-2315: The regression test only compares featureXML and OSW
outputs, so shared incorrect numeric-ID canonicalization could go undetected.
Add a committed golden reference for
OpenSwathWorkflow_numeric_ids_featurexml.tmp.xic.tsv and a corresponding
diff-based CMake test, anchored to
TOPP_OpenSwathWorkflow_numeric_ids_featurexml_xic_text, to assert the absolute
identifier values while retaining the existing cross-path comparison.

In `@src/topp/OpenSwathWorkflow.cpp`:
- Around line 607-616: The duplicated mapsToSelectedTarget_ wrappers should be
removed from src/topp/OpenSwathWorkflow.cpp lines 607-616 and
src/topp/TransitionListEvidenceFilter.cpp lines 386-395. Update the call sites
in OpenSwathWorkflow.cpp around line 682 and TransitionListEvidenceFilter.cpp
around line 435 to invoke
OpenSwathLibraryIDNormalizer::canonicalTargetForDecoyPrecursor directly, or
replace both with one shared helper.

In `@src/topp/TargetedFileConverter.cpp`:
- Around line 160-208: Filter empty source IDs from
precursor_canonical_to_source in the persistent PQP handling alongside
transition_canonical_to_source. Remove entries with empty values before building
precursor_source_to_canonical, while preserving duplicate-mapping validation for
remaining entries so both provenance maps follow the same contract.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 656364c6-c150-478e-bf25-2895e5e564db

📥 Commits

Reviewing files that changed from the base of the PR and between 294e4a4 and 42d80a1.

⛔ Files ignored due to path filters (4)
  • src/tests/topp/OpenSwathDecoyGenerator_parquet_output.tsv is excluded by !**/*.tsv
  • src/tests/topp/OpenSwathWorkflow_numeric_source_ids_input.tsv is excluded by !**/*.tsv
  • src/tests/topp/TargetedFileConverter_parquet_roundtrip.tsv is excluded by !**/*.tsv
  • src/tests/topp/TransitionListEvidenceFilter_prefixed_decoy_input.tsv is excluded by !**/*.tsv
📒 Files selected for processing (20)
  • CHANGELOG
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathLibraryIDNormalizer.h
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathOSWParquetWriter.h
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/TransitionPQPFile.h
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/TransitionParquetFile.h
  • src/openms/include/OpenMS/APPLICATIONS/OpenSwathBase.h
  • src/openms/source/ANALYSIS/OPENSWATH/OpenSwathLibraryIDNormalizer.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/OpenSwathOSWParquetWriter.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/TransitionPQPFile.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/TransitionParquetFile.cpp
  • src/openms/source/APPLICATIONS/OpenSwathBase.cpp
  • src/tests/class_tests/openms/source/OpenSwathLibraryIDNormalizer_test.cpp
  • src/tests/class_tests/openms/source/OpenSwathOSWParquetRoundTrip_test.cpp
  • src/tests/class_tests/openms/source/OpenSwathOSWParquetWriter_test.cpp
  • src/tests/class_tests/openms/source/TransitionPQPFile_test.cpp
  • src/tests/class_tests/openms/source/TransitionParquetFile_test.cpp
  • src/tests/topp/CMakeLists.txt
  • src/topp/OpenSwathWorkflow.cpp
  • src/topp/TargetedFileConverter.cpp
  • src/topp/TransitionListEvidenceFilter.cpp

Comment thread CHANGELOG Resolved
Comment thread src/topp/OpenSwathWorkflow.cpp 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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/openms/source/ANALYSIS/OPENSWATH/OpenSwathLibraryIDNormalizer.cpp`:
- Around line 38-49: Update hasCanonicalIDFormat_ to reject IDs beginning with a
sign, including "-0" and "-00", before parsing while preserving valid
non-negative canonical IDs. Add a regression test covering "-0".
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 97335cd6-2a7b-442c-b7c1-7d1c2630b592

📥 Commits

Reviewing files that changed from the base of the PR and between 8935e81 and fe42494.

📒 Files selected for processing (12)
  • CHANGELOG
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathLibraryIDNormalizer.h
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/TransitionPQPFile.h
  • src/openms/source/ANALYSIS/OPENSWATH/OpenSwathLibraryIDNormalizer.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/TransitionPQPFile.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/TransitionParquetFile.cpp
  • src/openms/source/APPLICATIONS/OpenSwathBase.cpp
  • src/tests/class_tests/openms/source/OpenSwathLibraryIDNormalizer_test.cpp
  • src/tests/class_tests/openms/source/OpenSwathOSWParquetWriter_test.cpp
  • src/tests/class_tests/openms/source/TransitionPQPFile_test.cpp
  • src/tests/class_tests/openms/source/TransitionParquetFile_test.cpp
  • src/topp/OpenSwathWorkflow.cpp
🚧 Files skipped from review as they are similar to previous changes (8)
  • CHANGELOG
  • src/tests/class_tests/openms/source/OpenSwathOSWParquetWriter_test.cpp
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/TransitionPQPFile.h
  • src/tests/class_tests/openms/source/OpenSwathLibraryIDNormalizer_test.cpp
  • src/openms/source/APPLICATIONS/OpenSwathBase.cpp
  • src/tests/class_tests/openms/source/TransitionPQPFile_test.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/TransitionParquetFile.cpp
  • src/topp/OpenSwathWorkflow.cpp

@singjc
singjc requested a review from timosachsenberg August 10, 2026 03:34

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

Looks good! I will need to check if this allows me to make ids of seeds simpler in featurefinderidentification at some point

@timosachsenberg
timosachsenberg merged commit 94251e8 into OpenMS:develop Aug 10, 2026
33 checks passed
timosachsenberg added a commit that referenced this pull request Aug 11, 2026
Audited PRs merged since the last CHANGELOG update (#9881): most of
them (#9879, #9880, #9882, #9884, #9886, #9892, #9896, #9898, #9900,
#9901, #9888) already carried their own CHANGELOG entries. Only the
Docker library-stage fix (#9891) was missing one.


Claude-Session: https://claude.ai/code/session_01Jgrv6mFL3oawgLdYs1efPH

Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants