Skip to content

Update QuantmsIO PSM schema field names and fix file metadata storage to match new quantms.io specification - #8206

Merged
timosachsenberg merged 2 commits into
OpenMS:copilot/fix-8568c86a-7f17-4893-a72c-132e6a9ae35cfrom
Avni2000:write-parquet
Sep 12, 2025
Merged

timosachsenberg merged 2 commits into
OpenMS:copilot/fix-8568c86a-7f17-4893-a72c-132e6a9ae35cfrom
Avni2000:write-parquet

Conversation

@Avni2000

@Avni2000 Avni2000 commented Sep 11, 2025 •

Copy link
Copy Markdown
Contributor

Supersedes #8198

+ FIX: Wrote metadata to table
+ QuantMSIO_Test passes locally

@coderabbitai

coderabbitai Bot commented Sep 11, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Updates Parquet output to embed file-level metadata, renames two PSM schema fields (mp_accessions -> protein_accessions, num_peaks -> number_peaks), refactors Parquet writing to use parquet::arrow::FileWriter with explicit metadata handling and error propagation, and aligns tests and header documentation with these changes.

Changes

Cohort / File(s) Summary
Header docs (QuantmsIO.h)
src/openms/include/OpenMS/FORMAT/QuantmsIO.h
Update documentation: rename mp_accessions → protein_accessions, num_peaks → number_peaks; document file-level metadata keys (quantmsio_version, creator, file_type, creation_date, uuid, scan_format, software_provider). No API signature changes.
Parquet writer & metadata (QuantmsIO.cpp)
src/openms/source/FORMAT/QuantmsIO.cpp
Generate file_metadata (ISO-8601 creation_date, simple UUID, version, creator, file_type, scan_format, software_provider); refactor Parquet write path to use parquet::arrow::FileWriter, call AddKeyValueMetadata, WriteTable, Close, and throw OpenMS::Exception::UnableToCreateFile on failures; rename schema fields to protein_accessions and number_peaks; add <chrono>, <iomanip>, <functional> includes.
Tests (QuantmsIO_test.cpp)
src/tests/class_tests/openms/source/QuantmsIO_test.cpp
Update expected schema field names and indices (protein_accessions, number_peaks); clarify column-count check excludes file-level metadata; add TODO to verify file-level Parquet metadata when API available.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Client
  participant Q as QuantmsIO::store()
  participant T as convertToArrowTable
  participant W as writeParquetFile
  participant F as parquet::arrow::FileWriter

  C->>Q: store(output_path, data)
  Note over Q: build file_metadata (quantmsio_version, creator,\nfile_type, creation_date ISO8601, uuid, scan_format, software_provider)
  Q->>T: convertToArrowTable(data)
  T-->>Q: arrow::Table (fields include protein_accessions, number_peaks)
  Q->>W: writeParquetFile(path, table, file_metadata)

  W->>F: FileWriter::Open(path)
  alt open failed
    F--xW: error
    W--xQ: throw UnableToCreateFile
    Q--xC: propagate
  else open ok
    W->>F: AddKeyValueMetadata(file_metadata)
    alt metadata add failed
      F--xW: error
      W--xQ: throw UnableToCreateFile
      Q--xC: propagate
    else ok
      W->>F: WriteTable(table)
      alt write failed
        F--xW: error
        W--xQ: throw UnableToCreateFile
        Q--xC: propagate
      else ok
        W->>F: Close()
        alt close failed
          F--xW: error
          W--xQ: throw UnableToCreateFile
          Q--xC: propagate
        else success
          F-->>W: success
          W-->>Q: return
          Q-->>C: done
        end
      end
    end
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested reviewers

  • cbielow

Poem

I stamped the parquet with a tiny hop,
A uuid whisk, a timestamp drop.
Fields renamed, the schema speaks,
protein_accessions, number_peaks.
I thump, I write, then nibble snacks — metadata snug in tidy stacks. 🐇

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.

Pre-merge checks (2 passed, 1 warning)

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The title accurately and concisely describes the PR's primary changes—renaming PSM schema fields (mp_accessions → protein_accessions, num_peaks → number_peaks) and changing file metadata storage to file-level Parquet metadata to match the quantms.io specification—making it specific and relevant to the diff and PR objectives.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

