Skip to content

Handle duplicate PKs and unidentified features in OpenMS conversion - #239

Merged
ypriverol merged 17 commits into
mainfrom
dev
Aug 6, 2026
Merged

ypriverol merged 17 commits into
mainfrom
dev

Conversation

@ypriverol

@ypriverol ypriverol commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

This pull request introduces significant improvements to the OpenMS consensusXML to QPX conversion workflow, focusing on enhanced metadata handling, better user guidance, and improved output configuration. The most important changes are summarized below.


Deprecation and User Guidance

  • The qpxc convert openms command (for OpenMS -out_qpx parquet files) is now officially deprecated due to known issues with mis-assigned PSM run_file_name and duplicate PSMs. Users are advised to use qpxc convert openms-consensus instead, which resolves these issues. Deprecation warnings and updated documentation have been added throughout the codebase and CLI. [1] [2] [3] [4]

Enhanced Metadata and Provenance Handling

  • The OpenMS consensus converter now writes comprehensive metadata tables (ontology, provenance, dataset) alongside the main data outputs. This includes collecting run-level ontology terms from the SDRF, capturing score names from output tables, and recording detailed provenance of the conversion steps. [1] [2] [3] [4]

Output Configuration Improvements

  • All output Parquet files now support configurable compression codecs (default: zstd), with the compression option plumbed through both streaming and in-memory conversion paths, as well as the CLI. [1] [2] [3] [4] [5] [6] [7] [8] [9] [10]

Project Metadata Support

  • The converter now accepts a --project-accession parameter, which is stamped into the output dataset.parquet for improved project-level metadata tracking. [1] [2] [3] [4]

Bug Fixes and Behavioral Improvements

  • Identity fallback for unidentified Features is now strictly controlled: fallback is only accepted if the derived primary key is unique, with collisions remaining a hard error and successful fallbacks reported as warnings. [1] [2]

These changes collectively improve the reliability, traceability, and configurability of the OpenMS consensusXML to QPX conversion pipeline.

Summary by CodeRabbit

  • New Features

    • Added OpenMS Consensus support for project accessions and configurable output compression.
    • Preserved OpenMS site-localization details, modifications, and localization scores in converted results.
    • Added workflow metadata, provenance, ontology, and dataset information to OpenMS Consensus outputs.
    • Unidentified Features can use validated composite identities when unique, with warnings for successful fallback.
  • Bug Fixes

    • Duplicate fallback identities are now rejected with clearer remediation guidance.
  • Deprecations

    • Deprecated native OpenMS conversion; use OpenMS Consensus conversion instead due to known multi-run assignment and duplication issues.

ypriverol and others added 15 commits August 5, 2026 18:27
…d Features

OpenMS -out_qpx (and other producers) can emit data that trips the mandatory-id
close-validation and crashes qpxc convert:
- Duplicate primary key -> now a WARNING, not a raise (e.g. per-protein PSM rows
  collapsing on [peptidoform,charge,run,scan]). Null id stays a hard error.
- Unidentified Feature (null peptidoform) with no producer id -> derive feature_id
  from the composite (null peptidoform + measured charge/run/rt) instead of raising.
  A producer id, when present, is still namespaced by run and stashed as a cv_param.

Aligns with the agreed design (clashes reported as warnings during conversion).
Tests updated; full suite 870 passed.
…ble path too

