Skip to content

feat: Arrow/Parquet IO for ProteinIdentification, FeatureMap, and ConsensusMap - #8774

Merged
timosachsenberg merged 1 commit into
developfrom
feature/protein-identification-parquet-export
Feb 23, 2026
Merged

timosachsenberg merged 1 commit into
developfrom
feature/protein-identification-parquet-export

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Feb 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds full round-trip Arrow/Parquet IO for ProteinIdentification, FeatureMap, and ConsensusMap. Each map type exports to a .cmd directory containing multiple Parquet files.

New classes

  • ProteinIdentificationArrowIO — export/import protein hits, groups, and search parameters
  • FeatureMapArrowIO — export/import features with convex hulls, nested subordinates, bounding boxes, and PSM linkage
  • ConsensusMapArrowIO — export/import consensus features with feature handles, column headers, and PSM linkage

Key design decisions

  • Reuses QPXFile for PSM export/import (shared across all map types)
  • Reuses ProteinIdentificationArrowIO for protein data (shared across FeatureMap and ConsensusMap)
  • Normalized schema: run-level metadata lives in `search_params.parquet`, linked by `run_identifier`
  • MetaValue list types (`INT_LIST`, `DOUBLE_LIST`, `STRING_LIST`) fully round-tripped
  • Per-PSM `higher_score_better` column for correct score orientation independent of run-level setting
  • Hide Arrow bundled dependency symbols on Linux (`--exclude-libs`) to prevent conflicts with pyarrow

Directory layout

```
experiment.cmd/
├── consensus_features.parquet (or features.parquet)
├── psms.parquet
├── proteins.parquet
├── protein_groups.parquet
└── search_params.parquet
```

Files changed (21 files, +9426 lines)

Category Files
Headers `ConsensusMapArrowIO.h`, `FeatureMapArrowIO.h`, `ProteinIdentificationArrowIO.h`
Sources `ConsensusMapArrowIO.cpp`, `FeatureMapArrowIO.cpp`, `ProteinIdentificationArrowIO.cpp`, `QPXFile.cpp`
pyOpenMS bindings `ConsensusMapArrowIO.pxd`, `FeatureMapArrowIO.pxd`, `ProteinIdentificationArrowIO.pxd`
Build config `sources.cmake` (x2), `CMakeLists.txt` (x2), `executables.cmake`, `create_cpp_extension.py`
Tests `ConsensusMapArrowIO_test.cpp`, `FeatureMapArrowIO_test.cpp`, `ProteinIdentificationArrowIO_test.cpp`, `QPXFile_test.cpp`

Test plan

  • `QPXFile_test` — PSM export with higher_score_better, scan, reference_file_name
  • `ProteinIdentificationArrowIO_test` — proteins, groups, search params round-trip
  • `FeatureMapArrowIO_test` — features, convex hulls, subordinates, PSMs, metavalues
  • `ConsensusMapArrowIO_test` — consensus features, handles, column headers, PSMs, metavalues
  • CI green on all 5 build platforms (Linux g++/clang++/ARM, macOS, Windows)
  • CI green on all 20 wheel test combinations (Python 3.10-3.14 x 4 OS)

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Feb 21, 2026 •

Copy link
Copy Markdown
Contributor

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

Adds an experimental OpenMS::ConsensusMapArrowIO (WITH_PARQUET) providing Arrow/Parquet export/import for ConsensusMap features, nested feature handles, PSM linkage, and multi-file Parquet orchestration; expands Arrow schemas, helpers, and tests to support list metavalue types, per-PSM fields, and metadata round-trips.

Changes

Cohort / File(s) Summary
ConsensusMapArrowIO
src/openms/include/OpenMS/FORMAT/ConsensusMapArrowIO.h, src/openms/source/FORMAT/ConsensusMapArrowIO.cpp, docs/plans/2026-02-20-consensusmap-arrow-io.md, docs/plans/2026-02-20-consensusmap-arrow-io-design.md
New experimental public class with static methods to export/import consensus features and PSMs as Arrow Tables and to read/write multi-file Parquet directories (consensus_features.parquet, psms.parquet, proteins.parquet, protein_groups.parquet, search_params.parquet). Implements nested handles, metavalues, map-level metadata, JSON helpers, and Parquet read/write helpers.
Build & Registration
src/openms/include/OpenMS/FORMAT/sources.cmake, src/openms/source/FORMAT/sources.cmake, src/tests/class_tests/openms/executables.cmake, src/tests/class_tests/openms/CMakeLists.txt, src/pyOpenMS/CMakeLists.txt
Adds header/source to WITH_PARQUET lists, registers ConsensusMapArrowIO_test and links Arrow/Parquet targets for tests, and adjusts pyOpenMS linking to avoid direct Arrow linkage for the zerocopy module.
Tests
src/tests/class_tests/openms/source/ConsensusMapArrowIO_test.cpp
New comprehensive test suite covering Arrow/Parquet export/import round-trips, empty/single-feature cases, nested handles, metavalue lists, PSM linkage/unassigned PSMs, per-PSM fields, proteins import/export, and metadata/DataProcessing round-trips.
Arrow I/O Schema Harmonization
src/openms/source/FORMAT/FeatureMapArrowIO.cpp, src/tests/class_tests/openms/source/FeatureMapArrowIO_test.cpp
Renames columns (overall_quality→quality, feature_id→feature_unique_id), adds getBoolValue_, standardizes metavalue type labels to double/string/int_list/double_list/string_list, and updates import/export parsing for list metavalue types.
ProteinIdentificationArrowIO
src/openms/source/FORMAT/ProteinIdentificationArrowIO.cpp, src/tests/class_tests/openms/source/ProteinIdentificationArrowIO_test.cpp, src/openms/include/OpenMS/FORMAT/ProteinIdentificationArrowIO.h
Simplifies exported protein/search-param schema, converts is_decoy to boolean, stores dates as epoch seconds, reduces per-run columns, relaxes import expectations, and adds support for metavalue lists.
QPXFile / PSMs
src/openms/source/FORMAT/QPXFile.cpp, src/tests/class_tests/openms/source/QPXFile_test.cpp
PSM schema changes: P_ID→peptide_identification_index, is_decoy → boolean, scan → int32, adds run_identifier and per-PSM higher_score_better, updates psm_metavalues/spectrum_metavalues type mappings and population logic.
Minor Test Updates
src/tests/class_tests/openms/source/FeatureMapArrowIO_test.cpp, src/tests/class_tests/openms/source/ProteinIdentificationArrowIO_test.cpp, src/tests/class_tests/openms/source/QPXFile_test.cpp
Adjust tests to new column names, types, ordering, and metavalue list handling; update assertions for boolean is_decoy, integer scan, renamed ID columns, and list metavalue preservation.

Sequence Diagram(s)

sequenceDiagram
    participant Client as User/Tool
    participant C as ConsensusMapArrowIO
    participant Q as QPXFile
    participant P as ProteinIdentificationArrowIO
    participant FS as ParquetFS

    Client->>C: exportToParquet(cmap, dir, config)
    C->>C: build consensus_features Arrow Table (scalars, handles, metavalues)
    C->>Q: exportPSMsToArrow(cmap)
    Q-->>C: PSM Arrow Table (peptide_identification_index, run_identifier, higher_score_better)
    C->>P: export protein tables (proteins, protein_groups, search_params)
    P-->>C: protein-related Arrow Tables
    C->>FS: write consensus_features.parquet (with map metadata)
    C->>FS: write psms.parquet, proteins.parquet, protein_groups.parquet, search_params.parquet
    FS-->>C: files written
    Client->>C: importFromParquet(dir)
    C->>FS: read consensus_features.parquet, psms.parquet, proteins*.parquet
    C->>P: import proteins -> ProteinIdentification objects
    C->>C: reconstruct ConsensusMap, link PSMs to features
    C-->>Client: ConsensusMap populated
Loading

Possibly related PRs

Suggested reviewers

  • jpfeuffer
  • cbielow

Poem

🐰 In burrows of bytes I hop and hum,

I stitch features, handles, PSMs in sum.
Parquet leaves crinkle, Arrow streams flow,
Round‑trips return where the data go.
A tiny carrot for each saved row!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 53.85% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'feat: Arrow/Parquet IO for ProteinIdentification, FeatureMap, and ConsensusMap' directly and clearly summarizes the main change: adding Arrow/Parquet I/O functionality across three major data structures, which aligns with the extensive refactoring and new implementations documented in the changeset.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/protein-identification-parquet-export

Tip

Issue Planner is now in beta. Read the docs and try it out! Share your feedback on Discord.


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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 15

Caution

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

⚠️ Outside diff range comments (1)
src/pyOpenMS/create_cpp_extension.py (1)

84-98: ⚠️ Potential issue | 🟡 Minor

Addon filter is asymmetric with the pxd filter — Arrow-named addons won't be excluded when WITH_PARQUET is disabled.

The _is_parquet_related predicate (line 87) correctly catches any filename containing 'Arrow', but _is_parquet_addon (lines 94–95) only checks for 'Parquet'. Since Arrow-related pxd files exist (FeatureMapArrowIO.pxd, MSExperimentArrowExport.pxd, ProteinIdentificationArrowIO.pxd), addon files with matching names could be added in the future. If an Arrow-named addon .pyx file is created (e.g. FeatureMapArrowIO.pyx), it will be included in a non-Parquet build, causing autowrap or Cython compile failures.

🔧 Proposed fix
     def _is_parquet_addon(name):
-      return 'Parquet' in name
+      return 'Arrow' in name or 'Parquet' in name
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/pyOpenMS/create_cpp_extension.py` around lines 84 - 98, The addon filter
is asymmetric: _is_parquet_related excludes names containing 'Arrow' or
'Parquet' for pxd_files but _is_parquet_addon only checks 'Parquet', which can
let Arrow-named addons slip through; update the _is_parquet_addon predicate used
for filtering addons to mirror _is_parquet_related (i.e., check for 'Arrow' or
'Parquet' in os.path.basename(a)) and keep the same conditional branch and
diagnostic print so that when WITH_PARQUET is False any addon with 'Arrow' or
'Parquet' in its basename is excluded from addons.
🧹 Nitpick comments (13)
docs/plans/2026-02-19-featuremap-arrow-io-design.md (1)

9-18: Add a language specifier to the fenced code block.

The markdownlint tool flags this block (MD040). Since the content is a directory listing, use text as the language identifier.

🔧 Proposed fix
-```
+```text
 <name>.fmd/
   features.parquet         # One row per feature (top-level + subordinates)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/plans/2026-02-19-featuremap-arrow-io-design.md` around lines 9 - 18, The