@Avni2000 Avni2000 changed the title Write parquet Update QuantmsIO PSM schema field names and fix file metadata storage to match new quantms.io specification Sep 11, 2025
- Tests pass, and builds correctly.

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

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

126-126: Variable names need to be updated to match new schema

The builder variables and related code still use the old field names (mp_accessions_builder and num_peaks_builder) while the schema has been updated to use protein_accessions and number_peaks. This inconsistency could cause confusion for maintainers.

Apply these changes to maintain consistency with the new schema:

-    arrow::StringBuilder mp_accessions_builder; // Use comma-separated string for now
+    arrow::StringBuilder protein_accessions_builder; // Use comma-separated string for now
-    arrow::Int32Builder num_peaks_builder;
+    arrow::Int32Builder number_peaks_builder;
-      status = mp_accessions_builder.Append(protein_accessions.c_str());
+      status = protein_accessions_builder.Append(protein_accessions.c_str());
-      // Num peaks
-      if (hit.metaValueExists(OpenMS::Constants::UserParam::NUM_PEAKS))
-      {
-        int num_peaks = hit.getMetaValue(OpenMS::Constants::UserParam::NUM_PEAKS);
-        status = num_peaks_builder.Append(num_peaks);
-      }
-      else
-      {
-        status = num_peaks_builder.AppendNull();
-      }
+      // Number peaks
+      if (hit.metaValueExists(OpenMS::Constants::UserParam::NUM_PEAKS))
+      {
+        int number_peaks = hit.getMetaValue(OpenMS::Constants::UserParam::NUM_PEAKS);
+        status = number_peaks_builder.Append(number_peaks);
+      }
+      else
+      {
+        status = number_peaks_builder.AppendNull();
+      }
-    std::shared_ptr<arrow::Array> mp_accessions_array;
-    status = mp_accessions_builder.Finish(&mp_accessions_array);
+    std::shared_ptr<arrow::Array> protein_accessions_array;
+    status = protein_accessions_builder.Finish(&protein_accessions_array);
     if (!status.ok()) {
       throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, 
-                                      "Failed to finish mp_accessions array: " + OpenMS::String(status.ToString()));
+                                      "Failed to finish protein_accessions array: " + OpenMS::String(status.ToString()));
     }
-    std::shared_ptr<arrow::Array> num_peaks_array;
-    status = num_peaks_builder.Finish(&num_peaks_array);
+    std::shared_ptr<arrow::Array> number_peaks_array;
+    status = number_peaks_builder.Finish(&number_peaks_array);
     if (!status.ok()) {
       throw OpenMS::Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, 
-                                      "Failed to finish num peaks array: " + OpenMS::String(status.ToString()));
+                                      "Failed to finish number peaks array: " + OpenMS::String(status.ToString()));
     }
-      arrow::MakeArrayOfNull(arrow::null(), sequence_array->length()).ValueOrDie(), // protein_accessions - using mp_accessions_array would need list type
+      arrow::MakeArrayOfNull(arrow::null(), sequence_array->length()).ValueOrDie(), // protein_accessions - using protein_accessions_array would need list type
-      num_peaks_array,
+      number_peaks_array,

Also applies to: 132-132, 242-246, 319-320, 324-329, 382-387, 424-429, 443-443, 450-450

🧹 Nitpick comments (1)
src/openms/source/FORMAT/QuantmsIO.cpp (1)

475-479: UUID generation needs improvement for production use

The current UUID generation method using hash functions doesn't produce valid RFC 4122 UUIDs. While functional for development, this should be replaced with a proper UUID library for production use.

Consider using a proper UUID library (e.g., boost::uuids or a dedicated UUID library) to generate RFC 4122 compliant UUIDs. The current implementation might produce collisions in high-throughput scenarios. Would you like me to provide an implementation using boost::uuids or open an issue to track this improvement?

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 44b5140 and 95ad0aa.

📒 Files selected for processing (3)
  • src/openms/include/OpenMS/FORMAT/QuantmsIO.h (1 hunks)
  • src/openms/source/FORMAT/QuantmsIO.cpp (7 hunks)
  • src/tests/class_tests/openms/source/QuantmsIO_test.cpp (2 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
src/openms/**/*.{cpp,h,hpp,cc,cxx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

src/openms/**/*.{cpp,h,hpp,cc,cxx}: Follow the existing C++ coding conventions in the codebase
Use the established naming patterns for classes, methods, and variables
Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)
Follow the established error handling patterns
Utilize OpenMS logging mechanisms
Be mindful of memory usage when processing large datasets
Consider algorithmic complexity for data processing operations
Use appropriate OpenMS containers and algorithms

Files:

  • src/openms/include/OpenMS/FORMAT/QuantmsIO.h
  • src/openms/source/FORMAT/QuantmsIO.cpp
src/openms/include/OpenMS/**/*.h

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Add Doxygen comments for new public methods and classes

Files:

  • src/openms/include/OpenMS/FORMAT/QuantmsIO.h
src/tests/class_tests/openms/**/*.cpp

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Write unit tests for new functionality

Files:

  • src/tests/class_tests/openms/source/QuantmsIO_test.cpp
🧠 Learnings (3)
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
PR: OpenMS/OpenMS#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/include/OpenMS/**/*.h : Add Doxygen comments for new public methods and classes

Applied to files:

  • src/openms/include/OpenMS/FORMAT/QuantmsIO.h
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
PR: OpenMS/OpenMS#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/tests/class_tests/openms/**/*.cpp : Write unit tests for new functionality

Applied to files:

  • src/tests/class_tests/openms/source/QuantmsIO_test.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
PR: OpenMS/OpenMS#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/tests/class_tests/openms/*Test.cpp : Follow naming convention: `ClassNameTest.cpp` for `ClassName`

Applied to files:

  • src/tests/class_tests/openms/source/QuantmsIO_test.cpp
🧬 Code graph analysis (1)
src/openms/source/FORMAT/QuantmsIO.cpp (1)
src/openms/source/CONCEPT/Exception.cpp (1)
  • UnableToCreateFile (235-239)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: build-and-test (macos-13, xcode, 14.2)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
  • GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
🔇 Additional comments (8)
src/openms/include/OpenMS/FORMAT/QuantmsIO.h (1)

36-36: Field names updated to match quantms.io PSM specification

The documentation correctly reflects the renamed fields (protein_accessions and number_peaks) to align with the quantms.io PSM specification.

Also applies to: 43-43, 46-46

src/tests/class_tests/openms/source/QuantmsIO_test.cpp (3)

135-136: Schema correctly excludes file-level metadata

The comment properly indicates that the Parquet schema should contain 19 columns without file_metadata, which is now stored at the file level.


149-149: Field names correctly updated in test assertions

The test assertions have been properly updated to verify the renamed fields (protein_accessions at index 9 and number_peaks at index 16).

Also applies to: 156-156


160-161: Good TODO for future metadata verification

The TODO appropriately identifies the need to verify file-level metadata once the Parquet metadata API becomes available. The comment correctly notes that metadata should be stored at the Parquet file level rather than as schema fields.

src/openms/source/FORMAT/QuantmsIO.cpp (4)

24-26: LGTM: Required headers for metadata generation

The new includes are necessary for the timestamp formatting and UUID generation functionality.


46-46: Schema fields correctly renamed

The PSM schema fields have been properly renamed to protein_accessions and number_peaks to align with the quantms.io specification.

Also applies to: 53-53


61-112: Well-structured Parquet writer with metadata support

The refactored writeParquetFile function properly uses parquet::arrow::FileWriter with comprehensive error handling at each stage (open, metadata addition, write, close). The metadata is correctly embedded at the file level using AddKeyValueMetadata.


469-490: File metadata generation implemented correctly

The metadata generation properly creates ISO 8601 timestamps and includes all required fields per the quantms.io specification. The metadata is correctly passed to the Parquet writer.

@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 (5)
src/openms/source/FORMAT/QuantmsIO.cpp (5)

100-101: Consider row group size instead of writing as a single row group.

Using num_rows() forces one large row group; prefer ~64K–256K rows for better IO.

-    auto status = writer->WriteTable(*table, table->num_rows());
+    constexpr int64_t kRowGroupSize = 128 * 1024; // tune if needed
+    auto status = writer->WriteTable(*table, kRowGroupSize);

471-472: gmtime is not thread-safe. Prefer gmtime_r/gmtime_s fallback or a safer utility.

-    creation_date_stream << std::put_time(std::gmtime(&time_t), "%Y-%m-%dT%H:%M:%SZ");
+    std::tm tm{};
+#if defined(_WIN32)
+    gmtime_s(&tm, &time_t);
+#else
+    gmtime_r(&time_t, &tm);
+#endif
+    creation_date_stream << std::put_time(&tm, "%Y-%m-%dT%H:%M:%SZ");

125-125: mp_accessions_builder is legacy naming and the array is unused.

Either implement list writing for protein_accessions or drop the builder to avoid wasted work. Rename to protein_accessions_builder if kept.

-    arrow::StringBuilder mp_accessions_builder; // Use comma-separated string for now
+    // TODO(soon): implement list<string> builder for protein_accessions or remove temporary builder.

Also applies to: 381-386


42-42: Confirm is_decoy type against spec.

If quantms.io expects boolean, switch schema to arrow::boolean() and use BooleanBuilder.


481-489: Hard-coded metadata values.

Consider surfacing quantmsio_version and software_provider as constants or parameters; avoid string duplication ("OpenMS" twice).

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 95ad0aa and 8341cdb.

📒 Files selected for processing (1)
  • src/openms/source/FORMAT/QuantmsIO.cpp (7 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/openms/**/*.{cpp,h,hpp,cc,cxx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

src/openms/**/*.{cpp,h,hpp,cc,cxx}: Follow the existing C++ coding conventions in the codebase
Use the established naming patterns for classes, methods, and variables
Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)
Follow the established error handling patterns
Utilize OpenMS logging mechanisms
Be mindful of memory usage when processing large datasets
Consider algorithmic complexity for data processing operations
Use appropriate OpenMS containers and algorithms

Files:

  • src/openms/source/FORMAT/QuantmsIO.cpp
🧬 Code graph analysis (1)
src/openms/source/FORMAT/QuantmsIO.cpp (1)
src/openms/source/CONCEPT/Exception.cpp (1)
  • UnableToCreateFile (235-239)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
  • GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (macos-13, xcode, 14.2)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
🔇 Additional comments (2)
src/openms/source/FORMAT/QuantmsIO.cpp (2)

53-53: Field rename to number_peaks looks good.


73-82: Incorrect FileWriter::Open argument (dereferencing schema) — likely compile error.

Pass shared_ptrarrow::Schema, not a reference.

-    auto writer_result = parquet::arrow::FileWriter::Open(*table->schema(), 
+    auto writer_result = parquet::arrow::FileWriter::Open(table->schema(),
                                                          arrow::default_memory_pool(),
                                                          outfile);

Likely an incorrect or invalid review comment.

arrow::field("observed_mz", arrow::float32()),
arrow::field("additional_scores", arrow::null(), true), // nullable - null for now
arrow::field("mp_accessions", arrow::null(), true), // nullable - null for now
arrow::field("protein_accessions", arrow::null(), true), // nullable - null for now

@coderabbitai coderabbitai Bot Sep 11, 2025 •

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.

🛠️ Refactor suggestion

Schema type for protein_accessions must be list, not Null.

Match quantms.io: keep the column present but type it correctly and emit null list values.

-      arrow::field("protein_accessions", arrow::null(), true), // nullable - null for now
+      arrow::field("protein_accessions", arrow::list(arrow::utf8()), true), // nullable list<string>
-      arrow::MakeArrayOfNull(arrow::null(), sequence_array->length()).ValueOrDie(), // protein_accessions - using mp_accessions_array would need list type
+      arrow::MakeArrayOfNull(arrow::list(arrow::utf8()), sequence_array->length()).ValueOrDie(), // protein_accessions (null lists for now)

Also applies to: 442-442

🤖 Prompt for AI Agents
In src/openms/source/FORMAT/QuantmsIO.cpp around lines 46 and 442, the schema
currently defines "protein_accessions" as arrow::null(); change the schema type
to a nullable list of strings (e.g., arrow::list(arrow::utf8())) and ensure when
emitting values you produce either a null list or an explicit empty/null value
encoded as a null list rather than a NullType column; update any related
builders/emit logic to use a ListBuilder (or equivalent) for string arrays and
write null list entries where appropriate.

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.

could be correct @Avni2000 can you check?

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.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Comment on lines +105 to 111
// Close writer
status = writer->Close();
if (!status.ok()) {
throw OpenMS::Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
filename, "Failed to close writer: " + OpenMS::String(status.ToString()));
}
}

@coderabbitai coderabbitai Bot Sep 11, 2025 •

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.

🛠️ Refactor suggestion

Ensure sink is closed; otherwise flush is not guaranteed on some platforms.

     // Close writer
     status = writer->Close();
     if (!status.ok()) {
       throw OpenMS::Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, 
                                       filename, "Failed to close writer: " + OpenMS::String(status.ToString()));
     }
