Skip to content

Use libdeflate for gzip/zlib/deflate compression and decompression - #108074

Merged
alexey-milovidov merged 25 commits into
masterfrom
integrate-libdeflate
Jul 14, 2026
Merged

alexey-milovidov merged 25 commits into
masterfrom
integrate-libdeflate

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 21, 2026 •

Copy link
Copy Markdown
Member

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:

  • Compression: HTTP responses (Content-Encoding: gzip), .gz output for file/url/s3/INTO OUTFILE, and the native Parquet GZIP codec.
  • Decompression: streaming reads of .gz from file/url/s3 and 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 as contrib/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). Backs LibdeflateDeflatingWriteBuffer.
  • 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. Backs LibdeflateInflatingReadBuffer. The one-shot decoder is left byte-for-byte unchanged (a separate DEFLATE_STREAMING template instantiation).

Both buffers are wired into CompressionMethod.cpp, so all CompressionMethod::Gzip/Zlib reads 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 system gzip/gunzip in both directions.

Performance

Measured on the same build/flags (aarch64, Graviton4):

  • Compression ~1.15× faster with a better ratio; the single-member streaming path runs at full one-shot speed (no chunking overhead).
  • Decompression ~1.4–1.5× faster at the codec level; end-to-end gzip file reads ~1.2× faster.

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):

  • Performance Improvement

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/s3 data and the Parquet GZIP codec.

🤖 Generated with Claude Code

Version info

  • Merged into: 26.7.1.887 (included in 26.7 and later)

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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0d2706a]

Summary: ✅


AI Review

Summary

This PR replaces ClickHouse's gzip/zlib/deflate wrappers with libdeflate-backed implementations for the CompressionMethod paths, switches Parquet GZIP and LLVM coverage-map zlib decompression to one-shot libdeflate where sizes are known, and vendors the required streaming extensions in contrib/libdeflate. After reviewing the current diff, reading the modified code and tests, and re-checking all prior discussion threads against the current code, I did not find any remaining correctness, compatibility, or safety issues that rise to review-comment level.

