Skip to content

Add transparent .zip decompression for XML formats and Bruker .d - #9139

Merged
timosachsenberg merged 12 commits into
developfrom
feature/zip-compressed-file-support
Apr 13, 2026
Merged

timosachsenberg merged 12 commits into
developfrom
feature/zip-compressed-file-support

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Apr 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Adds transparent .zip decompression for all XML-based file formats (mzML, featureXML, idXML, etc.), matching the existing .gz/.bz2 pattern
  • Adds .d.zip support for Bruker TimsTOF data (extract-to-temp-dir approach)
  • New ZipIfstream (libzip wrapper) and ZipInputStream (Xerces BinInputStream) classes stream-decompress single-entry ZIP archives
  • Wired into FileHandler (extension + magic byte detection), XMLFile::parse_(), and CompressedInputSource::makeStream()
  • Single non-directory entry ZIP archives only; directory entries silently filtered; multi-entry/empty ZIPs rejected with clear errors
  • Guarded with OPENMS_HAVE_LIBZIP — compiles cleanly when libzip is unavailable

Changes

Component What
ZipIfstream libzip wrapper — streams single non-directory entry from ZIP
ZipInputStream Xerces BinInputStream adapter wrapping ZipIfstream
FileTypes::ZIP New enum value + TypeNameBinding
FileHandler Extension stripping, magic byte detection, .d.zip extract-to-temp
XMLFile::parse_() ZIP magic byte → CompressedInputSource
CompressedInputSource makeStream() dispatches PK → ZipInputStream

Test plan

  • 12 unit test sections pass (open/read/stream/close, dir filtering, error cases, extension stripping, end-to-end mzML load from ZIP)
  • FileInfo -in data.mzML.zip works end-to-end
  • .d.zip loading via FileHandler::loadExperiment() loads 11,912 spectra from zipped TimsTOF DDA data
  • CI passes

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • ZIP support: automatic detection and transparent decompression of ZIP archives; ZIP streams integrate with XML parsing and can load zipped experiment folders (including Bruker .d.zip).
  • Bug Fixes / Improvements

    • File-type detection and dialogs now recognize .zip and PK signatures; compressed-file handling unified with existing compressors.
  • Tests

    • Added unit and end-to-end tests for ZIP streams, detection, error cases, and loading zipped experiments.
  • Chores

    • Build files updated to include new ZIP stream sources/headers.

timosachsenberg and others added 7 commits April 12, 2026 22:50
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Add missing #include <cstddef> for size_t in ZipIfstream.h
- Move test ZIP files to src/tests/class_tests/openms/data/
- Use Deisotoper_input1.mzML (exists in unit test data dir) instead of
  SimpleSearchEngine_1.mzML (only in TOPP test dir)

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Apr 12, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds native ZIP support: new ZipIfstream/ZipInputStream (libzip-backed), recognizes ZIP via 'P''K' magic bytes, integrates ZIP into compressed parsing and FileHandler detection (including .d.zip for BRUKER_TDF), updates CMake, and adds unit tests and FileTypes::ZIP.

Changes

Cohort / File(s) Summary
File Type Definitions
src/openms/include/OpenMS/FORMAT/FileTypes.h, src/openms/source/FORMAT/FileTypes.cpp
Added FileTypes::ZIP mapping ("zip", "ZIP compressed file", {PROP::READABLE}).
ZIP Stream Headers
src/openms/include/OpenMS/FORMAT/ZipIfstream.h, src/openms/include/OpenMS/FORMAT/ZipInputStream.h, src/openms/include/OpenMS/FORMAT/sources.cmake
New public headers declaring ZipIfstream (libzip wrapper) and ZipInputStream (xercesc::BinInputStream adapter); headers added to CMake header list.
ZIP Stream Implementations
src/openms/source/FORMAT/ZipIfstream.cpp, src/openms/source/FORMAT/ZipInputStream.cpp, src/openms/source/FORMAT/sources.cmake
Implemented archive open/read/close semantics, single-non-directory-entry enforcement, readBytes adapter, and added sources to CMake.
Integration: Detection & Parsing
src/openms/source/FORMAT/CompressedInputSource.cpp, src/openms/source/FORMAT/XMLFile.cpp, src/openms/source/FORMAT/FileHandler.cpp
Detect ZIP via 'P''K' signature, route compressed path to ZipInputStream, include ZIP in content-based type inference, strip .zip suffix in filename-based detection, and support extracting .d.zip for BRUKER_TDF (WITH_OPENTIMS).
Build & Tests
src/tests/class_tests/openms/executables.cmake, src/tests/class_tests/openms/source/ZipIfstream_test.cpp, src/tests/class_tests/openms/source/FileTypes_test.cpp
Added test executable entry and comprehensive unit tests for ZipIfstream, filename/type mapping with .zip, error cases, end-to-end mzML loading from ZIP, and updated expected FileTypes count.

Sequence Diagram

sequenceDiagram
    participant XMLFile as XMLFile
    participant CIS as CompressedInputSource
    participant ZIS as ZipInputStream
    participant ZIF as ZipIfstream
    participant LIB as libzip

    XMLFile->>CIS: makeStream(systemId)
    CIS->>CIS: read magic bytes
    alt magic == 'P''K'
        CIS->>ZIS: new ZipInputStream(systemId)
        ZIS->>ZIF: construct ZipIfstream(systemId)
        ZIF->>LIB: zip_open(filename)
        LIB-->>ZIF: archive handle
        ZIF->>LIB: enumerate entries (skip dirs)
        LIB-->>ZIF: entry list
        ZIF->>LIB: zip_fopen(single_entry)
        LIB-->>ZIF: entry handle
        ZIS-->>CIS: stream ready
    else other compression
        CIS->>CIS: use gzip/bzip2 path
    end

    XMLFile->>ZIS: readBytes(buffer, n)
    ZIS->>ZIF: read(buffer, n)
    ZIF->>LIB: zip_fread(entry, buffer, n)
    LIB-->>ZIF: bytes
    ZIF-->>ZIS: bytes read
    ZIS-->>XMLFile: decompressed data
Loading

Possibly related PRs

Suggested Reviewers

  • jpfeuffer
  • cbielow
  • pjones

Poem

🐰 I found a PK in a zip so bright,
I nibble bytes by soft moonlight,
Streams unzip and XML sings,
Tiny files unfold their wings,
Hooray — new inputs hop into sight! 📦✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 9.09% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Add transparent .zip decompression for XML formats and Bruker .d' directly and clearly describes the main change in the changeset: adding ZIP decompression support for XML-based formats and Bruker TimsTOF data.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/zip-compressed-file-support

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

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

381-400: Consider using Size instead of size_t.

Line 387 uses size_t for bytes_read, but OpenMS coding guidelines specify using Size from OpenMS/CONCEPT/Types.h for STL .size() values and similar size types. This is consistent with other parts of the codebase.

Note that the existing bzip2 and gzip blocks (lines 347, 367) also use size_t, so this may be an existing pattern in this function. Consider updating all three for consistency if you address this.