fenced code block showing the directory listing that begins with "<name>.fmd/"
should include a language specifier to satisfy markdownlint MD040; update the
opening fence from ``` to ```text so the block starts with "```text" and the
content remains unchanged (the directory listing lines including
"features.parquet", "psms.parquet", etc.).
docs/plans/2026-02-20-consensusmap-arrow-io.md (1)

932-932: Consider extracting shared helpers into a private internal header rather than copy-pasting.

The implementation notes explicitly document copy-pasting ~700 lines from FeatureMapArrowIO.cpp into ConsensusMapArrowIO.cpp. While anonymous-namespace helpers are TU-private, they can still be shared via a non-installed _impl.h (per the convention already described in the coding guidelines: "Use _impl.h files only when necessary for template implementations") or a private ArrowIOHelpers.h added to the source/FORMAT/ tree. This avoids maintaining identical helpers in two (or more) translation units.

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

In `@docs/plans/2026-02-20-consensusmap-arrow-io.md` at line 932, The duplicated
anonymous-namespace helpers (appendMetaValues_, writeArrowTableToParquet_,
readParquetTable_, getColumn_, the type-safe getters, readMetaValues_, and JSON
serialization logic) should be extracted into a shared private header to avoid
copy-paste: create a non-installed internal header (e.g., ArrowIOHelpers.h or a
_impl.h) in the same source tree, move the shared helper implementations there,
update ConsensusMapArrowIO.cpp and FeatureMapArrowIO.cpp to include that private
header, and keep the helpers' symbols but make them static/namespace-scoped or
inline as needed to preserve TU visibility and avoid ABI changes. Ensure
includes and build rules are updated so only internal code uses the header.
src/tests/class_tests/openms/source/FeatureMapArrowIO_test.cpp (1)

946-955: Minor: hit lookup by score threshold is fragile.

The approach of finding target/decoy hits by h.getScore() < 0.01 works for the current test data but could silently break if test scores are adjusted. A lookup by sequence string would be more robust and self-documenting:

💡 Suggested alternative
-  const PeptideHit* target_hit = nullptr;
-  const PeptideHit* decoy_hit = nullptr;
-  for (const auto& h : out_pid1.getHits())
-  {
-    if (h.getScore() < 0.01) target_hit = &h;
-    else decoy_hit = &h;
-  }
+  const PeptideHit* target_hit = nullptr;
+  const PeptideHit* decoy_hit = nullptr;
+  for (const auto& h : out_pid1.getHits())
+  {
+    if (h.getSequence().toString() == "PEPTIDER") target_hit = &h;
+    else if (h.getSequence().toString() == "ACDEFGHIK") decoy_hit = &h;
+  }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/tests/class_tests/openms/source/FeatureMapArrowIO_test.cpp` around lines
946 - 955, The hit selection by score in the loop over out_pid1.getHits() is
fragile; instead locate the target and decoy by their peptide sequence to make
the test deterministic: iterate out_pid1.getHits(), call the PeptideHit sequence
accessor (e.g., h.getSequence() or h.getMetaValue("sequence") as appropriate)
and set target_hit when it matches the known target sequence string and
decoy_hit when it matches the known decoy sequence string; keep the existing
TEST_NOT_EQUAL assertions to verify both were found.
src/tests/class_tests/openms/source/QPXFile_test.cpp (1)

34-181: Consider adding a value-level assertion for the run_identifier column.

The test verifies run_identifier exists in the schema (line 124) but never checks its actual values. Since each PSM should carry pep_id.getIdentifier() (set to "test_search" in the test data), a quick value check would increase confidence in the new column's correctness:

💡 Suggested addition (after line 168)
// Verify run_identifier values
auto ri_col = table->GetColumnByName("run_identifier");
auto ri_arr = std::static_pointer_cast<arrow::StringArray>(ri_col->chunk(0));
TEST_EQUAL(ri_arr->GetString(0), "test_search")
TEST_EQUAL(ri_arr->GetString(1), "test_search")
TEST_EQUAL(ri_arr->GetString(2), "test_search")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/tests/class_tests/openms/source/QPXFile_test.cpp` around lines 34 - 181,
Add value-level assertions for the run_identifier column to ensure it contains
each PeptideIdentification's identifier ("test_search"); after the Arrow export
(QPXFile::exportToArrow) retrieve the "run_identifier" column via
table->GetColumnByName("run_identifier"), cast its chunk to arrow::StringArray
and add TEST_EQUAL checks that GetString(0), GetString(1) and GetString(2) each
equal "test_search" (peptide_id identifiers set earlier with
peptide_id.setIdentifier("test_search")).
src/pyOpenMS/pxds/FeatureMapArrowIO.pxd (1)

26-30: exportToParquet lacks a default for config, requiring Python callers to always provide it.

The C++ declaration has const ParquetWriteConfig& config = ParquetWriteConfig{}, but the .pxd binding requires all three arguments. Python users must construct a ParquetWriteConfig explicitly for every call.

Consider adding a Python addon or a default-valued wrapper so the Python API mirrors the C++ convenience:

# In a pyOpenMS addon file:
def exportToParquet(feature_map, directory, config=None):
    if config is None:
        config = ParquetWriteConfig()
    return FeatureMapArrowIO._exportToParquet(feature_map, directory, config)

This is non-blocking since the binding is functional as-is.

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

In `@src/pyOpenMS/pxds/FeatureMapArrowIO.pxd` around lines 26 - 30, The binding
for exportToParquet currently requires a ParquetWriteConfig from Python even
though the C++ signature has a default; add a Python-facing default wrapper so
callers can omit config: create a thin addon or wrapper function (e.g.,
FeatureMapArrowIO.exportToParquet or exportToParquet wrapper) that accepts
(feature_map, directory, config=None), supplies config = ParquetWriteConfig()
when None, and calls the existing bound function (e.g.,
FeatureMapArrowIO._exportToParquet or the current exportToParquet binding) to
preserve behavior; ensure the wrapper name matches the public API and forwards
the objects by reference as before.
src/openms/source/FORMAT/ConsensusMapArrowIO.cpp (1)

490-553: Use OpenMS::String for numeric conversions in column‑header JSON.
std::to_string/std::stoull are used when serializing/deserializing map_index, size, and unique_id. The codebase prefers OpenMS::String conversions for numeric parsing/formatting. As per coding guidelines: Prefer OpenMS::String for numeric formatting and parsing due to precision and performance advantages.

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

In `@src/openms/source/FORMAT/ConsensusMapArrowIO.cpp` around lines 490 - 553, The
serializeColumnHeaders_ and deserializeColumnHeaders_ functions currently use
std::to_string and std::stoull for formatting/parsing map_index, size and
unique_id; replace those with OpenMS::String-based conversions (use
OpenMS::String for numeric -> string when building JSON in
serializeColumnHeaders_ and use OpenMS::String parsing utilities when reading
numbers in deserializeColumnHeaders_) so the code follows the project convention
and avoids std::string numeric conversions (update the places that call
std::to_string for map_index/size/unique_id and the std::stoull parsing in
deserializeColumnHeaders_ accordingly).
src/openms/source/FORMAT/FeatureMapArrowIO.cpp (1)

682-691: Prefer OpenMS::String for numeric parsing.
std::stol/stod are used for MetaValue parsing; the codebase guideline prefers OpenMS::String conversions for numeric parsing/formatting. As per coding guidelines: Prefer OpenMS::String for numeric formatting and parsing due to precision and performance advantages.

🔧 Example adjustment
-        try { target.setMetaValue(name, static_cast<int>(std::stol(value_str))); }
+        try { target.setMetaValue(name, String(value_str).toInt()); }
         catch (...) { target.setMetaValue(name, value_str); }
...
-        try { target.setMetaValue(name, std::stod(value_str)); }
+        try { target.setMetaValue(name, String(value_str).toDouble()); }
         catch (...) { target.setMetaValue(name, value_str); }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/source/FORMAT/FeatureMapArrowIO.cpp` around lines 682 - 691,
Replace std::stol/std::stod numeric parsing with OpenMS::String conversion
helpers: inside the branches that check type_str == "int" and type_str ==
"float", construct an OpenMS::String from value_str and call its
toInt()/toDouble() methods and pass the result to target.setMetaValue(name,...);
keep the existing fallback behavior to store the original value_str on
conversion failure by catching the appropriate exception (e.g.,
OpenMS::Exception::Conversion or std::exception). This touches the same symbols:
type_str, value_str, target.setMetaValue, and the int/float branches in
FeatureMapArrowIO.cpp.
src/openms/source/FORMAT/ProteinIdentificationArrowIO.cpp (6)

135-154: Missing default case in compression switch.

If a new ParquetWriteConfig::Compression enum value is added in the future, the switch will silently skip setting any compression. Add a default case to either use a safe fallback or trigger a warning.

Suggested fix
       case ParquetWriteConfig::Compression::ZSTD:
         builder.compression(arrow::Compression::ZSTD);
         builder.compression_level(config.compression_level);
         break;
+      default:
+        OPENMS_LOG_WARN << "ProteinIdentificationArrowIO: Unknown compression type, defaulting to uncompressed\n";
+        builder.compression(arrow::Compression::UNCOMPRESSED);
+        break;
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/source/FORMAT/ProteinIdentificationArrowIO.cpp` around lines 135 -
154, The switch over ParquetWriteConfig::Compression in
ProteinIdentificationArrowIO.cpp may leave builder.compression unset for unknown
enum values; add a default case after the existing cases that either sets a safe
fallback (e.g., call builder.compression(arrow::Compression::UNCOMPRESSED) and
optionally builder.compression_level(0)) or emits a warning/throw to surface the
unexpected value; update the switch that reads config.compression and ensure you
reference builder.compression and builder.compression_level in the default
branch so compression is always deterministically configured.

47-72: Silently discarding Arrow Status from Append() calls throughout the file.

The (void) cast pattern on Append() calls in appendMetaValues_ (and throughout all export methods) silently swallows failures. While individual Append() calls are unlikely to fail after a successful Reserve(), the metavalue helpers don't have a prior Reserve(). If an allocation failure occurs, data is silently lost.

Consider at minimum a debug-mode assertion, or propagating status from this helper.

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

In `@src/openms/source/FORMAT/ProteinIdentificationArrowIO.cpp` around lines 47 -
72, The appendMetaValues_ helper currently discards arrow::Status from multiple
Append() calls (name_b, value_b, type_b, struct_b) which can silently drop data
on allocation failures; change appendMetaValues_ to return an arrow::Status (or
bool) instead of void and check the result of each Append()/Reserve() call
(e.g., call Reserve on the builders where possible before appending), returning
early with the failure Status if any Append() fails, and update all callers to
propagate/handle that Status; reference symbols: appendMetaValues_, name_b,
value_b, type_b, struct_b, and the Append() calls.

416-449: Extract a helper to reduce massive Reserve/Finish boilerplate.