Missing context / blind spots
  • ⚠️ I did not run a fresh local build or test shard in this environment; confidence here comes from direct code inspection, the added focused unit/stateless coverage, and the green Praktika report for PR #108074.
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements submodule changed At least one submodule changed in this PR. labels Jun 21, 2026
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]>
Comment thread src/IO/tests/gtest_libdeflate.cpp Resolved
alexey-milovidov and others added 5 commits June 22, 2026 23:12
`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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 queries analysed

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.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 30 not_sure 268 229 -14.6% <0.0001 The PR only swaps gzip/zlib decoding to libdeflate; Q30's columnar aggregation scan can't be sped up by it. With recent master movement on this query, the -14.6% reads as variance.

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
  • StressHouse run: 2e33260e-35e5-40b0-9f8b-54f2fe65f655
  • MIRAI run: 1fb47c83-d4d4-47ea-8248-7adf97a2897e
  • PR check IDs:
    • clickbench_397117_1783927328
    • clickbench_397131_1783927328
    • clickbench_397137_1783927328
    • tpch_adapted_1_official_397143_1783927329
    • tpch_adapted_1_official_397150_1783927328
    • tpch_adapted_1_official_397159_1783927328

alexey-milovidov and others added 4 commits June 29, 2026 22:37
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the CI failures and the AI-review blockers (pushed dc1e0a7):

Blocker 1 — trailer validation (LibdeflateInflatingReadBuffer.cpp). The wrapper no longer exposes a member's final bytes before validating its trailer. The LIBDEFLATE_SUCCESS path now verifies CRC32/Adler32/ISIZE via finishMember → parseTrailer before the bytes reach the caller; output at a non-final block boundary is held back until the buffer fills at a provably-incomplete boundary or the final trailer is verified. Removed the dead State::Trailer. Added gtest CorruptTrailerRejectedOnExactRead (reads exactly the uncompressed size with readStrict, never reaching eof). Thread resolved.

TSan data race / "Server died" / 04408 under TSan. Root cause: libdeflate's lazy CPU-feature dispatch pointers were volatile (not atomic), so the benign first-call resolution race was undefined behavior and TSan flagged it in libdeflate_crc32. Fixed in the fork with relaxed __atomic_load_n/__atomic_store_n and bumped contrib/libdeflate to cb6b5c9 (now on the fork's default branch; fork PR ClickHouse/libdeflate#4 integrated).

02724_decompress_filename_exception. nextImpl now wraps the decompression loop and appends While reading from: <file> like the other *InflatingReadBuffer codecs.

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 .gz/zlib/deflate stream is unaffected). Left the thread open for a final call on whether the bound should change.

Also merged current master and renumbered the two stateless tests to 04489/04490 to avoid number-prefix collisions introduced by the merge.

The remaining red tests on the previous run (04240_iceberg…, 04230_iceberg…, test_storage_s3::test_key_value_args) are pre-existing flakes on master (unrelated to gzip/zlib), re-running with this push.

alexey-milovidov and others added 4 commits June 30, 2026 15:02
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]>
pull Bot pushed a commit to CrazyForks/ClickHouse that referenced this pull request Jul 1, 2026
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]>
@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator

CI finish ledger — be68cb8

CI 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.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug) / "Block structure mismatch in stream" (STID 0993-2c89) crash (chronic trunk AST-fuzzer UnionStep/IntersectOrExcept family, 0993-* sub-STIDs) #107719 (ours, open)

Session id: cron:our-pr-ci-monitor:20260703-053000

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The main question for now - are these gzip-compressed files with very large chunks normal, or an exception?
If it is more of an exception, it will be okay to allocate memory until it throws the Memory Limit Exceeded exception.
But if such files (or streams) are normal, we should reconsider our approach.

…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

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 MEMORY_LIMIT_EXCEEDED is the right model and the hardcoded 256 MiB fail-close cap is unnecessary. Pushed 27c40f4b7f1, which removes the MAX_OUTPUT_BUFFER ceiling and relies on the memory tracker instead.

Why large single blocks don't occur in practice

Every 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:

Encoder Governing constant Max uncompressed bytes / block
zlib (gzip, Python, Java Deflater, PHP, …), default memLevel 8 lit_bufsize = 1<<(memLevel+6) = 16384, flush at sym_end (16384−1)×258 ≈ 4.03 MiB
zlib, max memLevel 9 lit_bufsize = 32768 ≈ 8.06 MiB
libdeflate (encoder) SOFT_MAX_BLOCK_LENGTH = 300000 ≈ 305 KB
zopfli ZOPFLI_MASTER_BLOCK_SIZE = 1000000 ≈ 1 MiB
Go compress/flate maxFlateBlockTokens = 1<<15 ≈ 8.06 MiB
7-Zip kMaxUncompressedBlockSize = (1<<16)−1 64 KiB
miniz / miniz_oxide (Rust flate2) TDEFL_LZ_CODE_BUF_SIZE = 64K entries tens of KB (a few MiB worst case)
stored blocks (BTYPE=00), all encoders 16-bit LEN field 65535 (hard format cap)

So the output buffer for any real stream stays at one small block (≤ ~8 MiB, usually far less). Even a multi-GB .gz produced by gzip is millions of ~tens-of-KB blocks, not one giant block.

The bomb lives on the output side, and the memory tracker already handles it

RFC 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 (length=258, distance=1) pairs expands at ≈159:1 (≈1032:1 with a maximally skewed dynamic tree), so ~7 MB of one crafted block → 1 GiB of output with no intermediate suspend point. That is the only way to force a huge single block, and it is adversarial.

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, 27c40f4b7f1 treats it like any other oversized allocation: the output buffer (and in_buf) are allocated through ClickHouse's tracked allocator, so a bomb hits the query/server memory limit and throws MEMORY_LIMIT_EXCEEDED, while real streams never grow past one small block. I also switched the grow to geometric to avoid O(n²) reallocation on that (adversarial-only) grow path. This removes the read-contract divergence from ZlibInflatingReadBuffer the earlier review flagged: a legitimate single block larger than 256 MiB now decodes instead of throwing a special error, and the input-side thread is answered by the same 1:1, tracked-allocation reasoning.

One tradeoff for your call

The bomb ceiling is now the configured memory limit (default max_memory_usage 10 GiB per query) rather than a hardcoded 256 MiB, so a crafted stream can transiently allocate more before being stopped. That is the standard ClickHouse model — same as a huge string or array — but if you would rather keep an explicit, generous-but-bounded ceiling as a cheap DoS backstop independent of the memory-limit settings, that is a one-line change on top. Left it relying on the memory tracker per your note.

alexey-milovidov and others added 2 commits July 12, 2026 20:02
… 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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 49.50% 85.80% +36.30%
Functions 63.90% 92.70% +28.80%
Branches 38.30% 78.00% +39.70%

Changed lines: Changed C/C++ lines covered: 441/499 (88.38%) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov self-assigned this Jul 14, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 14, 2026
Merged via the queue into master with commit 67cc47a Jul 14, 2026
345 of 347 checks passed
@alexey-milovidov
alexey-milovidov deleted the integrate-libdeflate branch July 14, 2026 00:39
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 14, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…late

Use libdeflate for gzip/zlib/deflate compression and decompression
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants