Skip to content

fix(CometAdapter): rewrite Bruker native IDs in mzML path too - #9168

Merged
timosachsenberg merged 1 commit into
developfrom
fix/comet-bruker-mzml-native-id
Apr 17, 2026
Merged

timosachsenberg merged 1 commit into
developfrom
fix/comet-bruker-mzml-native-id

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Apr 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Extends the mzParser segfault workaround from #9160 to also cover the .d → FileConverter → .mzML → CometAdapter pipeline. Previously the native-ID rewrite (index=N) only fired for direct .d input.

Problem

FileConverter writes CV-compliant Bruker mzML with frame=F scan=S native IDs (MS:1002818). When CometAdapter reads this mzML, it takes the "existing mzML path" which passes the file directly to Comet — no ID rewrite. Comet's mzParser strstr("scan=") picks up non-monotonic TIMS scan values → cindex::compare UB → segfault. Same root cause as #9160, different entry point.

Fix

Detect Bruker-originated mzML by probing the first spectrum's native ID for frame=. When detected:

  1. Load with peak data (single full load — no double-loading)
  2. Rewrite all native IDs to index=N, preserve originals as original_native_id MetaValue
  3. Write temp mzML with rewritten IDs for Comet
  4. Clear peak data, keep metadata for post-Comet annotation

Non-Bruker mzML (Thermo, Sciex, etc.) keeps the original fast path — metadata-only load + pass-through. No behavioral change for non-Bruker input.

The post-Comet translation block (index=N → original IDs in PSM spectrum references) is generalized: now fires whenever original_native_id MetaValues are present, regardless of .d vs .mzML input.

Test Plan

  • CometAdapter builds cleanly
  • End-to-end: .d → FileConverter → .mzML → CometAdapter no longer segfaults (manual verification with Bruker fixture)

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved handling of Bruker-originated mzML so original spectrum identifiers are preserved in metadata and reliably mapped back after search.
    • Rewrote Bruker mzML to ensure monotonic indexed identifiers are used by the search engine while retaining originals for result mapping.
    • Ensured indexed mzML is produced when needed by checking indexing on a fresh load, avoiding metadata-only side effects.
    • Consistent post-search translation restores original spectrum IDs whenever preserved in metadata.

@coderabbitai

coderabbitai Bot commented Apr 17, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Detects Bruker-originated mzML by inspecting the first spectrum's nativeID for "frame="; Bruker mzML is reloaded with peaks, spectrum nativeIDs rewritten to monotonic index=N while originals are stored as original_native_id metadata, a temporary indexed mzML is written, and PSM nativeIDs are remapped when original_native_id exists.

Changes

Cohort / File(s) Summary
CometAdapter mzML detection & rewrite
src/topp/CometAdapter.cpp
Always load mzML metadata first (peaks disabled). If Bruker mzML ("frame=" in nativeID): reload with peaks, store original nativeID in original_native_id, rewrite nativeID → index=N, write temporary indexed mzML, then clear peaks. For non-Bruker mzML: ensure an indexed mzML only when needed. Removed #ifdef WITH_OPENTIMS guard; PSM nativeID translation now runs whenever original_native_id metadata is present.

Possibly related PRs

Suggested reviewers

  • jcharkow

Poem

🐰
I sniffed the frames where spectra hide,
I tagged each hop and kept old IDs beside,
I hopped, I wrote a temp file bright,
Then hopped back to fix each PSM's sight,
A rabbit's tweak — indexed paths now glide!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the main change: extending Bruker native ID rewriting to also handle the mzML input path, which is the primary fix in this changeset.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/comet-bruker-mzml-native-id

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 and usage tips.

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

Caution

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

⚠️ Outside diff range comments (1)
src/topp/CometAdapter.cpp (1)

891-897: ⚠️ Potential issue | 🟡 Minor

is_bruker_d-specific IM warning no longer fires for Bruker-originated mzML.

