Skip to content

[FEATURE,FORMAT,TEST] QPX: emit the mandatory identity ids and cross-reference feature<->PSM (#9864) - #9884

Merged
timosachsenberg merged 7 commits into
developfrom
qpx-identity-ids
Aug 7, 2026
Merged

timosachsenberg merged 7 commits into
developfrom
qpx-identity-ids

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Implements §C2 of #9864.

The gap

Every QPX view carries a mandatory int64 identity column that is its primary key:

view primary_key identity_composite
feature feature_id [peptidoform, charge, run_file_name, rt]
psm psm_id [peptidoform, charge, run_file_name, scan]
pg pg_id [anchor_protein, grouped_runs, label]

required: true, nullable: false. OpenMS emitted none of the three, so every -out_qpx file was invalid against the current spec.

Why the derivation has to be byte-exact

The id is BLAKE2b truncated to 8 bytes over the canonical JSON of a footer-declared composite, read as a signed big-endian int64. Matching qpx's own derivation exactly is not cosmetic — it is what keeps the cross-references from dangling.

qpxc convert openms re-derives feature_id for identified rows from the declared composite (FeatureWriter defaults override_provided_ids=True), but it never rewrites the psm.feature_id that points at it. Ids that were merely plausible would therefore turn an OpenMS collection into one with dangling references the moment it was converted — and qpx's own dataset.py reports exactly that, as dangling_feature_id.

So the composites OpenMS declares are the ones qpxc already hard-codes for -out_qpx input (qpx/converters/openms/converter.py:46), in that order:

feature: run_file_name, peptidoform, charge, rt, scan, observed_mz
psm:     run_file_name, scan, peptidoform, charge
pg:      anchor_protein, grouped_runs, label      (grouped_runs sorted)

Unidentified feature rows are the reason the feature composite carries floats at all: on the seeded fixture, 210 of 298 rows share an empty peptidoform and an empty scan, and (peptidoform, charge, run_file_name, scan) collides 25 deep. Only rt and observed_mz tell them apart.

The float problem, and how it was settled

qpx hashes each composite column as persisted, so a float32 rt is widened to double and rendered by Python's repr — shortest round-tripping digits, exponential notation when the decimal point falls at <= -4 or > 16, .0 appended to anything that would otherwise look like an integer. C++'s general format picks between fixed and scientific by a different rule, so it cannot be used directly.

Verified rather than assumed:

  • 399,325 float32 values against Python's json.dumps: uniformly random bit patterns (so subnormals, the full exponent range, ±0), the RT and m/z ranges QPX actually stores, and exact powers of two either side of both boundaries. 0 mismatches.
  • 60,000 random composites against qpx.core.data.identity: strings with control characters, astral-plane unicode (surrogate pairs), JSON metacharacters and embedded delimiters; int64 extremes; random float32 bit patterns; nulls; empty and non-empty int/string lists; set-valued positions. 0 mismatches on both canonical and derive_id.
  • End to end: every one of the 747 rows the four producers write, across 17 files, re-derives to the id OpenMS emitted.

Cross-references

psm.feature_id and feature.psm_ids — the thing a native producer can do that a converter re-deriving from consensusXML cannot do as cheaply.

A consensus feature spans runs but emits one row per run, so its identifications are distributed to the row of their own run. Listing them on every row would claim a PSM as evidence for a quantity measured in a different file. An unassigned identification keeps feature_id null, and so does every row of a psm-only producer (ProSE, any search engine) — which is what the spec prescribes for an unlinked PSM.

Both directions are produced by one pass over the feature rows. That is what makes them reciprocal, which qpx validates: a PSM pointing at a feature must be listed back by that feature's psm_ids.

Measured against the consensusXML on the shipped LFQ fixture:

consensus features 39
feature rows (23×1 + 11×2 + 5×3 runs) 60
attached identifications 39
unassigned identifications 65
links emitted 39
dangling, either direction 0
reciprocity desync 0

One shared derivation, deliberately

scan and run_file_name are part of the psm identity, and the feature view has to reproduce both exactly to work out which of its rows a PSM belongs to. They existed as verbatim copies in the two exporters. They are now one implementation in ArrowIOHelpers, because the linkage now depends on that agreement — two copies would be one edit away from a collection whose cross-references silently stop resolving.

qpxPsmRunFileName takes pre-resolved MetaInfoRegistry indices rather than looking keys up by name. MetaInfoRegistry::getIndex() takes an omp critical lock, and this runs once per row inside the exporters' parallel batch build; the by-name version would have serialized it, undoing the design both files already follow for every other metavalue key.

ParquetDiff: identity columns are not compared

The identity and cross-reference columns are left out of both the value comparison and the TSV dump, with -with_ids to opt back in. Two reasons, and the first is the spec's own:

"Identity is meaningful within a file only; distinct QPX files must not be joined on feature_id alone."

Comparing a file against a committed reference is that join. And feature_id hashes rt and observed_mz, so one ULP of platform drift would not shift a digit in one cell — it would produce a wholly different int64 and report every row as missing on both sides. Rows are still matched on the natural key, which degrades gracefully where a hash cannot.

-schema mode asserts instead what actually matters about an opaque id: present, never null, never repeated. QPXValueValidation enforces the same across streamed batches, so uniqueness holds for the whole file rather than within a batch.

Consequence: zero churn in the value references #9879 committed — verified, git status shows no reference file touched.

Verification

  • QPXIdentity_test pins the derivation against vectors produced by the reference implementation, not by running this code and recording what it printed. It has failed for a real reason: it caught std::from_chars silently parsing nothing from a '+'-signed exponent, which had every value above 1 rendering as 1.23456 instead of 123456.0.
  • ConsensusMapArrowExport_test re-derives each row's feature_id from the columns as written, passing them in the order the composite declares. That is what would catch this exporter hashing the right values in the wrong slots — which neither the schema check nor a value reference would notice.
  • The cross-reference test asserts resolvability in both directions plus reciprocity, and guards against vacuity. That guard fired twice, on a fixture whose PSMs had no resolvable run and therefore matched no feature row — exactly what it is there for.
  • Both new ParquetDiff checks were shown to fail on purpose: a table with duplicated ids and one with a null id are each reported by name and row, and the unmodified file passes.
  • Doxygen: run through the doc target, down to the two pre-existing HAVE_DOT warnings. One warning in this branch was mine — an undocumented @param that would have gone red on all five CI platforms.
  • Full suite -E "BrukerTims|PASEF": 8 failures, all in the known environmental baseline (6 CometAdapter_*_out1 version-string, PercolatorAdapter_1_subprocess_out numerics, Doxygen_Warning_test HAVE_DOT).

Schema churn

The three views gain columns, so the schema tests' field counts and positional pins move: psm 24 → 26, feature 31 → 33, pg 21 → 22. The new columns are pinned explicitly rather than only renumbered around — including their nullability, which is the part that carries meaning here (feature_id non-null on the feature view, nullable on the psm view, because a PSM belonging to no feature is a real state and not missing data).

Not in scope

feature.pg_ids. No upstream converter populates it — only a dataset.py dangling check and a DIA-NN null column reference it — and the documented semantic join is already fully available in OpenMS output: feature.anchor_protein = pg.anchor_protein AND feature.run_file_name ∈ pg.grouped_runs AND unnest(feature.intensities).label = pg.label. Populating it would need the pg view's QuantificationUnits threaded into the feature exporter, which writes first. Worth doing separately if a consumer asks for it.

bigbio/qpx#240 is still open. It re-keys the pg identity from anchor_protein to pg_accessions, because keying on the group leader collapses two genuinely distinct groups that share a leading protein. When it lands, PG_COMPOSITE and QPXIdentity::pgId change together and every pg_id moves — a one-line change here, but it will need re-verifying against the reference implementation.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Y9DY9JfJasCr76qof5n5rx

Summary by CodeRabbit

  • New Features

    • QPX feature, PSM, and protein-group exports now include deterministic identity fields.
    • Protein-group identities use complete accession membership, runs, and labels.
    • Feature and PSM records include synchronized cross-references when available; unassigned PSMs retain a null feature reference.
    • Identity and linkage data remain consistent across Arrow, Parquet, and streaming exports.
    • Added optional identity-aware Parquet comparison through the with_ids flag.
  • Bug Fixes

    • Validation detects missing, null, or duplicate identity values.
    • Parquet comparisons and dumps omit identity metadata by default while matching rows using natural keys.

@coderabbitai

coderabbitai Bot commented Aug 6, 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

QPX feature, PSM, and protein-group exports now include deterministic identity columns. Feature and PSM exports share bidirectional references. Parquet comparison and validation handle identity columns separately from natural-key row matching.

Changes

QPX identity and export integrity

Layer / File(s) Summary
Identity derivation foundation
src/openms/include/OpenMS/FORMAT/QPXIdentity.h, src/openms/source/FORMAT/QPXIdentity.cpp, src/tests/class_tests/openms/source/QPXIdentity_test.cpp
Adds canonical serialization, float formatting, BLAKE2b-based signed Int64 IDs, and identity helpers for features, PSMs, and protein groups.
Schema and metadata contracts
src/openms/include/OpenMS/FORMAT/ArrowSchemaRegistry.h, src/openms/source/FORMAT/ArrowSchemaRegistry.cpp, src/openms/include/OpenMS/FORMAT/ArrowIOHelpers.h, src/openms/source/FORMAT/ArrowIOHelpers.cpp, src/openms/include/OpenMS/FORMAT/ConsensusMapArrowExport.h, src/openms/include/OpenMS/FORMAT/QPXFile.h
Adds identity and cross-reference fields, identity metadata, canonical scan parsing, run-file resolution, and feature-link export parameters.
Identity-aware exports
src/openms/source/FORMAT/ConsensusMapArrowExport.cpp, src/openms/source/FORMAT/QPXFile.cpp, src/openms/source/FORMAT/ProteinGroupArrowExport.cpp, src/topp/IsobaricWorkflow.cpp, src/topp/ProteinQuantifier.cpp, src/topp/ProteomicsLFQ.cpp
Writes deterministic feature, PSM, and protein-group IDs. Feature exports collect links, and PSM exports consume them across one-shot and streaming paths.
Comparison and validation
src/openms/source/FORMAT/ParquetTableComparator.cpp, src/openms/source/FORMAT/QPXValueValidation.cpp, src/topp/ParquetDiff.cpp, CHANGELOG
Excludes identity columns from default comparisons and TSV dumps. It validates identity presence, non-nullness, and uniqueness.
Schema, export, and identity tests
src/tests/class_tests/openms/source/ArrowSchemaRegistry_test.cpp, src/tests/class_tests/openms/source/ConsensusMapArrowExport_test.cpp, src/tests/class_tests/openms/source/QPXFile_test.cpp, src/tests/class_tests/openms/source/ProteinGroupArrowExport_test.cpp, src/tests/class_tests/openms/source/QPXIdentity_test.cpp, src/tests/class_tests/openms/executables.cmake, src/pyOpenMS/bindings/bind_format.cpp, src/openms/include/OpenMS/FORMAT/sources.cmake, src/openms/source/FORMAT/sources.cmake
Updates schema and export coverage, registers the identity test, and preserves the Python binding and build manifests.

Sequence Diagram(s)

sequenceDiagram
  participant ConsensusMapArrowExport
  participant QPXIdentity
  participant QPXFile
  participant Parquet
  ConsensusMapArrowExport->>QPXIdentity: derive feature_id and psm_id
  ConsensusMapArrowExport->>Parquet: write feature_id and psm_ids
  ConsensusMapArrowExport->>QPXFile: pass FeatureLinks
  QPXFile->>Parquet: write psm_id and feature_id
Loading

Possibly related PRs

Poem

A rabbit checks each row,
While signed IDs grow.
Features link to PSM friends,
Streams merge when batches end.
Parquet keys stay bright.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.92% 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 summarizes the main changes: mandatory QPX identity IDs and feature-to-PSM cross-references.
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 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch qpx-identity-ids

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: 5

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/FORMAT/ParquetTableComparator.cpp (1)

638-662: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Use tolerance-aware matching for feature float key fields.

buildKeys_() forms exact canonical keys, including rt and observed_mz, before scalarsEqual_() applies tolerance. A one-ULP change in either feature float produces row-only or duplicate-key errors instead of a tolerated value difference.

Group feature rows by stable fields, then match rt and observed_mz with the configured tolerance. Report ambiguous floating-point candidate matches as key errors. Add a regression test with std::nextafter() values.

🤖 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/FORMAT/ParquetTableComparator.cpp` around lines 638 - 662,
The feature-key path in qpxPrimaryKey/buildKeys_ currently requires exact rt and
observed_mz matches before scalarsEqual_ tolerance is applied. Update feature
row matching to group by stable fields (peptidoform, charge, and run_file_name),
then match rt and observed_mz using the configured tolerance; report multiple
valid candidates as key errors, and add a regression test covering
std::nextafter() values.
🧹 Nitpick comments (3)
src/openms/include/OpenMS/FORMAT/QPXFile.h (1)

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

Add direction qualifiers to the new Doxygen parameters.

Use @param[in] feature_links for each new input parameter.

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

Also applies to: 88-88, 152-153

🤖 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/FORMAT/QPXFile.h` around lines 68 - 71, Add the
Doxygen direction qualifier <code>[in]</code> to each newly documented input
parameter in the affected declarations, including <code>feature_links</code> and
the parameters at the referenced locations. Keep the existing descriptions
unchanged.

Source: Coding guidelines

src/tests/class_tests/openms/source/QPXIdentity_test.cpp (1)

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

Include <limits> explicitly.

Lines 63-65 use std::numeric_limits<float>. The file relies on a transitive include from ClassTest.h or QPXIdentity.h for it. Add the direct include so the test stays compilable if those headers change.

♻️ Proposed change
 `#include` <OpenMS/CONCEPT/ClassTest.h>
 `#include` <OpenMS/test_config.h>
 
 ///////////////////////////
 
 `#include` <OpenMS/FORMAT/QPXIdentity.h>
+
+#include <limits>
🤖 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/QPXIdentity_test.cpp` around lines 9 -
14, Add an explicit <limits> include alongside the existing headers in
QPXIdentity_test.cpp so the std::numeric_limits<float> usage remains
self-contained and does not depend on transitive includes.
src/openms/source/FORMAT/QPXIdentity.cpp (1)

372-393: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Optional: sort the set-valued list once, not through repeated encoding.

The comparator encodes both operands on every comparison, so one composite with a set field re-encodes each element O(log n) times. grouped_runs is small today, so this is only a hygiene point. A decorate-sort-undecorate pass keeps one encode per element and makes the ordering key explicit.

♻️ Proposed refactor
-      auto sorted = std::get<std::vector<std::string>>(values[i]);
-      std::sort(sorted.begin(), sorted.end(),
-                [](const std::string& a, const std::string& b)
-                {
-                  std::string encoded_a, encoded_b;
-                  encodeString(a, encoded_a);
-                  encodeString(b, encoded_b);
-                  return encoded_a < encoded_b;
-                });
-      encodeValue(Value{std::move(sorted)}, out);
+      const auto& raw = std::get<std::vector<std::string>>(values[i]);
+      std::vector<std::pair<std::string, const std::string*>> keyed;
+      keyed.reserve(raw.size());
+      for (const auto& element : raw)
+      {
+        std::string encoded;
+        encodeString(element, encoded);
+        keyed.emplace_back(std::move(encoded), &element);
+      }
+      std::sort(keyed.begin(), keyed.end(),
+                [](const auto& a, const auto& b) { return a.first < b.first; });
+      std::vector<std::string> sorted;
+      sorted.reserve(keyed.size());
+      for (const auto& entry : keyed) { sorted.push_back(*entry.second); }
+      encodeValue(Value{std::move(sorted)}, 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/source/FORMAT/QPXIdentity.cpp` around lines 372 - 393, Update the
set-valued sorting branch in the identity encoding flow to use a
decorate-sort-undecorate approach: encode each string element once, sort by its
stored encoded key, then emit the original values in that order. Preserve the
existing JSON-encoding ordering and encodeValue behavior while eliminating
repeated work in the comparator.
🤖 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/include/OpenMS/FORMAT/QPXIdentity.h`:
- Around line 55-61: Update the stale linkage references in
src/openms/include/OpenMS/FORMAT/QPXIdentity.h lines 55-61 and
src/openms/include/OpenMS/FORMAT/QPXFile.h lines 68-71: replace
ConsensusMapArrowExport::featurePsmLinks() with the applicable
ConsensusMapArrowExport export overload that provides linkage through the
out_links parameter. No nanobind, addon, pyOpenMS test, or additional
documentation changes are required unless the API reference update affects them.

In `@src/openms/source/FORMAT/ArrowIOHelpers.cpp`:
- Around line 471-480: Update qpxScanComponents to use a small thread_local
cache of boost::regex objects keyed by regex_str, reusing the cached compiled
expression when the same native-ID pattern recurs while preserving the existing
empty-input, empty-pattern, and invalid-scan return behavior.

In `@src/openms/source/FORMAT/ConsensusMapArrowExport.cpp`:
- Around line 944-975: Update the PSM link collection around topHitPsmIdentity
and out_links to detect when the same psm_id is assigned to different feature_id
values, report the conflicting duplicate, and avoid silently overwriting the
existing mapping. Preserve per-row psm_ids deduplication while ensuring
conflicting feature-to-PSM links are surfaced.
- Around line 1620-1626: Update the streaming merge in exportToParquetStreaming
so duplicate psm_id entries use the same last-writer-wins assignment semantics
as the one-shot path’s (*out_links)[psm_id] = feature_id. Replace the
insert-only merge around out_links and part_links, while preserving error
filtering and thread-count-independent results.

In `@src/openms/source/FORMAT/ParquetTableComparator.cpp`:
- Around line 901-916: Guard the identity uniqueness scan in validate() against
non-Int64 identity fields before the static_cast to arrow::Int64Scalar. Verify
the field or scalar type and skip reading value—and corresponding uniqueness
checks—when a schema-type mismatch has been recorded, while preserving null
handling and valid Int64 scanning.

---

Outside diff comments:
In `@src/openms/source/FORMAT/ParquetTableComparator.cpp`:
- Around line 638-662: The feature-key path in qpxPrimaryKey/buildKeys_
currently requires exact rt and observed_mz matches before scalarsEqual_
tolerance is applied. Update feature row matching to group by stable fields
(peptidoform, charge, and run_file_name), then match rt and observed_mz using
the configured tolerance; report multiple valid candidates as key errors, and
add a regression test covering std::nextafter() values.

---

Nitpick comments:
In `@src/openms/include/OpenMS/FORMAT/QPXFile.h`:
- Around line 68-71: Add the Doxygen direction qualifier <code>[in]</code> to
each newly documented input parameter in the affected declarations, including
<code>feature_links</code> and the parameters at the referenced locations. Keep
the existing descriptions unchanged.

In `@src/openms/source/FORMAT/QPXIdentity.cpp`:
- Around line 372-393: Update the set-valued sorting branch in the identity
encoding flow to use a decorate-sort-undecorate approach: encode each string
element once, sort by its stored encoded key, then emit the original values in
that order. Preserve the existing JSON-encoding ordering and encodeValue
behavior while eliminating repeated work in the comparator.

In `@src/tests/class_tests/openms/source/QPXIdentity_test.cpp`:
- Around line 9-14: Add an explicit <limits> include alongside the existing
headers in QPXIdentity_test.cpp so the std::numeric_limits<float> usage remains
self-contained and does not depend on transitive includes.
🪄 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: efdd8730-95cb-454c-96e5-b01e9a2bfe42

📥 Commits

Reviewing files that changed from the base of the PR and between af31c76 and 877d676.

📒 Files selected for processing (27)
  • CHANGELOG
  • src/openms/include/OpenMS/FORMAT/ArrowIOHelpers.h
  • src/openms/include/OpenMS/FORMAT/ArrowSchemaRegistry.h
  • src/openms/include/OpenMS/FORMAT/ConsensusMapArrowExport.h
  • src/openms/include/OpenMS/FORMAT/ParquetTableComparator.h
  • src/openms/include/OpenMS/FORMAT/QPXFile.h
  • src/openms/include/OpenMS/FORMAT/QPXIdentity.h
  • src/openms/include/OpenMS/FORMAT/sources.cmake
  • src/openms/source/FORMAT/ArrowIOHelpers.cpp
  • src/openms/source/FORMAT/ArrowSchemaRegistry.cpp
  • src/openms/source/FORMAT/ConsensusMapArrowExport.cpp
  • src/openms/source/FORMAT/ParquetTableComparator.cpp
  • src/openms/source/FORMAT/ProteinGroupArrowExport.cpp
  • src/openms/source/FORMAT/QPXFile.cpp
  • src/openms/source/FORMAT/QPXIdentity.cpp
  • src/openms/source/FORMAT/QPXValueValidation.cpp
  • src/openms/source/FORMAT/sources.cmake
  • src/pyOpenMS/bindings/bind_format.cpp
  • src/tests/class_tests/openms/executables.cmake
  • src/tests/class_tests/openms/source/ArrowSchemaRegistry_test.cpp
  • src/tests/class_tests/openms/source/ConsensusMapArrowExport_test.cpp
  • src/tests/class_tests/openms/source/QPXFile_test.cpp
  • src/tests/class_tests/openms/source/QPXIdentity_test.cpp
  • src/topp/IsobaricWorkflow.cpp
  • src/topp/ParquetDiff.cpp
  • src/topp/ProteinQuantifier.cpp
  • src/topp/ProteomicsLFQ.cpp

timosachsenberg added a commit that referenced this pull request Aug 7, 2026
…aming link merge, cache the scan regex

Review follow-ups on #9884.

ParquetTableComparator::validate() recorded a field-type mismatch and then read the
identity column anyway. It runs on whatever file the caller passes, so a `feature_id`
stored as int32 reached a static_cast to arrow::Int64Scalar -- undefined behaviour rather
than a second error message. The scan now requires the field to actually be int64.

The streaming feature export merged each worker's links with unordered_map::insert, which
keeps the value already present, while the one-shot path assigns with operator[] and keeps
the last. A psm_id claimed by two feature rows would therefore resolve differently between
exportToParquet and exportToParquetStreaming, contradicting the documented promise that the
collected linkage does not depend on the thread count. Both paths now assign.

That cross-row case is the one way the two directions of the cross-reference could disagree
after being built from a single loop, so it is now pinned by a test rather than argued: two
consensus features in one run whose identifications share all four psm-key columns really do
derive one psm_id and are really listed by both rows -- and the psm view refuses exactly that
input as a repeated identity, so the state cannot reach disk. The test asserts the premise
before the refusal, so it cannot pass vacuously.

qpxScanComponents compiled a boost::regex per exported row. getRegExFromNativeID returns one
of seven fixed patterns, so the pattern is now cached thread_local -- per thread rather than
shared, since the exporters call this from inside an OpenMP region where a shared cache would
need a lock and give back what it saves. (Pre-existing: the two extractScan copies this
replaced did the same.)

Docs: the FeatureLinks comments named a ConsensusMapArrowExport::featurePsmLinks() that does
not exist -- the design moved to an out-parameter on the export functions and the comments did
not follow. Also added the missing @PARAM directions and an explicit <limits> include.

Re-verified after the changes: all 747 ids across the four producers still re-derive to what
qpx.core.data.identity computes; 82 QPX/Arrow/Parquet tests pass; Doxygen is clean apart from
the two pre-existing HAVE_DOT warnings.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Y9DY9JfJasCr76qof5n5rx
@timosachsenberg

Copy link
Copy Markdown
Contributor Author

Thanks — five actionable items, four addressed in aa0c035, one skipped with a reason.

The Int64Scalar cast was a real defect. validate() records a field-type mismatch and then reads the identity column anyway, and it runs on whatever file the caller passes, so a feature_id stored as int32 reached a static_cast to a scalar of the wrong dynamic type. Now guarded on arrow::Type::INT64.

The streaming/one-shot merge inconsistency was real too. unordered_map::insert keeps the value already present; the one-shot path's operator[] keeps the last. Both now assign, so the map matches the documented promise that it does not depend on the thread count.

On two feature rows claiming one psm_id — the concern is right about the in-memory state, but it cannot reach disk, and that is now pinned by a test rather than argued. Those two identifications are, by construction, a repeated psm primary key: same run_file_name, scan, peptidoform, charge. The psm view refuses exactly that, and since the collection is transactional the feature file written before it is rolled back. The new section builds that map, asserts the premise first (both rows really do list one psm_id, links.size() == 1), and then asserts the refusal — so it cannot pass vacuously. Detecting it a second time in the collector would report a state that is already reported, one view later.

The regex compile was worth fixing. getRegExFromNativeID returns one of seven fixed patterns, so it is now cached thread_local — per thread, since the exporters call this from inside an OpenMP region where a shared cache would need a lock and give back what it saves. Not a regression from this PR: the two extractScan copies it replaced compiled per call as well.

Also fixed: the FeatureLinks docs named a ConsensusMapArrowExport::featurePsmLinks() that does not exist — the design moved to an out_links parameter and the comments did not follow. Plus the missing @param directions and the explicit <limits>.

Skipped — tolerance-aware matching for the feature float key (the outside-diff comment). Out of scope here: buildKeys_ matching on exact rt/observed_mz is #9877's existing design, not something this PR changes, and it is exactly why the identity columns are not compared — a hash of those floats degrades far worse than the floats themselves. Where a reference needs to be insensitive to them, the fix is a float-free -pk, which is what the #9864 Phase 3 plan does. Worth its own issue if you want it changed.

Skipped — decorate-sort-undecorate for grouped_runs. It is the fractions of one quantification unit, typically 1–3 strings; the extra encodes are not measurable and the current form is shorter.

Re-verified after the changes: all 747 ids across the four producers still re-derive to what qpx.core.data.identity computes, 82 QPX/Arrow/Parquet tests pass, and Doxygen is clean apart from the two pre-existing HAVE_DOT warnings.

The docstring-coverage pre-merge check reports 19% — that metric counts Python docstrings and this PR is C++; the new headers are fully Doxygen-documented, which the doc target verifies.

timosachsenberg and others added 2 commits August 7, 2026 09:17
…reference feature<->PSM (#9864)

Every QPX view carries a mandatory int64 identity column that is its primary key --
feature_id, psm_id, pg_id. OpenMS emitted none of the three, so every -out_qpx file was
invalid against the current spec.

The ids are derived exactly as qpx.core.data.identity derives them: BLAKE2b truncated to
8 bytes over the canonical JSON of a footer-declared identity_composite, read as a signed
big-endian int64. Byte-exactness is not cosmetic. `qpxc convert openms` re-derives
feature_id for identified rows from that declared composite but never rewrites the
psm.feature_id pointing at it, so ids that were merely plausible would turn an OpenMS
collection into one with dangling cross-references the moment it was converted -- which
qpx's own dataset validation reports as dangling_feature_id.

The composites are the ones qpxc already hard-codes for OpenMS -out_qpx input, in that
order, so a conversion reproduces what OpenMS wrote.

Reproducing Python's float repr is the one genuinely fiddly part, because the feature
composite hashes rt and observed_mz as persisted. Verified against the reference
implementation on 399,325 float32 values (uniformly random bit patterns, the RT and m/z
ranges QPX actually stores, and exact powers of two either side of both fixed/exponential
boundaries) and on 60,000 random composites carrying control characters, astral-plane
unicode, JSON metacharacters, int64 extremes, nulls and set-valued lists. Zero
mismatches. Then end to end: every one of the 747 rows all four producers write
re-derives to the id OpenMS emitted.

Cross-references: psm.feature_id and feature.psm_ids. A consensus feature emits one row
per run, so its identifications are distributed to the row of their own run -- claiming a
PSM as evidence for a quantity measured in a different file would be wrong. An unassigned
identification keeps feature_id null, as does any psm-only producer. Both directions come
out of one pass over the feature rows, which is what makes them reciprocal: qpx validates
that a PSM pointing at a feature is listed back by that feature.

Measured on the shipped LFQ fixture: 39 consensus features with one identification each
produce 39 links, all resolving, while the other 65 identifications are unassigned and
correctly null; 23x1 + 11x2 + 5x3 = 60 feature rows confirms the per-run distribution.

The scan and run_file_name derivations the two views must agree on were verbatim copies
in both exporters. They are now one shared implementation, because the linkage depends on
that agreement -- two copies would be one edit away from a collection whose
cross-references silently stop resolving.

ParquetDiff leaves the identity and cross-reference columns out of both the comparison and
the TSV dump, with -with_ids to opt back in. The spec states identity is meaningful within
a file only, so comparing a file against a committed reference is a join it tells you not
to make; and feature_id hashes rt, so one ULP of platform drift would not shift a digit,
it would report every row as missing on both sides. Rows are still matched on the natural
key, which degrades gracefully. -schema mode asserts instead what actually matters: the id
is present, never null and never repeated. Consequence: zero churn in the references #9879
committed, verified.

Verification
- QPXIdentity_test pins the derivation against vectors taken from the reference
  implementation, not from this code's own output. It has failed for a real reason: it
  caught std::from_chars silently parsing nothing from a '+'-signed exponent.
- ConsensusMapArrowExport_test re-derives each row's feature_id from the columns as
  written, in the declared order, which is what would catch this exporter hashing the
  right values in the wrong slots.
- The cross-reference test asserts resolvability in both directions plus reciprocity, and
  guards against vacuity -- that guard fired twice on a fixture whose PSMs had no
  resolvable run, which is exactly what it is for.
- Both new ParquetDiff checks were shown to fail on purpose: a table with duplicated ids
  and one with a null id are each reported, and the unmodified file passes.
- Full suite: 8 failures, all in the known environmental baseline (6 CometAdapter
  version-string, PercolatorAdapter numerics, Doxygen HAVE_DOT).

Not in scope: feature.pg_ids. No upstream converter populates it, and the documented
semantic join (anchor_protein + run_file_name in grouped_runs + intensities[].label) is
already fully available in OpenMS output.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Y9DY9JfJasCr76qof5n5rx
…aming link merge, cache the scan regex

Review follow-ups on #9884.

ParquetTableComparator::validate() recorded a field-type mismatch and then read the
identity column anyway. It runs on whatever file the caller passes, so a `feature_id`
stored as int32 reached a static_cast to arrow::Int64Scalar -- undefined behaviour rather
than a second error message. The scan now requires the field to actually be int64.

The streaming feature export merged each worker's links with unordered_map::insert, which
keeps the value already present, while the one-shot path assigns with operator[] and keeps
the last. A psm_id claimed by two feature rows would therefore resolve differently between
exportToParquet and exportToParquetStreaming, contradicting the documented promise that the
collected linkage does not depend on the thread count. Both paths now assign.

That cross-row case is the one way the two directions of the cross-reference could disagree
after being built from a single loop, so it is now pinned by a test rather than argued: two
consensus features in one run whose identifications share all four psm-key columns really do
derive one psm_id and are really listed by both rows -- and the psm view refuses exactly that
input as a repeated identity, so the state cannot reach disk. The test asserts the premise
before the refusal, so it cannot pass vacuously.

qpxScanComponents compiled a boost::regex per exported row. getRegExFromNativeID returns one
of seven fixed patterns, so the pattern is now cached thread_local -- per thread rather than
shared, since the exporters call this from inside an OpenMP region where a shared cache would
need a lock and give back what it saves. (Pre-existing: the two extractScan copies this
replaced did the same.)

Docs: the FeatureLinks comments named a ConsensusMapArrowExport::featurePsmLinks() that does
not exist -- the design moved to an out-parameter on the export functions and the comments did
not follow. Also added the missing @PARAM directions and an explicit <limits> include.

Re-verified after the changes: all 747 ids across the four producers still re-derive to what
qpx.core.data.identity computes; 82 QPX/Arrow/Parquet tests pass; Doxygen is clean apart from
the two pre-existing HAVE_DOT warnings.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Y9DY9JfJasCr76qof5n5rx
@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

qpx re-keyed the pg view on 2026-08-06 (`7fc1b333`, "fix(pg): key pg_id on
full group membership, not the leader"): `identity_composite` is now
`[pg_accessions, grouped_runs, label]`, not `[anchor_protein, ...]`. This
follows it, and fixes a second divergence found on the way.

Why it matters beyond matching the spec. Keying on the leading protein alone
means two groups that share a leader -- `P1;P2` and `P1;P3` -- derive one
pg_id. Measured, with qpx's own derivation and with this branch's code before
the change: both give -1371905184718538057. pg_id is this view's primary key
and qpx does not prevent hash collisions by construction (`identity.py`
defers them to the `duplicate_pk` validation), so the collision refuses the
export rather than merely mislabelling a row.

OpenMS builds pg rows from getIndistinguishableProteins(), whose groups
partition the accessions, so a repeated leader does not arise from its own
inference -- but nothing in the exporter enforces that, and the point of
deriving the id qpx's way is that it agrees for input this code did not
produce.

Both leading members are sets. qpx picks the unordered positions by field
NAME -- `grouped_runs` and `pg_accessions` (writers/base.py) -- so for this
composite they are positions 0 and 1.

Second fix, in canonical(): a set-valued field was sorted but not
deduplicated. qpx keys a dict on each element's JSON encoding and walks the
sorted keys, so equal elements collapse. Sorting alone agrees on every list
with no repeat and disagrees on exactly the ones that have one -- latent for
grouped_runs, reachable for pg_accessions.

Expected ids in the test are computed with a standalone replica of qpx's
derivation, not read back from this implementation; the replica was first
validated by reproducing a value the pre-change code already passed.
Verified the new assertions can fail: reverting to leader-only keying turns
the collision case red with both sides equal, and also breaks the
accession-order and dedup cases.

QPXValueValidation keeps refusing a repeated (anchor_protein, grouped_runs,
label) -- stricter than the identity now is. Only the message and comment
change, to stop calling it "the QPX pg primary key", which pg_id now is.

Local: 250/250 over QPX/Arrow/ParquetDiff/ProteomicsLFQ/ProteinQuantifier/
IsobaricWorkflow/ProSE/MzTab.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Y9DY9JfJasCr76qof5n5rx

@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/tests/class_tests/openms/source/ProteinGroupArrowExport_test.cpp`:
- Around line 504-507: Update the comment describing the QPX natural key to use
pg_accessions, matching the declared pg_id composite (pg_accessions,
grouped_runs, label); only describe anchor_protein as an internal validation key
if that distinction is needed.
🪄 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: 2493096b-3ecc-49d2-a802-61ba37d33905

📥 Commits

Reviewing files that changed from the base of the PR and between 5776d7e and edafa1b.

📒 Files selected for processing (7)
  • CHANGELOG
  • src/openms/include/OpenMS/FORMAT/QPXIdentity.h
  • src/openms/source/FORMAT/ProteinGroupArrowExport.cpp
  • src/openms/source/FORMAT/QPXIdentity.cpp
  • src/openms/source/FORMAT/QPXValueValidation.cpp
  • src/tests/class_tests/openms/source/ProteinGroupArrowExport_test.cpp
  • src/tests/class_tests/openms/source/QPXIdentity_test.cpp
🚧 Files skipped from review as they are similar to previous changes (6)
  • src/tests/class_tests/openms/source/QPXIdentity_test.cpp
  • src/openms/source/FORMAT/ProteinGroupArrowExport.cpp
  • CHANGELOG
  • src/openms/source/FORMAT/QPXValueValidation.cpp
  • src/openms/source/FORMAT/QPXIdentity.cpp
  • src/openms/include/OpenMS/FORMAT/QPXIdentity.h

…leader

Follow-up to the previous commit, which moved pg_id onto the group's full
membership. The value validator still enforced uniqueness of
(anchor_protein, grouped_runs, label), so the two disagreed about what "the
same pg row" is: two groups sharing a leading protein got distinct pg_ids and
were then refused as a repeated primary key. It now builds its key from the
same three values pg_id hashes.

The accession list is canonicalized the way the identity canonicalizes it --
sorted and deduplicated -- so neither the order inference happens to list a
group's members in nor a repeated accession makes two rows look distinct to
the check when the identity calls them the same row.

The run-reuse guard moves with it: one raw file may contribute at most one
quantity of the same GROUP at a label, rather than of the same leader.

anchor_protein stays required -- it is non-nullable in the schema -- but as a
descriptive field, not as a key component. pg_accessions gains the empty and
blank-member checks grouped_runs already had; an empty group was already
refused, via the anchor_protein check, so no input that used to pass now
fails.

Test: two indistinguishable groups sharing a leader (PROT_A;PROT_B and
PROT_A;PROT_C) are two rows with distinct pg_ids that the validator accepts.
Verified it fails for the right reason -- restoring leader-only keying turns
exactly that assertion red (TEST_TRUE(validation.valid), line 572), while the
neighbouring section, where two runs share a stem and the rows really are
duplicates, keeps being refused.

Local: 250/250 over QPX/Arrow/ParquetDiff/ProteomicsLFQ/ProteinQuantifier/
IsobaricWorkflow/ProSE/MzTab.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Y9DY9JfJasCr76qof5n5rx

@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/FORMAT/QPXValueValidation.cpp`:
- Around line 565-573: Update the if statement checking anchor, pg_accessions,
grouped_runs, label, and intensity to place the opening and closing braces on
their own aligned lines, while preserving its existing early return behavior.
🪄 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: eeebe18c-da13-42b8-907b-5924fda94baf

📥 Commits

Reviewing files that changed from the base of the PR and between edafa1b and 5b98cdd.

📒 Files selected for processing (2)
  • src/openms/source/FORMAT/QPXValueValidation.cpp
  • src/tests/class_tests/openms/source/ProteinGroupArrowExport_test.cpp

Refuse a psm_id claimed by different feature rows while collecting links in both the one-shot and streaming exporters. Keep the first owner and report the conflicting ids instead of overwriting silently.

The two ProteomicsLFQ comparison producers are independent executions, and MSVC showed 1.4e-4 relative integration drift. Use a 1e-3 relative ceiling, still orders of magnitude below the 5.3-12x normalization regression this test guards against.
@timosachsenberg
timosachsenberg merged commit 1640a43 into develop Aug 7, 2026
38 of 39 checks passed
@timosachsenberg
timosachsenberg deleted the qpx-identity-ids branch August 7, 2026 21:06
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.

1 participant