♻️ Suggested fix
     else if (bz[0] == 'P' && bz[1] == 'K') // ZIP
     {
       ZipIfstream zip_file(filename.c_str());
 
       // read in 1024 bytes (keep last byte for zero to end string)
       char buffer[1024];
-      size_t bytes_read = zip_file.read(buffer, 1024-1);
+      Size bytes_read = zip_file.read(buffer, 1024-1);
       buffer[bytes_read] = '\0';

As per coding guidelines: "Use Size/SignedSize types for STL .size() values in OpenMS".

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

In `@src/openms/source/FORMAT/FileHandler.cpp` around lines 381 - 400, Replace the
use of size_t for read-length variables with OpenMS's Size type: change the
declaration of bytes_read in the ZIP branch (the variable read from ZipIfstream
in the block using ZipIfstream zip_file and char buffer[1024]) to Size, and
update the analogous bytes_read declarations in the bzip2 and gzip branches for
consistency; ensure the OpenMS/CONCEPT/Types.h header is included if not already
so Size is available.
🤖 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/ZipInputStream.h`:
- Around line 38-42: Add Doxygen method-level comments for the three newly added
public overrides: curPos(), readBytes(XMLByte* const to_fill, const XMLSize_t
max_to_read), and getContentType() const in class ZipInputStream; for each
method add an `@brief` line, a blank line, and a short detailed description
following the project's Doxygen style (e.g., purpose, parameters for readBytes,
return details), ensuring the required `@brief` tag is present and placed
immediately above each method declaration.

In `@src/openms/source/FORMAT/ZipIfstream.cpp`:
- Around line 107-124: In ZipIfstream::read, zip_fread returning 0 is treated as
EOF which incorrectly triggers close() and sets stream_at_end_ even when the
caller requested a zero-length read (n == 0); modify ZipIfstream::read to
immediately return 0 when n == 0 before calling zip_fread so the stream state is
preserved, i.e. add an early-return for n==0 at the start of ZipIfstream::read
and keep the existing handling of zip_fread == 0 (EOF) only for actual non-zero
reads, leaving close() and stream_at_end_ unchanged for true EOF cases.

---

Nitpick comments:
In `@src/openms/source/FORMAT/FileHandler.cpp`:
- Around line 381-400: Replace the use of size_t for read-length variables with
OpenMS's Size type: change the declaration of bytes_read in the ZIP branch (the
variable read from ZipIfstream in the block using ZipIfstream zip_file and char
buffer[1024]) to Size, and update the analogous bytes_read declarations in the
bzip2 and gzip branches for consistency; ensure the OpenMS/CONCEPT/Types.h
header is included if not already so Size is available.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 85a7fae7-d04a-4bae-b2de-e5343e7214a3

📥 Commits

Reviewing files that changed from the base of the PR and between 6301612 and 430e935.

⛔ Files ignored due to path filters (4)
  • src/tests/class_tests/openms/data/Deisotoper_input1.mzML.zip is excluded by !**/*.zip
  • src/tests/class_tests/openms/data/DirEntry.mzML.zip is excluded by !**/*.zip
  • src/tests/class_tests/openms/data/Empty.zip is excluded by !**/*.zip
  • src/tests/class_tests/openms/data/MultiEntry.mzML.zip is excluded by !**/*.zip
📒 Files selected for processing (13)
  • src/openms/include/OpenMS/FORMAT/FileTypes.h
  • src/openms/include/OpenMS/FORMAT/ZipIfstream.h
  • src/openms/include/OpenMS/FORMAT/ZipInputStream.h
  • src/openms/include/OpenMS/FORMAT/sources.cmake
  • src/openms/source/FORMAT/CompressedInputSource.cpp
  • src/openms/source/FORMAT/FileHandler.cpp
  • src/openms/source/FORMAT/FileTypes.cpp
  • src/openms/source/FORMAT/XMLFile.cpp
  • src/openms/source/FORMAT/ZipIfstream.cpp
  • src/openms/source/FORMAT/ZipInputStream.cpp
  • src/openms/source/FORMAT/sources.cmake
  • src/tests/class_tests/openms/executables.cmake
  • src/tests/class_tests/openms/source/ZipIfstream_test.cpp

Extract ZIP archive to temp directory, find the .d directory inside,
and pass it to BrukerTimsFile::load(). Temp directory is cleaned up
automatically when the TempDir goes out of scope.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@timosachsenberg timosachsenberg changed the title Add transparent .zip decompression for XML formats Add transparent .zip decompression for XML formats and Bruker .d Apr 12, 2026
Address CodeRabbit review:
- Add Doxygen blocks for curPos, readBytes, getContentType overrides
- Early-return on n==0 in ZipIfstream::read() to avoid false EOF

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

@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

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

244-248: ⚠️ Potential issue | 🟡 Minor

Remove or restrict ZIP suffix stripping in getTypeByFileName() to input-only paths, since ZIP output is not supported.

getTypeByFileName() strips compression suffixes (.zip, .gz, .bz2) by recursively calling itself on the prefix. However, this method is used by storeExperiment() and other output methods (line 1012). ZIP archives are not in the storeExperiment() switch statement (which defaults to throwing InvalidFileType), so .zip should not be accepted as a suffix for output files—yet the recursive stripping silently converts foo.mzML.zip to MZML type, allowing the file to be written without compression.

Additionally, there is a case-sensitivity mismatch: line 189 checks normalized.hasSuffix(".zip") (lowercase only), while getTypeByFileName() uses tmp.toUpper() then compares to "ZIP". This means .ZIP (uppercase) is handled differently in the read and write paths.

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

In `@src/openms/source/FORMAT/FileHandler.cpp` around lines 244 - 248,
getTypeByFileName() currently strips compression suffixes ("BZ2","GZ","ZIP")
unconditionally and uses uppercase tmp, causing ZIP to be treated differently
across read/write paths and allowing unsupported .zip outputs; update
getTypeByFileName() to stop stripping ".zip" for output paths (either remove
"ZIP" from the stripped-list or add a boolean parameter like
strip_compression_only_for_input and use it where called from input routines),
ensure callers such as storeExperiment() still receive the full filename so .zip
is not converted to MZML for writing, and normalize case handling to be
consistent with normalized.hasSuffix() (use a single case-insensitive check or
lowercase comparisons) so ".ZIP" and ".zip" behave identically.
🤖 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/FileHandler.cpp`:
- Around line 189-190: The runtime checks that test normalized.hasSuffix(".zip")
are case-sensitive and should be adjusted to be case-insensitive to match
getTypeByFileName(); update the checks in FileHandler.cpp (the conditional using
File::exists, File::isDirectory and normalized.hasSuffix(".zip")) to either call
a case-insensitive hasSuffix overload (e.g. hasSuffix(".zip",
/*caseInsensitive*/ true)) or compare a lowercased filename suffix (e.g.
normalized.toLower().hasSuffix(".zip")), and apply the same change to the other
occurrence noted near line 937 so both places accept .ZIP, .Zip, etc.,
consistently with getTypeByFileName().
- Around line 941-949: The code currently only checks the temp directory's first
level with std::filesystem::directory_iterator and can leave load_path
unchanged, so before calling BrukerTimsFile::load() update the logic that finds
the `.d` folder: use std::filesystem::recursive_directory_iterator (or
explicitly descend one extra level) to locate the first directory whose
extension() == ".d", set load_path to that path when found, and otherwise fail
early (throw/log an error) indicating no valid `.d` folder was found so
BrukerTimsFile::load() is not called with an incorrect path; update references
around the directory scan (the loop using std::filesystem::directory_iterator
and the variable load_path) to implement this validation.
- Around line 387-389: The current check in FileHandler.cpp uses only bz[0]=='P'
&& bz[1]=='K', which is too broad; change the detection to verify a full ZIP
signature before constructing ZipIfstream (e.g., check bz[0]=='P' && bz[1]=='K'
&& bz[2]==0x03 && bz[3]==0x04 or accept other valid ZIP signatures like
PK\x01\x02/PK\x05\x06), so only real ZIP files are routed into ZipIfstream and
spurious two-byte matches do not cause decompression errors.

---

Outside diff comments:
In `@src/openms/source/FORMAT/FileHandler.cpp`:
- Around line 244-248: getTypeByFileName() currently strips compression suffixes
("BZ2","GZ","ZIP") unconditionally and uses uppercase tmp, causing ZIP to be
treated differently across read/write paths and allowing unsupported .zip
outputs; update getTypeByFileName() to stop stripping ".zip" for output paths
(either remove "ZIP" from the stripped-list or add a boolean parameter like
strip_compression_only_for_input and use it where called from input routines),
ensure callers such as storeExperiment() still receive the full filename so .zip
is not converted to MZML for writing, and normalize case handling to be
consistent with normalized.hasSuffix() (use a single case-insensitive check or
lowercase comparisons) so ".ZIP" and ".zip" behave identically.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 727805b3-7829-4e0b-827a-5e9e37b4a5fc

📥 Commits

Reviewing files that changed from the base of the PR and between 430e935 and f611411.

📒 Files selected for processing (1)
  • src/openms/source/FORMAT/FileHandler.cpp

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/openms/include/OpenMS/FORMAT/ZipInputStream.h`:
- Around line 20-36: The public API lacks full Doxygen blocks: replace the terse
/// comments for class ZipInputStream and its public methods (constructors
ZipInputStream(const String&), ZipInputStream(const char* const), destructor
~ZipInputStream(), and bool getIsOpen() const) with proper Doxygen `@brief` blocks
followed by a blank line and a short detailed description, add an `@ingroup` tag
to the class docblock, and for each constructor document possible exceptions
(e.g. file-not-found, invalid-zip, IO errors) using `@throws` (or `@exception`) so
callers know what can be thrown; ensure the destructor and getIsOpen() have full
Doxygen descriptions as well.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 35744104-9747-4c41-b161-fcb8c5024005

📥 Commits

Reviewing files that changed from the base of the PR and between f611411 and 61e5fae.

📒 Files selected for processing (2)
  • src/openms/include/OpenMS/FORMAT/ZipInputStream.h
  • src/openms/source/FORMAT/ZipIfstream.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/openms/source/FORMAT/ZipIfstream.cpp

Comment on lines +20 to +36
/**
* @brief Implements the BinInputStream class of the xerces-c library in order to read ZIP compressed XML files.
*/
class OPENMS_DLLAPI ZipInputStream :
public xercesc::BinInputStream
{
public:
/// Constructor
explicit ZipInputStream(const String& file_name);

explicit ZipInputStream(const char* const file_name);

/// Destructor
~ZipInputStream() override;

/// returns true if file is open
bool getIsOpen() const;

@coderabbitai coderabbitai Bot Apr 12, 2026 •

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 | 🟡 Minor

Complete Doxygen coverage for the new public API surface.

The class-level block and method docs are partially complete, but Line 27–Line 36 still use minimal /// comments (no full @brief blocks), and constructor docs do not list possible exceptions. Also add the relevant @ingroup tag to the class documentation block.

As per coding guidelines: "Add Doxygen comments for new public methods and classes", "Document possible exceptions in C++ function/method documentation", "Use @brief plus blank line plus detailed description in Doxygen comments; required @brief tag", and "Use @defgroup and @ingroup tags for grouping related documentation in Doxygen".

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

In `@src/openms/include/OpenMS/FORMAT/ZipInputStream.h` around lines 20 - 36, The
public API lacks full Doxygen blocks: replace the terse /// comments for class
ZipInputStream and its public methods (constructors ZipInputStream(const
String&), ZipInputStream(const char* const), destructor ~ZipInputStream(), and
bool getIsOpen() const) with proper Doxygen `@brief` blocks followed by a blank
line and a short detailed description, add an `@ingroup` tag to the class
docblock, and for each constructor document possible exceptions (e.g.
file-not-found, invalid-zip, IO errors) using `@throws` (or `@exception`) so callers
know what can be thrown; ensure the destructor and getIsOpen() have full Doxygen
descriptions as well.

Resolved in commits 61e5fae and 2b9c95b.

timosachsenberg and others added 3 commits April 13, 2026 07:05
- Use full 4-byte ZIP signature (PK\x03\x04) instead of just PK
- Use recursive_directory_iterator for .d.zip extraction, error if no .d found
- Make .zip suffix checks case-insensitive

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The ZIP type added READABLE property but the test expectation was not
updated to reflect the new count.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@timosachsenberg
timosachsenberg merged commit c39955c into develop Apr 13, 2026
41 checks passed
@timosachsenberg
timosachsenberg deleted the feature/zip-compressed-file-support branch April 13, 2026 11:16
github-actions Bot pushed a commit that referenced this pull request Apr 14, 2026
Add two missing changelog entries for commits after the last sync (#9140):
- #9139: Transparent .zip decompression for XML formats and Bruker .d
- #9143: Fix segfault in OpenSwathWorkflow with use_consensus=false

Co-authored-by: Copilot <[email protected]>
timosachsenberg pushed a commit that referenced this pull request Apr 14, 2026
Add two missing changelog entries for commits after the last sync (#9140):
- #9139: Transparent .zip decompression for XML formats and Bruker .d
- #9143: Fix segfault in OpenSwathWorkflow with use_consensus=false

Co-authored-by: GitHub Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
@coderabbitai coderabbitai Bot mentioned this pull request Jun 6, 2026
5 tasks done
@timosachsenberg timosachsenberg mentioned this pull request Jun 8, 2026
timosachsenberg added a commit that referenced this pull request Sep 26, 2026
…ller (#10273)

* [FIX] BrukerTimsFile: read zipped .d directories (.d.zip) in every caller

'FileConverter -in DDA_HeLa_50ng_5_6min.d.zip -out x.mzML' failed with
"File not readable (... .d.zip (opentims: Not a directory))", and so did
pyOpenMS BrukerTimsFile().load() on the archive, although the CHANGELOG
announces transparent .zip input for Bruker .d directories (#9139).

#9139 unpacked a .d.zip only inside FileHandler::loadExperiment(). Its
getType() reports the archive as BRUKER_TDF, and every caller that needs
BrukerTimsFile::Config calls BrukerTimsFile directly instead of going
through FileHandler: FileConverter, PeakPickerIM, CometAdapter,
ProteomicsLFQ, SwathFile (OpenSwathWorkflow) and the pyOpenMS binding.
They passed the archive path straight to opentims, which only opens
directories. #9139 verified .d.zip loading through FileHandler only, and
no test loads a .d.zip at all (the "[DATA] .d.zip load" item of the
3.6.0 testing plan #9460 was never done).

The unpacking moves from FileHandler into BrukerTimsFile, the component
that hands the path to opentims: load(), transform(), readDIAMetadata()
and loadDIAStreaming() unpack a .d.zip into a TempDir that lives for the
call and read the (possibly nested) .d directory inside, with the same
lookup and "ZIP archive does not contain a .d directory" error as
before. The source file metadata keeps naming the archive the user gave,
not the temporary directory. FileHandler now delegates, so there is one
implementation instead of a second one in each tool.

Test: an SDK- and data-free BrukerTimsFile_test section zips a directory
without a .d (ParseError) and one with a nested run.d (which must reach
opentims). Both checks fail before this change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01YC1T2K9HQEUk2kQMZqC8h7

* [FIX] BrukerTimsFile, ZipArchiveFile: unpack a DIA .d.zip once, bound extraction

This addresses the two concerns CodeRabbit's security review raised on
this PR.

DIA. SwathFile (OpenSwathWorkflow) sizes its consumer from
readDIAMetadata() and then streams the spectra with loadDIAStreaming(),
on one BrukerTimsFile. Each call unpacked the .d.zip into its own
temporary directory. The archive was unpacked twice, and the metadata
and the spectra could come from different extractions.
readDIAMetadata() now keeps its extraction, and the next call on the
same object reads it if that call asks for the same archive. Any call
other than readDIAMetadata() removes the kept files, as does destroying
the object.

Extraction. ZipArchiveFile::unzipDirectory() had no limit on what an
archive can write, and this PR makes it reachable from every
BrukerTimsFile caller, not only FileHandler. Before writing anything, it
now rejects an archive with more than 100000 entries, or one whose
declared uncompressed size exceeds the free space of the temporary
directory. It also stops an entry that inflates beyond its declared
size. With libzip 1.11.4, the version vcpkg builds, the old code wrote a
256 MiB entry declared as 1000 bytes in full and reported success.

Tests. ZipArchiveFile_test extracts a stored entry whose headers
declare 1000 of its 1 MiB. BrukerTimsFile_test deletes the archive
after readDIAMetadata(). It then expects loadDIAStreaming() to read the
kept files, and load() after that to find nothing kept. Both sections
fail without this change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01YC1T2K9HQEUk2kQMZqC8h7

* ZipArchiveFile: reject an archive when the free space is unknown

If std::filesystem::space() failed, unzipDirectory() skipped the
free-space check and extracted anyway, so the stated limit did not hold
on that path (found by CodeRabbit). It now rejects the archive with the
error the query returned. The query asks about the directory that
unzipDirectory() has just created, so this should happen only in unusual
setups.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01YC1T2K9HQEUk2kQMZqC8h7

* [FIX] BrukerTimsFile: read the .d that holds analysis.tdf, skip __MACOSX

Unpacking a .d.zip took the first .d directory that
recursive_directory_iterator returned. That order is unspecified, and an
archive made with macOS's "Compress" also holds __MACOSX/<name>.d with
AppleDouble files only. On ext4, run.d.zip, A.d.zip and X1.d.zip in that
layout handed __MACOSX/<name>.d to opentims; sample.d.zip, B.d.zip and
run2.d.zip did not.

Now the shallowest .d that holds analysis.tdf or analysis.tdf_bin is
read, as FileHandler::getType() requires of a directory, and the first by
name among equals. __MACOSX is skipped. An archive without such a .d is
reported as a ParseError before opentims sees it.

Also from the review:
- ZipArchiveFile::unzipDirectory compared paths as string prefixes, so
  '../parquet_unpacked_x/f' was extracted next to the target directory.
  It now compares path elements (lexically_relative). Such a file stayed
  inside the per-call TempDir.
- FileTypes.cpp still said that FileHandler unpacks .d.zip.

Tests: a BrukerTimsFile section with a macOS-style archive and one
without analysis.tdf, and a ZipArchiveFile section for the sibling
entry. Both fail on the previous head and pass now. The two existing
.d.zip sections put a placeholder analysis.tdf into run.d, so they
still reach opentims.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01YC1T2K9HQEUk2kQMZqC8h7

* ZipArchiveFile: let an archive use at most 90% of the free space

CodeRabbit's security review of #10273 kept one concern. The free-space
check let an archive declare, and write, all of the free space in the
temporary directory, so a crafted archive could fill a filesystem that
other work shares. unzipDirectory now rejects an archive whose declared
size is more than 90% of the free space. That also leaves room for the
output, which usually goes to the same filesystem.

Checked with ZIP64 archives that declare 95% and 80% of the free space
in /tmp. The first is now rejected (d01ebca extracted it), and the
second still extracts. The crafted bomb, 1 PiB and 100,001-entry
archives are rejected as before. The 361 MB DDA_HeLa_50ng_5_6min.d.zip
converts to the same mzML apart from the output name and the index
offsets it shifts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01YC1T2K9HQEUk2kQMZqC8h7

---------

Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant