Skip to content

Fix memory leak in SZ3 compression scratch buffers - #113916

Merged
alexey-milovidov merged 5 commits into
masterfrom
fix/sz3-compress-scratch-buffer-leak
Aug 10, 2026
Merged

alexey-milovidov merged 5 commits into
masterfrom
fix/sz3-compress-scratch-buffer-leak

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 8, 2026 •

Copy link
Copy Markdown
Member

Bump contrib/sz3 (ClickHouse/SZ3@f36e8b0) to make the compress-side scratch buffers exception-safe.

Lossless_zstd::compress throws std::length_error when the destination capacity is too small for poorly-compressible data, and the Huffman encoder can also throw on encode. Every compress-side scratch buffer in SZ3 was a raw malloc with a bare free at the end of the function, so each failed compression leaked the buffer. CompressionCodecSZ3::doCompressData catches the exception and rethrows it as CORRUPTED_DATA, so the server keeps running and accumulates the leaked buffers.

This was observed by LeakSanitizer in a stress test (383 KB leaked in 2 allocations from SZ3::SZGenericCompressor::compress): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105249&sha=e803b6fd63e0a94ea3529b56af8a31fc8ada9562&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29

The fix applies the same unique_ptr-with-free RAII pattern already used in SZGenericCompressor::decompress to all compress-side scratch buffers (SZGenericCompressor, SZTruncateCompressor, SZExaaltCompressor, SZDispatcher, SZAlgoInterp), and hardens the Exaalt decompression path the same way (it parses untrusted data and could leak on corrupted input). It also makes the heap-owning SZ_compress(const Config &, const T *, size_t &) overload in include/SZ3/api/sz.hpp (the entry point used by CompressionCodecSZ3::doCompressData) exception-safe: its top-level output buffer was a bare new char[] and leaked when the inner compression threw before the pointer reached the caller.

It also makes SZ_compress_OMP (include/SZ3/api/impl/SZImplOMP.hpp) exception-safe: its per-thread scratch chunks were raw malloc buffers freed only after SZ_compress_dispatcher returned, and their capacity did not reserve room for the size header that Lossless_zstd::compress writes in front of the zstd stream. That path is _OPENMP-guarded and is not compiled in the ClickHouse build, so it was verified by compiling the header standalone with -fopenmp.

No behavior change; the existing SZ3 tests (03202_sz3_codec, 04603_sz3_codec_non_finite, 04604_sz3_codec_lorenzo_reg) pass locally with the patched submodule.

Related: #105249

Changelog category (leave one):

  • Bug Fix

Changelog entry:

Fix a memory leak in the experimental SZ3 compression codec: when compression of poorly-compressible or corrupted data failed with an exception, temporary scratch buffers were left allocated.

Version info

  • Merged into: 26.8.1.1101 (included in 26.8 and later)

Bump contrib/sz3 to make the compress-side scratch buffers exception-safe.
`Lossless_zstd::compress` throws `std::length_error` when the destination
capacity is too small for poorly-compressible data, and every compress-side
scratch buffer in SZ3 was a raw `malloc` with a bare `free` at the end of the
function, so each failed compression leaked the buffer. Observed by
LeakSanitizer in a stress test as a leak in `SZ3::SZGenericCompressor::compress`
reached from `CompressionCodecSZ3::doCompressData`:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105249&sha=e803b6fd63e0a94ea3529b56af8a31fc8ada9562&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29
Related PR: #105249

The buffers now use the same `unique_ptr`-with-`free` RAII pattern already
used in `SZGenericCompressor::decompress`; the Exaalt decompression path is
hardened the same way.
@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4dd1e8c]

Summary: ✅


AI Review

Summary

This PR bumps contrib/sz3 through three upstream commits that make the codec's compress-side temporary buffers exception-safe and fix the missing Lossless_zstd header reservation in the _OPENMP chunk path. The current code matches the earlier inline findings, but the PR still lacks regression evidence for the Bug Fix claim: the cited local codec tests do not exercise the exception path that leaked, so they do not prove that the leak is gone.

Findings

⚠️ Majors

  • [contrib/sz3:1] The PR promises that the linked LeakSanitizer repro is fixed, but the only evidence here is code inspection plus existing SZ3 functional tests. Those tests do not drive the throwing compression path, so they would still pass if the leak persisted.
    Suggested fix: rerun the linked sanitizer repro on this submodule revision, or add the smallest focused sanitizer test that forces the same exception path and shows a clean leak report.
