Skip to content

Support Zstandard (zstd) binary data array compression in mzML - #10287

Merged
timosachsenberg merged 9 commits into
developfrom
copilot/add-zstandard-compression
Sep 29, 2026
Merged

timosachsenberg merged 9 commits into
developfrom
copilot/add-zstandard-compression

Conversation

Copilot AI commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Adds reading and writing of zstd-compressed mzML binary data arrays: the PSI-MS terms MS:1003780–MS:1003785 from the dia-ims-1.0 spec. The implementation follows the spec and the mzd.cpp reference.

Codec: new ZstdCompression class (FORMAT/)

  • Provides plain zstd compress/uncompress plus the two byte transforms: byte shuffle and dictionary encoding.
  • Decompression streams its output. It accepts frames with no recorded content size and multiple concatenated frames. The initial buffer is the frame header's content size, capped at the size the caller expects: arrayLength × element size, passed down from MzMLHandlerHelper, or an upper bound for dictionary payloads. When no size is known, the cap is 16× the input size. 256 MB is the absolute limit. So a malformed header cannot force a huge allocation, and the buffer grows as needed. Truncated or invalid input throws Exception::ConversionError.
  • Dictionary layout follows the spec: a u64 offset, a u64 n_values, the byte-shuffled sorted unique values, then the byte-shuffled indices.
    • The writer uses the spec's index width: u8 for fewer than 256 unique values, then u16, u32, u64. ProteoWizard and mzd.cpp's writer do the same.
    • Other implementations differ at the boundaries. mzd.cpp's reader expects u16 at 255 values. The Rust library mzdata (mobiusklein/mzdata) uses u8 for up to 256 values and u16 for up to 65536. The reader therefore takes the index width from the index region size divided by arrayLength, if that is 1, 2, 4 or 8 bytes and next to the spec's width. Otherwise it uses the spec's width. It accepts all three conventions.
  • Compressed output is always a single frame with its content size recorded, which is what the reference readers expect.

mzML I/O (MzMLHandlerHelper, MzMLHandler)

  • Reading: all six terms are supported: plain, byte-shuffled and dictionary zstd, and Numpress LINEAR/PIC/SLOF followed by zstd. This covers float32/64, int32/64 and null-terminated string arrays.
  • Writing: chosen by the new PeakFileOptions::setZstdCompression(), which takes precedence over zlib:
    • numeric arrays: byte-shuffled zstd (MS:1003781)
    • string arrays: plain zstd (MS:1003780)
    • Numpress-encoded arrays: Numpress + zstd (MS:1003783–85)
  • The writer's encode calls now go through new MzMLHandlerHelper::encode{Numeric,String,Numpress}Array helpers, so the zlib/zstd choice lives in one place.
  • Data is converted to little-endian before the byte transforms, reusing Base64.h's invertEndianess.

Options, tools and bindings

  • New PeakFileOptions::setZstdCompression() / getZstdCompression(), default off.
  • New advanced tool options: FileConverter -zstd_compression and FileFilter -peak_options:zstd_compression.
  • pyOpenMS bindings for the new setter and getter.
opts = pyopenms.PeakFileOptions()
opts.setZstdCompression(True)
f = pyopenms.MzMLFile(); f.setOptions(opts); f.store("out.mzML", exp)