The earlier fix only relaxed the whole-file close check; write_table validates with
strict=True, under which duplicate_pk is an error, so OpenMS -out_qpx multi-engine PSM
rows (same [peptidoform,charge,run,scan], different engine score/mz — the #229 merged-
engine case) still crashed qpxc convert openms. write_table now warns on duplicate_pk
while keeping null/type issues as hard errors. Adds a write_table dup-PK test; suite 871.
The openms converter re-validates staged core files (_validate_core, strict=True) and
raised on duplicate_pk — a THIRD gate (after write_table and the close check) that
still crashed qpxc convert openms on OpenMS -out_qpx multi-engine PSM rows. It now
warns on duplicate_pk while keeping null/type issues as hard failures, and no longer
blocks installation of the converted file. Test updated to assert the tolerant
behavior (duplicate identity warns + converts). Suite 871.
OpenMS -out_qpx emits one PSM row per search engine (Comet + MS-GF+):
same spectrum+peptidoform, differing only in the per-engine score
(OpenMS#9871). Dedup these on the identity composite — keep the
lowest-PEP row and fold the other engines' additional_scores into it,
so psm_id is unique and no engine's score is lost.
OpenMS -out_qpx stamps every PSM with the first run's file (map_index
dropped, OpenMS#9872) — ~half the PSMs get the wrong run on multi-run
designs. Read the authoritative per-PSM run from the companion
consensusXML (psm_refs.py) and restore run_file_name, matched on the
exact (plain_sequence, charge, scan) key; chemistry stays from the
parquet. Also collapse OpenMS's assigned+unassigned duplicate PSMs
(OpenMS#9871), preferring the feature-attached row.

Verified on real phospho output: 496 all-rep1 -> 254 rep1 / 238 rep2,
240 corrected, 4 merged, zero duplicate identities.
Extract _collapse_duplicate_psms/_fold_additional_scores/_relabel_psm_runs
so the merge and run-repair paths share one collapse implementation
(cuts _repair_psm_run_files complexity 17->low, removes the
loop-closure warnings). Suppress the PsmRef too-many-attributes notice
(it's a reference-field record) and the unused iterparse event var.
Behavior unchanged (real phospho: 492 rows, 240 relabeled, 4 merged,
0 dup identities).
Reviewed Dai's openms_consensus converter: it reads the consensusXML
natively (pyopenms), resolves run_file_name per PSM via
map_index/id_merge_index/feature-element runs (handles multi-run
isobaric), derives peptidoform via to_proforma, and dedups on
[peptidoform,charge,run,scan]. It is strictly cleaner and more correct
than the -out_qpx parquet path, so the run_file_name repair I prototyped
(psm_refs.py + _repair_psm_run_files) is redundant — reverted.

The -out_qpx parquet path is fundamentally broken upstream: it
mis-assigns every PSM's run to the first run (OpenMS#9872) and duplicates
PSMs (OpenMS#9871). Mark 'qpxc convert openms' deprecated (Click
deprecated flag + docstring + a runtime warning) and steer to
'qpxc convert openms-consensus'. Keep the writer-level duplicate-PK
warning so the deprecated path degrades gracefully.
…, metadata tables

Extend the openms-consensus converter to parity with the openms enrichment path:

- Populate the structured `modifications` column in feature and psm views from
  pyopenms AASequence per-residue / terminal modifications (canonical UNIMOD:N).
- Extract site-localisation scores from OpenMS UserParams for Luciphor, Ascore,
  and PhosphoRS (`<algo>_pep_score`, `<algo>_global_flr`, `<algo>_site_scores`)
  into `additional_scores` and per-position `modifications[].positions[].scores`.
- Write the ontology / provenance / dataset metadata tables so the output is a
  complete 8-structure QPX dataset, matching the openms converter.
- Add `--project-accession` and `--compression` CLI options, threaded through
  every writer, matching the openms command.

Co-Authored-By: Claude <[email protected]>
Resolve the CI pre-commit failures:
- Remove the unused `headers` assignment in `_consensus_is_isobaric`.
- Re-sort the `qpx._version` import ahead of `qpx.converters.*` (ruff I001).
- Apply `ruff format` to cli/convert.py, converter.py, feature_adapter.py.

Co-Authored-By: Claude <[email protected]>
feat(openms-consensus): structured modifications, localization scores, metadata tables
deprecate qpxc convert openms (-out_qpx parquet) in favour of openms-consensus
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@coderabbitai

coderabbitai Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@ypriverol, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 8 minutes

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: f3bed6d3-74da-4f03-9014-fc681dc02780

📥 Commits

Reviewing files that changed from the base of the PR and between f6af094 and 07e6f7d.

📒 Files selected for processing (4)
  • qpx/converters/openms_consensus/converter.py
  • qpx/converters/openms_consensus/feature_adapter.py
  • qpx/writers/feature.py
  • tests/unit/test_identity.py
📝 Walkthrough

Walkthrough

The change updates OpenMS consensus conversion with metadata, localization fields, and compression options. It deprecates the native OpenMS conversion path. FeatureWriter now supports validated composite fallback identities for unidentified Features.

Changes

OpenMS conversion

Layer / File(s) Summary
Conversion entry points and deprecation
qpx/cli/convert.py, qpx/converters/openms/converter.py, CHANGELOG.md
The openms command and converter path are deprecated. The CLI directs users to openms-consensus and passes project accession and compression values.
Consensus metadata and compression
qpx/converters/openms_consensus/converter.py
Streaming and in-memory conversion propagate the selected compression codec and write ontology, provenance, and dataset metadata.
Localization and modification records
qpx/converters/openms_consensus/feature_adapter.py, qpx/converters/openms_consensus/psm_adapter.py
Feature and PSM records now include structured modifications and localization scores.

Feature identity fallback

Layer / File(s) Summary
Fallback identity validation
qpx/writers/feature.py, tests/unit/test_identity.py, CHANGELOG.md
Unidentified Features can use composite-derived IDs when full-file uniqueness succeeds. Producer IDs remain namespaced and preserved as provided_feature_id. Tests cover warnings, collisions, and table writes.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related PRs

  • bigbio/qpx#218: Both changes address composite identity handling for unidentified Features.
  • bigbio/qpx#227: Both changes extend OpenMS consensus conversion and Feature identity behavior.

Suggested reviewers: shen-yufei

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main changes: duplicate primary-key handling and unidentified feature support in OpenMS conversion.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch dev

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.

@codacy-production

codacy-production Bot commented Aug 6, 2026 •

Copy link
Copy Markdown

Not up to standards ⛔

🔴 Issues 1 medium · 1 minor

Alerts:
⚠ 2 issues (≤ 0 issues of at least minor severity)

Results:
2 new issues

Category Results
ErrorProne 1 medium
CodeStyle 1 minor

View in Codacy

🟢 Metrics 71 complexity · 2 duplication

Metric Results
Complexity 71
Duplication 2

View in Codacy

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@ypriverol
ypriverol requested a lite review from Copilot August 6, 2026 08:43

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

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

🧹 Nitpick comments (2)
qpx/converters/openms_consensus/feature_adapter.py (1)

141-148: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Key the modification grouping by (name, accession).

key = name or accession or "" groups two different modifications together when both report an empty getId(). Their positions then merge into a single entry whose name is "" and whose accession is the first one seen, so the second accession is lost. Using the pair as the key removes that case.

♻️ Proposed change
-        key = name or accession or ""
+        key = (name, accession)
🤖 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 `@qpx/converters/openms_consensus/feature_adapter.py` around lines 141 - 148,
Update the modification grouping key in _add_mod to use the combined (name,
accession) pair rather than preferring name or accession, preserving separate
entries when names are empty but accessions differ. Keep the existing entry
creation and position-appending behavior unchanged.
qpx/converters/openms/converter.py (1)

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

Consider also emitting a DeprecationWarning for Python API users.

The log warning reaches CLI users. Users of OpenMSConverter.convert in Python code may run with logging disabled and see nothing. A warnings.warn(..., DeprecationWarning, stacklevel=2) alongside the log makes the deprecation visible to both audiences.

♻️ Proposed addition
+        import warnings
+
+        warnings.warn(
+            "OpenMSConverter (the -out_qpx parquet path) is deprecated; "
+            "use OpenMSConsensusConverter (`qpxc convert openms-consensus`) instead.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
         logger.warning(
             "`qpxc convert openms` (over the OpenMS -out_qpx parquet folder) is DEPRECATED. "
🤖 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 `@qpx/converters/openms/converter.py` around lines 368 - 374, In the deprecated
OpenMS conversion path around OpenMSConverter.convert, emit a Python
DeprecationWarning alongside the existing logger.warning call, using the same
deprecation message and stacklevel=2 so API callers receive the warning at their
call site.
🤖 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 `@qpx/converters/openms_consensus/converter.py`:
- Around line 241-249: Remove the file-reloading logic from
`_consensus_is_isobaric` and stop calling `load_consensus_map` during provenance
generation. Compute the isobaric flag from `consensus_channels(cm)` during
`_convert_streaming`, where the existing consensus map and
`feature_map_info(cm)` are available, then pass that value through
`_write_metadata` into `_build_provenance`; update related call sites and
signatures while preserving non-streaming behavior.
- Around line 420-430: Update the step-2 provenance record in the converter to
derive output_views from the caller’s requested structures, retaining only views
that are actually generated; preserve the existing ordering and ensure
unrequested SAMPLE or RUN views are omitted.
- Around line 229-238: Update _collect_score_names to explicitly import
pyarrow.parquet as pq and call pq.read_table instead of pa.parquet.read_table,
matching the sibling OpenMS converter and preventing an AttributeError from
escaping the guarded metadata path.

In `@qpx/converters/openms_consensus/feature_adapter.py`:
- Around line 196-209: Normalize localization score names before appending them
in the loop over _LOCALIZATION_ALGORITHMS: use the same lowercase snake_case
form for pep_key and flr_key that site scores use, while preserving their
existing suffixes and values. Ensure _collect_score_names and
score_ontology_entries receive consistent normalized names so all localization
scores can be resolved.
- Around line 105-124: In the site-score parsing function, replace the eval call
with ast.literal_eval and import ast as needed. Preserve the existing dictionary
validation, value conversion, and fallback behavior for invalid literals, while
removing the S307 suppression tied to eval.

In `@qpx/writers/feature.py`:
- Around line 25-34: Update _fallback_collision_error to track the actual IDs
derived from fallback rows and enrich a duplicate-primary-key error only when
the reported duplicate intersects that set, rather than relying on
_unidentified_fallback_count alone. Preserve the original error for duplicates
involving only identified Features, and add a regression test covering one
unique fallback row plus a separate identified duplicate.

---

Nitpick comments:
In `@qpx/converters/openms_consensus/feature_adapter.py`:
- Around line 141-148: Update the modification grouping key in _add_mod to use
the combined (name, accession) pair rather than preferring name or accession,
preserving separate entries when names are empty but accessions differ. Keep the
existing entry creation and position-appending behavior unchanged.

In `@qpx/converters/openms/converter.py`:
- Around line 368-374: In the deprecated OpenMS conversion path around
OpenMSConverter.convert, emit a Python DeprecationWarning alongside the existing
logger.warning call, using the same deprecation message and stacklevel=2 so API
callers receive the warning at their call site.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: b8904b95-b506-43d9-925b-33d01d6fdb32

📥 Commits

Reviewing files that changed from the base of the PR and between a246f0f and f6af094.

📒 Files selected for processing (8)
  • CHANGELOG.md
  • qpx/cli/convert.py
  • qpx/converters/openms/converter.py
  • qpx/converters/openms_consensus/converter.py
  • qpx/converters/openms_consensus/feature_adapter.py
  • qpx/converters/openms_consensus/psm_adapter.py
  • qpx/writers/feature.py
  • tests/unit/test_identity.py

Comment thread qpx/writers/feature.py Resolved
…dling

- Use ast.literal_eval instead of eval when parsing site-localization score
  dicts from consensusXML UserParams (removes code-injection risk).
- Import pyarrow.parquet explicitly; pa.parquet is not auto-imported.
- Detect isobaric labeling via the streaming header reader so provenance no
  longer reloads the whole ConsensusMap into memory; log load failures.
- Filter provenance step-2 output_views by the requested structures.
- Normalize localization pep/flr score names to snake_case so ontology
  resolution does not drop mixed-case names.
- Key modification grouping by (name, accession) to avoid merging distinct
  empty-id modifications.
- Attribute a duplicate-PK error to the unidentified composite fallback only
  when a fallback-derived id is the actual duplicate, not for identified
  collisions; add regression test.
… excepts

Extract shared helpers (_cf_feature_psm_records, _write_view,
_stream_feature_psm) so _convert_streaming and _convert_in_memory drop
below the branch/statement thresholds CodeFactor/Codacy flagged, and the
streaming and in-memory paths share one per-consensus-feature builder.
Narrow the two broad 'except Exception' (site-score parse ->
ValueError/SyntaxError/TypeError; isobaric-label probe -> read/parse
errors). Behavior-preserving: 169 converter/writer/identity tests pass;
all functions now under mccabe complexity 12.
@ypriverol
ypriverol merged commit aaa07e7 into main Aug 6, 2026
16 of 17 checks passed
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.

4 participants