Tests
  • ⚠️ Re-run the linked stress repro under LeakSanitizer, or add a focused sanitizer test that makes SZ3 throw during compression. That is the smallest evidence that would substantiate the Bug Fix claim.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required action: attach regression evidence for the linked leak repro, or a smaller sanitizer reproduction that proves the exception-path leak is gone.

@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4dd1e8cdd with master f70042f01 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 690.92 MiB 687.89 MiB -3.03 MiB (-0.44%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

7 translation units recompiled, 18 s compile time in total, 7 of them have a recent master baseline.

Job report

Comment thread contrib/sz3 Resolved
…tion-safe

Addresses the review finding that `CompressionCodecSZ3::doCompressData` calls
the heap-owning `SZ_compress(config, data, compressed_size)` overload, whose
top-level output buffer (a bare `new char[]` in `include/SZ3/api/sz.hpp`) was
still leaked when the inner compression threw before the pointer reached
`compressed.reset`. The buffer is now held in `std::unique_ptr` and released
only on success (ClickHouse/SZ3@89c5e97).

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread contrib/sz3 Resolved
Addresses the review finding that the OpenMP compressor still kept its
per-thread scratch chunks in raw `malloc` buffers freed only on the success
path, and that their capacity did not account for the size header written by
`Lossless_zstd::compress`.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: 04305_autopr_output_bytes_estimation_join in Stateless tests (amd_tsan, parallel) and provide a fix in a separate PR. If the fix is already in progress, link it here.

It is unrelated to this PR (which only bumps contrib/sz3): the harness labelled it flaky and all 7 reruns with the same randomized settings passed. The test produced an extra 04305_join_inner 0 3943574 line, i.e. an unexpected row in the estimation output. The same test has been failing across several unrelated PRs (#113563, #113412, #113382, #112688), so it looks like a master-wide flake with no tracking issue yet.

The other red, test_dirty_pages_force_purge, is already fixed by the merged #113811, which this branch has now picked up by merging master.

Comment thread contrib/sz3
@@ -1 +1 @@
Subproject commit ff760cc4c011cbdef5dc0025dc1bec45b1931cc8
Subproject commit f36e8b064fdde4bac260988ea459786964bbb492

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 code changes look consistent with the earlier leak reports, but the PR still does not provide proof for the Bug Fix claim. The linked local codec tests are functional tests; they do not force the throwing compression path that originally leaked, so they would still pass if one of these scratch buffers were still lost on exception.

Please attach either:

  • a rerun of the linked LeakSanitizer stress repro against f36e8b0, or
  • the smallest focused sanitizer test that makes SZ3 throw during compression and shows a clean leak report.

Without that, this remains a reasoned fix rather than a verified one.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I built the focused sanitizer probe you asked for. It reddens on the base pin and is clean on this PR's pin, so the Bug Fix claim now has a measurement behind it. One correction to the reply above, though: the "not compiled in the ClickHouse build" argument covers only 1 of the 7 changed files.

The reason the linked functional tests cannot see this is worse than them being round-trip tests. The exception never reaches the caller: SZ_compress_dispatcher catches the length_error and downgrades to lossless, so the public SZ_compress call returns successfully while the scratch buffers abandoned by the unwind are already lost. The leak is silent, which is also why my first three probe designs measured 0 throws across 2700 swept configurations and would have been vacuous greens.

Trigger: uniform [0,1) Float64 with EB_ABS bound 1e-6. Worst ZSTD_compressBound(srcLen) / (dstCap - 8) is 1.1560, so the bound is genuinely missed. Random-bit and mixed-scale data never exceed 1.0, which is why "incompressible data" does not reach it.

A/B, n=8192, 40 rounds x 3 algorithms, counting the inner length_error separately from the leak report:

arm inner throws reached LSan
ff760cc4 (base) 120 22471492 bytes in 160 allocations
f36e8b06 (this PR) 120 clean
f36e8b06 with the SZGenericCompressor guard removed 120 19850052 bytes in 120 allocations

Reached is identical in all three arms, so the clean arm is not an unreached path, and I asserted LeakSanitizer: checking for leaks is present in it so it is not a skipped check. Four distinct leak sites on the base pin: three at SZGenericCompressor.hpp:51 (via SZ_compress_LorenzoReg and SZ_compress_Interp) and one at SZAlgoInterp.hpp:181 (via SZ_compress_Interp_lorenzo). The mutation arm loses exactly the three SZGenericCompressor ones, so per-hunk attribution holds.

This matches a live CI report rather than a synthetic one. CIDB STID 3671-3a9b on Stress test (arm_asan_ubsan) and (amd_asan_ubsan) has the same file, line and callers: most recently #113963 at 2026-08-10 00:34 (1352832 bytes / 6 objects), #113796 at 2026-08-09 20:55 (209040 bytes), #109453 at 2026-08-09 07:57 (1890620 bytes).

It is user-reachable without any unusual configuration: EB_ABS with a caller-supplied bound is parsed straight from SQL at CompressionCodecSZ3.cpp:371, so CODEC(SZ3('ALGO_LORENZO_REG', 'ABS', 0.000001)) on such a Float64 column reaches it from an ordinary INSERT.

Where the "not compiled" argument does apply, and only there: SZImplOMP.hpp. I confirmed -fopenmp and -D_OPENMP are absent from the SZ3 codec translation unit in compile_commands.json and from cmake/, contrib/sz3-cmake/ and src/CMakeLists.txt, and SZImpl.hpp:11-13 forces conf.openmp = false under #ifndef _OPENMP. So no ClickHouse test can reach that hunk and the standalone -fopenmp compile is the right proof for it. The SZTruncateCompressor and SZExaaltCompressor hunks are also unreachable, since the codec only permits ALGO_LORENZO_REG, ALGO_INTERP_LORENZO and ALGO_INTERP. The other four files are compiled and reachable, and two of them are where the bytes above leak.

Probe source and both arms are reproducible with the pins unpacked side by side:

clang++-21 -std=c++23 -g -O1 -fsanitize=address -fno-omit-frame-pointer \
  -DSZ3_USE_SKA_HASH=0 -I <pin>/include -I contrib/sz3-cmake -I contrib/zstd/lib \
  leak_probe.cpp build/contrib/zstd-cmake/lib_zstd.a -o probe
ASAN_OPTIONS=detect_leaks=1 ./probe 40 8192

I have not pushed anything here. If a committed regression test is wanted, the honest shape is a gtest over the codec rather than a stateless query, because the leak produces no user-visible symptom to assert on and only LSan can observe it.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is already in progress: #113908 (yours, open) pins query_plan_optimize_join_order_randomize=0, enable_join_runtime_filters=0 inside 04305_autopr_output_bytes_estimation_join.sql, plus the four AutoPR siblings 04340/04341/04342/04655. This test is its first hunk.

That matches this failure and the carriers you listed. CIDB over the last 30 days, excluding the flaky-check reruns: 14 failures across 12 PRs and 8 check names, 0 on master. On #113563, #113412, #113382 and #112688 the harness minimization named query_plan_optimize_join_order_randomize as a culprit in all four. Here the draw was --query_plan_optimize_join_order_randomize 1 --enable_join_runtime_filters True --join_runtime_filter_min_probe_rows 8783: the join plan then differs between the single-replica build and the candidate-replicas build, AutoPR skips the instrumentation, and output_bytes stays 0. So the extra 04305_join_inner 0 3943574 line is a fail-closed skip, not a wrong estimate.

One caveat so the link is not read as covering everything: 2 of those 14 failures are Fast test (#69540), which runs with --no-random-settings --no-random-merge-tree-settings (ci/jobs/fast_test.py:375), so no randomization draw is possible there. That arm prints all three lines at 0 rather than one, and #113908 will not affect it. It is a separate, PR-local mode.

@alexey-milovidov alexey-milovidov self-assigned this Aug 10, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 10, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

It shows that SZ3 is written by someone who doesn't know C++.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Submitted upstream: szcompressor/SZ3#139

Merged via the queue into master with commit 50ba465 Aug 10, 2026
181 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix/sz3-compress-scratch-buffer-leak branch August 10, 2026 13:09
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 10, 2026
alexey-milovidov added a commit that referenced this pull request Aug 10, 2026
Pulls in the fix for the SZ3 compress-side scratch buffer leak (#113916),
which was the only remaining CI red on this pull request (LeakSanitizer
report in `SZ3::SZGenericCompressor::compress` via `CompressionCodecSZ3::doCompressData`).

# Conflicts:
#	src/Storages/MergeTree/MergeTreeData.cpp
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default 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