The IM-coverage warning is still gated on is_bruker_d (direct .d only), but the new code path means a .d → FileConverter → .mzML → CometAdapter run with partial IM coverage will silently skip this diagnostic. If Bruker-originated mzML should also emit the warning, consider widening the condition to "any input where original_native_id was set" (mirroring the translation block at line 908).

♻️ Suggested widening
-#ifdef WITH_OPENTIMS
-    else if (is_bruker_d)
+    else if (!exp.empty() && exp[0].metaValueExists("original_native_id"))
     {
-      OPENMS_LOG_WARN << "Warning: Bruker .d input but not all peptide IDs could be annotated with ion mobility values. "
+      OPENMS_LOG_WARN << "Warning: Bruker input but not all peptide IDs could be annotated with ion mobility values. "
                       << "This may indicate a native ID mismatch between the .d data and Comet results." << std::endl;
     }
-#endif
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/topp/CometAdapter.cpp` around lines 891 - 897, The Bruker-specific IM
coverage warning is still only shown when is_bruker_d is true, so
Bruker-originated mzML (where original_native_id was preserved) now misses the
diagnostic; update the condition that surrounds the OPENMS_LOG_WARN block in
CometAdapter.cpp to trigger not only when is_bruker_d is true but also when
original_native_id (the translated native ID field used earlier around the
translation block) is present/non-empty (i.e., mirror the "original_native_id
was set" check used at the translation logic) so the warning fires for any input
that originated from a Bruker .d file even after conversion to mzML.
🧹 Nitpick comments (2)
src/topp/CometAdapter.cpp (2)

771-774: Duplicate / redundant MzMLFile::getOptions() calls on the probe.

  • Line 771: setMetadataOnly(false) is the default and can be dropped.
  • Line 774: setFillData(false) is already set on line 772 — the second call is a no-op.

Minor cleanup while you're here (will go away entirely if you adopt the source-file-based detection above).

♻️ Proposed cleanup
-        probe_file.getOptions().setMetadataOnly(false);
         probe_file.getOptions().setFillData(false);
         probe_file.getOptions().addMSLevel(ms_level);
-        probe_file.getOptions().setFillData(false);  // metadata only, no peak data
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/topp/CometAdapter.cpp` around lines 771 - 774, Remove the redundant
option calls on the probe's options: drop the explicit
probe_file.getOptions().setMetadataOnly(false) call and remove the duplicate
probe_file.getOptions().setFillData(false) (the single setFillData(false) call
already present is sufficient), leaving only
probe_file.getOptions().addMSLevel(ms_level) and one setFillData(false) as
needed; locate these via the probe_file.getOptions(), setMetadataOnly,
setFillData, and addMSLevel symbols in CometAdapter.cpp to make the cleanup.

766-778: Consider detecting Bruker origin via SourceFile nativeID CV term instead of probing spectra.

The probe currently opens the entire mzML (with setFillData(false) only — headers for every spectrum are still parsed) just to inspect probe[0].getNativeID(). For large Bruker mzMLs this doubles the parse cost (probe + full load). The PSI-MS nativeIDFormat for Bruker TDF is MS:1002818, which is declared once in <sourceFileList>. Checking that accession via MSExperiment/SourceFile metadata (e.g. setMetadataOnly(true) on the probe, or reading via FileHandler) avoids walking the spectrumList at all and is also more robust than a substring match on the first spectrum (which can fail if the first scan has unusual formatting or if some upstream tool strips the precursor=… suffix but keeps frame=/scan=).

Based on learnings: the correct PSI-MS CV term for Bruker TimsTOF TDF nativeID format is MS:1002818 ("Bruker TDF nativeID format"), set via setNativeIDTypeAccession("MS:1002818") — this is the canonical, file-level signal for Bruker-originated mzML.

♻️ Sketch of source-file-based detection
bool is_bruker_mzml = false;
{
  MSExperiment probe;
  MzMLFile probe_file;
  probe_file.getOptions().setMetadataOnly(true);  // skip spectrumList entirely
  probe_file.load(inputfile_name, probe);
  for (const auto& sf : probe.getSourceFiles())
  {
    if (sf.getNativeIDTypeAccession() == "MS:1002818")
    {
      is_bruker_mzml = true;
      break;
    }
  }
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/topp/CometAdapter.cpp` around lines 766 - 778, The current quick-probe
opens spectra and checks probe[0].getNativeID(), which still walks the
spectrumList; instead change the probe to metadata-only and detect Bruker by
inspecting SourceFile CV term: in the block using MSExperiment probe and
MzMLFile probe_file, call probe_file.getOptions().setMetadataOnly(true)
(remove/replace the setFillData(false) probe settings), load the file, then
iterate probe.getSourceFiles() and set is_bruker_mzml = true if any
sourceFile.getNativeIDTypeAccession() == "MS:1002818"; remove the reliance on
probe[0].getNativeID() substring matching.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@src/topp/CometAdapter.cpp`:
- Around line 891-897: The Bruker-specific IM coverage warning is still only
shown when is_bruker_d is true, so Bruker-originated mzML (where
original_native_id was preserved) now misses the diagnostic; update the
condition that surrounds the OPENMS_LOG_WARN block in CometAdapter.cpp to
trigger not only when is_bruker_d is true but also when original_native_id (the
translated native ID field used earlier around the translation block) is
present/non-empty (i.e., mirror the "original_native_id was set" check used at
the translation logic) so the warning fires for any input that originated from a
Bruker .d file even after conversion to mzML.

---

Nitpick comments:
In `@src/topp/CometAdapter.cpp`:
- Around line 771-774: Remove the redundant option calls on the probe's options:
drop the explicit probe_file.getOptions().setMetadataOnly(false) call and remove
the duplicate probe_file.getOptions().setFillData(false) (the single
setFillData(false) call already present is sufficient), leaving only
probe_file.getOptions().addMSLevel(ms_level) and one setFillData(false) as
needed; locate these via the probe_file.getOptions(), setMetadataOnly,
setFillData, and addMSLevel symbols in CometAdapter.cpp to make the cleanup.
- Around line 766-778: The current quick-probe opens spectra and checks
probe[0].getNativeID(), which still walks the spectrumList; instead change the
probe to metadata-only and detect Bruker by inspecting SourceFile CV term: in
the block using MSExperiment probe and MzMLFile probe_file, call
probe_file.getOptions().setMetadataOnly(true) (remove/replace the
setFillData(false) probe settings), load the file, then iterate
probe.getSourceFiles() and set is_bruker_mzml = true if any
sourceFile.getNativeIDTypeAccession() == "MS:1002818"; remove the reliance on
probe[0].getNativeID() substring matching.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 061c505f-5a26-442d-8802-50ee74cfc823

📥 Commits

Reviewing files that changed from the base of the PR and between 26c8613 and e528ff6.

📒 Files selected for processing (1)
  • src/topp/CometAdapter.cpp

@timosachsenberg
timosachsenberg force-pushed the fix/comet-bruker-mzml-native-id branch from e528ff6 to 38066f8 Compare April 17, 2026 08:52
The mzParser segfault workaround from #9160 only fired when CometAdapter
received a .d directory directly. When users converted .d → mzML via
FileConverter first, the mzML contained Bruker-format native IDs
(frame=F scan=S, CV term MS:1002818) that triggered the same
cindex::compare strict-weak-ordering UB in Comet's mzParser.

Fix: detect Bruker-originated mzML by probing the first spectrum's
native ID for "frame=". When detected, take the full-data path (load
with peaks → rewrite IDs to index=N → write temp mzML → clear peaks),
matching the direct .d branch exactly. Non-Bruker mzML keeps the
original fast path (metadata-only load + pass-through).

The post-Comet translation block (index=N → original ID) is also
generalized: it now fires whenever original_native_id MetaValues are
present, regardless of whether the input was .d or .mzML.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@timosachsenberg
timosachsenberg force-pushed the fix/comet-bruker-mzml-native-id branch from 38066f8 to bf20c98 Compare April 17, 2026 09:01

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

🧹 Nitpick comments (2)
src/topp/CometAdapter.cpp (2)

737-751: Duplicated native-ID rewrite + temp-mzML-write logic across the .d and Bruker-mzML branches.

The block that (a) stamps original_native_id, (b) rewrites to index=N, (c) writes a temp mzML, (d) clears peaks while keeping metadata is now copy-pasted between the WITH_OPENTIMS .d branch (737-751) and the new Bruker-mzML branch (786-797). Extracting a small helper keeps the two entry points in lockstep and avoids future drift (e.g., if the MetaValue key or the clear(false) contract changes).

♻️ Sketch of a helper
// Rewrite native IDs to monotonic index=N and persist originals; write a
// temporary indexed mzML for Comet; free peaks but keep spectrum metadata.
static String rewriteNativeIdsAndWriteTempMzML_(MSExperiment& exp)
{
  size_t idx = 0;
  for (auto& spec : exp.getSpectra())
  {
    spec.setMetaValue("original_native_id", spec.getNativeID());
    spec.setNativeID("index=" + String(idx++));
  }
  auto tmp_mzml = File::getTemporaryFile() + ".mzML";
  MzMLFile().store(tmp_mzml, exp);
  for (auto& spec : exp.getSpectra()) { spec.clear(false); }
  return tmp_mzml;
}

…and use it from both branches:

input_file_with_index = rewriteNativeIdsAndWriteTempMzML_(exp);

As per coding guidelines: "Code smells such as violations of SOLID, DRY, KISS, or YAGNI principles".

Also applies to: 786-797

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/topp/CometAdapter.cpp` around lines 737 - 751, Extract the duplicated
logic that stamps original_native_id, rewrites native IDs to "index=N", writes a
temporary mzML, and clears peaks (keeping metadata) into a helper (e.g., static
String rewriteNativeIdsAndWriteTempMzML_(MSExperiment& exp)); inside the helper
loop over exp.getSpectra() call spec.setMetaValue("original_native_id",
spec.getNativeID()) and spec.setNativeID("index="+String(idx++)), then create a
tmp file via File::getTemporaryFile()+".mzML", call MzMLFile().store(tmp_mzml,
exp), clear peaks with spec.clear(false) for each spectrum, and return the
tmp_mzml; replace the two inlined blocks in the WITH_OPENTIMS `.d` branch and
the Bruker-mzML branch by assigning input_file_with_index =
rewriteNativeIdsAndWriteTempMzML_(exp).

767-768: Consider detecting Bruker-originated mzML via SourceFile nativeID accession (MS:1002818) rather than a substring on the first spectrum.

exp[0].getNativeID().hasSubstring("frame=") is fine for the current pipeline, but it is fragile against: (a) the MS-level filter dropping frame-annotated spectra if an mzML happens to place a non-MS2 spectrum first, (b) future formats reusing frame= for unrelated semantics, and (c) having to keep the metadata-only load solely as a probe. The more authoritative signal is the PSI-MS CV term declared on the SourceFile — for Bruker TDF that is MS:1002818 ("Bruker TDF nativeID format"), which FileConverter propagates when converting .d→mzML.

Using the SourceFile accession would also let you skip the metadata-only load entirely for non-Bruker inputs (inspecting exp.getSourceFiles()[0].getNativeIDTypeAccession() after a lightweight load would suffice), and restore the pre-change behavior for the common non-Bruker path. SageAdapter already uses this pattern successfully elsewhere in the codebase.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/topp/CometAdapter.cpp` around lines 767 - 768, Replace the fragile
first-spectrum substring probe with a SourceFile-based check: instead of
computing is_bruker_mzml from exp[0].getNativeID().hasSubstring("frame="),
inspect exp.getSourceFiles() (ensure not empty) and check the SourceFile native
ID type accession via getNativeIDTypeAccession() against the Bruker TDF PSI-MS
term "MS:1002818"; set is_bruker_mzml true when that accession matches, and
optionally fall back to the original frame= substring test only if no SourceFile
entries exist to preserve backward compatibility. Ensure you update the code
paths that use is_bruker_mzml (the local variable in CometAdapter.cpp) so they
rely on this new check.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/topp/CometAdapter.cpp`:
- Around line 737-751: Extract the duplicated logic that stamps
original_native_id, rewrites native IDs to "index=N", writes a temporary mzML,
and clears peaks (keeping metadata) into a helper (e.g., static String
rewriteNativeIdsAndWriteTempMzML_(MSExperiment& exp)); inside the helper loop
over exp.getSpectra() call spec.setMetaValue("original_native_id",
spec.getNativeID()) and spec.setNativeID("index="+String(idx++)), then create a
tmp file via File::getTemporaryFile()+".mzML", call MzMLFile().store(tmp_mzml,
exp), clear peaks with spec.clear(false) for each spectrum, and return the
tmp_mzml; replace the two inlined blocks in the WITH_OPENTIMS `.d` branch and
the Bruker-mzML branch by assigning input_file_with_index =
rewriteNativeIdsAndWriteTempMzML_(exp).
- Around line 767-768: Replace the fragile first-spectrum substring probe with a
SourceFile-based check: instead of computing is_bruker_mzml from
exp[0].getNativeID().hasSubstring("frame="), inspect exp.getSourceFiles()
(ensure not empty) and check the SourceFile native ID type accession via
getNativeIDTypeAccession() against the Bruker TDF PSI-MS term "MS:1002818"; set
is_bruker_mzml true when that accession matches, and optionally fall back to the
original frame= substring test only if no SourceFile entries exist to preserve
backward compatibility. Ensure you update the code paths that use is_bruker_mzml
(the local variable in CometAdapter.cpp) so they rely on this new check.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 796777da-d7fa-471d-801e-d9175d0d82f3

📥 Commits

Reviewing files that changed from the base of the PR and between 38066f8 and bf20c98.

📒 Files selected for processing (1)
  • src/topp/CometAdapter.cpp

@timosachsenberg
timosachsenberg merged commit bc479b4 into develop Apr 17, 2026
15 checks passed
@timosachsenberg
timosachsenberg deleted the fix/comet-bruker-mzml-native-id branch April 17, 2026 09:48
github-actions Bot pushed a commit that referenced this pull request Apr 18, 2026
Add missing entries for commits since the 2026-04-17 sync:
- CometAdapter #9168: Bruker native-ID rewrite covers mzML inputs too
- ProSE #9166: new -out_pin parameter for Percolator input file output
- ProSE #9167: fix ions:add_* parameters honored in scoring path
- ProSE #9175: BREAKING rename matched_b/y_ions → matched_prefix/suffix_ions; delta_score and matched_ion_current added; HyperScore ETD/EThcD fix
- ProSE #9177: database chunking (-Search:database:chunk_size); Percolator feature and calibration fixes

Co-authored-by: Copilot <[email protected]>
timosachsenberg pushed a commit that referenced this pull request Apr 18, 2026
Add missing entries for commits since the 2026-04-17 sync:
- CometAdapter #9168: Bruker native-ID rewrite covers mzML inputs too
- ProSE #9166: new -out_pin parameter for Percolator input file output
- ProSE #9167: fix ions:add_* parameters honored in scoring path
- ProSE #9175: BREAKING rename matched_b/y_ions → matched_prefix/suffix_ions; delta_score and matched_ion_current added; HyperScore ETD/EThcD fix
- ProSE #9177: database chunking (-Search:database:chunk_size); Percolator feature and calibration fixes

Co-authored-by: GitHub Copilot <[email protected]>
Co-authored-by: Copilot <[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.

1 participant