The Reserve block (lines 416–449) and the Finish block (lines 636–673) together account for ~70 lines of near-identical code per export method, and the same pattern repeats in exportSearchParamsToArrow (lines 1004–1046, 1256–1307). A small template helper or macro would dramatically reduce noise and cyclomatic complexity (flagged by CodeFactor as "Very Complex Method").

Example helper approach
// Helper to reserve and check status, returning false on failure
template <typename Builder>
bool reserveOrLog_(Builder& builder, int64_t n, const char* name)
{
  auto s = builder.Reserve(n);
  if (!s.ok())
  {
    OPENMS_LOG_ERROR << "ProteinIdentificationArrowIO: " << name
                     << " Reserve failed: " << s.ToString() << "\n";
    return false;
  }
  return true;
}

// Helper to finish and check status, returning false on failure
template <typename Builder>
bool finishOrLog_(Builder& builder, std::shared_ptr<arrow::Array>* out, const char* name)
{
  auto s = builder.Finish(out);
  if (!s.ok())
  {
    OPENMS_LOG_ERROR << "ProteinIdentificationArrowIO: " << name
                     << " Finish failed: " << s.ToString() << "\n";
    return false;
  }
  return true;
}

Usage:

if (!reserveOrLog_(accession_builder, num_rows, "accession_builder")) return nullptr;
// ...
if (!finishOrLog_(accession_builder, &arr_accession, "accession_builder")) return nullptr;

Also applies to: 636-673

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

In `@src/openms/source/FORMAT/ProteinIdentificationArrowIO.cpp` around lines 416 -
449, Replace the repeated Reserve/Finish boilerplate with two small template
helpers (e.g., reserveOrLog_<Builder> and finishOrLog_<Builder>) that call
builder.Reserve(num_rows) / builder.Finish(&out), check status.ok(), log the
same OPENMS_LOG_ERROR message with the builder name and status.ToString(), and
return false on failure; then update the sequences that currently call
accession_builder.Reserve(...), score_builder.Reserve(...), ... and their
corresponding Finish calls to use these helpers and return nullptr when they
fail (also apply the same changes in exportSearchParamsToArrow). Use the exact
builder identifiers (accession_builder, score_builder, score_type_builder, ...,
date_builder) when invoking the helpers so the replacements are easily
locatable.

778-867: append_group lambda returns bool but always returns true; return value is never checked.

The lambda (line 782) has return type -> bool and always returns true (line 866). The call sites at lines 878 and 885 discard the return value. Either remove the return type or check it.

Suggested simplification
-  auto append_group = [&](const ProteinIdentification::ProteinGroup& group,
-                          const std::string& type_str,
-                          const String& run_id,
-                          int32_t index) -> bool
+  auto append_group = [&](const ProteinIdentification::ProteinGroup& group,
+                          const std::string& type_str,
+                          const String& run_id,
+                          int32_t index)
   {
     // ... body unchanged ...
-    return true;
   };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/source/FORMAT/ProteinIdentificationArrowIO.cpp` around lines 778 -
867, The append_group lambda declares a bool return but always returns true and
callers ignore it; change append_group to return void (remove "-> bool" and the
final "return true;") and update its captures if needed, or alternatively
implement meaningful error signaling inside append_group and check/propagate the
boolean at its call sites; prefer the simpler fix: convert append_group to void
and remove the unused return value to eliminate misleading API.

88-88: Use "\n" instead of std::endl in logging statements.

Multiple logging statements use std::endl (e.g., lines 88, 127, 178, 193, 210, 217, 236, 242, 252, and many more throughout the file). This flushes the stream on every log call. As per coding guidelines, prefer "\n" for better performance.

Also applies to: 127-127, 177-178, 193-193, 201-201, 210-210, 217-217, 236-236, 242-242, 252-252

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

In `@src/openms/source/FORMAT/ProteinIdentificationArrowIO.cpp` at line 88,
Logging calls in ProteinIdentificationArrowIO.cpp use std::endl which forces a
flush; replace those with "\n" for better performance. Locate all occurrences of
std::endl used with the OPENMS_LOG_* macros (e.g., the message in
writeArrowTableToParquet_ that currently reads OPENMS_LOG_ERROR <<
"ProteinIdentificationArrowIO: null table passed to writeArrowTableToParquet_"
<< std::endl;) and replace std::endl with "\n"; do the same for the other
reported lines (and any other std::endl usages in this file) so every
OPENMS_LOG_ERROR/INFO/DEBUG stream concatenation ends with "\n" instead of
std::endl.

1718-1788: Three nearly identical lambda functions for reading typed data arrays.

readFloatDataArrays, readStringDataArrays, and readIntegerDataArrays (lines 1718–1788) share the same structural pattern, differing only in the Arrow array type and the target data array type. A template function parameterized on the Arrow value type and the OpenMS data array type would eliminate ~50 lines of duplication.

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

In `@src/openms/source/FORMAT/ProteinIdentificationArrowIO.cpp` around lines 1718
- 1788, Replace the three duplicated lambdas (readFloatDataArrays,
readStringDataArrays, readIntegerDataArrays) with a single templated helper that
takes the Arrow value-array type and the OpenMS DataArray type as template
parameters plus a small value-conversion callable; implement a template like
readTypedDataArrays<ArrowValueArrayT, OpenMSDataArrayT> that performs the same
null checks, casts the outer ListArray and inner StructArray, reads name_arr and
values_list_arr, iterates rows to construct an OpenMSDataArrayT, casts
values_list_arr->value_slice(i) to ArrowValueArrayT, converts each entry (via
static_cast or provided converter) and pushes into the OpenMSDataArrayT, then
moves it into group.get...DataArrays(); then replace calls to
readFloatDataArrays/readStringDataArrays/readIntegerDataArrays with explicit
template instantiations (e.g., readTypedDataArrays<arrow::DoubleArray,
ProteinIdentification::ProteinGroup::FloatDataArray>,
readTypedDataArrays<arrow::StringArray,
ProteinIdentification::ProteinGroup::StringDataArray>,
readTypedDataArrays<arrow::Int64Array,
ProteinIdentification::ProteinGroup::IntegerDataArray>) so behavior is
preserved.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/plans/2026-02-19-featuremap-arrow-io-implementation.md`:
- Around line 15-16: The heading "### Task 1: Create header file with class
declaration" is at H3 directly after an H1, violating MD001; change it to an H2
("## Task 1: Create header file with class declaration") or insert an
intervening H2 section above it so heading levels increment correctly, updating
the heading token for that specific line.

In `@docs/plans/2026-02-20-consensusmap-arrow-io-design.md`:
- Around line 36-38: Update the docs to match the implementation: change the
metavalues struct description (the `metavalues` struct referenced next to
`FeatureMapArrowIO`) so that `value_type` is described as a UTF-8 string (e.g.,
"int/float/str") instead of `int32`; ensure the wording explicitly states the
field is a UTF-8 string that holds type names to align with the actual Arrow
schema used by FeatureMapArrowIO.

In `@docs/plans/2026-02-20-consensusmap-arrow-io.md`:
- Line 3: Remove the embedded AI model directive string "**For Claude:**
REQUIRED SUB-SKILL: Use superpowers:executing-plans" from the document (the
markdown content introduced at line with > **For Claude:** ...), deleting that
quoted instruction so the committed design doc contains no model-specific
tooling artifacts; also scan the file for any other "For Claude" or "REQUIRED
SUB-SKILL" occurrences and remove them or convert them into neutral author
notes, then commit the change with a clear message like "docs: remove embedded
AI model directive from plan."
- Around line 199-213: The rt type note is self-contradictory; remove the "use
float32" clause and clearly state the final decision that rt (and mz) use
float64 to match Peak2D/FeatureMapArrowIO precision: replace the two conflicting
bullets with a single line saying "Use float64 for rt and mz (to match
Peak2D::getRT()/Peak2D::getMZ() and FeatureMapArrowIO::exportFeaturesToArrow
precision)." Keep the rest of the bullets (handles from cf.getFeatures(),
cf.getMZ(), cf.getIntensity(), cf.getCharge(), cf.getQuality(), cf.getWidth(),
metavalues) unchanged.
- Around line 247-258: The loop currently discards arrow::Status from all
Append() calls (e.g., handle_struct_b->Append(),
handle_map_index_b->Append(...), handle_unique_id_b->Append(...), etc.), which
can hide errors; update the loop to check each Append() result and
propagate/report failures instead of casting to void—use
ARROW_RETURN_NOT_OK(handle_struct_b->Append(...)) or accumulate with
arrow::internal::checked_status consistent with how
feature_id_builder.Finish(&feature_id_array) is handled so OOM/append errors are
detected before calling Finish().

In `@src/openms/include/OpenMS/FORMAT/ConsensusMapArrowIO.h`:
- Around line 42-137: The review points out that the new C++ class
ConsensusMapArrowIO lacks a pyOpenMS .pxd binding; add
src/pyOpenMS/pxds/ConsensusMapArrowIO.pxd that cimports the appropriate OpenMS
C++ headers and declares the class ConsensusMapArrowIO with the same static
methods (exportFeaturesToArrow, exportPSMsToArrow, exportToParquet,
importFeaturesFromArrow, importPSMsFromArrow, importFromParquet) and matching
parameter/return types (use the existing pxd patterns from FeatureMapArrowIO.pxd
and ProteinIdentificationArrowIO.pxd for arrow::Table/shared_ptr, ConsensusMap,
String, ParquetWriteConfig, etc.), and update the pyOpenMS addon registration
(or the corresponding .pxi wrapper) so the class is exposed to Python; follow
the exact naming and signatures from the C++ header to ensure compatibility.

In `@src/openms/include/OpenMS/FORMAT/ProteinIdentificationArrowIO.h`:
- Around line 121-137: The doc for importFromParquet says files are read in
order "search_params, proteins, and protein_groups" but the function signature
for importFromParquet(const String& proteins_filename, const String&
protein_groups_filename, const String& search_params_filename, ...) places
search_params_filename last; fix by reordering the function parameter list to
(const String& search_params_filename, const String& proteins_filename, const
String& protein_groups_filename, std::vector<ProteinIdentification>&
protein_identifications) or alternatively update the doc comment to reflect the
actual parameter order; if you choose to reorder the signature, update all
callers (notably in ConsensusMapArrowIO.cpp and FeatureMapArrowIO.cpp) to pass
arguments in the new order and adjust any related declarations/definitions to
match.

In `@src/openms/source/FORMAT/ConsensusMapArrowIO.cpp`:
- Around line 1491-1506: The importFromParquet function currently appends into
the provided ConsensusMap (cmap); to avoid silently merging with caller's
existing data, clear the map at the start of
ConsensusMapArrowIO::importFromParquet before importing (e.g., call cmap.clear()
or assign a fresh ConsensusMap) so the import produces a fresh map; update any
tests/comments to reflect this non‑appending behavior if needed.
- Around line 28-32: The JSON parsing code in ConsensusMapArrowIO.cpp uses
std::isdigit but the header <cctype> is missing; add the include <cctype>
alongside the other includes at the top of ConsensusMapArrowIO.cpp so
std::isdigit is properly declared and portable across toolchains (locate the
include block that currently has <cstdio>, <cstring>, <filesystem>, <random>,
<unordered_set> and add <cctype> there).

In `@src/openms/source/FORMAT/FeatureMapArrowIO.cpp`:
- Around line 1586-1601: The FeatureMapArrowIO::importFromParquet function
currently appends data into the provided FeatureMap (via
importFeaturesFromArrow), causing silent accumulation when callers reuse a
non-empty map; modify FeatureMapArrowIO::importFromParquet to clear/reset the
feature_map at the start (e.g., call feature_map.clear() or an equivalent reset)
before importing proteins and features, ensuring subsequent calls do not merge
old and new data, and keep existing setProteinIdentifications(prot_ids) behavior
unchanged.
- Around line 423-526: Replace costly std::endl uses in logging hot paths with
'\n' to avoid unnecessary flushes: in the function writeArrowTableToParquet_
(and other logging sites in FeatureMapArrowIO.cpp) change lines like
OPENMS_LOG_ERROR << "FeatureMapArrowIO: null table passed to
writeArrowTableToParquet_" << std::endl; and similar OPENMS_LOG_ERROR << "... "
<< std::endl; to use '\n' instead (e.g., OPENMS_LOG_ERROR << "..." << '\n';),
and apply the same replacement for all occurrences of std::endl in this file.

In `@src/openms/source/FORMAT/ProteinIdentificationArrowIO.cpp`:
- Around line 309-347: The round-trip loses list and empty MetaValue types
because appendMetaValues_ only handles INT_VALUE, DOUBLE_VALUE, STRING_VALUE and
falls back to string for INT_LIST/DOUBLE_LIST/STRING_LIST/EMPTY_VALUE; update
appendMetaValues_ to detect DataValue kinds INT_LIST, DOUBLE_LIST, STRING_LIST
and EMPTY_VALUE and emit a corresponding type string (e.g.,
"int_list"/"double_list"/"string_list"/"empty") and a serialized representation
that preserves list boundaries (or use repeated entries with the same
name/type), and update readMetaValues_ to recognize those type_str values and
reconstruct the original list/empty MetaValue (calling
MetaInfoInterface::setMetaValue with the appropriate list or empty form) instead
of treating them as plain strings; refer to appendMetaValues_ and
readMetaValues_ to locate the changes.
- Around line 92-111: Extract the repeated RFC 4122 v4 UUID generation into a
single utility function and replace the inline code in
ProteinIdentificationArrowIO, FeatureMapArrowIO, and ConsensusMapArrowIO with
calls to it: create e.g. ArrowIOUtils::generateUUIDv4() that encapsulates the
random_device/mt19937/uniform_int_distribution loop, the version/variant bit
tweaks, formatting to string, and returns std::string; then in
ProteinIdentificationArrowIO (and the other two classes) remove the 20-line
block and call ArrowIOUtils::generateUUIDv4() where the uuid_str is currently
created.

In `@src/tests/class_tests/openms/CMakeLists.txt`:
- Around line 95-102: Add the missing Arrow/Parquet link libraries to the
ConsensusMapArrowIO_test target: locate where other Arrow-backed tests (e.g.,
ProteinIdentificationArrowIO_test and FeatureMapArrowIO_test) call
target_link_libraries with ${OPENMS_ARROW_TARGET} and ${OPENMS_PARQUET_TARGET},
and add an equivalent target_link_libraries(ConsensusMapArrowIO_test
${OPENMS_ARROW_TARGET} ${OPENMS_PARQUET_TARGET}) so the ConsensusMapArrowIO_test
(registered via executables.cmake) links the Arrow and Parquet dependencies.

In `@src/tests/class_tests/openms/source/ConsensusMapArrowIO_test.cpp`:
- Around line 799-801: The test uses START_TEST/END_TEST guarded by WITH_PARQUET
but only the START_TEST is inside the `#ifdef`, leaving END_TEST always compiled;
wrap the entire START_TEST...END_TEST pair in the `#ifdef` and add an `#else` branch
that defines the same START_TEST test but calls
TEST_IGNORE_MESSAGE("WITH_PARQUET disabled") (i.e. add an `#else` block that
creates a fallback test using START_TEST(...){ TEST_IGNORE_MESSAGE(...); }
END_TEST) so the macro pairs match when WITH_PARQUET is not defined.

---

Outside diff comments:
In `@src/pyOpenMS/create_cpp_extension.py`:
- Around line 84-98: The addon filter is asymmetric: _is_parquet_related
excludes names containing 'Arrow' or 'Parquet' for pxd_files but
_is_parquet_addon only checks 'Parquet', which can let Arrow-named addons slip
through; update the _is_parquet_addon predicate used for filtering addons to
mirror _is_parquet_related (i.e., check for 'Arrow' or 'Parquet' in
os.path.basename(a)) and keep the same conditional branch and diagnostic print
so that when WITH_PARQUET is False any addon with 'Arrow' or 'Parquet' in its
basename is excluded from addons.

---

Nitpick comments:
In `@docs/plans/2026-02-19-featuremap-arrow-io-design.md`:
- Around line 9-18: The fenced code block showing the directory listing that
begins with "<name>.fmd/" should include a language specifier to satisfy
markdownlint MD040; update the opening fence from ``` to ```text so the block
starts with "```text" and the content remains unchanged (the directory listing
lines including "features.parquet", "psms.parquet", etc.).

In `@docs/plans/2026-02-20-consensusmap-arrow-io.md`:
- Line 932: The duplicated anonymous-namespace helpers (appendMetaValues_,
writeArrowTableToParquet_, readParquetTable_, getColumn_, the type-safe getters,
readMetaValues_, and JSON serialization logic) should be extracted into a shared
private header to avoid copy-paste: create a non-installed internal header
(e.g., ArrowIOHelpers.h or a _impl.h) in the same source tree, move the shared
helper implementations there, update ConsensusMapArrowIO.cpp and
FeatureMapArrowIO.cpp to include that private header, and keep the helpers'
symbols but make them static/namespace-scoped or inline as needed to preserve TU
visibility and avoid ABI changes. Ensure includes and build rules are updated so
only internal code uses the header.

In `@src/openms/source/FORMAT/ConsensusMapArrowIO.cpp`:
- Around line 490-553: The serializeColumnHeaders_ and deserializeColumnHeaders_
functions currently use std::to_string and std::stoull for formatting/parsing
map_index, size and unique_id; replace those with OpenMS::String-based
conversions (use OpenMS::String for numeric -> string when building JSON in
serializeColumnHeaders_ and use OpenMS::String parsing utilities when reading
numbers in deserializeColumnHeaders_) so the code follows the project convention
and avoids std::string numeric conversions (update the places that call
std::to_string for map_index/size/unique_id and the std::stoull parsing in
deserializeColumnHeaders_ accordingly).

In `@src/openms/source/FORMAT/FeatureMapArrowIO.cpp`:
- Around line 682-691: Replace std::stol/std::stod numeric parsing with
OpenMS::String conversion helpers: inside the branches that check type_str ==
"int" and type_str == "float", construct an OpenMS::String from value_str and
call its toInt()/toDouble() methods and pass the result to
target.setMetaValue(name,...); keep the existing fallback behavior to store the
original value_str on conversion failure by catching the appropriate exception
(e.g., OpenMS::Exception::Conversion or std::exception). This touches the same
symbols: type_str, value_str, target.setMetaValue, and the int/float branches in
FeatureMapArrowIO.cpp.

In `@src/openms/source/FORMAT/ProteinIdentificationArrowIO.cpp`:
- Around line 135-154: The switch over ParquetWriteConfig::Compression in
ProteinIdentificationArrowIO.cpp may leave builder.compression unset for unknown
enum values; add a default case after the existing cases that either sets a safe
fallback (e.g., call builder.compression(arrow::Compression::UNCOMPRESSED) and
optionally builder.compression_level(0)) or emits a warning/throw to surface the
unexpected value; update the switch that reads config.compression and ensure you
reference builder.compression and builder.compression_level in the default
branch so compression is always deterministically configured.
- Around line 47-72: The appendMetaValues_ helper currently discards
arrow::Status from multiple Append() calls (name_b, value_b, type_b, struct_b)
which can silently drop data on allocation failures; change appendMetaValues_ to
return an arrow::Status (or bool) instead of void and check the result of each
Append()/Reserve() call (e.g., call Reserve on the builders where possible
before appending), returning early with the failure Status if any Append()
fails, and update all callers to propagate/handle that Status; reference
symbols: appendMetaValues_, name_b, value_b, type_b, struct_b, and the Append()
calls.
- Around line 416-449: Replace the repeated Reserve/Finish boilerplate with two
small template helpers (e.g., reserveOrLog_<Builder> and finishOrLog_<Builder>)
that call builder.Reserve(num_rows) / builder.Finish(&out), check status.ok(),
log the same OPENMS_LOG_ERROR message with the builder name and
status.ToString(), and return false on failure; then update the sequences that
currently call accession_builder.Reserve(...), score_builder.Reserve(...), ...
and their corresponding Finish calls to use these helpers and return nullptr
when they fail (also apply the same changes in exportSearchParamsToArrow). Use
the exact builder identifiers (accession_builder, score_builder,
score_type_builder, ..., date_builder) when invoking the helpers so the
replacements are easily locatable.
- Around line 778-867: The append_group lambda declares a bool return but always
returns true and callers ignore it; change append_group to return void (remove
"-> bool" and the final "return true;") and update its captures if needed, or
alternatively implement meaningful error signaling inside append_group and
check/propagate the boolean at its call sites; prefer the simpler fix: convert
append_group to void and remove the unused return value to eliminate misleading
API.
- Line 88: Logging calls in ProteinIdentificationArrowIO.cpp use std::endl which
forces a flush; replace those with "\n" for better performance. Locate all
occurrences of std::endl used with the OPENMS_LOG_* macros (e.g., the message in
writeArrowTableToParquet_ that currently reads OPENMS_LOG_ERROR <<
"ProteinIdentificationArrowIO: null table passed to writeArrowTableToParquet_"
<< std::endl;) and replace std::endl with "\n"; do the same for the other
reported lines (and any other std::endl usages in this file) so every
OPENMS_LOG_ERROR/INFO/DEBUG stream concatenation ends with "\n" instead of
std::endl.
- Around line 1718-1788: Replace the three duplicated lambdas
(readFloatDataArrays, readStringDataArrays, readIntegerDataArrays) with a single
templated helper that takes the Arrow value-array type and the OpenMS DataArray
type as template parameters plus a small value-conversion callable; implement a
template like readTypedDataArrays<ArrowValueArrayT, OpenMSDataArrayT> that
performs the same null checks, casts the outer ListArray and inner StructArray,
reads name_arr and values_list_arr, iterates rows to construct an
OpenMSDataArrayT, casts values_list_arr->value_slice(i) to ArrowValueArrayT,
converts each entry (via static_cast or provided converter) and pushes into the
OpenMSDataArrayT, then moves it into group.get...DataArrays(); then replace
calls to readFloatDataArrays/readStringDataArrays/readIntegerDataArrays with
explicit template instantiations (e.g., readTypedDataArrays<arrow::DoubleArray,
ProteinIdentification::ProteinGroup::FloatDataArray>,
readTypedDataArrays<arrow::StringArray,
ProteinIdentification::ProteinGroup::StringDataArray>,
readTypedDataArrays<arrow::Int64Array,
ProteinIdentification::ProteinGroup::IntegerDataArray>) so behavior is
preserved.

In `@src/pyOpenMS/pxds/FeatureMapArrowIO.pxd`:
- Around line 26-30: The binding for exportToParquet currently requires a
ParquetWriteConfig from Python even though the C++ signature has a default; add
a Python-facing default wrapper so callers can omit config: create a thin addon
or wrapper function (e.g., FeatureMapArrowIO.exportToParquet or exportToParquet
wrapper) that accepts (feature_map, directory, config=None), supplies config =
ParquetWriteConfig() when None, and calls the existing bound function (e.g.,
FeatureMapArrowIO._exportToParquet or the current exportToParquet binding) to
preserve behavior; ensure the wrapper name matches the public API and forwards
the objects by reference as before.

In `@src/tests/class_tests/openms/source/FeatureMapArrowIO_test.cpp`:
- Around line 946-955: The hit selection by score in the loop over
out_pid1.getHits() is fragile; instead locate the target and decoy by their
peptide sequence to make the test deterministic: iterate out_pid1.getHits(),
call the PeptideHit sequence accessor (e.g., h.getSequence() or
h.getMetaValue("sequence") as appropriate) and set target_hit when it matches
the known target sequence string and decoy_hit when it matches the known decoy
sequence string; keep the existing TEST_NOT_EQUAL assertions to verify both were
found.

In `@src/tests/class_tests/openms/source/QPXFile_test.cpp`:
- Around line 34-181: Add value-level assertions for the run_identifier column
to ensure it contains each PeptideIdentification's identifier ("test_search");
after the Arrow export (QPXFile::exportToArrow) retrieve the "run_identifier"
column via table->GetColumnByName("run_identifier"), cast its chunk to
arrow::StringArray and add TEST_EQUAL checks that GetString(0), GetString(1) and
GetString(2) each equal "test_search" (peptide_id identifiers set earlier with
peptide_id.setIdentifier("test_search")).

@timosachsenberg
timosachsenberg force-pushed the feature/protein-identification-parquet-export branch 2 times, most recently from 5e696cb to ab2b03d Compare February 21, 2026 09:43

@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 (3)
src/openms/source/FORMAT/ProteinIdentificationArrowIO.cpp (1)

332-341: Prefer OpenMS::String for numeric parsing in readMetaValues_
Use OpenMS::String conversions rather than std::stod to align with project guidance.

💡 Suggested adjustment
-        try { target.setMetaValue(name, std::stod(value_str)); }
+        try { target.setMetaValue(name, String(value_str).toDouble()); }
         catch (...) { target.setMetaValue(name, value_str); }
As per coding guidelines: Prefer OpenMS::String for numeric formatting and parsing due to precision and performance advantages.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/source/FORMAT/ProteinIdentificationArrowIO.cpp` around lines 332 -
341, In readMetaValues_ replace raw std::stol/std::stod parsing with
OpenMS::String conversions: construct an OpenMS::String from value_str and call
its toInt()/toDouble()/toFloat() helpers (e.g. OpenMS::String(value_str).toInt()
or .toDouble()) when setting target.setMetaValue(name, ...), preserving the
existing try/catch fallback that stores the original value_str on failure;
reference the symbols type_str, value_str, target.setMetaValue and the
readMetaValues_ function to locate the change.
src/openms/source/FORMAT/FeatureMapArrowIO.cpp (1)

689-698: Prefer OpenMS::String for numeric parsing in metavalues
Use OpenMS::String conversions rather than std::stod to align with project guidance.

💡 Suggested adjustment
-        try { target.setMetaValue(name, std::stod(value_str)); }
+        try { target.setMetaValue(name, String(value_str).toDouble()); }
         catch (...) { target.setMetaValue(name, value_str); }
As per coding guidelines: Prefer OpenMS::String for numeric formatting and parsing due to precision and performance advantages.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/source/FORMAT/FeatureMapArrowIO.cpp` around lines 689 - 698,
Replace the std::stol/std::stod calls with OpenMS::String conversion methods:
when parsing in the block that checks type_str ("int"/"double"/"float"),
construct an OpenMS::String from value_str and call toInt() for integers and
toDouble() for floating-point, e.g. use OpenMS::String(value_str).toInt() and
OpenMS::String(value_str).toDouble() inside the existing try/catch before
falling back to target.setMetaValue(name, value_str); keep the same catch
behavior and the same target.setMetaValue(name, ...) call sites so only the
conversion routine (used where target.setMetaValue is invoked) is changed.
src/openms/source/FORMAT/ConsensusMapArrowIO.cpp (1)

1333-1380: PSM grouping silently corrupts the import if peptide_identification_index rows are not contiguous.

The stream-based grouping at line 1337 (p_id != current_p_id) creates a new PepIdGroup whenever p_id changes. If rows with the same p_id are not contiguous (e.g., the Parquet file is sorted externally by score or RT), a single PeptideIdentification would be split into multiple groups, producing duplicated or incorrectly partitioned PeptideHit assignments with no warning.

The standard OpenMS round-trip preserves row order and works correctly, but the format is meant to be an interoperable Parquet file. A robust approach groups by key regardless of order:

♻️ Suggested alternative (map-based grouping)
-  std::vector<PepIdGroup> groups;
-  int32_t current_p_id = -1;
+  std::map<int32_t, PepIdGroup> groups_map;   // ordered by p_id for deterministic output
+  std::vector<int32_t> p_id_order;            // preserve insertion order

   for (int64_t row = 0; row < num_rows; ++row)
   {
     int32_t p_id = getInt32Value_(col_p_id, row, -1);
-    if (groups.empty() || p_id != current_p_id)
+    if (groups_map.find(p_id) == groups_map.end())
     {
       // ... build group header
-      groups.push_back(std::move(group));
-      current_p_id = p_id;
+      p_id_order.push_back(p_id);
+      groups_map[p_id] = std::move(group);
     }
-    groups.back().pep_id.getHits().push_back(std::move(hit));
+    groups_map[p_id].pep_id.getHits().push_back(std::move(hit));
   }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/source/FORMAT/ConsensusMapArrowIO.cpp` around lines 1333 - 1380,
The current stream-based grouping (using getInt32Value_(col_p_id, row) compared
to current_p_id and creating PepIdGroup when p_id changes) silently corrupts
imports when peptide_identification_index rows are not contiguous; replace this
logic with a key-based grouping: accumulate rows into a map keyed by
peptide_identification_index (e.g., std::unordered_map<int32_t, PepIdGroup>),
populate each PepIdGroup by reading rows (using getInt32Value_, getInt64Value_,
readMetaValues_, etc.) into the corresponding map entry, and after the loop move
map values into groups (preserving deterministic order if needed); update code
that references current_p_id/current grouping to use the map-aggregated groups
so PeptideIdentification/PeptideHit assignments are correct regardless of row
order.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/plans/2026-02-20-consensusmap-arrow-io-design.md`:
- Line 9: Add a language specifier to the fenced code block that contains the
directory tree listing to satisfy markdownlint MD040; update the triple-backtick
fence around the block that contains "output_dir/" and
"consensus_features.parquet" to use "text" (i.e., ```text) so the snippet is
marked as plain text.

In `@docs/plans/2026-02-20-consensusmap-arrow-io.md`:
- Line 15: The heading "Task 1: Create header file and register in CMake" is
written as an H3 (###) which skips H2 and triggers MD001; change that heading to
H2 (## Task 1: Create header file and register in CMake) so it directly follows
the document H1 and satisfies markdownlint (ensure any subsequent task headings
use consistent H2 levels as well).

In `@src/openms/source/FORMAT/ConsensusMapArrowIO.cpp`:
- Around line 1437-1452: The code dereferences
struct_arr->GetFieldByName("score_name") and ("score_value") into names_arr and
values_arr without null checks, which can crash if those fields are missing;
update the block that handles col_additional_scores in ConsensusMapArrowIO.cpp
to check the pointers returned by struct_arr->GetFieldByName for nullptr before
casting/using them (i.e., verify the raw Field* or the resulting names_arr and
values_arr are non-null), and if either is null, skip processing the score
entries for that row or log/handle the schema mismatch gracefully instead of
calling names_arr->GetString(k) or values_arr->Value(k) and then calling
hit.setMetaValue.
- Around line 891-1041: Add a pyOpenMS .pxd for the C++ class
ConsensusMapArrowIO: declare the class ConsensusMapArrowIO with a default
constructor and copy constructor annotated with "except +" and "nogil", and
expose its public methods (at minimum exportFeaturesToArrow and any other public
API mirrors like importFeaturesFromArrow if present) with correct signatures so
the C++ methods can be called from Python; follow the existing pattern used by
FeatureMapArrowIO and ProteinIdentificationArrowIO .pxd files for naming, method
signatures, and exception/nogil annotations.

In `@src/openms/source/FORMAT/ProteinIdentificationArrowIO.cpp`:
- Around line 1474-1476: Replace the use of std::endl in the warning log inside
ProteinIdentificationArrowIO (the OPENMS_LOG_WARN call that references run_id
and the "creating minimal ProteinIdentification" message) with the newline
character '\n' to avoid unnecessary stream flushing; locate the OPENMS_LOG_WARN
statement and change the trailing std::endl to '\n' (and apply the same change
to any nearby logging lines in ProteinIdentificationArrowIO if present).

---

Duplicate comments:
In `@docs/plans/2026-02-20-consensusmap-arrow-io-design.md`:
- Around line 22-38: The documentation schema in
docs/plans/2026-02-20-consensusmap-arrow-io-design.md does not match the
implemented types and names in ConsensusMapArrowIO.cpp; update the doc to match
the implementation: change unique_id and handles.{map_index,unique_id} from
uint64 to int64, change rt and handles.rt from float32 to float64, change
metavalues.value_type from int32 to utf8 (string), and rename the PSM linkage
column from consensus_feature_id (uint64) to consensus_feature_unique_id (int64)
to match the symbol names and types used in ConsensusMapArrowIO.cpp (refer to
getUniqueId/getRT/getMZ/getFeatures and the consensus_feature_unique_id field).

In `@docs/plans/2026-02-20-consensusmap-arrow-io.md`:
- Around line 247-258: The example discards Arrow builder Append() Status
results (e.g., handles_builder.Append(), handle_struct_b->Append(),
handle_map_index_b->Append(), etc.); update the loop to check and handle each
Append() Status instead of ignoring it — use the project's error handling idiom
(e.g., return or propagate errors via ARROW_RETURN_NOT_OK / if (!status.ok()) {
log/return status }) for every Append() call and for the initial
handles_builder.Append() so failures are not silently dropped.
- Around line 199-213: The note about rt type is contradictory: update the
documentation to consistently state that rt (and mz) should be float64 (not
float32) to match Peak2D::getRT() / FeatureMapArrowIO conventions; change the
earlier bullet that says "Use rt as float32" to "Use rt as float64", and ensure
the `handles` nested column description (the rt field inside list<struct{...}>)
is also listed as float64 so all references (including the comparison to
FeatureMapArrowIO::exportFeaturesToArrow and Peak2D::getRT()) are consistent.
- Line 3: Remove the embedded AI model directive line that reads "**For
Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this
plan task-by-task." from the document; locate the exact string in the file (the
"**For Claude:** ..." directive) and delete it or replace it with a neutral,
human-facing instruction (e.g., a generic task assignment or nothing) so the
committed document contains no model-specific directive.

In `@src/openms/source/FORMAT/ConsensusMapArrowIO.cpp`:
- Around line 28-32: The file is using std::isdigit but does not include
<cctype>; add the missing include by inserting `#include` <cctype> alongside the
other headers (e.g., next to <cstring> or the other includes) so functions like
std::isdigit are declared for use in ConsensusMapArrowIO.cpp.
- Around line 1500-1514: The importFromParquet function currently appends data
into the provided ConsensusMap (cmap) without resetting it; before any imports
(e.g., before the protein import block), call cmap.clear() to remove existing
consensus elements/metadata so the file data doesn't get appended to prior
content. Update ConsensusMapArrowIO::importFromParquet to invoke cmap.clear() at
the start of the function (or immediately before populating with prot_ids and
other imported structures) so subsequent calls replace, not append to, the
existing cmap.

In `@src/tests/class_tests/openms/source/ConsensusMapArrowIO_test.cpp`:
- Around line 799-801: The END_TEST macro is outside the `#ifdef` WITH_PARQUET
guard while START_TEST is inside, causing unmatched test markers when
WITH_PARQUET is not defined; fix this by moving the END_TEST invocation so it is
inside the same `#ifdef` WITH_PARQUET block as START_TEST (or wrap END_TEST with
`#ifdef` WITH_PARQUET/#endif) so START_TEST and END_TEST are always paired;
reference the START_TEST/END_TEST macros and the WITH_PARQUET conditional to
locate and adjust the block.

---

Nitpick comments:
In `@src/openms/source/FORMAT/ConsensusMapArrowIO.cpp`:
- Around line 1333-1380: The current stream-based grouping (using
getInt32Value_(col_p_id, row) compared to current_p_id and creating PepIdGroup
when p_id changes) silently corrupts imports when peptide_identification_index
rows are not contiguous; replace this logic with a key-based grouping:
accumulate rows into a map keyed by peptide_identification_index (e.g.,
std::unordered_map<int32_t, PepIdGroup>), populate each PepIdGroup by reading
rows (using getInt32Value_, getInt64Value_, readMetaValues_, etc.) into the
corresponding map entry, and after the loop move map values into groups
(preserving deterministic order if needed); update code that references
current_p_id/current grouping to use the map-aggregated groups so
PeptideIdentification/PeptideHit assignments are correct regardless of row
order.

In `@src/openms/source/FORMAT/FeatureMapArrowIO.cpp`:
- Around line 689-698: Replace the std::stol/std::stod calls with OpenMS::String
conversion methods: when parsing in the block that checks type_str
("int"/"double"/"float"), construct an OpenMS::String from value_str and call
toInt() for integers and toDouble() for floating-point, e.g. use
OpenMS::String(value_str).toInt() and OpenMS::String(value_str).toDouble()
inside the existing try/catch before falling back to target.setMetaValue(name,
value_str); keep the same catch behavior and the same target.setMetaValue(name,
...) call sites so only the conversion routine (used where target.setMetaValue
is invoked) is changed.

In `@src/openms/source/FORMAT/ProteinIdentificationArrowIO.cpp`:
- Around line 332-341: In readMetaValues_ replace raw std::stol/std::stod
parsing with OpenMS::String conversions: construct an OpenMS::String from
value_str and call its toInt()/toDouble()/toFloat() helpers (e.g.
OpenMS::String(value_str).toInt() or .toDouble()) when setting
target.setMetaValue(name, ...), preserving the existing try/catch fallback that
stores the original value_str on failure; reference the symbols type_str,
value_str, target.setMetaValue and the readMetaValues_ function to locate the
change.

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

🧹 Nitpick comments (4)
src/openms/source/FORMAT/ConsensusMapArrowIO.cpp (3)

430-430: Replace std::endl with '\n' throughout the file.

All logging calls in this new file use std::endl, which flushes the stream on every call. As per coding guidelines, prefer '\n' for better performance in logging and output operations.

♻️ Example adjustment (apply across all log statements)
-      OPENMS_LOG_WARN << "ConsensusMapArrowIO: Unknown processing action: " << action_name << std::endl;
+      OPENMS_LOG_WARN << "ConsensusMapArrowIO: Unknown processing action: " << action_name << '\n';

Based on learnings: "Avoid std::endl; prefer \n for better performance in logging and output operations."

Also applies to: 670-670, 717-717, 765-765, 781-781, 789-789, 798-798, 805-805, 823-823, 829-829, 839-839

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

In `@src/openms/source/FORMAT/ConsensusMapArrowIO.cpp` at line 430, Replace all
uses of std::endl with '\n' in this file: whenever logging macros like
OPENMS_LOG_WARN (e.g., the line that logs "ConsensusMapArrowIO: Unknown
processing action: " << action_name) or other OPENMS_LOG_* calls are followed by
std::endl, change them to use '\n' instead to avoid flushing the stream; scan
for the listed occurrences (around the lines that currently use
OPENMS_LOG_WARN/INFO/ERROR with std::endl) and update each to use '\n' while
keeping the rest of the log message intact.

562-582: Use OpenMS::String for numeric-to-string conversion instead of std::to_string.

Lines 571, 574, 575, and 1257 use std::to_string(...) to serialize integer fields into the JSON/metadata string. Per coding guidelines, prefer OpenMS::String for numeric formatting.

♻️ Example adjustment
-      json += "{\"map_index\":" + std::to_string(map_index)
-            + ",\"size\":" + std::to_string(header.size)
-            + ",\"unique_id\":" + std::to_string(header.unique_id)
+      json += "{\"map_index\":" + String(map_index)
+            + ",\"size\":" + String(header.size)
+            + ",\"unique_id\":" + String(header.unique_id)

Based on learnings: "Prefer OpenMS::String for numeric formatting and parsing due to precision and performance advantages."

Also applies to: 1257-1257

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

In `@src/openms/source/FORMAT/ConsensusMapArrowIO.cpp` around lines 562 - 582,
Replace uses of std::to_string in serializeColumnHeaders_ with
OpenMS::String-based conversions: convert map_index, header.size and
header.unique_id using OpenMS::String(...) (or OpenMS::String::number style per
project's convention) before concatenating into the JSON string; keep
escapeJsonString_ and serializeMetaValues_ calls unchanged so the final
concatenation uses OpenMS::String for all numeric fields in
serializeColumnHeaders_.

164-224: Extensive code duplication with FeatureMapArrowIO.cpp.

The following ~500 lines of helpers are copy-pasted verbatim (or near-verbatim) from FeatureMapArrowIO.cpp:

  • escapeJsonString_, unescapeJsonString_, parseJsonString_, skipWhitespace_
  • serializeDataProcessing_, deserializeDataProcessing_
  • writeArrowTableToParquet_, readParquetTable_
  • getColumn_, getStringValue_, getDoubleValue_, getFloatValue_, getInt64Value_, getInt32Value_, getBoolValue_, isNull_, readMetaValues_

This means the empty-list round-trip bug described for FeatureMapArrowIO.cpp (lines 370–401 and 920–950 below) also exists here. Any future fix must be applied to three locations.

Consider extracting these helpers into a shared translation unit (e.g., src/openms/source/FORMAT/ArrowIOUtils.cpp + ArrowIOUtils.h internal header) so all Arrow IO classes share a single implementation.

Also applies to: 660-957

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

In `@src/openms/source/FORMAT/ConsensusMapArrowIO.cpp` around lines 164 - 224,
This file duplicates a large set of JSON/Arrow helper functions (e.g.,
escapeJsonString_, unescapeJsonString_, parseJsonString_, skipWhitespace_,
serializeDataProcessing_, deserializeDataProcessing_, writeArrowTableToParquet_,
readParquetTable_, getColumn_, getStringValue_, getDoubleValue_, getFloatValue_,
getInt64Value_, getInt32Value_, getBoolValue_, isNull_, readMetaValues_) already
present in FeatureMapArrowIO.cpp which also causes the empty-list round-trip
bug; refactor by extracting these helpers into a single internal utility (create
ArrowIOUtils.h + ArrowIOUtils.cpp) and replace the duplicated implementations in
ConsensusMapArrowIO.cpp and FeatureMapArrowIO.cpp with calls to the shared
functions (keep the same function names/signatures or provide thin wrappers),
and while doing so fix the empty-list serialization/deserialization logic in
serializeDataProcessing_ / deserializeDataProcessing_ so that empty action and
metavalues arrays are emitted and parsed correctly (ensure completion_time
formatting/parsing is preserved and add unit tests covering empty lists
round-trip).
src/openms/source/FORMAT/FeatureMapArrowIO.cpp (1)

1044-1044: Builder/array variable names still use the old overall_quality name after the column rename to "quality".

overall_quality_builder, arr_overall_quality, and col_overall_quality all refer to the now-renamed "quality" Parquet column. This creates a mismatch between variable names and the schema field they represent, which could confuse future maintainers.

♻️ Suggested rename sweep
-  arrow::FloatBuilder overall_quality_builder, quality_rt_builder, quality_mz_builder;
+  arrow::FloatBuilder quality_builder, quality_rt_builder, quality_mz_builder;

-  RESERVE_OR_RETURN(overall_quality_builder)
+  RESERVE_OR_RETURN(quality_builder)

-  (void)overall_quality_builder.Append(feature.getOverallQuality());
+  (void)quality_builder.Append(feature.getOverallQuality());

-  std::shared_ptr<arrow::Array> arr_charge, arr_overall_quality;
+  std::shared_ptr<arrow::Array> arr_charge, arr_quality;

-  FINISH_OR_RETURN(overall_quality_builder, arr_overall_quality)
+  FINISH_OR_RETURN(quality_builder, arr_quality)

-    arr_charge, arr_overall_quality,
+    arr_charge, arr_quality,

-  auto col_overall_quality = getColumn_(tbl, "quality");
+  auto col_quality = getColumn_(tbl, "quality");

Also applies to: 1059-1059

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

In `@src/openms/source/FORMAT/FeatureMapArrowIO.cpp` at line 1044, The Parquet
field was renamed to "quality" but the related builder/array/column variables
still use the old overall_quality name; update all occurrences of
overall_quality_builder, arr_overall_quality, and col_overall_quality to use
consistent names matching the schema (for example quality_builder, arr_quality,
col_quality) and adjust any references/usages in the same function (including
where the field is constructed and pushed into the schema/columns) so variable
names and the arrow::field("quality", ...) column are consistent.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/openms/source/FORMAT/ConsensusMapArrowIO.cpp`:
- Around line 370-401: The parsed-list branches for mv_type "int_list",
"double_list" and "string_list" incorrectly turn "[]" into a non-empty
single-empty-string list or throw; after stripping leading/trailing brackets
(the String s(mv_value); if (s.hasPrefix("[") && s.hasSuffix("]")) s =
s.substr(...);) add a guard: if s.empty() then directly set an empty list meta
value (for ints: DataValue(ListUtils::create<Int>("") is not used — instead
construct/assign an empty IntList/List<Int>), for doubles: an empty
DoubleList/List<double>, and for strings: an empty StringList) and
return/continue; apply this fix in the same handling blocks shown and also in
the deserializeDataProcessing_ and readMetaValues_ code paths mentioned.
- Around line 617-626: The code in ConsensusMapArrowIO.cpp inside
importFromParquet reads numeric strings into num_str and calls std::stoull for
map_index, header.size and header.unique_id without validation or exception
handling; validate that num_str is non-empty and contains only an optional
leading '-' and digits, then wrap each std::stoull call in a try/catch that
catches std::invalid_argument and std::out_of_range and converts them into a
clear failure path (e.g., throw a descriptive std::runtime_error mentioning
importFromParquet and the offending key/value, or set a safe default and
continue if that is acceptable for the function), referencing the symbols
map_index, header.size and header.unique_id so the fixes are applied at those
assignments.

In `@src/openms/source/FORMAT/FeatureMapArrowIO.cpp`:
- Around line 376-412: The list deserialization branches (mv_type ==
"int_list"/"double_list"/"string_list") incorrectly treat the bracket-stripped
empty string ("") as a non-empty input which causes exceptions or wrong results;
update the branches in both deserializeDataProcessing_ and readMetaValues_ to
detect the empty-body case after removing surrounding brackets and, if
s.empty(), directly assign an empty typed list (e.g., an empty
IntList/DoubleList/StringList wrapped in a DataValue) instead of calling
ListUtils::create on "" or splitting "", otherwise proceed with the existing
parsing and trimming logic; modify the int_list, double_list and string_list
blocks to perform this s.empty() guard before calling
ListUtils::create<String/Int/double> or splitting.

---

Duplicate comments:
In `@src/openms/source/FORMAT/ConsensusMapArrowIO.cpp`:
- Around line 1090-1107: The nested Arrow builder Append() calls (e.g.,
handles_builder.Append(), handle_struct_b->Append(),
handle_map_index_b->Append(), etc.) currently ignore return Statuss by casting
to void; capture and check each arrow::Status (or the specific Append return
type) and handle failures instead of swallowing them: assign the result of each
Append to a Status variable, check .ok(), and on failure either return/propagate
the error or log and abort as appropriate for the surrounding function (same
behavior used by appendMetaValues_ if any). Remove the (void) casts and ensure
appendMetaValues_ calls are similarly checked so any builder Append failures are
not silently ignored.
- Around line 1543-1558: The code dereferences results of
struct_arr->GetFieldByName("score_name") and ("score_value") without null
checks, which can crash on schema mismatch; update the block that builds
names_arr and values_arr (variables col_additional_scores, list_arr, struct_arr,
names_arr, values_arr) to first retrieve the Field pointers and verify they are
non-null and of the expected type before static_pointer_casting and using them,
and if either field is missing or a cast would fail, skip processing that row
(or the entire additional_scores block) instead of dereferencing, ensuring
hit.setMetaValue is only called when both name and value arrays are valid.
- Around line 997-1147: The binding layer is missing a pyOpenMS .pxd declaration
for ConsensusMapArrowIO, so add a Cython .pxd entry exposing the
ConsensusMapArrowIO class and its exportFeaturesToArrow method (with appropriate
C++ signatures and return type mapping), declare the necessary includes/types
used by exportFeaturesToArrow (e.g., arrow::Table pointer or a wrapped typedef)
and ensure the method is wrapped for Python use; reference the C++ symbols
ConsensusMapArrowIO and exportFeaturesToArrow when adding the declaration so the
wrapper generator picks up and compiles the binding.

In `@src/openms/source/FORMAT/ProteinIdentificationArrowIO.cpp`:
- Around line 1509-1511: The warning log in ProteinIdentificationArrowIO (the
OPENMS_LOG_WARN call that mentions run_identifier and creating minimal
ProteinIdentification) uses std::endl which forces a flush; change it to use
'\n' at the end of the stream instead (replace std::endl with '\n') to avoid
unnecessary flushing and improve logging performance while leaving the rest of
the message intact.

In `@src/tests/class_tests/openms/source/ConsensusMapArrowIO_test.cpp`:
- Around line 810-812: The END_TEST macro is compiled even when WITH_PARQUET is
disabled, breaking the START_TEST/END_TEST pairing; update the preprocessor
guards so START_TEST and END_TEST are both inside the same WITH_PARQUET
conditional (or move the END_TEST inside the corresponding `#ifdef` WITH_PARQUET)
so that when WITH_PARQUET is off the whole test block (START_TEST ... END_TEST)
is omitted; adjust the `#endif` placement around the START_TEST/END_TEST block to
restore correct pairing.

---

Nitpick comments:
In `@src/openms/source/FORMAT/ConsensusMapArrowIO.cpp`:
- Line 430: Replace all uses of std::endl with '\n' in this file: whenever
logging macros like OPENMS_LOG_WARN (e.g., the line that logs
"ConsensusMapArrowIO: Unknown processing action: " << action_name) or other
OPENMS_LOG_* calls are followed by std::endl, change them to use '\n' instead to
avoid flushing the stream; scan for the listed occurrences (around the lines
that currently use OPENMS_LOG_WARN/INFO/ERROR with std::endl) and update each to
use '\n' while keeping the rest of the log message intact.
- Around line 562-582: Replace uses of std::to_string in serializeColumnHeaders_
with OpenMS::String-based conversions: convert map_index, header.size and
header.unique_id using OpenMS::String(...) (or OpenMS::String::number style per
project's convention) before concatenating into the JSON string; keep
escapeJsonString_ and serializeMetaValues_ calls unchanged so the final
concatenation uses OpenMS::String for all numeric fields in
serializeColumnHeaders_.
- Around line 164-224: This file duplicates a large set of JSON/Arrow helper
functions (e.g., escapeJsonString_, unescapeJsonString_, parseJsonString_,
skipWhitespace_, serializeDataProcessing_, deserializeDataProcessing_,
writeArrowTableToParquet_, readParquetTable_, getColumn_, getStringValue_,
getDoubleValue_, getFloatValue_, getInt64Value_, getInt32Value_, getBoolValue_,
isNull_, readMetaValues_) already present in FeatureMapArrowIO.cpp which also
causes the empty-list round-trip bug; refactor by extracting these helpers into
a single internal utility (create ArrowIOUtils.h + ArrowIOUtils.cpp) and replace
the duplicated implementations in ConsensusMapArrowIO.cpp and
FeatureMapArrowIO.cpp with calls to the shared functions (keep the same function
names/signatures or provide thin wrappers), and while doing so fix the
empty-list serialization/deserialization logic in serializeDataProcessing_ /
deserializeDataProcessing_ so that empty action and metavalues arrays are
emitted and parsed correctly (ensure completion_time formatting/parsing is
preserved and add unit tests covering empty lists round-trip).

In `@src/openms/source/FORMAT/FeatureMapArrowIO.cpp`:
- Line 1044: The Parquet field was renamed to "quality" but the related
builder/array/column variables still use the old overall_quality name; update
all occurrences of overall_quality_builder, arr_overall_quality, and
col_overall_quality to use consistent names matching the schema (for example
quality_builder, arr_quality, col_quality) and adjust any references/usages in
the same function (including where the field is constructed and pushed into the
schema/columns) so variable names and the arrow::field("quality", ...) column
are consistent.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

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

⚠️ Outside diff range comments (1)
src/openms/source/FORMAT/FeatureMapArrowIO.cpp (1)

1424-1653: ⚠️ Potential issue | 🟠 Major

Add type validation before casting Arrow arrays to prevent memory misinterpretation from schema mismatches.

In getBoolValue_() and getInt32Value_() (and similar helpers), the std::static_pointer_cast assumes the array has the expected Arrow type without validation. If an older Parquet file or external file uses int32 for is_decoy (instead of boolean) or string for scan (instead of int32), the cast will silently succeed but reinterpret memory incorrectly, causing data corruption or crashes.

Check array->type_id() before casting, or fail fast with a clear error message indicating schema incompatibility. Consider also adding schema version checking during import to provide better error messages for users attempting to import files from other sources or older versions.

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

In `@src/openms/source/FORMAT/FeatureMapArrowIO.cpp` around lines 1424 - 1653, The
code casts Arrow arrays (e.g., when reading is_decoy, scan, etc.) without
validating the actual Arrow type, which can silently reinterpret memory if the
file schema differs; update the helper functions getBoolValue_, getInt32Value_
(and other similar helpers used here) to first check array->type_id() (or
array->type()->id()) and return a clear error or fallback if the type is
unexpected, e.g., verify boolean for getBoolValue_, int32 for getInt32Value_,
string/list/struct for others, and log/throw a descriptive schema mismatch
message so callers like the code in FeatureMapArrowIO.cpp that reads
col_is_decoy, col_scan, col_protein_accs, col_additional_scores, etc. fail fast
instead of performing unsafe std::static_pointer_casts.
🧹 Nitpick comments (2)
src/openms/source/FORMAT/ConsensusMapArrowIO.cpp (2)

668-770: Replace std::endl with '\n' in logging.

std::endl forces a flush and is slower in hot paths; prefer '\n' in log streams across this file.

As per coding guidelines: "Avoid std::endl; prefer \n for better performance in logging and output operations."

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

In `@src/openms/source/FORMAT/ConsensusMapArrowIO.cpp` around lines 668 - 770,
Replace uses of std::endl with '\n' in the logging calls inside
writeArrowTableToParquet_ (specifically the OPENMS_LOG_ERROR lines that report
"null table passed to writeArrowTableToParquet_" and "Failed to open file: " and
"Failed to write Parquet: " if present here) so the logger doesn't force flush
on each message; locate these calls (OPENMS_LOG_ERROR << ... << std::endl) and
change them to use '\n' instead (e.g., OPENMS_LOG_ERROR << ... << '\n'), and
scan the rest of ConsensusMapArrowIO.cpp for any remaining OPENMS_LOG_* usages
that use std::endl and update them similarly.

563-626: Prefer OpenMS::String/Size for numeric formatting and parsing here.

Column‑header JSON uses std::to_string, std::stoull, and size_t indices. Align with OpenMS conventions (String conversions and Size) for consistency and performance.

As per coding guidelines: "Prefer OpenMS::String for numeric formatting and parsing due to precision and performance advantages" and "Use OpenMS primitive types from OpenMS/CONCEPT/Types.h (e.g., Size, SignedSize) instead of standard types like int, unsigned int for STL container sizes."

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

In `@src/openms/source/FORMAT/ConsensusMapArrowIO.cpp` around lines 563 - 626, The
code uses std::to_string/std::stoull and raw integer types in
serializeColumnHeaders_ and deserializeColumnHeaders_; change these to use
OpenMS conventions: build JSON with OpenMS::String (use OpenMS::String
concatenation instead of std::to_string), replace numeric index/size types with
OpenMS::Size (and other OpenMS typedefs from OpenMS/CONCEPT/Types.h) such that
map_index is a Size and header.size/unique_id use OpenMS types, and parse
numbers in deserializeColumnHeaders_ by collecting into an OpenMS::String and
converting with its conversion methods (e.g., toSize/toInt/toUInt64 as
appropriate) rather than std::stoull; ensure necessary OpenMS headers are
included.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@src/openms/source/FORMAT/FeatureMapArrowIO.cpp`:
- Around line 1424-1653: The code casts Arrow arrays (e.g., when reading
is_decoy, scan, etc.) without validating the actual Arrow type, which can
silently reinterpret memory if the file schema differs; update the helper
functions getBoolValue_, getInt32Value_ (and other similar helpers used here) to
first check array->type_id() (or array->type()->id()) and return a clear error
or fallback if the type is unexpected, e.g., verify boolean for getBoolValue_,
int32 for getInt32Value_, string/list/struct for others, and log/throw a
descriptive schema mismatch message so callers like the code in
FeatureMapArrowIO.cpp that reads col_is_decoy, col_scan, col_protein_accs,
col_additional_scores, etc. fail fast instead of performing unsafe
std::static_pointer_casts.

---

Duplicate comments:
In `@src/openms/source/FORMAT/ConsensusMapArrowIO.cpp`:
- Around line 9-20: Add pyOpenMS bindings for the new ConsensusMapArrowIO C++
class: create/update the corresponding .pxd declaration and any .pyx addon
wrapper exposing ConsensusMapArrowIO and its public methods/constructors so
Python can import it, and ensure the addon is compiled into pyOpenMS;
additionally, if this new format affects file-type registration, update
FileHandler::NamesOfTypes (and any schema entries), and if a TOPP tool was
added, register it in the executables.cmake and ToolHandler.cpp; search for
identifiers ConsensusMapArrowIO, FileHandler::NamesOfTypes, and ToolHandler to
locate the spots to modify.
- Around line 1561-1574: The code dereferences fields returned by
struct_arr->GetFieldByName("score_name") and ("score_value") without null
checks; update the block that creates list_arr/struct_arr/names_arr/values_arr
to verify struct_arr is non-null and that GetFieldByName(...) returned valid
field arrays (i.e., check pointers before static_pointer_cast) and that the
casted arrays have the expected types, and if any are null or of the wrong type
skip processing the additional_scores for this row (or log/throw as appropriate)
before iterating and calling hit.setMetaValue.
- Around line 617-626: The parsing block currently calls std::stoull on num_str
which may be empty or malformed; guard against this by validating num_str before
conversion (ensure it's non-empty and contains only digits, no leading '-') and
wrap the conversion in a try/catch for std::invalid_argument and
std::out_of_range to avoid exceptions propagating; on error, handle gracefully
(e.g. skip setting map_index/header.size/header.unique_id or assign a safe
default and log/report the malformed header) — apply this to the branches that
set map_index, header.size and header.unique_id so the code using key, num_str,
map_index, header.size and header.unique_id is safe.
- Around line 370-401: The int_list/double_list/string_list branches (in
deserializeDataProcessing_, deserializeMetaValues_, and readMetaValues_) strip
surrounding brackets then incorrectly treat an empty body ("[]") as a parse
error or as a single empty string; add a guard after the bracket-strip (e.g. if
s.empty()) that sets the meta value to an actual empty List of the appropriate
type instead of calling ListUtils::create on an empty string or falling into the
catch; for string_list trim entries only when non-empty, and use
DataValue(ListType{}) (or the equivalent empty List created for
Int/double/String) via ListUtils/DataValue to store an empty list for mv_name.

In `@src/openms/source/FORMAT/FeatureMapArrowIO.cpp`:
- Around line 381-412: In the int_list/double_list/string_list branches in
FeatureMapArrowIO.cpp (inside deserializeDataProcessing_ and readMetaValues_),
after you strip the surrounding brackets from mv_value into String s, add a
guard that detects an empty body (s.empty() or only whitespace) and directly set
dp.setMetaValue(mv_name, DataValue(ListUtils::create<T>(""))) to produce an
empty TypedList (or construct an empty List<T>) instead of calling
ListUtils::create on an empty string which currently throws or yields
StringList{""}; apply this for Int (ListUtils::create<Int>), double
(ListUtils::create<double>) and String (ListUtils::create<String>) branches and
ensure the string-list branch still trims elements when non-empty.

In `@src/tests/class_tests/openms/source/ConsensusMapArrowIO_test.cpp`:
- Around line 18-39: The test harness macros are mismatched:
START_TEST(ConsensusMapArrowIO, ...) is inside the `#ifdef` WITH_PARQUET guard but
the corresponding END_TEST is emitted unconditionally, causing compilation
failures when WITH_PARQUET is not defined; fix by making the macro pair
conditional—either move START_TEST out of the `#ifdef` so both START_TEST and
END_TEST are always compiled, or wrap the END_TEST (and any test body related to
ConsensusMapArrowIO) inside the same `#ifdef` WITH_PARQUET block so START_TEST and
END_TEST are both enclosed by WITH_PARQUET.

---

Nitpick comments:
In `@src/openms/source/FORMAT/ConsensusMapArrowIO.cpp`:
- Around line 668-770: Replace uses of std::endl with '\n' in the logging calls
inside writeArrowTableToParquet_ (specifically the OPENMS_LOG_ERROR lines that
report "null table passed to writeArrowTableToParquet_" and "Failed to open
file: " and "Failed to write Parquet: " if present here) so the logger doesn't
force flush on each message; locate these calls (OPENMS_LOG_ERROR << ... <<
std::endl) and change them to use '\n' instead (e.g., OPENMS_LOG_ERROR << ... <<
'\n'), and scan the rest of ConsensusMapArrowIO.cpp for any remaining
OPENMS_LOG_* usages that use std::endl and update them similarly.
- Around line 563-626: The code uses std::to_string/std::stoull and raw integer
types in serializeColumnHeaders_ and deserializeColumnHeaders_; change these to
use OpenMS conventions: build JSON with OpenMS::String (use OpenMS::String
concatenation instead of std::to_string), replace numeric index/size types with
OpenMS::Size (and other OpenMS typedefs from OpenMS/CONCEPT/Types.h) such that
map_index is a Size and header.size/unique_id use OpenMS types, and parse
numbers in deserializeColumnHeaders_ by collecting into an OpenMS::String and
converting with its conversion methods (e.g., toSize/toInt/toUInt64 as
appropriate) rather than std::stoull; ensure necessary OpenMS headers are
included.

@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 the current code and only fix it if needed.

Inline comments:
In `@src/openms/CMakeLists.txt`:
- Around line 148-150: The current CMake condition uses WITH_PARQUET AND
ARROW_USE_STATIC AND NOT MSVC but omits an Apple guard, causing macOS ld64 to
choke on the LINKER:--exclude-libs option; update the conditional that wraps
target_link_options(OpenMS PRIVATE
"LINKER:--exclude-libs,libarrow_bundled_dependencies.a") to also require NOT
APPLE (e.g., add AND NOT APPLE) so the --exclude-libs linker flag is only
applied on supported ELF/PE platforms.

---

Duplicate comments:
In `@src/tests/class_tests/openms/CMakeLists.txt`:
- Around line 103-106: No change required: the new target_link_libraries block
for ConsensusMapArrowIO_test correctly mirrors the existing pattern and is
properly guarded by WITH_PARQUET; leave the
target_link_libraries(ConsensusMapArrowIO_test ${OPENMS_ARROW_TARGET}
${OPENMS_PARQUET_TARGET}) block as-is to maintain consistency with Arrow_test,
MSExperimentArrowExport_test, ConsensusMapArrowExport_test, QPXFile_test,
ProteinIdentificationArrowIO_test, and FeatureMapArrowIO_test.

Comment thread src/openms/CMakeLists.txt Resolved
@timosachsenberg
timosachsenberg force-pushed the feature/protein-identification-parquet-export branch from 5904fc3 to c4b3e6f Compare February 23, 2026 09:01
…sensusMap

Add full round-trip Arrow/Parquet support for ProteinIdentification,
FeatureMap, and ConsensusMap data structures. Each map type exports to a
`.cmd` directory containing multiple Parquet files (features, PSMs,
proteins, protein groups, search parameters).

Key changes:
- ProteinIdentificationArrowIO: export/import protein hits, groups,
  and search parameters with full metadata round-trip
- FeatureMapArrowIO: export/import features with convex hulls, nested
  subordinate features, bounding boxes, and PSM linkage
- ConsensusMapArrowIO: export/import consensus features with feature
  handles, column headers, and PSM linkage
- QPXFile: shared PSM export with per-PSM higher_score_better column
- MetaValue list types (INT_LIST, DOUBLE_LIST, STRING_LIST) supported
- Windows DateTime epoch handling for cross-platform compatibility
- Hide Arrow bundled dependency symbols on Linux to prevent conflicts

Co-Authored-By: Claude Opus 4.6 <[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