+    // Close the underlying output stream
+    auto close_out = outfile->Close();
+    if (!close_out.ok()) {
+      throw OpenMS::Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
+                                      filename, "Failed to close file stream: " + OpenMS::String(close_out.ToString()));
+    }
📝 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.

Suggested change
// Close writer
status = writer->Close();
if (!status.ok()) {
throw OpenMS::Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
filename, "Failed to close writer: " + OpenMS::String(status.ToString()));
}
}
// Close writer
status = writer->Close();
if (!status.ok()) {
throw OpenMS::Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
filename, "Failed to close writer: " + OpenMS::String(status.ToString()));
}
// Close the underlying output stream
auto close_out = outfile->Close();
if (!close_out.ok()) {
throw OpenMS::Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
filename, "Failed to close file stream: " + OpenMS::String(close_out.ToString()));
}
🤖 Prompt for AI Agents
In src/openms/source/FORMAT/QuantmsIO.cpp around lines 105 to 111, the current
code closes the writer but does not close the underlying sink, which can leave
buffered data unflushed on some platforms; after calling writer->Close() and
checking its status, call sink->Close() (or the concrete sink close method) and
check its Status as well, throwing an OpenMS::Exception::UnableToCreateFile with
the same style of message if sink->Close() returns a non-ok status so the sink
is guaranteed to be flushed and closed.

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.

probably correct

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.

, but this behavior can vary across platforms and implementations.

  1. Best practices: Many experienced developers recommend explicitly closing both the high-level writer and the underlying stream, especially for critical data like Parquet files where corruption could be devastating.

The pattern I suggested follows the established practice in Arrow's own examples and ensures that:

  • The Parquet metadata and file structure are properly written (via writer->Close())
  • Any buffered data in the underlying output stream is flushed to disk (via outfile->Close())

This is particularly important for the QuantmsIO use case since you're dealing with scientific data where file integrity is crucial. The small overhead of an extra Close() call is worth the guarantee of proper data persistence.

Would you like me to research any specific aspects further, or are you comfortable proceeding with this approach?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

That makes sense

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.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Comment on lines +474 to +479
// Generate a simple UUID based on current time and process
std::ostringstream uuid_stream;
uuid_stream << std::hex << std::hash<std::string>{}(creation_date_str) << "-0000-4000-8000-"
<< std::setfill('0') << std::setw(12) << (std::hash<const void*>{}(&protein_identifications) & 0xFFFFFFFFFFFF);
std::string uuid_str = uuid_stream.str();

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.

⚠️ Potential issue

Non-RFC4122 UUID; leaks pointer info and segment widths are invalid. Generate a proper v4 UUID.

-    // Generate a simple UUID based on current time and process
-    std::ostringstream uuid_stream;
-    uuid_stream << std::hex << std::hash<std::string>{}(creation_date_str) << "-0000-4000-8000-" 
-                << std::setfill('0') << std::setw(12) << (std::hash<const void*>{}(&protein_identifications) & 0xFFFFFFFFFFFF);
-    std::string uuid_str = uuid_stream.str();
+    // Generate RFC 4122 version-4 UUID (random)
+    std::array<uint8_t,16> u{};
+    std::random_device rd;
+    for (auto& b : u) b = static_cast<uint8_t>(rd());
+    u[6] = (u[6] & 0x0F) | 0x40; // version 4
+    u[8] = (u[8] & 0x3F) | 0x80; // variant 10
+    char uuid_buf[37];
+    std::snprintf(uuid_buf, sizeof(uuid_buf),
+                  "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
+                  u[0],u[1],u[2],u[3],u[4],u[5],u[6],u[7],u[8],u[9],u[10],u[11],u[12],u[13],u[14],u[15]);
+    std::string uuid_str(uuid_buf);

Add headers:

 #include <iomanip>
 #include <functional>
+#include <random>
+#include <cstdio>
📝 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.