Build and dependencies

  • zstd is now a required dependency. CMake uses find_package(zstd CONFIG) with whichever of zstd::libzstd, _shared or _static exists, and falls back to a plain header/library search. The result is OPENMS_ZSTD_TARGET.
  • vcpkg (the CMake presets, CI, and the Linux and Windows wheels since [CI] Build the Windows pyOpenMS wheel with vcpkg instead of contrib #10331 and [CI] Build the Linux pyOpenMS wheels with vcpkg in the stock manylinux images #10333): zstd is listed as a direct dependency in vcpkg.json rather than relying on Arrow's transitive copy. The CI vcpkg cache key hashes that file, so the first CI run rebuilds the cache.
  • opentims (FetchContent build) links the same ${OPENMS_ZSTD_TARGET}. Its own find_package(zstd) is gone, and so is the fallback to its bundled zstddeclib.c, which could have put a second zstd decoder into libOpenMS. The enable_language(C) that only served that fallback is dropped too.
  • macOS wheel: installs zstd with Homebrew.
  • System packages: the Dockerfile now installs libzstd-dev / libzstd1.
  • The wheel jobs need no zstd steps of their own. The earlier contrib-based ones were dropped when develop was merged in (f2919f5): libzstd/libzstd-devel in the manylinux jobs and a zstd source build into contrib/ on Windows.

Tests

  • ZstdCompression_test:
    • fixed vectors generated independently with Python numpy + zstandard from the spec
    • hand-built dictionary buffers at the index-width boundaries: 256 values with u8 indices (the Rust library mzdata, mobiusklein/mzdata) and 255 values with u16 indices (mzd.cpp reader), both decoded via the array length, plus the spec's widths with and without it
    • the expected decoded size affects only the initial allocation, and truncated input still throws
  • New MzMLFile_zstd.mzML, generated externally, with arrays in modes 1003780/81/82 across float, int, string and empty arrays, plus a chromatogram.
  • New MzMLFile_test checks:
    • the zstd round trip is lossless
    • zstd takes precedence over zlib
    • Numpress LINEAR, SLOF and PIC (MS:1003783/84/85) followed by zstd decode to the same values as Numpress followed by zlib
  • New cases in PeakFileOptions_test and a pyOpenMS test.

Review notes

  • The $Maintainer:$ / $Authors:$ fields in the new files are placeholders.
  • Not every external tool can read zstd-compressed mzML yet, so writing it stays opt-in.

Copilot AI changed the title [WIP] Add support for Zstandard binary data array compression in mzML Support Zstandard (zstd) binary data array compression in mzML Sep 26, 2026
Copilot AI requested a review from jpfeuffer September 26, 2026 14:43
@jpfeuffer

Copy link
Copy Markdown
Contributor

@copilot building zstd from source in CI fails on Windows. Fix it

Copilot AI commented Sep 27, 2026

Copy link
Copy Markdown
Contributor Author

@copilot building zstd from source in CI fails on Windows. Fix it

Fixed in b0a0972, not yet run on Windows CI. The zstd 1.5.7 tarball contains symlinks under tests/cli-tests/bin/, which Windows tar in Git Bash can't create, so extraction failed. The step now extracts only lib/ and build/cmake/, which is all the library build needs; I checked that a build and install from just those two directories works. It also checks the tarball's SHA-256 now.

@jpfeuffer

Copy link
Copy Markdown
Contributor

@copilot resolve the merge conflicts in this pull request

…ard-compression

# Conflicts:
#	CHANGELOG

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

Copilot AI commented Sep 27, 2026

Copy link
Copy Markdown
Contributor Author

@copilot resolve the merge conflicts in this pull request

Merged develop in 4dfe4d1. The only conflict was in CHANGELOG, where both branches added a line under build requirements; I kept both. The other files merged cleanly, and nothing from develop overlaps with the zstd changes. I haven't rebuilt locally; CI will be the first build of the merged branch.

@jpfeuffer

Copy link
Copy Markdown
Contributor

@copilot Of course.. still doesn't work on windows..

Copilot AI commented Sep 27, 2026

Copy link
Copy Markdown
Contributor Author

@copilot Of course.. still doesn't work on windows..

Sorry, my previous fix extracted too little. On Windows the zstd CMake build also needs build/VS2010/libzstd-dll/libzstd-dll.rc for the DLL's resource file, so configuring failed. In 1e36da6 the step extracts the whole tarball except tests/, which holds its only symlinks. I checked on Linux that the build and install work from that extraction. The Windows-only .rc step can't be tested here, so the Windows CI run is still the real check.

@jpfeuffer
jpfeuffer marked this pull request as ready for review September 28, 2026 16:24

@timosachsenberg timosachsenberg 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.

The zstd codec itself looks solid:

  • Byte-shuffle and dictionary output are byte-identical to mzd.cpp's writer at 1–1000 and 65534–65537 distinct values.
  • Fuzzing the decoders under ASan/UBSan (truncated, concatenated and skippable frames, unknown sizes, random dictionary buffers) found no crashes and no bad input that was silently accepted.
  • Every writer path pairs its compression term with the matching encoding, and the zlib paths are unchanged.
  • MS:1003780–85 are in the shipped psi-ms.obo under MS:1000572, with the same names the writer uses.
  • ProteoWizard returns early on an empty <binary/>, so empty zstd arrays written here read fine there.

Two things I'd settle before merging (details inline):

  1. Build: zstd becomes a required dependency, but contrib doesn't provide it. Contrib-based builds stop at configure: the documented Windows build, probably the devcontainer, and Jenkins packaging if it uses contrib.
  2. Interop: the dictionary decoder can't read mzdata-written arrays with exactly 256 or 65536 distinct values, and a single such array fails the whole file.

Design question: Arrow is already required, and OpenMS's Parquet writers default to zstd, so they already assume Arrow has it. Using arrow::util::Codec (Compression::ZSTD, with MakeDecompressor() for streaming) for compress/decompress would avoid the new direct dependency and the CI and packaging changes. The cost is that mzML zstd support would depend on how Arrow was built. The byte-shuffle and dictionary transforms would stay as they are.

Also inline: a 256 MB allocation driven by an untrusted frame header, a zstd context created for every array (about 16 µs fixed cost each), opentims' separate zstd lookup, and a few nits and test gaps.


Generated by Claude Code

Comment thread cmake/cmake_findExternalLibs.cmake Resolved
capacity = static_cast<size_t>(std::min<unsigned long long>(std::max<unsigned long long>(content_size, 1), 1ull << 28));
}

