Repository navigation
Use libdeflate for gzip/zlib/deflate compression and decompression - #108074
Conversation
libdeflate is faster than the zlib-ng that ClickHouse used for the DEFLATE
family. This adds it as a contrib (the ClickHouse/libdeflate fork) and routes
every gzip/zlib/deflate code path through it:
- compression: HTTP responses, file/url/s3 .gz output, Parquet GZIP
- decompression: file/url/s3/HTTP streaming, Parquet GZIP, LLVM coverage maps
libdeflate's public API is one-shot only. The fork adds two small streaming
entry points used here:
- libdeflate_deflate_compress_stream_chunk(): emits non-final byte-aligned
blocks so chunks concatenate into a single valid gzip/zlib member, backing
LibdeflateDeflatingWriteBuffer (a single-member streaming compressor).
- libdeflate_deflate_decompress_stream(): suspends at DEFLATE block boundaries
(rolling back on input/output exhaustion), backing LibdeflateInflatingReadBuffer
(a streaming decompressor with a caller-managed 32 KiB window).
Both buffers are wired into CompressionMethod.cpp, so all CompressionMethod::Gzip
and ::Zlib reads and writes use libdeflate, with zlib kept only as a build-time
fallback (USE_LIBDEFLATE) and for compression levels outside libdeflate's range.
Performance, measured on the same build/flags: compression ~1.15x faster with a
better ratio, decompression ~1.4-1.5x faster (codec level); end-to-end gzip file
reads ~1.2x faster.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [0d2706a] Summary: ✅
AI ReviewSummaryThis PR replaces ClickHouse's gzip/zlib/deflate wrappers with libdeflate-backed implementations for the Missing context / blind spots
Final Verdict
|
fillInput() copied the entire available nested buffer into in_buf, so reading a memory-mapped .gz pulled the whole compressed stream into a second heap buffer (e.g. +287 MB peak RSS on a 299 MB compressed / 2.77 GB uncompressed file). Cap each refill to INPUT_CHUNK (1 MiB); the rest stays in the nested buffer until needed. Peak RSS now matches the previous zlib path. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Points the submodule at the fork commit that gives libdeflate_deflate_decompress_stream() the same runtime BMI2 dispatch the one-shot decompressor has, so streaming gzip/zlib decompression uses the BMI2 path on capable x86 CPUs. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`Build (arm_tidy)` failed because `LibdeflateDeflatingWriteBuffer::method` was left uninitialized in the constructor's member-init list (`cppcoreguidelines-pro-type-member-init`); give it a default value of `CompressionMethod::None`. `Style check` (`catch_all`) failed because the libdeflate branch in `LLVMCoverageMapping` swallows decompression failures with a bare `catch (...)`. Annotate it with an `Ok` comment: skipping a record that fails to decompress mirrors the existing zlib path right below it. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Address review feedback on the libdeflate inflating read buffer. Header validation parity with `ZlibInflatingReadBuffer`: previously the wrapper parser accepted malformed gzip/zlib streams that zlib rejected. Now reject reserved gzip `FLG` bits, verify the gzip `FHCRC` header checksum when present (CRC-32 accumulated incrementally as header bytes are consumed, since `fillInput` may discard already-read bytes when it compacts), and reject a zlib `CINFO` above 7 (window larger than 32 KiB). Bounded memory: `libdeflate_deflate_decompress_stream` only suspends at DEFLATE block boundaries, so a single huge block forced the output buffer to grow until the whole block fit — input-controlled memory growth that regressed the bounded zlib streaming behavior and let a crafted decompression bomb drive unbounded allocation. Cap the buffer at a fixed 256 MiB bound and fail closed past it; no real-world encoder emits a single block anywhere near that large. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Address review feedback and remaining clang-tidy errors in the tests. Independent decoder/encoder: the cross-compatibility tests used `wrapReadBufferWithCompressionMethod` / `wrapWriteBufferWithCompressionMethod`, which dispatch back to libdeflate when `USE_LIBDEFLATE` is on, so they round-tripped through the new implementation instead of checking against zlib. Use `ZlibDeflatingWriteBuffer` / `ZlibInflatingReadBuffer` directly so the format-interchange checks really exercise an independent codec. Add focused header-validation tests (reserved gzip flags, oversized zlib `CINFO`, wrong gzip header CRC16). Fix `Build (arm_tidy)`: silence `cert-msc32-c`/`cert-msc51-cpp` on the intentionally deterministic test-data seeds, and use `empty()` instead of `size()` for the emptiness check (`readability-container-size-empty`). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
After merging master, `04402` is now taken by `04402_kql_array_sort_removed`. Renumber the Parquet libdeflate gzip round-trip test to the next free number, `04408`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: This PR swaps the gzip/zlib compression and decompression path over to libdeflate; it does not touch the columnar query-execution hot path, which reads data compressed with native LZ4/ZSTD. Accordingly the deltas on clickbench Q4 (-15.8%), Q15 (-20.3%) and Q30 (-14.6%) cannot plausibly be caused by this change. Q4 and Q15 already sit within master's normal variance band and were correctly left as no-change; Q30's apparent improvement was downgraded to not-sure because the code cannot speed up that query and it shows recent master movement, so treat it as run-to-run variance. clickbenchFlagged queries (1 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
The `crc32`/`adler32`/`decompress`/`stream-decompress` dispatchers cache the runtime-resolved best implementation in a function pointer on first use. That pointer was `volatile`, which is not atomic, so the benign first-call race (every thread resolves the same pointer, a pure function of the CPU) was undefined behavior. ThreadSanitizer flagged it as a data race in `libdeflate_crc32`, producing the TSan "data race" and "Server died" failures and an intermittent `04408_parquet_gzip_libdeflate` result mismatch under TSan. Access the pointers with relaxed atomics (`__atomic_load_n`/`__atomic_store_n`) instead. The generated code is unchanged on real hardware, but the access is now well-defined and TSan-clean. Relaxed ordering is sufficient because no other memory is published through the pointer. Fork commit: ClickHouse/libdeflate@cb6b5c96c7d5 Related: ClickHouse/libdeflate#4 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…errors with the file name `LibdeflateInflatingReadBuffer` returned the final DEFLATE block's output before verifying the gzip/zlib trailer: it set `state = Trailer` and handed the bytes back immediately, so a caller that reads an exact byte count with `readStrict` and never calls `eof` never ran `parseTrailer`, silently accepting CRC32/Adler32/ISIZE mismatches. `ZlibInflatingReadBuffer` has already validated the trailer by the time it returns the final bytes. Restructure the body loop so output produced at a non-final block boundary is held back until either the output buffer fills at a provably-incomplete boundary (more output must follow) or the final block is decoded and its trailer verified by `finishMember`. The now-dead `State::Trailer` is removed. Also wrap the decompression loop (`decompressImpl`) in `nextImpl` with a function-try-block that appends "While reading from: <file>" to failures, matching the other `*InflatingReadBuffer` codecs, so a corrupted `.gz`/`url`/`s3` source reports its file name. This fixes `02724_decompress_filename_exception`. A new gtest `CorruptTrailerRejectedOnExactRead` reads exactly the uncompressed size with `readStrict` and asserts that a flipped trailer byte is rejected. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The merge of `master` introduced several tests sharing the `04403`/`04408` number prefixes. Renumber the two libdeflate tests to the next free numbers: `04403_libdeflate_gzip_external` -> `04489_libdeflate_gzip_external` and `04408_parquet_gzip_libdeflate` -> `04490_parquet_gzip_libdeflate`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Addressed the CI failures and the AI-review blockers (pushed Blocker 1 — trailer validation ( TSan data race / "Server died" /
Blocker 2 — 256 MiB output cap. Kept as a deliberate fail-close decompression-bomb guard, now documented in-code; libdeflate's streaming decoder suspends only at block boundaries, so a whole block must be buffered, and no standard encoder emits a single DEFLATE block remotely this large (every real Also merged current The remaining red tests on the previous run ( |
The previous bump (cb6b5c9) made the per-codec dispatch function pointers
(`crc32_impl`, `adler32_impl`, ...) atomic, but each dispatcher still calls
`get_x86_cpu_features` / `get_arm_cpu_features`, which lazily initialize the
global `libdeflate_x86_cpu_features` / `libdeflate_arm_cpu_features` bitmask on
the first call. That global was only `volatile`, so a plain load racing with
the store in `libdeflate_init_*_cpu_features` is still undefined behavior and
was flagged by ThreadSanitizer:
WARNING: ThreadSanitizer: data race
Write ... libdeflate_init_x86_cpu_features cpu_features.c:210
Read ... get_x86_cpu_features cpu_features.h:62
Location is global 'libdeflate_x86_cpu_features'
It reproduced as a "Server died" failure under TSan when two HTTP connections
first compressed a gzip error response concurrently (e.g.
`test_profile_max_sessions_for_user` on the amd_tsan integration shard).
The global is now accessed with relaxed `__atomic_load_n` / `__atomic_store_n`,
matching the dispatch-pointer fix. Fork commit:
ClickHouse/libdeflate@ec0718b
Related: ClickHouse/libdeflate#5
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`04230_iceberg_optimize_metadata_not_initialized_104711` and `04240_iceberg_supports_parallel_insert_mv_104891` corrupt the on-disk iceberg `deflate` metadata by writing it with an out-of-range `output_format_compression_level`, so the INSERT fails with `INCORRECT_DATA`. They used level 11, which exceeds zlib's maximum of 9. libdeflate accepts levels 1..12, so level 11 now succeeds and the INSERT no longer fails, dropping the "INSERT failed as expected" line. Use level 13, which exceeds the maximum supported deflate level for both zlib (9) and libdeflate (12), so the metadata write still fails and the tests reproduce the corrupted-metadata state as intended. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…sage Reading non-gzip data with `compression_method = 'gzip'` now goes through `LibdeflateInflatingReadBuffer`, which reports `Not a gzip stream` instead of zlib-ng's `inflate failed`. Accept either message so the test passes with both the libdeflate build and the zlib-ng fallback build. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The test was renumbered from 04403 to 04489, but the INTO OUTFILE temp file name still used the old `04403_out_` prefix. Update it to `04489_out_` to match. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The test restarts all three Keeper containers, then waits for them to come back. stop_zookeeper_nodes() stops them serially, but start_zookeeper_nodes() went through process_integration_nodes(), which ran one `docker compose start <node>` process per node concurrently (ThreadPoolExecutor) against the same compose project. Concurrent `docker compose` invocations on one project race on the project's shared state: on a loaded CI runner (integration tests run with -n workers), the start of one node can be silently dropped. On the amd_msan failure the Keeper's graceful stop overran docker's stop timeout and was SIGKILLed (exit 137); the three concurrent `docker compose start` processes then fired within 2 ms of that stop returning, and dockerd received no /start for zoo3 (it did for zoo1/zoo2). zoo3 never came back, so wait_zookeeper_to_start() timed out after 180 s and raised the generic "Cannot wait ZooKeeper container ... iptables-nft" exception. The same latent race affected kill_zookeeper_nodes(). Use a single `docker compose <action> <node1> <node2> ...` invocation instead of N concurrent ones. This is the pattern the framework already uses for startup (a single `docker compose up -d`); compose parallelizes the services internally, so there is no loss of parallelism and no shared-project race. Verified via the CI report for PR ClickHouse#108074 (amd_msan 5/8): dockerd received zoo3's container /json inspects but no /start, while zoo1/zoo2 got /start; docker.log shows "zoo3-1 exited with code 137" with no subsequent restart. Co-Authored-By: Claude Opus 4.8 <[email protected]>
CI finish ledger — be68cb8CI fully finished (Finish Workflow + Mergeable Check pass). This PR fixes flaky test_keeper_session_refuse_stale_server; the sole failure is a chronic trunk AST-fuzzer logical error, not PR-caused.
Session id: cron:our-pr-ci-monitor:20260703-053000 |
|
The main question for now - are these gzip-compressed files with very large chunks normal, or an exception? |
…on cap `LibdeflateInflatingReadBuffer` must buffer one whole DEFLATE block's output because libdeflate's streaming decoder only suspends at block boundaries. The previous code capped that buffer at a hardcoded 256 MiB (`MAX_OUTPUT_BUFFER`) and failed closed past it, which also rejected legitimate — if unusual — single blocks larger than that with a special error, diverging from `ZlibInflatingReadBuffer`. Every mainstream gzip/zlib/deflate encoder bounds a single block to well under a megabyte of uncompressed data (`zlib` flushes roughly every `lit_bufsize` symbols — about 4 MiB at the default `memLevel` 8, at most ~8 MiB at `memLevel` 9; libdeflate's `SOFT_MAX_BLOCK_LENGTH` is 300000 bytes; `zopfli` ~1 MiB; Go's `compress/flate` ~8 MiB; 7-Zip 64 KiB). Only a hand-crafted stream emits a single block that decompresses to hundreds of MiB or more, and on the compressed side the buffered input is 1:1 with the bytes actually transmitted (no amplification). So a very large single block is exceptional, not normal. Remove the artificial ceiling and grow the output buffer geometrically instead of linearly. The buffer is allocated through ClickHouse's tracked allocator, so a crafted single-block decompression bomb runs into the query/server memory limit and throws `MEMORY_LIMIT_EXCEEDED`, exactly like any other oversized allocation, while every real-world stream keeps the buffer at one small block. This also removes the read-contract divergence from the zlib path. The input side is left as is: `in_buf` is a tracked `PODArray` that likewise grows only with the real transmitted bytes and hits the same memory limit under pressure. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Researched this thoroughly — the short answer is that gzip/zlib/deflate streams with a single very large block are exceptional, not normal, so allocating until Why large single blocks don't occur in practiceEvery mainstream encoder bounds a single DEFLATE block to well under a megabyte of uncompressed data, because block flushing is driven by a fixed-size internal symbol/token buffer (or an explicit block-length target) that never scales with input size:
So the output buffer for any real stream stays at one small block (≤ ~8 MiB, usually far less). Even a multi-GB The bomb lives on the output side, and the memory tracker already handles itRFC 1951 puts no length limit on fixed/dynamic-Huffman blocks (only stored blocks are capped at 65535) — a block ends only at the end-of-block symbol 256, which a hand-rolled encoder can defer arbitrarily. A single fixed-Huffman block of The compressed input side has no such amplification: buffering one block's compressed bytes is 1:1 with what is actually transmitted. Since the only oversized-block scenario is adversarial, One tradeoff for your callThe bomb ceiling is now the configured memory limit (default |
… 10-12 in `INTO OUTFILE` docs Levels above 9 for `gzip` and `deflate` require the default build with libdeflate (`ENABLE_LIBDEFLATE=1`); a build without libdeflate still rejects them, as exercised by 04491_outfile_compression_level_range.sh. Match the build-conditional wording already used in `Settings.cpp` (`http_zlib_compression_level`) and `clickhouse_grpc.proto`. Co-Authored-By: Claude Fable 5 <[email protected]>
Address review: if a tracked allocation (`in_buf.resize` / `scratch.resize`) throws while constructing `LibdeflateInflatingReadBuffer` or `LibdeflateDeflatingWriteBuffer` (for example on `MEMORY_LIMIT_EXCEEDED`), the constructor unwinds without running the destructor, so the handle from `libdeflate_alloc_decompressor` / `libdeflate_alloc_compressor` leaks. On user-driven read/write paths (`file`/`url`/`s3`/HTTP), repeated failures under memory pressure accumulate native heap outside the failed query. Hold each native handle in a local `unique_ptr` with the matching `libdeflate_free_*` deleter and transfer ownership to the raw member only after the throwing allocation has succeeded. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 441/499 (88.38%) · Uncovered code |
The test restarts all three Keeper containers, then waits for them to come back. stop_zookeeper_nodes() stops them serially, but start_zookeeper_nodes() went through process_integration_nodes(), which ran one `docker compose start <node>` process per node concurrently (ThreadPoolExecutor) against the same compose project. Concurrent `docker compose` invocations on one project race on the project's shared state: on a loaded CI runner (integration tests run with -n workers), the start of one node can be silently dropped. On the amd_msan failure the Keeper's graceful stop overran docker's stop timeout and was SIGKILLed (exit 137); the three concurrent `docker compose start` processes then fired within 2 ms of that stop returning, and dockerd received no /start for zoo3 (it did for zoo1/zoo2). zoo3 never came back, so wait_zookeeper_to_start() timed out after 180 s and raised the generic "Cannot wait ZooKeeper container ... iptables-nft" exception. The same latent race affected kill_zookeeper_nodes(). Use a single `docker compose <action> <node1> <node2> ...` invocation instead of N concurrent ones. This is the pattern the framework already uses for startup (a single `docker compose up -d`); compose parallelizes the services internally, so there is no loss of parallelism and no shared-project race. Verified via the CI report for PR ClickHouse#108074 (amd_msan 5/8): dockerd received zoo3's container /json inspects but no /start, while zoo1/zoo2 got /start; docker.log shows "zoo3-1 exited with code 137" with no subsequent restart. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…late Use libdeflate for gzip/zlib/deflate compression and decompression
Replaces zlib-ng with libdeflate for the DEFLATE family (gzip / zlib / raw deflate). libdeflate is faster and compresses slightly better; this routes every gzip/zlib/deflate path in ClickHouse through it:
Content-Encoding: gzip),.gzoutput forfile/url/s3/INTO OUTFILE, and the native Parquet GZIP codec..gzfromfile/url/s3and HTTP request bodies, the native Parquet GZIP codec, and LLVM coverage maps.How
libdeflate's public API is one-shot only, so two small streaming entry points were added to a ClickHouse fork of libdeflate (
ClickHouse/libdeflate, vendored ascontrib/libdeflate):libdeflate_deflate_compress_stream_chunk()— emits non-final, byte-aligned DEFLATE blocks so consecutive chunks concatenate into a single valid gzip/zlib member (HTTP-safe, unlike multi-member). BacksLibdeflateDeflatingWriteBuffer.libdeflate_deflate_decompress_stream()— suspends at DEFLATE block boundaries, rolling back to the last boundary on input/output exhaustion; the caller carries a 32 KiB window. BacksLibdeflateInflatingReadBuffer. The one-shot decoder is left byte-for-byte unchanged (a separateDEFLATE_STREAMINGtemplate instantiation).Both buffers are wired into
CompressionMethod.cpp, so allCompressionMethod::Gzip/Zlibreads and writes use libdeflate. zlib-ng remains as a build-time fallback (USE_LIBDEFLATE) and for compression levels outside libdeflate's[1, 12]range. Output is verified interoperable with the systemgzip/gunzipin both directions.Performance
Measured on the same build/flags (aarch64, Graviton4):
The decompressor streaming change was fuzzed with 50,000 randomized round-trips against zlib; unit tests (
gtest_libdeflate*) cover one-shot, streaming compress, and streaming decompress (gzip+zlib, single/multi-member, byte-at-a-time input, malformed input).Related: ClickHouse/libdeflate#1
Related: ClickHouse/libdeflate#2
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Use libdeflate for gzip/zlib/deflate compression and decompression, making it faster (compression ~1.15× with a better ratio, decompression ~1.4–1.5×) for
.gz/HTTP/url/s3data and the Parquet GZIP codec.🤖 Generated with Claude Code
Version info
26.7.1.887(included in26.7and later)