Suggested change
// Generate a simple UUID based on current time and process
std::ostringstream uuid_stream;
uuid_stream << std::hex << std::hash<std::string>{}(creation_date_str) << "-0000-4000-8000-"
<< std::setfill('0') << std::setw(12) << (std::hash<const void*>{}(&protein_identifications) & 0xFFFFFFFFFFFF);
std::string uuid_str = uuid_stream.str();
// Generate RFC 4122 version-4 UUID (random)
std::array<uint8_t,16> u{};
std::random_device rd;
for (auto& b : u) b = static_cast<uint8_t>(rd());
u[6] = (u[6] & 0x0F) | 0x40; // version 4
u[8] = (u[8] & 0x3F) | 0x80; // variant 10
char uuid_buf[37];
std::snprintf(uuid_buf, sizeof(uuid_buf),
"%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
u[0],u[1],u[2],u[3],u[4],u[5],u[6],u[7],u[8],u[9],u[10],u[11],u[12],u[13],u[14],u[15]);
std::string uuid_str(uuid_buf);
🤖 Prompt for AI Agents
In src/openms/source/FORMAT/QuantmsIO.cpp around lines 474-479, the current UUID
construction leaks pointer info and doesn't follow RFC4122; replace it with a
proper RFC4122 v4 generator: add includes (<random>, <array>, <sstream>,
<iomanip>), generate 16 cryptographically-seeded random bytes
(std::random_device + std::mt19937 or std::uniform_int_distribution<uint8_t>),
set the version nibble to 4 and the variant bits to 10xx per RFC4122, then
format the bytes into the canonical 8-4-4-4-12 hex string using std::hex,
std::setw and std::setfill('0'); do not use pointer addresses or std::hash.

@Avni2000
Avni2000 changed the base branch from develop to copilot/fix-8568c86a-7f17-4893-a72c-132e6a9ae35c September 11, 2025 17:01
md_keys.push_back(kv.first);
md_values.push_back(kv.second);
}
const auto metadata = arrow::key_value_metadata(md_keys,md_values);

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.

@jpfeuffer can you confirm?

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.

Looks good! Can we re-read this in the test @Avni2000
Can you maybe even upload the parquet file from a test for me/us to check it?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@jpfeuffer should we just change the QuantMSIO test to use an actual idxml instead? Not sure why it simulates OpenMS' psm algorithm to input data.

Unless there's a reason for that and I should just make another subsection for the parquet i/o test?

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.

Yes you can use an existing idxml. Might be better.

@Avni2000 Avni2000 Sep 13, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@jpfeuffer Sounds good. Should the idxml topp test replace the class test? Seems like all metadata works so far btw

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.

We need two tests.
The class test for QuantMSIO and a tool test for the Converter.
For class tests I prefer constructing the data in the test (without loading another format),
For tool tests, we pass a file (see https://github.com/OpenMS/OpenMS/blob/develop/src/tests/topp/CMakeLists.txt ) .

@timosachsenberg

Copy link
Copy Markdown
Contributor

ok before things get complicate I will merge this into the old PR and then in develop.

@timosachsenberg
timosachsenberg merged commit a1a94dd into OpenMS:copilot/fix-8568c86a-7f17-4893-a72c-132e6a9ae35c Sep 12, 2025
timosachsenberg added a commit that referenced this pull request Sep 12, 2025
… to match new quantms.io specification (#8198)

* Initial plan

* Update QuantmsIO PSM schema field names to match new quantms.io specification

Co-authored-by: timosachsenberg <[email protected]>

* Add file_metadata field to QuantmsIO PSM schema with dummy values

- Added file_metadata struct field to PSM schema with 7 required fields
- Implemented dummy values for all file_metadata fields (quantmsio_version, creator, file_type, creation_date, uuid, scan_format, software_provider)
- Updated tests to verify new field structure and column count (19->20)
- Updated documentation to include file_metadata field description

Co-authored-by: timosachsenberg <[email protected]>

* Fix file-level metadata handling in QuantmsIO - use meaningful creation_date and UUID values

Co-authored-by: timosachsenberg <[email protected]>

* Remove file_metadata from PSM schema and prepare for Parquet file-level metadata

Co-authored-by: timosachsenberg <[email protected]>

* Update QuantmsIO PSM schema field names and fix file metadata storage to match new quantms.io specification (#8206)

* Added metadata to table using AddKeyValueMetadata

* unique ptr writer and passed writer result in directly
- Tests pass, and builds correctly.

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: timosachsenberg <[email protected]>
Co-authored-by: Avni2000 <[email protected]>
Co-authored-by: Timo Sachsenberg <[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.

3 participants