std::unique_ptr<ZSTD_DCtx, DCtxDeleter> dctx(ZSTD_createDCtx());

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.

Optional (performance): every array decode creates and frees a zstd decompression context, then copies the data through three zero-filled buffers: the decompressed string, the unshuffled string, and the std::vector in decodeZstdNumeric.

I ran a quick micro-benchmark of this path (byte-shuffled doubles, level 3, zstd 1.5.5). The alternative reuses a thread_local context, decompresses in one shot into an exact-size buffer, and unshuffles straight into the vector:

Doubles per array As in this PR Reused context + exact buffer
200 17 µs 1.1 µs
2000 25 µs 7.7 µs
20000 114 µs 85 µs

So small MS2 spectra pay about 16 µs of fixed cost per array. OpenMS and ProteoWizard always record the content size, so a fast path using ZSTD_decompressDCtx into an exact-size buffer would cover almost all files, with the streaming loop kept as the fallback. On the write side, ZSTD_compress likewise builds a new compression context for every array.


Generated by Claude Code

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.

This is optional, so this PR leaves it as is. A reused thread_local context with an exact-size fast path would make a good follow-up.


Generated by Claude Code

Comment thread cmake/cmake_findExternalLibs.cmake Resolved
Base64::decodeSingleString(bindata.base64, compressed, false);
std::string decoded;
ZstdCompression::decode(compressed.data(), compressed.size(), bindata.zstd_transform, 1, decoded);
// split at null bytes (skipping empty strings, identical to Base64::decodeStrings)

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.

Nit: this re-implements the null-byte splitting of Base64::decodeStrings, and the zstd branch of encodeStringArray re-implements the joining in Base64::encodeStrings. If one side changes, for example to keep empty strings, zlib and zstd string arrays would decode differently without any error. One shared split/join helper that works on an already-decoded buffer would keep them in sync.


Generated by Claude Code

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.

This is an optional nit, so it stays as is here; a shared split/join helper is a possible follow-up.


Generated by Claude Code

}
}

void MzMLHandlerHelper::encodeNumericArray(std::vector<Int32>& in, const PeakFileOptions& opt, std::string& out)

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.

Nit: the four encodeNumericArray overloads are identical apart from calling Base64::encode or encodeIntegers, and this Int32 one has no caller, because the writers widen integer arrays to Int64. A single template with if constexpr (std::is_integral_v<T>) would do, and the unused overload could be dropped from the installed header.


Generated by Claude Code

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.

This is an optional nit, so it stays as is. Merging the overloads and dropping the unused Int32 one changes the installed header, which is a possible follow-up.


Generated by Claude Code

}
END_SECTION

START_SECTION([EXTRA] load and store zstd compressed binary data arrays)

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.

Test gaps worth closing:

  • MS:1003784 (PIC + zstd) is never exercised.
  • Numpress + zstd (MS:1003783/85) is only written and read by OpenMS itself, so a misreading of the format that is the same on both sides would still pass. A vector generated by another implementation (mzd.cpp, mzdata or msconvert) would pin it down.
  • There is no dictionary vector from another implementation at the index-width boundaries (see the comment on ZstdCompression.cpp).
  • MzMLFile_zstd.mzML could also be read through OnDiscMSExperiment / MzMLSpectrumDecoder. That path uses the same helper but isn't covered by a test.

Generated by Claude Code

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.

39f5052 adds a PIC + zstd (MS:1003784) round-trip to MzMLFile_test and hand-built dictionary buffers at the 255/256 boundaries. The remaining gaps are left as possible follow-ups: vectors from another implementation (mzd.cpp, mzdata or msconvert) and the OnDiscMSExperiment/MzMLSpectrumDecoder path. Leaving this thread open for those.


Generated by Claude Code

Jenkins is no longer used. Remove the old packaging instructions and
OS/compiler matrix to avoid suggesting that this infrastructure is active.
@jpfeuffer

Copy link
Copy Markdown
Contributor

