Repository navigation
Add FeatureMapArrowIO for Parquet-based FeatureMap round-trip - #8768
Conversation
… and tests Add new class ProteinIdentificationArrowExport for exporting ProteinIdentification data to Apache Arrow Tables and Parquet files. The proteins table schema has 19 columns (one row per ProteinHit) including accession, score, coverage, is_decoy, run_identifier, search/inference engine info, modifications, and metavalues. Includes shared helpers writeArrowTableToParquet_() and appendMetaValues_() in anonymous namespace, stub methods for protein groups and search params exports, and comprehensive test coverage using the OpenMS ClassTest framework. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Replace stub implementations for protein group export with full 8-column Arrow table export (group_type, probability, accessions, run_identifier, group_index, float_data, string_data, integer_data). Also wire up exportProteinGroupsToParquet to delegate through the shared writeArrowTableToParquet_ helper. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Add run_identifier as column 24 to the Arrow table exported by QPXFile, sourced from PeptideIdentification::getIdentifier(). This enables downstream consumers to link PSMs back to their originating search run. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…xport Co-Authored-By: Claude Opus 4.6 <[email protected]>
Implements the reverse of ProteinIdentificationArrowExport: reads Parquet files back into vector<ProteinIdentification>. Supports import of search parameters, protein hits, and protein groups with a combined importFromParquet convenience method. Splits the search_params metavalues column into separate metavalues (ProteinIdentification) and sp_metavalues (SearchParameters) columns to ensure correct round-trip of metavalues on both objects (26 cols). Includes Python bindings and comprehensive round-trip tests covering metavalue type preservation, data arrays, and multi-run scenarios. Co-Authored-By: Claude Opus 4.6 <[email protected]>
📝 WalkthroughWalkthroughAdds Arrow/Parquet I/O for ProteinIdentification and FeatureMap (new classes ProteinIdentificationArrowIO, FeatureMapArrowIO), wires build/test/pyOpenMS bindings under WITH_PARQUET, adds a QPX run_identifier column, and includes extensive tests and design/implementation docs. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant PI as ProteinIdentificationArrowIO
participant Arrow as arrow::Table
participant Parquet as ParquetFile
User->>PI: exportProteinsToArrow(protein_ids)
PI->>Arrow: build columns (accession, score, run_identifier, ...)
Arrow-->>PI: arrow::Table
PI-->>User: shared_ptr<arrow::Table>
User->>PI: exportProteinsToParquet(protein_ids, file, config)
PI->>Arrow: build table
PI->>Parquet: write(table, config)
Parquet-->>PI: write result
PI-->>User: bool
sequenceDiagram
participant User
participant FM as FeatureMapArrowIO
participant PI as ProteinIdentificationArrowIO
participant Parquet as ParquetDir
participant FS as Filesystem
User->>FM: exportToParquet(feature_map, out_dir)
FM->>Parquet: export features.parquet, psms.parquet
FM->>PI: delegate proteins -> proteins.parquet
Parquet->>FS: create files in out_dir
FS-->>User: parquet files available
User->>FM: importFromParquet(out_dir)
FM->>PI: read proteins.parquet
FM->>Parquet: read features.parquet, psms.parquet
FM->>FM: reconstruct features tree & PSM associations
FM-->>User: FeatureMap populated (bool)
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (8)
src/pyOpenMS/pxds/ProteinIdentificationArrowExport.pxd (1)
26-51: Add default parameter forParquetWriteConfigto match C++ signatures.The C++ header declares all three export methods with a default
ParquetWriteConfig{}parameter (lines 67, 91, 115), and the C++ tests call them with only 2 arguments. The.pxdshould declare the same default to maintain Python API consistency with C++ and improve ergonomics—without the default, Python callers must always construct and pass aParquetWriteConfigexplicitly.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/pyOpenMS/pxds/ProteinIdentificationArrowExport.pxd` around lines 26 - 51, Update the three function declarations exportProteinsToParquet, exportProteinGroupsToParquet, and exportSearchParamsToParquet in ProteinIdentificationArrowExport.pxd to include the same default for the ParquetWriteConfig parameter as in the C++ headers (ParquetWriteConfig{}), so Python wrappers can be called with only the two required arguments; ensure the signature for each function uses ParquetWriteConfig defaulting to ParquetWriteConfig{} while keeping except + nogil and the existing wrap-doc lines unchanged.src/openms/include/OpenMS/FORMAT/ProteinIdentificationArrowImport.h (1)
59-63: Parameter order doesn't match documented/actual execution order.The Doxygen says "Reads search_params, proteins, and protein_groups files in order", and the implementation confirms this sequence. However the parameters list
proteins_filenamefirst andsearch_params_filenamelast. Aligning parameter order with execution order (search_params, proteins, protein_groups) would reduce caller confusion and make the API self-documenting.💡 Suggested parameter reordering
static bool importFromParquet( - const String& proteins_filename, - const String& protein_groups_filename, const String& search_params_filename, + const String& proteins_filename, + const String& protein_groups_filename, std::vector<ProteinIdentification>& protein_identifications);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/include/OpenMS/FORMAT/ProteinIdentificationArrowImport.h` around lines 59 - 63, The declaration of ProteinIdentificationArrowImport::importFromParquet currently lists parameters as (proteins_filename, protein_groups_filename, search_params_filename) but the function reads files in order search_params, proteins, protein_groups; reorder the function signature to (const String& search_params_filename, const String& proteins_filename, const String& protein_groups_filename) and update all corresponding declarations/definitions and call sites to match, plus update the Doxygen comment if present to reflect the new parameter order to keep the API consistent and self-documenting.src/openms/source/FORMAT/ProteinIdentificationArrowImport.cpp (1)
104-128: Type-accessor helpers use uncheckedstatic_pointer_cast.If a column has an unexpected Arrow type (e.g., a
StringArrayaccessed viagetDoubleValue_), thestatic_pointer_castproduces undefined behavior. Since the schema is controlled by the export side this is safe in the normal workflow, but external Parquet files could trigger UB. Adynamic_pointer_castwith a null check in the helper, or a type assertion on column fetch, would harden this.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/source/FORMAT/ProteinIdentificationArrowImport.cpp` around lines 104 - 128, The helpers getStringValue_, getDoubleValue_, getInt32Value_, and getBoolValue_ currently use std::static_pointer_cast which can UB if the Arrow array is an unexpected type; change each to use std::dynamic_pointer_cast to the appropriate Arrow array type (arrow::StringArray, arrow::DoubleArray, arrow::Int32Array, arrow::BooleanArray), check the result for null and return the existing default ("" or default_val) when the cast fails or the element is null, and optionally emit a warning/log when a type mismatch is detected to aid debugging.src/openms/source/FORMAT/ProteinIdentificationArrowExport.cpp (4)
290-440: AllAppendreturn values are silently discarded via(void)casts.While
Reservewas called beforehand,StringBuilder::Reserveonly reserves slot count, not the byte buffer for string data. An OOM or corruption duringAppendwould be silently swallowed. This is a common pattern in Arrow example code and unlikely to cause issues with typical proteomics data sizes, but it's worth noting as a reliability tradeoff.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/source/FORMAT/ProteinIdentificationArrowExport.cpp` around lines 290 - 440, The code currently ignores Arrow builder Append return values (e.g., accession_builder.Append, sequence_builder.Append, modifications_builder.Append, metavalues_builder.Append, and others) which can hide allocation/append failures; update the hit loop in ProteinIdentificationArrowExport.cpp to check each Append/AppendNull/Append() return Status/Result and handle errors (propagate/throw or log and abort) rather than casting to void; also ensure string/binary appends consider StringBuilder::Reserve limitations (called earlier) by validating results from Append for string fields (sequence_builder, description_builder, reference_file_builder, search_engine_version_builder, inference_engine_version_builder, date_builder, mod_name_b, mv_value_b) and handle failures consistently (use the same error path as other export failures) and apply the same checks for struct/child builders (mod_struct_b, mod_position_b, mod_name_b, mv_struct_b, mv_name_b, mv_type_b) including the final metavalues append and any Append() calls that open a nested struct.
232-265: Consider a helper macro or lambda for the repetitive Reserve + error check pattern.17 builders each have identical
Reserve→ check → log →return nullptrboilerplate. A small inline lambda or macro would reduce ~35 lines of repetition and make future column additions less error-prone.💡 Example helper lambda
auto reserve_or_fail = [&](auto& builder, Size n, const char* name) -> bool { auto s = builder.Reserve(n); if (!s.ok()) { OPENMS_LOG_ERROR << "ProteinIdentificationArrowExport: " << name << " Reserve failed: " << s.ToString() << "\n"; return false; } return true; }; if (!reserve_or_fail(accession_builder, num_rows, "accession_builder")) return nullptr; // ... etc.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/source/FORMAT/ProteinIdentificationArrowExport.cpp` around lines 232 - 265, The repeated pattern in ProteinIdentificationArrowExport.cpp (in the function performing Arrow export) calls X_builder.Reserve(num_rows) then checks status and logs+returns nullptr for each builder (e.g., accession_builder, score_builder, score_type_builder, higher_score_better_builder, rank_builder, coverage_builder, sequence_builder, description_builder, is_decoy_builder, run_identifier_builder, reference_file_builder, search_engine_builder, search_engine_version_builder, inference_engine_builder, inference_engine_version_builder, significance_threshold_builder, date_builder); replace this boilerplate with a small helper (lambda or inline function) reserve_or_fail(builder, num_rows, "builder_name") that calls builder.Reserve, logs the same OPENMS_LOG_ERROR message including s.ToString() on failure, and returns a bool so the callers can return nullptr on failure (e.g., if (!reserve_or_fail(accession_builder, num_rows, "accession_builder")) return nullptr;). Ensure the helper captures by reference and preserves the original log text and return behavior.
41-66:appendMetaValues_silently downgrades list-typedDataValues to string.
DataValue::INT_LISTandDataValue::DOUBLE_LISTfall through to thedefaultcase, exporting them withvalue_type = "str". On import,readMetaValues_only recognizes"int","float", and"str", so list-typed metavalues will be imported back as plain strings instead of their original type. If list-typed metavalues are in practice unused on these objects this is fine, but it's worth a brief comment or an explicit case to make the lossy conversion intentional.💡 Make the lossy conversion explicit
case DataValue::STRING_VALUE: (void)type_b->Append("str"); break; - default: (void)type_b->Append("str"); break; + case DataValue::INT_LIST: // fall through: lists serialized as string (lossy) + case DataValue::DOUBLE_LIST: + case DataValue::STRING_LIST: + case DataValue::EMPTY_VALUE: + default: (void)type_b->Append("str"); break;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/source/FORMAT/ProteinIdentificationArrowExport.cpp` around lines 41 - 66, appendMetaValues_ currently falls through list-typed DataValue cases so INT_LIST and DOUBLE_LIST are written with type "str", causing loss on import because readMetaValues_ only recognizes "int", "float", "str"; update appendMetaValues_ to explicitly handle DataValue::INT_LIST and DataValue::DOUBLE_LIST (e.g., append a distinct type string like "int_list"/"float_list" and serialize the list consistently via value.toString() or a stable encoding) and ensure the chosen type strings match what readMetaValues_ will parse, or if lossy conversion is intentional add a clear comment and keep explicit case branches that append "str" to make the intent obvious (refer to function appendMetaValues_, switch on val.valueType(), and the builders name_b/value_b/type_b/struct_b).
86-105: Extract RFC 4122 v4 UUID generation into a shared utility function.The UUID generation code (lines 86–105) is duplicated verbatim in
src/openms/source/FORMAT/QPXFile.cpp. Extract this logic into a single utility function to improve maintainability and reduce duplication. Note thatwriteArrowTableToParquet_is a private method within this file, not shared across Arrow export modules.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/source/FORMAT/ProteinIdentificationArrowExport.cpp` around lines 86 - 105, Extract the duplicated RFC4122 v4 UUID generation into a single helper function (e.g., std::string generateUUIDv4()) and replace the block in ProteinIdentificationArrowExport.cpp (inside writeArrowTableToParquet_ or wherever it was used) and the duplicate in QPXFile.cpp to call this new function; implement the helper to encapsulate the std::random_device/std::mt19937/std::uniform_int_distribution logic, byte-manipulation for version/variant bits, formatting to the 36-char dashed string, and ensure the new header is included where called and necessary <random>, <cstring>, <cstdio> (or corresponding includes) are present so behavior is unchanged.src/tests/class_tests/openms/source/ProteinIdentificationArrowExport_test.cpp (1)
36-216: Good coverage of the proteins Arrow export path.Thorough verification of schema, data types, values, and nullability for both target and decoy hits. One gap: neither hit has protein modifications set, so the non-null modifications export path (the
elsebranch at line ~427 in the export.cpp) is never exercised in this test.Consider adding a hit with modifications to cover the non-null
modificationslist serialization.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/tests/class_tests/openms/source/ProteinIdentificationArrowExport_test.cpp` around lines 36 - 216, Add a ProteinHit to the test that has non-empty protein modifications so the non-null branch in ProteinIdentificationArrowExport::exportProteinsToArrow is exercised; create a new ProteinHit, populate accession/score/rank as done for hit1/hit2, set at least one protein modification via the ProteinHit modifications API (e.g. the class method that sets protein modifications on ProteinHit), call prot_id.insertHit(new_hit) and update the assertions: expect num_rows to increase, check the "modifications" column is non-null for that row and contains the expected entry, and adjust any counts/indices used later (e.g. metavalues/modifications checks) accordingly.
🤖 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/ProteinIdentificationArrowImport.cpp`:
- Around line 299-304: The ProteaseDB::getEnzyme call in the enzyme import (use
getStringValue_(col_enzyme, row) → enzyme_name and assignment to
sp.digestion_enzyme) is unguarded and will throw for unknown names; wrap the
ProteaseDB::getInstance()->getEnzyme(enzyme_name) call in a try-catch like the
ModificationsDB handling, catch the exception, log a warning/error referencing
the enzyme_name and row (or context), and skip assigning sp.digestion_enzyme
when lookup fails so the import continues safely.
In
`@src/tests/class_tests/openms/source/ProteinIdentificationArrowImport_test.cpp`:
- Around line 292-294: Replace uses of NEW_TMP_FILE followed by appending
".parquet" to the temporary filename (e.g., the local variable tmp_file in
ProteinIdentificationArrowImport_test.cpp) with the cleanup-aware macro
NEW_TMP_FILE_EXT(tmp_file, ".parquet"); update each occurrence (lines near where
tmp_file is created/modified) so the full ".parquet" filename is registered for
cleanup by using NEW_TMP_FILE_EXT instead of NEW_TMP_FILE + string append.
---
Nitpick comments:
In `@src/openms/include/OpenMS/FORMAT/ProteinIdentificationArrowImport.h`:
- Around line 59-63: The declaration of
ProteinIdentificationArrowImport::importFromParquet currently lists parameters
as (proteins_filename, protein_groups_filename, search_params_filename) but the
function reads files in order search_params, proteins, protein_groups; reorder
the function signature to (const String& search_params_filename, const String&
proteins_filename, const String& protein_groups_filename) and update all
corresponding declarations/definitions and call sites to match, plus update the
Doxygen comment if present to reflect the new parameter order to keep the API
consistent and self-documenting.
In `@src/openms/source/FORMAT/ProteinIdentificationArrowExport.cpp`:
- Around line 290-440: The code currently ignores Arrow builder Append return
values (e.g., accession_builder.Append, sequence_builder.Append,
modifications_builder.Append, metavalues_builder.Append, and others) which can
hide allocation/append failures; update the hit loop in
ProteinIdentificationArrowExport.cpp to check each Append/AppendNull/Append()
return Status/Result and handle errors (propagate/throw or log and abort) rather
than casting to void; also ensure string/binary appends consider
StringBuilder::Reserve limitations (called earlier) by validating results from
Append for string fields (sequence_builder, description_builder,
reference_file_builder, search_engine_version_builder,
inference_engine_version_builder, date_builder, mod_name_b, mv_value_b) and
handle failures consistently (use the same error path as other export failures)
and apply the same checks for struct/child builders (mod_struct_b,
mod_position_b, mod_name_b, mv_struct_b, mv_name_b, mv_type_b) including the
final metavalues append and any Append() calls that open a nested struct.
- Around line 232-265: The repeated pattern in
ProteinIdentificationArrowExport.cpp (in the function performing Arrow export)
calls X_builder.Reserve(num_rows) then checks status and logs+returns nullptr
for each builder (e.g., accession_builder, score_builder, score_type_builder,
higher_score_better_builder, rank_builder, coverage_builder, sequence_builder,
description_builder, is_decoy_builder, run_identifier_builder,
reference_file_builder, search_engine_builder, search_engine_version_builder,
inference_engine_builder, inference_engine_version_builder,
significance_threshold_builder, date_builder); replace this boilerplate with a
small helper (lambda or inline function) reserve_or_fail(builder, num_rows,
"builder_name") that calls builder.Reserve, logs the same OPENMS_LOG_ERROR
message including s.ToString() on failure, and returns a bool so the callers can
return nullptr on failure (e.g., if (!reserve_or_fail(accession_builder,
num_rows, "accession_builder")) return nullptr;). Ensure the helper captures by
reference and preserves the original log text and return behavior.
- Around line 41-66: appendMetaValues_ currently falls through list-typed
DataValue cases so INT_LIST and DOUBLE_LIST are written with type "str", causing
loss on import because readMetaValues_ only recognizes "int", "float", "str";
update appendMetaValues_ to explicitly handle DataValue::INT_LIST and
DataValue::DOUBLE_LIST (e.g., append a distinct type string like
"int_list"/"float_list" and serialize the list consistently via value.toString()
or a stable encoding) and ensure the chosen type strings match what
readMetaValues_ will parse, or if lossy conversion is intentional add a clear
comment and keep explicit case branches that append "str" to make the intent
obvious (refer to function appendMetaValues_, switch on val.valueType(), and the
builders name_b/value_b/type_b/struct_b).
- Around line 86-105: Extract the duplicated RFC4122 v4 UUID generation into a
single helper function (e.g., std::string generateUUIDv4()) and replace the
block in ProteinIdentificationArrowExport.cpp (inside writeArrowTableToParquet_
or wherever it was used) and the duplicate in QPXFile.cpp to call this new
function; implement the helper to encapsulate the
std::random_device/std::mt19937/std::uniform_int_distribution logic,
byte-manipulation for version/variant bits, formatting to the 36-char dashed
string, and ensure the new header is included where called and necessary
<random>, <cstring>, <cstdio> (or corresponding includes) are present so
behavior is unchanged.
In `@src/openms/source/FORMAT/ProteinIdentificationArrowImport.cpp`:
- Around line 104-128: The helpers getStringValue_, getDoubleValue_,
getInt32Value_, and getBoolValue_ currently use std::static_pointer_cast which
can UB if the Arrow array is an unexpected type; change each to use
std::dynamic_pointer_cast to the appropriate Arrow array type
(arrow::StringArray, arrow::DoubleArray, arrow::Int32Array,
arrow::BooleanArray), check the result for null and return the existing default
("" or default_val) when the cast fails or the element is null, and optionally
emit a warning/log when a type mismatch is detected to aid debugging.
In `@src/pyOpenMS/pxds/ProteinIdentificationArrowExport.pxd`:
- Around line 26-51: Update the three function declarations
exportProteinsToParquet, exportProteinGroupsToParquet, and
exportSearchParamsToParquet in ProteinIdentificationArrowExport.pxd to include
the same default for the ParquetWriteConfig parameter as in the C++ headers
(ParquetWriteConfig{}), so Python wrappers can be called with only the two
required arguments; ensure the signature for each function uses
ParquetWriteConfig defaulting to ParquetWriteConfig{} while keeping except +
nogil and the existing wrap-doc lines unchanged.
In
`@src/tests/class_tests/openms/source/ProteinIdentificationArrowExport_test.cpp`:
- Around line 36-216: Add a ProteinHit to the test that has non-empty protein
modifications so the non-null branch in
ProteinIdentificationArrowExport::exportProteinsToArrow is exercised; create a
new ProteinHit, populate accession/score/rank as done for hit1/hit2, set at
least one protein modification via the ProteinHit modifications API (e.g. the
class method that sets protein modifications on ProteinHit), call
prot_id.insertHit(new_hit) and update the assertions: expect num_rows to
increase, check the "modifications" column is non-null for that row and contains
the expected entry, and adjust any counts/indices used later (e.g.
metavalues/modifications checks) accordingly.
| // Enzyme | ||
| String enzyme_name = getStringValue_(col_enzyme, row); | ||
| if (!enzyme_name.empty()) | ||
| { | ||
| sp.digestion_enzyme = *ProteaseDB::getInstance()->getEnzyme(enzyme_name); | ||
| } |
There was a problem hiding this comment.
Unguarded ProteaseDB::getEnzyme call will throw on unrecognized enzyme names.
Unlike the modifications import at line 497 which wraps ModificationsDB::getModification in a try-catch, this enzyme lookup has no exception guard. If the Parquet file contains an enzyme name not in ProteaseDB, this will throw an unhandled exception and crash the import.
🛡️ Proposed fix: add try-catch consistent with modifications handling
String enzyme_name = getStringValue_(col_enzyme, row);
if (!enzyme_name.empty())
{
- sp.digestion_enzyme = *ProteaseDB::getInstance()->getEnzyme(enzyme_name);
+ try
+ {
+ sp.digestion_enzyme = *ProteaseDB::getInstance()->getEnzyme(enzyme_name);
+ }
+ catch (...)
+ {
+ OPENMS_LOG_WARN << "ProteinIdentificationArrowImport: Unknown enzyme '"
+ << enzyme_name << "', using default" << std::endl;
+ }
}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/openms/source/FORMAT/ProteinIdentificationArrowImport.cpp` around lines
299 - 304, The ProteaseDB::getEnzyme call in the enzyme import (use
getStringValue_(col_enzyme, row) → enzyme_name and assignment to
sp.digestion_enzyme) is unguarded and will throw for unknown names; wrap the
ProteaseDB::getInstance()->getEnzyme(enzyme_name) call in a try-catch like the
ModificationsDB handling, catch the exception, log a warning/error referencing
the enzyme_name and row (or context), and skip assigning sp.digestion_enzyme
when lookup fails so the import continues safely.
| String tmp_file; | ||
| NEW_TMP_FILE(tmp_file) | ||
| tmp_file += ".parquet"; |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check how other Parquet tests handle temp file naming
rg -n 'NEW_TMP_FILE.*parquet\|\.parquet' --type=cpp -C2 -g '*_test.cpp'Repository: OpenMS/OpenMS
Length of output: 39
🏁 Script executed:
# Find the NEW_TMP_FILE macro definition
fd -e h -e hpp | xargs rg -l 'NEW_TMP_FILE' | head -5Repository: OpenMS/OpenMS
Length of output: 102
🏁 Script executed:
# Search for NEW_TMP_FILE macro definition
rg -n 'define.*NEW_TMP_FILE\|NEW_TMP_FILE.*{' --type=cpp --type=hRepository: OpenMS/OpenMS
Length of output: 194
🏁 Script executed:
# Read the ClassTest.h file to see NEW_TMP_FILE definition
cat src/openms/include/OpenMS/CONCEPT/ClassTest.h | head -150Repository: OpenMS/OpenMS
Length of output: 5136
🏁 Script executed:
# Search more carefully for NEW_TMP_FILE definition
rg -n 'NEW_TMP_FILE' src/openms/include/OpenMS/CONCEPT/ClassTest.h -A 5Repository: OpenMS/OpenMS
Length of output: 1333
🏁 Script executed:
# Read the specific lines from ProteinIdentificationArrowImport_test.cpp
sed -n '290,295p; 320,325p; 347,352p; 459,467p' src/tests/class_tests/openms/source/ProteinIdentificationArrowImport_test.cppRepository: OpenMS/OpenMS
Length of output: 685
🏁 Script executed:
# Also check how many times this pattern appears in the file
rg -n 'NEW_TMP_FILE|\.parquet' src/tests/class_tests/openms/source/ProteinIdentificationArrowImport_test.cpp -B1 -A1Repository: OpenMS/OpenMS
Length of output: 584
Use NEW_TMP_FILE_EXT() macro with .parquet extension for proper cleanup registration.
The NEW_TMP_FILE macro registers the original filename for cleanup. Appending .parquet afterward creates a mismatch—the cleanup framework tracks the unmodified path, but the actual file written has a different name. Use NEW_TMP_FILE_EXT(filename, ".parquet") instead to ensure the full path is properly registered for cleanup.
Applies to lines 292-294, 322-324, 349-351, and 461-466.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In
`@src/tests/class_tests/openms/source/ProteinIdentificationArrowImport_test.cpp`
around lines 292 - 294, Replace uses of NEW_TMP_FILE followed by appending
".parquet" to the temporary filename (e.g., the local variable tmp_file in
ProteinIdentificationArrowImport_test.cpp) with the cleanup-aware macro
NEW_TMP_FILE_EXT(tmp_file, ".parquet"); update each occurrence (lines near where
tmp_file is created/modified) so the full ".parquet" filename is registered for
cleanup by using NEW_TMP_FILE_EXT instead of NEW_TMP_FILE + string append.
…dentificationArrowIO Combine the separate Export and Import classes into a single ProteinIdentificationArrowIO class to simplify the API surface. Deduplicates anonymous namespace helpers and updates all cmake files, tests, and Python bindings accordingly. Co-Authored-By: Claude Opus 4.6 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (4)
src/tests/class_tests/openms/source/ProteinIdentificationArrowIO_test.cpp (1)
593-593:ValueOrDie()may be deprecated in newer Arrow versions.
reader_result.ValueOrDie()was deprecated in Arrow in favor ofMoveValueUnsafe(). Since you already checkreader_result.ok()beforehand, consider usingstd::move(*reader_result)consistently (which is the pattern used at line 589 forinfile_result). This pattern appears in several Parquet read-back sections (lines 593, 640, 692).Suggested fix
- std::unique_ptr<parquet::arrow::FileReader> reader = std::move(reader_result.ValueOrDie()); + std::unique_ptr<parquet::arrow::FileReader> reader = std::move(*reader_result);Apply the same pattern at lines 640 and 692.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/tests/class_tests/openms/source/ProteinIdentificationArrowIO_test.cpp` at line 593, Replace deprecated ValueOrDie() calls by moving the contained value like you do for infile_result: instead of std::move(reader_result.ValueOrDie()) use std::move(*reader_result) (or std::move(reader_result->) equivalent) when constructing the std::unique_ptr<parquet::arrow::FileReader>, and apply the same change to the other Parquet read-back occurrences (the reader_result usages around the second and third read sections currently at lines analogous to 640 and 692) so all places consistently use std::move(*reader_result).src/openms/source/FORMAT/ProteinIdentificationArrowIO.cpp (3)
366-709: Very complex method — consider extracting builder setup and finalization into helpers.Static analysis flags
exportProteinsToArrow(345 lines) andexportSearchParamsToArrow(407 lines) as very complex. The repetitive Reserve+check and Finish+check patterns dominate the line count. A small helper (e.g., aReserveOrFailtemplate andFinishOrFailtemplate) could reduce each block to a single line and improve maintainability.This is a non-blocking suggestion since the code is correct and the pattern is consistent.
🤖 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 366 - 709, The exportProteinsToArrow method contains long repetitive Reserve+check and Finish+check blocks (and similarly exportSearchParamsToArrow) that inflate complexity; add small helper templates (e.g., ReserveOrFail<TBuilder>(TBuilder&, Size num_rows, const char* name) and FinishOrFail<TBuilder>(TBuilder&, std::shared_ptr<arrow::Array>& out, const char* name)) that encapsulate calling Reserve/Finish, checking arrow::Status, logging the error and returning nullptr on failure, then replace all direct calls like accession_builder.Reserve(...)/accession_builder.Finish(...) (and score_builder, score_type_builder, modifications_builder, metavalues_builder, etc.) with single-line ReserveOrFail/FinishOrFail calls inside exportProteinsToArrow and do the same refactor in exportSearchParamsToArrow to drastically reduce duplication and method length while preserving current behavior.
47-72: Ignoring ArrowStatusfromAppendcalls throughout the file.All
Append()calls on Arrow builders are cast to(void), silently discarding thearrow::Status. While this is common whenReserve()was called, the struct/list sub-builders (name_b,value_b,type_b,struct_b) inappendMetaValues_and the nested builders inexportProteinGroupsToArrownever haveReserve()called. A memory allocation failure during append would be silently swallowed.This is a known trade-off for readability and is used in other Arrow export code in the codebase, so flagging it as a minor concern. Consider a helper macro or function if this pattern expands further.
🤖 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, appendMetaValues_ (and related code paths such as exportProteinGroupsToArrow) currently discards arrow::Status results from builder->Append() calls (name_b, value_b, type_b, struct_b etc.), which can hide allocation failures; update each Append() call to capture and check the returned arrow::Status and on failure propagate or surface the error (e.g., throw a descriptive exception or return an error Status) instead of casting to void. To keep this concise and consistent, add a small helper (e.g., CheckArrowStatusOrThrow) used everywhere Append() is called, and replace occurrences like (void)builder->Append(...) with checking via that helper so allocation/append errors are not silently swallowed.
92-111: UUID generation could use a library or be extracted to a shared utility.The inline RFC 4122 v4 UUID generator works correctly, but this is ~20 lines of low-level byte manipulation with
snprintf. If other Parquet writers in the codebase also need UUIDs, consider extracting this to a shared utility. Additionally,std::random_devicemay not provide high-quality entropy on all platforms (e.g., MinGW), though this is fine for non-cryptographic file metadata.🤖 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 92 - 111, The inline RFC4122 v4 UUID generation in ProteinIdentificationArrowIO.cpp (the bytes/uuid_str/snprintf block) should be extracted to a shared utility (e.g., a new generate_uuid_v4() in a common util/uuid module) or replaced with an existing UUID provider (boost::uuids or project-wide helper); move the logic out of the current function, return a std::string, and call that function instead of duplicating the byte-manipulation and snprintf here, and ensure the implementation centralizes RNG seeding (avoid per-call std::random_device where platform entropy is weak) so other Parquet writers can reuse it.
🤖 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/include/OpenMS/FORMAT/ProteinIdentificationArrowIO.h`:
- Around line 153-179: Update the Doxygen `@param` direction for parameters that
are both read and modified: change the `@param[out] protein_identifications` to
`@param[in,out] protein_identifications` in the documentation for
importProteinsFromArrow and importProteinGroupsFromArrow, and make the same
`@param[in,out]` change for the corresponding Parquet methods (e.g.,
importProteinsFromParquet and importProteinGroupsFromParquet) so the docs
reflect that the vector is inspected and updated rather than purely output-only.
In `@src/openms/source/FORMAT/ProteinIdentificationArrowIO.cpp`:
- Around line 1466-1471: The code calls
ProteaseDB::getInstance()->getEnzyme(enzyme_name) without handling the case
where the enzyme is unknown; wrap the call in a try/catch (catching the same
Exception type used elsewhere, e.g. Exception::ElementNotFound) around where
getStringValue_(col_enzyme, row) is read and when assigning sp.digestion_enzyme,
and on exception log a warning and leave sp.digestion_enzyme unset or set to a
safe default (matching the approach used for
ModificationsDB::getModification()), so unknown or corrupted enzyme names don't
throw.
---
Nitpick comments:
In `@src/openms/source/FORMAT/ProteinIdentificationArrowIO.cpp`:
- Around line 366-709: The exportProteinsToArrow method contains long repetitive
Reserve+check and Finish+check blocks (and similarly exportSearchParamsToArrow)
that inflate complexity; add small helper templates (e.g.,
ReserveOrFail<TBuilder>(TBuilder&, Size num_rows, const char* name) and
FinishOrFail<TBuilder>(TBuilder&, std::shared_ptr<arrow::Array>& out, const
char* name)) that encapsulate calling Reserve/Finish, checking arrow::Status,
logging the error and returning nullptr on failure, then replace all direct
calls like accession_builder.Reserve(...)/accession_builder.Finish(...) (and
score_builder, score_type_builder, modifications_builder, metavalues_builder,
etc.) with single-line ReserveOrFail/FinishOrFail calls inside
exportProteinsToArrow and do the same refactor in exportSearchParamsToArrow to
drastically reduce duplication and method length while preserving current
behavior.
- Around line 47-72: appendMetaValues_ (and related code paths such as
exportProteinGroupsToArrow) currently discards arrow::Status results from
builder->Append() calls (name_b, value_b, type_b, struct_b etc.), which can hide
allocation failures; update each Append() call to capture and check the returned
arrow::Status and on failure propagate or surface the error (e.g., throw a
descriptive exception or return an error Status) instead of casting to void. To
keep this concise and consistent, add a small helper (e.g.,
CheckArrowStatusOrThrow) used everywhere Append() is called, and replace
occurrences like (void)builder->Append(...) with checking via that helper so
allocation/append errors are not silently swallowed.
- Around line 92-111: The inline RFC4122 v4 UUID generation in
ProteinIdentificationArrowIO.cpp (the bytes/uuid_str/snprintf block) should be
extracted to a shared utility (e.g., a new generate_uuid_v4() in a common
util/uuid module) or replaced with an existing UUID provider (boost::uuids or
project-wide helper); move the logic out of the current function, return a
std::string, and call that function instead of duplicating the byte-manipulation
and snprintf here, and ensure the implementation centralizes RNG seeding (avoid
per-call std::random_device where platform entropy is weak) so other Parquet
writers can reuse it.
In `@src/tests/class_tests/openms/source/ProteinIdentificationArrowIO_test.cpp`:
- Line 593: Replace deprecated ValueOrDie() calls by moving the contained value
like you do for infile_result: instead of std::move(reader_result.ValueOrDie())
use std::move(*reader_result) (or std::move(reader_result->) equivalent) when
constructing the std::unique_ptr<parquet::arrow::FileReader>, and apply the same
change to the other Parquet read-back occurrences (the reader_result usages
around the second and third read sections currently at lines analogous to 640
and 692) so all places consistently use std::move(*reader_result).
| /** | ||
| @brief Import protein hits from Arrow Table | ||
|
|
||
| Adds ProteinHits to matching ProteinIdentifications by run_identifier. | ||
| If no matching ProteinIdentification exists, creates new ones. | ||
|
|
||
| @param[in] table Arrow Table with protein hits | ||
| @param[out] protein_identifications Protein identifications to populate | ||
| @return true on success, false on error | ||
| */ | ||
| static bool importProteinsFromArrow( | ||
| const std::shared_ptr<arrow::Table>& table, | ||
| std::vector<ProteinIdentification>& protein_identifications); | ||
|
|
||
| /** | ||
| @brief Import protein groups from Arrow Table | ||
|
|
||
| Adds ProteinGroups and IndistinguishableProteins to matching | ||
| ProteinIdentifications by run_identifier. | ||
|
|
||
| @param[in] table Arrow Table with protein groups | ||
| @param[out] protein_identifications Protein identifications to populate | ||
| @return true on success, false on error | ||
| */ | ||
| static bool importProteinGroupsFromArrow( | ||
| const std::shared_ptr<arrow::Table>& table, | ||
| std::vector<ProteinIdentification>& protein_identifications); |
There was a problem hiding this comment.
@param direction should be [in,out] for methods that update existing entries.
importProteinsFromArrow and importProteinGroupsFromArrow both read the existing protein_identifications vector to match by run_identifier and add hits/groups to existing shells. Documenting the parameter as @param[out] is misleading since the vector is also read. Use @param[in,out] for consistency with the actual semantics.
Same applies to the Parquet variants at lines 199–201 and 210–212.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/openms/include/OpenMS/FORMAT/ProteinIdentificationArrowIO.h` around lines
153 - 179, Update the Doxygen `@param` direction for parameters that are both read
and modified: change the `@param[out] protein_identifications` to
`@param[in,out] protein_identifications` in the documentation for
importProteinsFromArrow and importProteinGroupsFromArrow, and make the same
`@param[in,out]` change for the corresponding Parquet methods (e.g.,
importProteinsFromParquet and importProteinGroupsFromParquet) so the docs
reflect that the vector is inspected and updated rather than purely output-only.
Describes the multi-file directory approach for exporting/importing FeatureMap data to Apache Arrow/Parquet as a replacement for FeatureXML. Co-Authored-By: Claude Opus 4.6 <[email protected]>
14 tasks covering header, implementation, tests, and pyOpenMS bindings for full lossless FeatureMap round-trip via Arrow/Parquet. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Replaces the stub with a full implementation that exports FeatureMap features to a 17-column Arrow table with recursive subordinate support. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…nates Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
…er invalidation The previous implementation stored Feature* pointers that could be invalidated by vector reallocation when adding subsequent features. Switch to bottom-up tree assembly where children are attached to parents in the entries vector before moving to the FeatureMap. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Collects PeptideIdentifications from features (recursively including subordinates) and unassigned, delegates to QPXFile::exportToArrow for the base PSM table, then adds a feature_id column linking each PSM row back to its parent feature (null for unassigned PSMs). Co-Authored-By: Claude Opus 4.6 <[email protected]>
Reads a PSM Arrow table (produced by exportPSMsToArrow), reconstructs PeptideIdentifications by grouping rows on P_ID, recreates PeptideHits with sequence (via ProForma), charge, score, and rank, then links each PeptideIdentification to its parent feature via feature_id or adds it as unassigned when feature_id is null. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Add three new test sections: - exportPSMsToArrow with empty FeatureMap (verifies feature_id column exists) - exportPSMsToArrow with feature and unassigned PSMs (verifies feature_id values, sequences, scores, and charges in the exported Arrow table) - importPSMsFromArrow round-trip (export features + PSMs, import back, verify that feature-linked and unassigned PeptideIdentifications are correctly reconstructed with sequence, score, charge, and score type) Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Exposes exportToParquet and importFromParquet for Python usage. Co-Authored-By: Claude Opus 4.6 <[email protected]>
- C1: Change export_all_psms to true and emit one feature_id per PeptideHit (not per PeptideIdentification) to match QPXFile output - C3: Exclude FWHM from metavalues export (dedicated column/derived) - I1: Remove unused col_higher_better variable from importPSMsFromArrow - I5: Wrap std::filesystem::create_directories in try-catch Co-Authored-By: Claude Opus 4.6 <[email protected]>
…, higher_score_better Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ataProcessing) Store FeatureMap-level metadata as Parquet file-level key-value metadata on features.parquet. This includes DocumentIdentifier fields (document_id, loaded_file_path, loaded_file_type) and DataProcessing entries serialized as JSON (software name/version, completion time, processing actions, and metavalues). Co-Authored-By: Claude Opus 4.6 <[email protected]>
Tests higher_score_better propagation from ProteinIdentification, is_decoy/target_decoy, protein accessions (PeptideEvidence), multi-hit PeptideIdentifications, and unassigned PSMs through the full Parquet directory round-trip. Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Add try-catch around std::stoi/stod in deserializeDataProcessing_ to prevent crashes on malformed JSON metavalues - Document P_ID contiguous grouping assumption in importPSMsFromArrow - Exclude dedicated-column keys (target_decoy, predicted_RT, etc.) when reading psm_metavalues to prevent double-setting - Fix header docstrings to accurately describe all 5 Parquet files Co-Authored-By: Claude Opus 4.6 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (5)
src/tests/class_tests/openms/source/FeatureMapArrowIO_test.cpp (1)
175-176: Minor: Misleading comment — "subordinate 2 (unique_id=2)" refers tosub1, notsub2.The comment says "Give subordinate 2 (unique_id=2) its own subordinate" but it's
sub1that hasunique_id=2.sub2hasunique_id=3. The subsub (uid=4) is added tosub1on line 183.- // Give subordinate 2 (unique_id=2) its own subordinate (unique_id=4) + // Give sub1 (unique_id=2) its own subordinate (unique_id=4)🤖 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 175 - 176, The comment incorrectly labels "subordinate 2 (unique_id=2)" — update the comment near the Feature subsub declaration to correctly reference sub1 (unique_id=2) or rephrase to avoid numeric ambiguity (e.g., "Give sub1 (unique_id=2) its own subordinate (unique_id=4)"), ensuring it matches the subsequent code that adds subsub to sub1 rather than sub2.src/openms/source/FORMAT/FeatureMapArrowIO.cpp (4)
845-854: Width == 0.0 treated as null loses intentionally-set zero widths.If a feature genuinely has
width == 0.0f, it will be stored as null and on import will remain 0.0f (the default). This is a lossless round-trip for the value but loses the distinction between "width was explicitly set to zero" vs "width was never set." Likely fine for practical purposes, but worth a brief inline comment clarifying this semantic.🤖 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 845 - 854, The code in FeatureMapArrowIO.cpp treats width == 0.0f as null when appending to width_builder (using feature.getWidth()), which collapses the distinction between an explicitly set zero width and an unset width; add a concise inline comment next to this block (near the width_builder.AppendNull()/Append calls) that explains this behavior and its consequence for round-trip import/export (zero values are stored as null and will be interpreted as default 0.0f on read), so future maintainers understand this deliberate semantic loss or can change it deliberately later.
146-209: Hand-rolled JSON serializer/deserializer is fragile — consider using nlohmann_json.The manual JSON parser doesn't handle all edge cases (e.g., numeric values not wrapped in quotes, boolean JSON values, escaped forward slashes). Since the codebase already depends on nlohmann_json (as a private dependency), using it here would reduce ~250 lines to ~30 while being more robust. The current implementation works for its own output but is not resilient to external editing.
If keeping the hand-rolled approach, consider adding a brief comment explaining why nlohmann_json was not used (e.g., to avoid pulling in the header dependency).
Also applies to: 254-398
🤖 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 146 - 209, serializeDataProcessing_ currently constructs JSON by hand; replace it with nlohmann::json usage to produce robust output and handle numeric/boolean types and escaping. In function serializeDataProcessing_ build a nlohmann::json array where each element is an object with keys "software_name" (dp.getSoftware().getName()), "software_version" (dp.getSoftware().getVersion()), "completion_time" (dp.getCompletionTime().isValid() ? dp.getCompletionTime().toString("yyyy-MM-ddThh:mm:ss") : "" ), "actions" (vector of DataProcessing::processingActionToString(action)), and "metavalues" (array of objects with name, value and a type determined from DataValue::valueType() mapping to proper JSON types: int, float, bool, string; use DataValue accessors to set numeric/boolean types rather than always string). Serialize the nlohmann::json with dump() and replace the hand-rolled loop; apply the same refactor to the corresponding deserialization/related code ranges referenced (around 254-398) or add a short comment in both functions explaining why nlohmann::json is not used if you intentionally keep the hand-rolled approach.
1382-1393: P_ID grouping relies on row contiguity — non-contiguous rows with same P_ID silently split into separate PeptideIdentifications.The comment on lines 1389-1392 documents this, but there's no validation. If a downstream tool re-sorts the Parquet file (e.g., sorting by score globally), PSMs from the same PeptideIdentification will be split into multiple objects. Consider either:
- Using a
std::unordered_map<int32_t, size_t>to group by P_ID regardless of order, or- Adding a validation log when a previously-seen P_ID reappears non-contiguously.
🤖 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 1382 - 1393, The code currently assumes contiguous P_ID groups (variables: current_p_id, p_id, groups, getInt32Value_) but never validates re-appearance; add a lightweight validation that tracks seen P_IDs (e.g., std::unordered_set<int32_t> seen_p_ids) while iterating rows and if (p_id != current_p_id && seen_p_ids.contains(p_id)) emit a warning (include p_id and row) so users know the Parquet was re-ordered; alternatively (preferred for correctness) replace the contiguous-only logic by building a std::unordered_map<int32_t, size_t> p_id_to_group_index to append rows to the correct PeptideIdentification regardless of order (use p_id_to_group_index to find or create the group instead of only comparing to current_p_id).
401-514: ExtractwriteArrowTableToParquet_to a shared utility module to eliminate code duplication.The function is duplicated across
ProteinIdentificationArrowIO.cppandFeatureMapArrowIO.cpp. Both implementations contain identical UUID generation logic, Parquet writer configuration, and file I/O handling (~110 lines). The FeatureMapArrowIO version includes anextra_metadataparameter for extensibility, which should be preserved in a refactored shared version.Suggested approach: Create a shared internal utility (e.g.,
src/openms/source/FORMAT/ArrowIOHelpers.hwith implementation in.cpp, or add to an existing Arrow IO utilities file) and export the function with the extra_metadata parameter to support both use cases.🤖 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 401 - 514, The duplicated writeArrowTableToParquet_ implementation (used in FeatureMapArrowIO.cpp and ProteinIdentificationArrowIO.cpp) should be moved to a shared helper to remove duplication: create a new internal utility (e.g., ArrowIOHelpers.h/.cpp) that exports a function signature matching writeArrowTableToParquet_(std::shared_ptr<arrow::Table>, const String&, const std::string&, const ParquetWriteConfig&, const std::unordered_map<std::string,std::string>& extra_metadata = {}), preserve the existing UUID generation, metadata assembly (including extra_metadata), Parquet writer configuration (using ParquetWriteConfig), file I/O and error logging, then replace the duplicates in FeatureMapArrowIO.cpp and ProteinIdentificationArrowIO.cpp with calls to the shared ArrowIOHelpers::writeArrowTableToParquet_.
🤖 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-design.md`:
- Around line 11-18: The fenced code block in the file contains no language
identifier (the block starting with ``` and showing "<name>.fmd/"); add the
language identifier "text" to the opening fence (i.e., change ``` to ```text) so
markdownlint and coding guidelines are satisfied and the snippet is treated as
plain text.
In `@docs/plans/2026-02-19-featuremap-arrow-io-implementation.md`:
- Line 15: The document jumps from the h1 "# FeatureMapArrowIO Implementation
Plan" directly to "### Task 1", violating MD001; fix by either changing each
"### Task N" heading to "## Task N" or inserting a new "## Tasks" section header
immediately after the h1 and leaving "### Task N" as subtasks; update all
subsequent "### Task N" headings accordingly (e.g., adjust "### Task 1", "###
Task 2", etc.) so heading levels increment by one.
- Line 3: Remove the AI-agent instruction line that reads "**For Claude:**
REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan
task-by-task." from the committed documentation; locate the exact string in the
markdown (e.g., the quoted line in the document) and delete it so the file
contains only repository-facing documentation without any AI-specific
directives.
In `@src/openms/source/FORMAT/FeatureMapArrowIO.cpp`:
- Around line 118-132: The current handling of the '\u' escape in the case 'u'
block casts the parsed hex value to char (static_cast<char>(cp)), which silently
truncates codepoints > 0xFF; change the logic in that case inside the unescape
routine (the case 'u' block in FeatureMapArrowIO.cpp) to: 1) detect and combine
UTF-16 surrogate pairs (if a high surrogate \uXXXX is followed by another \uYYYY
low surrogate) to form the full codepoint, 2) encode the resulting Unicode
codepoint into its UTF-8 byte sequence and append those bytes to result (instead
of a single char), and 3) adjust the index advancement to account for the extra
consumed characters when a surrogate pair is used; this ensures correct
round-trip of arbitrary \uXXXX escapes and avoids silent corruption.
---
Nitpick comments:
In `@src/openms/source/FORMAT/FeatureMapArrowIO.cpp`:
- Around line 845-854: The code in FeatureMapArrowIO.cpp treats width == 0.0f as
null when appending to width_builder (using feature.getWidth()), which collapses
the distinction between an explicitly set zero width and an unset width; add a
concise inline comment next to this block (near the
width_builder.AppendNull()/Append calls) that explains this behavior and its
consequence for round-trip import/export (zero values are stored as null and
will be interpreted as default 0.0f on read), so future maintainers understand
this deliberate semantic loss or can change it deliberately later.
- Around line 146-209: serializeDataProcessing_ currently constructs JSON by
hand; replace it with nlohmann::json usage to produce robust output and handle
numeric/boolean types and escaping. In function serializeDataProcessing_ build a
nlohmann::json array where each element is an object with keys "software_name"
(dp.getSoftware().getName()), "software_version"
(dp.getSoftware().getVersion()), "completion_time"
(dp.getCompletionTime().isValid() ?
dp.getCompletionTime().toString("yyyy-MM-ddThh:mm:ss") : "" ), "actions" (vector
of DataProcessing::processingActionToString(action)), and "metavalues" (array of
objects with name, value and a type determined from DataValue::valueType()
mapping to proper JSON types: int, float, bool, string; use DataValue accessors
to set numeric/boolean types rather than always string). Serialize the
nlohmann::json with dump() and replace the hand-rolled loop; apply the same
refactor to the corresponding deserialization/related code ranges referenced
(around 254-398) or add a short comment in both functions explaining why
nlohmann::json is not used if you intentionally keep the hand-rolled approach.
- Around line 1382-1393: The code currently assumes contiguous P_ID groups
(variables: current_p_id, p_id, groups, getInt32Value_) but never validates
re-appearance; add a lightweight validation that tracks seen P_IDs (e.g.,
std::unordered_set<int32_t> seen_p_ids) while iterating rows and if (p_id !=
current_p_id && seen_p_ids.contains(p_id)) emit a warning (include p_id and row)
so users know the Parquet was re-ordered; alternatively (preferred for
correctness) replace the contiguous-only logic by building a
std::unordered_map<int32_t, size_t> p_id_to_group_index to append rows to the
correct PeptideIdentification regardless of order (use p_id_to_group_index to
find or create the group instead of only comparing to current_p_id).
- Around line 401-514: The duplicated writeArrowTableToParquet_ implementation
(used in FeatureMapArrowIO.cpp and ProteinIdentificationArrowIO.cpp) should be
moved to a shared helper to remove duplication: create a new internal utility
(e.g., ArrowIOHelpers.h/.cpp) that exports a function signature matching
writeArrowTableToParquet_(std::shared_ptr<arrow::Table>, const String&, const
std::string&, const ParquetWriteConfig&, const
std::unordered_map<std::string,std::string>& extra_metadata = {}), preserve the
existing UUID generation, metadata assembly (including extra_metadata), Parquet
writer configuration (using ParquetWriteConfig), file I/O and error logging,
then replace the duplicates in FeatureMapArrowIO.cpp and
ProteinIdentificationArrowIO.cpp with calls to the shared
ArrowIOHelpers::writeArrowTableToParquet_.
In `@src/tests/class_tests/openms/source/FeatureMapArrowIO_test.cpp`:
- Around line 175-176: The comment incorrectly labels "subordinate 2
(unique_id=2)" — update the comment near the Feature subsub declaration to
correctly reference sub1 (unique_id=2) or rephrase to avoid numeric ambiguity
(e.g., "Give sub1 (unique_id=2) its own subordinate (unique_id=4)"), ensuring it
matches the subsequent code that adds subsub to sub1 rather than sub2.
| ``` | ||
| <name>.fmd/ | ||
| features.parquet # One row per feature (top-level + subordinates) | ||
| psms.parquet # QPXFile schema + feature_id linkage | ||
| proteins.parquet # ProteinIdentificationArrowIO (reused) | ||
| protein_groups.parquet # ProteinIdentificationArrowIO (reused) | ||
| search_params.parquet # ProteinIdentificationArrowIO (reused) | ||
| ``` |
There was a problem hiding this comment.
Add language identifier to fenced code block.
As per coding guidelines and the markdownlint hint:
-```
+```text
<name>.fmd/🧰 Tools
🪛 markdownlint-cli2 (0.21.0)
[warning] 11-11: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
🤖 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 11 - 18,
The fenced code block in the file contains no language identifier (the block
starting with ``` and showing "<name>.fmd/"); add the language identifier "text"
to the opening fence (i.e., change ``` to ```text) so markdownlint and coding
guidelines are satisfied and the snippet is treated as plain text.
| @@ -0,0 +1,739 @@ | |||
| # FeatureMapArrowIO Implementation Plan | |||
|
|
|||
| > **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. | |||
There was a problem hiding this comment.
Remove AI agent instruction from committed documentation.
Line 3 contains > **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. which is an AI-specific instruction that shouldn't be in repository documentation.
-> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
-
**Goal:** Full lossless round-trip export/import of FeatureMap data to Arrow/Parquet, replacing FeatureXML.📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| > **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. | |
| **Goal:** Full lossless round-trip export/import of FeatureMap data to Arrow/Parquet, replacing FeatureXML. |
🤖 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-implementation.md` at line 3,
Remove the AI-agent instruction line that reads "**For Claude:** REQUIRED
SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task."
from the committed documentation; locate the exact string in the markdown (e.g.,
the quoted line in the document) and delete it so the file contains only
repository-facing documentation without any AI-specific directives.
|
|
||
| --- | ||
|
|
||
| ### Task 1: Create header file with class declaration |
There was a problem hiding this comment.
Heading level jumps from h1 to h3 — add h2 or use h2 for tasks.
Per markdownlint MD001, heading levels should increment by one. The document jumps from # FeatureMapArrowIO Implementation Plan (h1) directly to ### Task 1 (h3).
-### Task 1: Create header file with class declaration
+## Task 1: Create header file with class declaration(Apply similarly for all subsequent ### Task N headings, or add a ## Tasks section before them.)
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| ### Task 1: Create header file with class declaration | |
| ## Task 1: Create header file with class declaration |
🧰 Tools
🪛 markdownlint-cli2 (0.21.0)
[warning] 15-15: Heading levels should only increment by one level at a time
Expected: h2; Actual: h3
(MD001, heading-increment)
🤖 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-implementation.md` at line 15, The
document jumps from the h1 "# FeatureMapArrowIO Implementation Plan" directly to
"### Task 1", violating MD001; fix by either changing each "### Task N" heading
to "## Task N" or inserting a new "## Tasks" section header immediately after
the h1 and leaving "### Task N" as subtasks; update all subsequent "### Task N"
headings accordingly (e.g., adjust "### Task 1", "### Task 2", etc.) so heading
levels increment by one.
| case 'u': | ||
| if (i + 4 < s.size()) | ||
| { | ||
| unsigned int cp = 0; | ||
| for (int j = 0; j < 4; ++j) // parse 4 hex digits | ||
| { | ||
| char ch = s[i + 1 + j]; | ||
| cp <<= 4; | ||
| if (ch >= '0' && ch <= '9') cp |= (ch - '0'); | ||
| else if (ch >= 'a' && ch <= 'f') cp |= (ch - 'a' + 10); | ||
| else if (ch >= 'A' && ch <= 'F') cp |= (ch - 'A' + 10); | ||
| } | ||
| result += static_cast<char>(cp); | ||
| i += 4; | ||
| } |
There was a problem hiding this comment.
\uXXXX unescape silently truncates codepoints above 0xFF.
Line 130: static_cast<char>(cp) works for control characters (the only thing escapeJsonString_ emits \u escapes for), but if a Parquet file is edited externally or if a metavalue name/value contains embedded \uXXXX sequences above 0xFF, they'll be silently corrupted. Consider proper UTF-8 encoding for the codepoint:
Proposed fix for proper UTF-8 encoding
- result += static_cast<char>(cp);
+ // Encode as UTF-8
+ if (cp < 0x80)
+ {
+ result += static_cast<char>(cp);
+ }
+ else if (cp < 0x800)
+ {
+ result += static_cast<char>(0xC0 | (cp >> 6));
+ result += static_cast<char>(0x80 | (cp & 0x3F));
+ }
+ else
+ {
+ result += static_cast<char>(0xE0 | (cp >> 12));
+ result += static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
+ result += static_cast<char>(0x80 | (cp & 0x3F));
+ }🤖 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 118 - 132, The
current handling of the '\u' escape in the case 'u' block casts the parsed hex
value to char (static_cast<char>(cp)), which silently truncates codepoints >
0xFF; change the logic in that case inside the unescape routine (the case 'u'
block in FeatureMapArrowIO.cpp) to: 1) detect and combine UTF-16 surrogate pairs
(if a high surrogate \uXXXX is followed by another \uYYYY low surrogate) to form
the full codepoint, 2) encode the resulting Unicode codepoint into its UTF-8
byte sequence and append those bytes to result (instead of a single char), and
3) adjust the index advancement to account for the extra consumed characters
when a surrogate pair is used; this ensures correct round-trip of arbitrary
\uXXXX escapes and avoids silent corruption.
- Add FeatureMapArrowIO.h to header sources.cmake (was missing, causing
pyOpenMS wheel builds to fail with "No such file or directory")
- Add target_link_libraries for ProteinIdentificationArrowIO_test and
FeatureMapArrowIO_test (missing Arrow/Parquet link, causing Windows
build failure with "Cannot open include file: arrow/api.h")
- Fix pyOpenMS pxd exclusion filter to use 'Arrow' in name instead of
startswith('Arrow'), catching FeatureMapArrowIO and similar files
Co-Authored-By: Claude Opus 4.6 <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/pyOpenMS/create_cpp_extension.py (1)
93-98: Align addon filter with pxd filter to prevent future inconsistencies.The pxd filter (lines 87–88) excludes basenames containing
'Arrow'whenWITH_PARQUETis disabled, but the addon filter (lines 15–16) only checks for'Parquet'. While no Arrow-named addon files currently exist, this inconsistency should be corrected to ensure future-proof consistency.♻️ Proposed fix — align addon filter with pxd filter
if not WITH_PARQUET: def _is_parquet_addon(name): - return 'Parquet' in name + return 'Arrow' in name or 'Parquet' in name addons = [a for a in addons if not _is_parquet_addon(os.path.basename(a))] - print("WITH_PARQUET is disabled, excluding Parquet* addons from wrapping") + print("WITH_PARQUET is disabled, excluding Arrow*/Parquet* addons from wrapping")🤖 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 93 - 98, The addon filtering when WITH_PARQUET is False is inconsistent with the pxd filter: update the _is_parquet_addon predicate used to filter the addons list so it excludes basenames containing either "Parquet" or "Arrow" (mirror the pxd logic); locate the function _is_parquet_addon and the line where addons = [a for a in addons if not _is_parquet_addon(os.path.basename(a))] and change the check to test for both substrings in the basename so future Arrow-named addons are excluded when WITH_PARQUET is disabled.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@src/pyOpenMS/create_cpp_extension.py`:
- Around line 93-98: The addon filtering when WITH_PARQUET is False is
inconsistent with the pxd filter: update the _is_parquet_addon predicate used to
filter the addons list so it excludes basenames containing either "Parquet" or
"Arrow" (mirror the pxd logic); locate the function _is_parquet_addon and the
line where addons = [a for a in addons if not
_is_parquet_addon(os.path.basename(a))] and change the check to test for both
substrings in the basename so future Arrow-named addons are excluded when
WITH_PARQUET is disabled.
- Guard ProteaseDB::getEnzyme() with hasEnzyme() check in ProteinIdentificationArrowIO import, following the established pattern used in IdXMLFile, FeatureXMLHandler, and ConsensusXMLHandler - Fix \uXXXX unescape in FeatureMapArrowIO to properly encode codepoints above 0x7F as multi-byte UTF-8 instead of truncating via static_cast<char> Co-Authored-By: Claude Opus 4.6 <[email protected]>
Summary
FeatureMapArrowIOclass for full lossless round-trip export/import ofFeatureMapdata to Apache Arrow / Parquet format, as a mid-term replacement for FeatureXML.fmd/directory containing 5 Parquet files:features.parquet,psms.parquet,proteins.parquet,protein_groups.parquet,search_params.parquetparent_feature_id/depthcolumns for queryability while supporting arbitrary nesting depthQPXFile::exportToArrowwith an addedfeature_idcolumn linking to features; unassigned peptide IDs usenullfeature_idProteinIdentificationArrowIOFeatureMapArrowIO.pxd)Test plan
FeatureMapArrowIO_testsections passWITH_PARQUET=ON🤖 Generated with Claude Code
Summary by CodeRabbit
Release Notes
New Features