Repository navigation
[FIX] QPX: validate values and normalize SILAC labels - #9846
Conversation
Reject invalid QPX primary keys, quantitative values, and grouped-runs invariants before writing, including duplicates across streaming batches. Normalize FeatureFinderMultiplex SILAC channels to the shared SDRF/QPX vocabulary.\n\nRefs #9817
📝 WalkthroughWalkthroughQPX exports now normalize intensity labels, validate PSM, feature, and protein-group tables, track primary-key uniqueness across batches, and reject invalid data before Parquet output creation. ChangesQPX export validation
Sequence Diagram(s)sequenceDiagram
participant QPXExport
participant QPXValueValidation
participant ParquetWriter
QPXExport->>QPXValueValidation: Validate table or streaming batch
QPXValueValidation-->>QPXExport: Return validation result
QPXExport->>ParquetWriter: Write valid data
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 3❌ Failed checks (3 warnings)
✅ Passed checks (2 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
src/openms/source/FORMAT/ConsensusMapArrowExport.cpp (1)
1532-1538: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winConsider removing the partial output when a streaming batch is refused.
The one-shot path at Line 1377 validates before
FileOutputStream::Open, so a rejected table leaves no file. The streaming path cannot do that, because the writer is already open when the first batch is validated. A refusal here returnsfalseafter earlier batches were written, so a truncatedfeature.parquetstays on disk.The tool reports the failure, so this is not a correctness defect. It is the same failure mode the
#9816pre-pass was added to avoid for the PSM view. Deleting the output after a failed close would make the streaming path match the one-shot contract.♻️ Proposed change at the end of `exportToParquetStreaming`
auto outfile_close = outfile->Close(); if (!outfile_close.ok()) { OPENMS_LOG_ERROR << "ConsensusMapArrowExport: Failed to close output stream for " << filename << ": " << outfile_close.ToString() << std::endl; ok = false; } + if (!ok) + { + // A refused batch leaves a prefix of the intended rows on disk. The one-shot path + // validates before creating its destination; remove the partial file so a failed + // streaming export does not look like a complete, shorter feature table. + File::remove(filename); + } return ok;🤖 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/ConsensusMapArrowExport.cpp` around lines 1532 - 1538, Update exportToParquetStreaming so validation failure in the value_validation check removes the partially written output file before returning false. Preserve the existing error logging and ensure cleanup also covers failures after earlier streaming batches have been written, matching the one-shot export behavior.src/tests/class_tests/openms/source/ArrowIOHelpers_test.cpp (1)
288-293: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd cases for the role-validation branches and for a non-SILAC map.
The
unsupportedmap covers only the!supported_silac_plexbranch. Three branches inqpxIntensityLabelsstay untested:
!all_silac_roles_known, when a label names no mass class.- Two-plex
light_count != 1.- Three-plex duplicate roles.
A non-SILAC
ConsensusMapis also untested, so nothing pins the fallback to the scalar resolver atArrowIOHelpers.cpplines 395-400. That case would also pin the marker-detection behaviour discussed onhasSILACMarker.💚 Proposed additional cases
ConsensusMap unsupported; unsupported.setExperimentType("labeled_MS1"); heavy.filename = "unsupported_silac.mzML"; unsupported.setColumnHeaders({{0, heavy}}); labels = ArrowIOHelpers::qpxIntensityLabels(unsupported); TEST_STRING_EQUAL(labels.at(0), "") + + // A two-plex needs exactly one light channel; two non-light channels are unrepresentable. + ConsensusMap no_light; + no_light.setExperimentType("labeled_MS1"); + medium.filename = "no_light.mzML"; + heavy.filename = "no_light.mzML"; + no_light.setColumnHeaders({{0, medium}, {1, heavy}}); + labels = ArrowIOHelpers::qpxIntensityLabels(no_light); + TEST_STRING_EQUAL(labels.at(0), "") + TEST_STRING_EQUAL(labels.at(1), "") + + // A three-plex needs one channel per role; a repeated role is unrepresentable. + ConsensusMap duplicate_role; + duplicate_role.setExperimentType("labeled_MS1"); + light.filename = "duplicate_role.mzML"; + medium.filename = "duplicate_role.mzML"; + ConsensusMap::ColumnHeader medium_again = medium; + duplicate_role.setColumnHeaders({{0, light}, {1, medium}, {2, medium_again}}); + labels = ArrowIOHelpers::qpxIntensityLabels(duplicate_role); + TEST_STRING_EQUAL(labels.at(0), "") + TEST_STRING_EQUAL(labels.at(2), "") + + // A label-free map must fall back to the scalar resolver and stay exportable. + ConsensusMap label_free; + label_free.setExperimentType("label-free"); + ConsensusMap::ColumnHeader lfq; + lfq.filename = "lfq.mzML"; + lfq.label = "label-free"; + label_free.setColumnHeaders({{0, lfq}}); + labels = ArrowIOHelpers::qpxIntensityLabels(label_free); + TEST_STRING_EQUAL(labels.at(0), "LFQ")🤖 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/ArrowIOHelpers_test.cpp` around lines 288 - 293, Extend the qpxIntensityLabels tests around the existing unsupported ConsensusMap case to cover unknown SILAC roles, invalid two-plex light-role counts, duplicate roles in a three-plex map, and a non-SILAC map. Assert each branch’s expected label output, including that non-SILAC input uses the scalar resolver fallback and preserves hasSILACMarker detection behavior.
🤖 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/ArrowIOHelpers.cpp`:
- Around line 281-289: Update hasSILACMarker to recognize only labels containing
a complete, resolvable SILAC mass-class token rather than arbitrary “arg” or
“lys” substrings; retain case-insensitive matching and use the existing SILAC
role/mass-class definitions where available. Add the required <array> include
for the token table, and ensure labels such as “Lysate_A” and “catalyst” return
false so they remain on the label-free path.
In `@src/openms/source/FORMAT/QPXValueValidation.cpp`:
- Around line 334-342: The primary-key validation blocks in
src/openms/source/FORMAT/QPXValueValidation.cpp lines 334-342 and 405-416 must
report every null key component instead of silently marking the key invalid. In
the psm block, add an error naming null charge and validate run_file_name
independently of peptidoform; in the feature block, add errors naming null
peptidoform and charge. Preserve the existing behavior that an
empty-but-non-null peptidoform is valid for unmapped features.
- Around line 308-313: Replace the exhaustive table check in the streaming QPX
export path with table->Validate(), or gate ValidateFull() behind an optional
configuration setting. Preserve the existing error reporting and early return
through addError when validation fails, while avoiding the extra per-value
validation during QPXFile::writeBatch().
---
Nitpick comments:
In `@src/openms/source/FORMAT/ConsensusMapArrowExport.cpp`:
- Around line 1532-1538: Update exportToParquetStreaming so validation failure
in the value_validation check removes the partially written output file before
returning false. Preserve the existing error logging and ensure cleanup also
covers failures after earlier streaming batches have been written, matching the
one-shot export behavior.
In `@src/tests/class_tests/openms/source/ArrowIOHelpers_test.cpp`:
- Around line 288-293: Extend the qpxIntensityLabels tests around the existing
unsupported ConsensusMap case to cover unknown SILAC roles, invalid two-plex
light-role counts, duplicate roles in a three-plex map, and a non-SILAC map.
Assert each branch’s expected label output, including that non-SILAC input uses
the scalar resolver fallback and preserves hasSILACMarker detection behavior.
🪄 Autofix (Beta)
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: 37708a03-9646-404d-acd8-5e758500c772
📒 Files selected for processing (15)
CHANGELOGsrc/openms/include/OpenMS/FORMAT/ArrowIOHelpers.hsrc/openms/include/OpenMS/FORMAT/QPXValueValidation.hsrc/openms/include/OpenMS/FORMAT/sources.cmakesrc/openms/source/FORMAT/ArrowIOHelpers.cppsrc/openms/source/FORMAT/ConsensusMapArrowExport.cppsrc/openms/source/FORMAT/ProteinGroupArrowExport.cppsrc/openms/source/FORMAT/QPXCollectionExport.cppsrc/openms/source/FORMAT/QPXFile.cppsrc/openms/source/FORMAT/QPXValueValidation.cppsrc/openms/source/FORMAT/sources.cmakesrc/tests/class_tests/openms/source/ArrowIOHelpers_test.cppsrc/tests/class_tests/openms/source/ConsensusMapArrowExport_test.cppsrc/tests/class_tests/openms/source/ProteinGroupArrowExport_test.cppsrc/tests/class_tests/openms/source/QPXFile_test.cpp
Narrow SILAC detection, remove failed streaming outputs, and report all null primary-key components with regression coverage.
…e a partial collection (#9849) * [FIX,TEST] QPX: separate unmapped features, never leave a partial collection Three defects in the QPX export contract added by #9846/#9843, found reviewing #9847. Tightening the contract is fine where the producers can satisfy it; these are cases where they cannot, or where the enforcement is not clean. 1. Feature primary key refused maps OpenMS itself produces. The key is (peptidoform, charge, run_file_name, rt). QPX permits unmapped features and ConsensusMapArrowExport writes them with an empty peptidoform, so for those rows the key collapses to (charge, run_file_name, rt) - and 'rt' is narrowed to float32 on write, one ULP being 244 us at 3000 s. Two co-eluting unmapped features of the same charge in one run then share a key although they are plainly different features, and the whole table is refused. Not a corner case for the tools that write QPX: ProteomicsLFQ with seeds leaves 79 % of the ProteomicsLFQ_3 fixture's consensus features unidentified, and a real run carries tens of thousands, where the birthday bound over the ~2.2e7 representable float32 retention times makes a collision expected. The only ProteomicsLFQ QPX test uses the unseeded configuration, whose features are all identified, so nothing exercised it. 'observed_mz' - written one column over, previously excluded - joins the key. Genuine duplicates (same run, charge, rt AND m/z) are still refused. 2. A refused collection left its earlier files behind. requireExportable() catches everything decidable from the input, but a view can still refuse a row it only sees while building its table, and a write can fail on I/O; by then quantms.feature.parquet is on disk, and a directory holding it without a PSM file is indistinguishable from a complete export of a smaller dataset. New QPXCollectionExport::Transaction scope guard: constructed before the first write, committed after the last, and on any other exit - a view returning false, a writer throwing, an early return - it removes every collection file present. Used by ProteinQuantifier, ProteomicsLFQ and IsobaricWorkflow. Guarding the scope rather than enumerating the failure sites covers the next refusal mode without anyone having to remember it. 3. QPXFile::exportToParquetStreaming() left a truncated PSM file. One validator spans all batches so it can fail on a late one, and the writer and sink are closed regardless, so the footer is written and the file reads as a valid, merely smaller, PSM table. It is now removed, matching what ConsensusMapArrowExport's streaming writer already did for the same situation. Each fix ships with a test that was confirmed to fail without it: the feature-key section fails at the validate() of two co-eluting unmapped features, and the streaming section at TEST_FALSE(File::exists(duplicate_file)). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VcFtJVe1PcMsBzMnnnpWBJ * [DOC,TEST] QPX: record the input contract once, and test the validator directly Documentation and tests only; no behaviour change. The QPX input contract was not written down anywhere a user could find it: the tools that offer -out_qpx just fail with UnableToCreateFile, and the four requirements a foreign consensus map can miss (a scan per identification, a resolvable origin file, uniqueness per (peptidoform, charge, run, scan), and a channel label from the QPX vocabulary) were only discoverable by reading QPXValueValidation. It is now stated on that class - the code that enforces it, so it cannot drift - and nowhere else. ProteinQuantifier's -out_qpx parameter and its documentation page point there rather than restating it, naming ProteomicsLFQ and IsobaricWorkflow as the producers that satisfy the contract by construction. QPXValueValidation had no test file of its own although every sibling QPX class has one, and it is a 600-line OPENMS_DLLAPI class that decides whether an export happens at all. QPXValueValidation_test covers all three views: the psm view's empty-scan, empty/blank run_file_name and duplicate-key refusals, the feature view's separation of unmapped rows by observed_mz and its non-finite coordinate refusals, the documented statefulness (a validator spans batches so a key repeated after a batch boundary is caught; a rejected batch does not advance the key state; reset() starts a new file), the schema-mismatch path, multi-chunk columns, null and 0-row tables, and Result::toString(). The invalid inputs are built through the exporters rather than by patching columns, so each section exercises a shape a producer really emits - an identification without a spectrum reference, or the one-MS2-on-two-features duplication IDMapper creates. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VcFtJVe1PcMsBzMnnnpWBJ * [FIX,TEST] Transaction must not delete a collection that predates it Addresses the CodeRabbit review on #9849. The scope guard removed every collection file in the output directory on a failed export, including files that were already there. Re-running a pipeline into the same -out_qpx directory is the normal case, so a failed re-run destroyed the previous, complete result. The test encoded that behaviour by creating its stub files before constructing the guard. The guard now records which of the three files exist at construction and removes only the ones this export created. A run that fails after overwriting a pre-existing file still leaves the directory mixing two exports - that cannot be undone without staging - so the destructor names the surviving files in a warning instead of letting the directory look coherent. The test creates its files inside the guard's lifetime, as an export does, and gains coverage that a failed export preserves a complete previous collection; that assertion fails without the fix. Also from the same review: - QPXFile and ConsensusMapArrowExport left a zero-byte .parquet behind when parquet::arrow::FileWriter::Open failed: arrow::io::FileOutputStream::Open had already created and truncated the file, and this early return happens before the close-and-remove block that covers every later failure. Both now close and remove it. (ConsensusMapArrowExport is not otherwise part of this PR's changes, but the two writers are deliberately symmetric here.) - Doxygen: the Transaction constructor, destructor and commit() use /** */ with @brief, and the constructor documents @PARAM[in] directory. - Style: braces on their own aligned lines, and '\n' instead of std::endl in the new logging. Verified end to end: a failed export into a fresh directory still leaves it empty, and a failed export into a directory holding a previous collection leaves all three of its files in place with the warning. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VcFtJVe1PcMsBzMnnnpWBJ * [FIX] Link QPXValueValidation_test against Arrow Fixes the windows-2025/cl.exe build failure on this branch: 37 LNK2019s, all unresolved __declspec(dllimport) arrow:: symbols, on QPXValueValidation_test.exe. The test was added to executables.cmake without the matching target_link_libraries(... ${OPENMS_ARROW_TARGET} ${OPENMS_PARQUET_TARGET}) that every other Arrow-using class test carries. It builds its invalid inputs with arrow::FloatBuilder and ArrayData::Make rather than through the exporters - deliberately, so each section exercises a shape a producer really emits - so it needs Arrow itself, not just what OpenMS re-exports. On Linux/macOS libOpenMS statically links Arrow and re-exports its symbols, so the link happens to succeed; on Windows they are dllimport and nothing satisfies them. QPXCollectionExport_test, added alongside it, uses no Arrow type and correctly stays unlinked. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VcFtJVe1PcMsBzMnnnpWBJ * [FIX,TEST] Remove the partial file when a one-shot Parquet write fails This PR taught both streaming writers to clean up after themselves, but the one-shot writers next to them still leak. arrow::io::FileOutputStream::Open creates and truncates the file before the table is written, so a write that fails afterwards leaves a fragment carrying little more than the Parquet magic bytes - no footer, so a reader reports it as corrupt rather than as the smaller table it looks like. Two sites, both now closing the stream and removing the file on any failure after the open: - ConsensusMapArrowExport::exportToParquet, directly above the streaming function this PR already fixed. - ArrowIOHelpers::writeTableToParquet, the shared path behind the psm, pg, OpenSwath and MSExperiment exports. ConsensusMapArrowExport::exportToParquet additionally closes explicitly instead of leaving it to the stream's destructor, which discards the error: the final flush is where a full disk surfaces, and that used to be reported as success with a truncated file on disk. Inside the three tools this was contained by QPXCollectionExport::Transaction, which is why it did not show up as a bug; it was not contained for pyOpenMS and library callers, or for ProSE, whose -out_qpx layout the guard cannot cover. Each fix ships with a test confirmed to fail without it - both at the TEST_FALSE(File::exists(...)) line, with the write failing for the intended reason. A row group size of 0 is refused by Parquet for a non-empty table, which reaches a post-open write failure deterministically on every platform. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VcFtJVe1PcMsBzMnnnpWBJ * [TEST] Cover -out_qpx from the seeded ProteomicsLFQ configuration The feature-key defect this PR fixes reached develop because the only ProteomicsLFQ QPX test runs -targeted_only true, whose consensus features are all identified: 0 of its 60 feature rows are unmapped, so nothing ever exported the shape the key could not distinguish. The class test added here reproduces that shape synthetically, but nothing asserts that the tool still produces it. New TOPP_ProteomicsLFQ_qpx_seeds runs TOPP_ProteomicsLFQ_3's seeded configuration with -out_qpx: 210 of 298 feature rows are unmapped, and all three collection files must exist afterwards. Kept as a separate run rather than folded into TOPP_ProteomicsLFQ_3 so no reference file is touched. What it guards is that the shape reaches the exporter and clears it end to end. It is not a reproducer for the float32-rt collision itself - measured on the produced table, the pre-fix key happens not to collide at this fixture's size - and the comment says so rather than implying more; ConsensusMapArrowExport_test covers that directly. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VcFtJVe1PcMsBzMnnnpWBJ --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Summary
grouped_runs/label combinationsSILAC light,SILAC medium, andSILAC heavy, including correct two-plex heavy-channel handlingarg/lyssubstrings as SILAC markersWhy
Arrow schema validation checks declarations, but does not enforce every physical or semantic QPX 1.1 invariant. Consequently, writers could emit schema-shaped files with null required values, duplicate primary keys, ambiguous protein-group run sets, non-canonical labels, or non-finite quantities.
SILAC export also derived labels from modification mass patterns. In a two-plex experiment this could describe the non-light channel as medium even though it is the experiment's heavy channel, and the resulting vocabulary did not match the canonical SDRF/QPX labels.
Impact
Invalid QPX content now fails deterministically at the writer boundary. One-shot exports validate before creating their destination, while streaming validation retains primary-key state across batches and removes incomplete feature output after failure. Valid output remains schema-compatible with the active QPX 1.1 development contract.
This is a follow-up to #9843 and part of #9817. Canonical SILAC vocabulary follows bigbio/qpx#163.
This PR does not fix #9796 (
best_charge_and_fractionnumerical semantics); that remains the next quantification-correctness step.Validation
cmake --build . --target ArrowIOHelpers_test ConsensusMapArrowExport_test ProteinGroupArrowExport_test QPXFile_test -j4ctest -R '^(ArrowIOHelpers|ConsensusMapArrowExport|ProteinGroupArrowExport|QPXFile)_test$' --output-on-failure— 4/4 passedctest -R '^TOPP_ProteinQuantifier_(4|5|6|7|8|9|12|13|15|18_qpx)' --output-on-failure— 23/23 passedgit diff --check origin/develop...HEADSummary by CodeRabbit
Bug Fixes
Improvements