Hmm yeah I'm not sure if we should depend on arrow or just look for a standalone zstd. I think I tend towards finding standalone again. Just in case we ever move away from arrow or they stop shipping zstd. Also the code would be more portable then.
@timosachsenberg what do you think? We would need a contrib addition until we are fully vcpkg

@cbielow

cbielow commented Sep 29, 2026

Copy link
Copy Markdown
Contributor

I thought we are 100% vcpkg already on all platforms?

@timosachsenberg

Copy link
Copy Markdown
Contributor

No working on it right now (pyopenms is missing on some platforms)

This comment was marked as resolved.

Resolve the conflict in .github/workflows/pyopenms-wheels-cibuildwheel.yml
in favour of develop. Since #10331 and #10333 the Linux and Windows
wheels build OpenMS with vcpkg instead of the contrib, and vcpkg builds
zstd as a dependency of Arrow. The libzstd and libzstd-devel packages
in the contrib manylinux jobs and the Windows zstd source build into
contrib/ are therefore no longer needed. The macOS job already installs
zstd with Homebrew.

tools/jenkins/ is already gone on develop (#10325).

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

This comment was marked as resolved.

…ndex width, decode allocation)

- vcpkg.json: list zstd as a direct dependency instead of relying on
  Arrow's transitive copy.
- opentims (FetchContent build): link ${OPENMS_ZSTD_TARGET} instead of a
  separate find_package(zstd) with a fallback to the bundled
  zstddeclib.c, and drop the enable_language(C) that only served that
  fallback.
- Dictionary-encoded zstd (MS:1003782): take the index width from the
  index region size divided by the array length (arrayLength, threaded
  through from MzMLHandlerHelper) when that yields 1, 2, 4 or 8 bytes
  adjacent to the specification's width. This reads mzdata's u8 indices
  for 256 values and u16 indices for 255 values (mzd.cpp reader).
- uncompressData(): cap the initial output allocation at the expected
  decoded size (or 16x the input size if unknown) rather than trusting
  the frame header's content size alone; the buffer still grows as
  needed.
- Tests: hand-built dictionary buffers at the 255/256 boundaries,
  expected-size handling, and a numpress PIC + zstd (MS:1003784)
  round-trip in MzMLFile_test.

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

Avoids confusion with the deprecated mzData XML format. Comment-only change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017gpru7cpwhZCABTWXpD1Vd
@timosachsenberg
timosachsenberg merged commit 55f7bdb into develop Sep 29, 2026
32 checks passed
@timosachsenberg
timosachsenberg deleted the copilot/add-zstandard-compression branch September 29, 2026 20:01
timosachsenberg added a commit that referenced this pull request Sep 30, 2026
…10348)

* [DOC] Document zstd compression of the mzML peak data

The pyOpenMS mzML page gains a Zstandard section: enabling it with
PeakFileOptions.setZstdCompression, the cvParam it writes, reading such a
file back, and how it combines with zlib and numpress. The OpenMS
file-formats page describes FileConverter -zstd_compression and FileFilter
-peak_options:zstd_compression. Both follow #10287.

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

* [DOC] CHANGELOG: known issues of the bundled engines and OpenSSL

Comet embeds zlib 1.2.11 and expat 2.2.9 and MaRaCluster zlib 1.2.3; both
engines ship with 3.6.0 and will be rebuilt afterwards. The packages and
wheels carry OpenSSL 3.6.4, whose CVE-2026-84782 concerns only DTLS, which
OpenMS does not use.

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

* [DOC] Known issues: OpenSSL 3.6.4 is in every artifact; name the Low advisories

The Windows installer and wheel link OpenSSL 3.6.4 statically, so the note
covers all installers and wheels, not only Linux and macOS. Besides the High
CVE-2026-84782 (DTLS only), twelve Low advisories published with 3.6.5 affect
3.6.4; CVE-2026-35189 is the one that reaches OpenMS, through HTTPS downloads.

The pyOpenMS zstd section limits byte shuffling to arrays without numpress
encoding, which use their own numpress-plus-zstd terms.

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

* [DOC] CHANGELOG: date the 3.6.0 heading; Sage's SQLite as a known issue

The heading says "Released September 2026" instead of "under development".
Sage 0.14.6 embeds SQLite 3.41.2 (with FTS5); like the Comet and
MaRaCluster copies, it ships with 3.6.0 and will be rebuilt afterwards.

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

* Update CHANGELOG for OpenMS 3.6.0 release

Added details about the OpenMS 3.6.0 release, including new features and improvements.

---------

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.

Add support for Zstandard binary data array compression in mzML

5 participants